# Question
Title: t function doesnt work in this module: Geolocation
Why is t() not working as expected in thre following situation?

I am using Geolocation field module for D7 (drupal.org/project/geolocation). The strings inside this module which are used in the widget don't appear in the translate interface searches. All my other modules' strings are correctly showing up in translate interface. Also the strings coming from JS for that module (that are enclosed in Drupal.t()) works ok.

For example "Get location" string is not translatable.

Here is a part of the module:

```
function geolocation_googlemaps_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  // In order to make Geolocation field work with the popular Field collection module
  // we check if our map widget is part of a Field collection and add the
  // #field_parents delta.
  if ($instance['entity_type'] == 'field_collection_item') {
    $depth = count($element['#field_parents']) - 1;
    $parent_delta = $element['#field_parents'][$depth];
    $id = $instance['id'] . '-' . $parent_delta . '-' . $delta;
  }
  else {
    $id = $instance['id'] . '-' . $delta;
  }

  $lat_value = isset($items[$delta]['lat']) ? $items[$delta]['lat'] : NULL;
  // To make this widget compatible with geofiled we need to rename the keys for
  // longitude. Geofield uses "lon" while Geolocation Field uses "lng".
  if ($field['type'] == 'geofield') {
    $lng_value = isset($items[$delta]['lon']) ? $items[$delta]['lon'] : NULL;
  } else {
    $lng_value = isset($items[$delta]['lng']) ? $items[$delta]['lng'] : NULL;
  }
  $element += array(
    '#delta' => $delta,
  );

  switch ($instance['widget']['type']) {

    case 'geolocation_googlemap':
      $element['address'] = array(
        '#type' => 'item',
        '#title' => $element['#title'],
        '#prefix' => '<div id="geolocation-address-' . $id . '" class="geolocation-address">',
        '#suffix' => '</div>',
        '#required' => $instance['required'],
      );
      $element['address']['field'] = array(
        '#type' => 'textfield',
        '#maxlength' => 120,
      );
      $element['address']['geocode'] = array(
        '#prefix' => '<span id="geolocation-address-geocode-' . $id . '" class="geolocation-address-geocode">',
        '#suffix' => '</span>',
        '#markup' => t('Get location'),
      );
      $element['help'] = array(
        '#prefix' => '<div id="geolocation-help-' . $id . '" class="geolocation-help">',
        '#suffix' => '</div>',
        '#markup' => t('Enter an address / location in the textfield or you can also click on the map to set a marker'),
      );
      $element['googlemap'] = array(
        '#prefix' => '<div id="geolocation-map-' . $id . '" class="geolocation-map" style="width:100%;height:400px;">',
        '#suffix' => '</div>',
      );
      // Presentational item.
      $element['latitem'] = array(
        '#type' => 'item',
        '#title' => t('Latitude:'),
        '#prefix' => '<div id="geolocation-lat-item-' . $id . '" class="geolocation-lat-item">',
        '#suffix' => '</div>',
        '#markup' => '<span class="geolocation-lat-item-value">' . $lat_value . '</span>',
        '#required' => $instance['required'],
      );
      $element['lat'] = array(
        '#type' => 'hidden',
        '#prefix' => '<div id="geolocation-lat-' . $id . '" class="geolocation-lat">',
        '#suffix' => '</div>',
        '#default_value' => $lat_value,
      );
      // Presentational item.
      $element['lngitem'] = array(
        '#type' => 'item',
        '#title' => t('Longitude:'),
        '#prefix' => '<div id="geolocation-lng-item-' . $id . '" class="geolocation-lng-item">',
        '#suffix' => '</div>',
        '#markup' => '<span class="geolocation-lat-item-value">' . $lat_value . '</span>',
        '#required' => $instance['required'],
      );
      $element['lng'] = array(
        '#type' => 'hidden',
        '#prefix' => '<div id="geolocation-lng-' . $id . '" class="geolocation-lng">',
        '#suffix' => '</div>',
        '#default_value' => $lng_value,
      );
      $element['remove'] = array(
        '#prefix' => '<div id="geolocation-remove-' . $id . '" class="geolocation-remove"><span>',
        '#suffix' => '</span></div>',
        '#markup' => t('Remove'),
      );

      // Attach CSS and JS files via FAPI '#attached'.
      $element['googlemap']['#attached']['css'][] = drupal_get_path('module', 'geolocation_googlemaps') . '/geolocation_googlemaps.css';
      $element['googlemap']['#attached']['js'][] = array(
        'data' => '//maps.google.com/maps/api/js?sensor=false',
        'type' => 'external',
      );
      $element['googlemap']['#attached']['js'][] = array(
        'data' => '//www.google.com/jsapi',
        'type' => 'external',
      );
      $element['googlemap']['#attached']['js'][] = array(
        'data' => drupal_get_path('module', 'geolocation_googlemaps') . '/geolocation_googlemaps_widget.js',
        'type' => 'file',
        'scope' => 'footer',
      );

      // Make defaults available as javascript settings. In JS files use:
      // Drupal.settings.mapDefaults.lat
      $map_defaults_lat = ($lat_value) ? $lat_value : '';
      $map_defaults_lng = ($lng_value) ? $lng_value : '';
      $map_defaults = array(
        $id => array(
          'lat' => $map_defaults_lat,
          'lng' => $map_defaults_lng,
        ),
      );
      $data = array(
        'defaults' => $map_defaults,
        'settings' => $instance['widget']['settings'],
      );
      $element['googlemap']['#attached']['js'][] = array(
        'data' => array('geolocation' => $data),
        'type' => 'setting',
      );

      $element['field_type'] = array('#type' => 'value', '#value' => $field['type']);
      $element['#element_validate'] = array('geolocation_googlemaps_field_widget_validate');
      $element['#element_validate'][] = 'geolocation_googlemaps_field_widget_set_value';

      break;
  }
  return $element;
}

```

# Answer
It happens. Try to flush cache and open page with this form (googlemaps widget settings) in language other than English.
After the first request for translation strings should appear.
> 3 votes

---
Tags: i18n-l10n
---


title: Ajax error while saving a view

text:
# Question
Title: Ajax error while saving a view
When I edit a view, and click on the "Save" button, I get the following message:

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: /admin/structure/views/view/vouchers\_list/preview/page/ajax
> StatusText: OK

What does that message mean? How can I fix the error?

# Answer
When you make a change to a view in the UI and click "save" before the preview has finished loading, you'll get this error. It's simply because you've made a 2nd request to the server while the ajax request to load the preview is still running.

You can either wait for the preview "loading" icon to finish before you save the view, or you can ignore it :)
> 2 votes

---
Tags: views, ajax
---


# Question
Title: Google keeps indexing /comment/reply URL
With the new update of Google algorithm called Penguin, I think my site was being penalized due to webspam. But of course I don't create post which seems to be spam to Google. It is just I think how Google index my site.

I found out that Google index the URL of my site like:

http://www.example.com/comment/reply/3866/26556

So there are so many comment/reply URL index by Google. I have already added:

Disallow: /comment/reply/ Disallow: /?q=comment/reply/

but still Google still index this URL.

Any idea how to prevent Google from indexing comments?

Here's my .htaccess:

```
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

Options -Indexes
Options +FollowSymLinks
ErrorDocument 404 /index.php
DirectoryIndex index.php index.html index.htm

<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive On

  ExpiresDefault A1209600

  <FilesMatch \.php$>
    ExpiresActive Off
  </FilesMatch>
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule "(^|/)\." - [F]
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  <IfModule mod_headers.c>
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      Header set Content-Encoding gzip
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

# Answer
I would try adding

```
RewriteCond %{HTTP_USER_AGENT} ^Googlebot
RewriteRule ^comment/reply/$ - [G,L]
RewriteRule ^comment/reply/(.*) - [G,L]

```

to `.htaccess` or Apache config to inform spiders that the links should be removed. Just make sure to put it before the catch-all rule at the bottom of the standard Drupal `.htaccess`. The problem is coming up with a list of spiders to add as `[OR]` conditions to the `RewriteCond` so that they get a 410 but Drupal handles normal requests.

Google Webmaster Tools has a URL removal tool, too, but I have never tried using it with patterns before.
> 3 votes

# Answer
I am facing the same problem at the moment. One possibility is to modify the "reply" link of the main posts, by adding the rel="nofollow" option. This should be doable by writing an external module, or a custom theme function.

The advantage of this method, is that all search engines will avoid following these links, so you do not have to be explicit for google
> 1 votes

---
Tags: uri
---


title: Views taxonomy contextual filter?

text:
# Question
Title: Views taxonomy contextual filter?
I have taxonomy vocabulary called “`Groups`”, with 3 terms. I have two content types that both use a `Groups` term reference field. These content types are called “`Media`” and “`Links`”.

When displaying “`Media`” (node), I have an embedded view that shows “`Links`”. How can I only show “`Links`” that have the same terms as the actual “`Media`”?

Is it possible to do with contextual filters?

# Answer
> 5 votes
> I have ***embed view*** that shows “Links”. How can I only show “Links” that have the same terms as the actual “Media”?

I'm not sure you used Entity Views Attach module to attach the View or just placing the View as a block.

Whatever it is, you can do it. But if you have EVA, you will be able to set the current node ID argument easily.

1. Add a new View as **Show**: *Content*, **Of Type** *links*. Continue and Edit.
2. Then, in the Views UI, you will see a filter to show only Link nodes are added. Now, add extra fields you want from the Link nodes.
3. Set configuration as marked in the image below.
4. Save the View.
5. Save the View and enjoy!

* if you have EVA module, do not set to inherit node ID to the View (it will give wrong results). Send the term ID as argument(s) if possible.

# Answer
> 2 votes
Yes, you can do this using contextual filters. You need to add a *"Content has taxonomy term ID"* contextual filter, and set the default value to *"Taxonomy term ID from URL"* and check *"Load default filter from node page, that's good for related taxonomy blocks"*. now check *"Limit terms by vocabulary"* and select *"Groups"* vocabulary.

---
Tags: 7, taxonomy-terms, views
---


title: Use Ajax in a view outside Its path

text:
# Question
Title: Use Ajax in a view outside Its path
I am using a view that I get from views\_get\_view('') and I put it inside a node page. The problem is that the view normally uses AJAX (to filter,pagination,etc...) only when called through Its path. This is not my case here because the view is calling from the node page.

Do you know how to handle this? note that I retrieve a page view using views\_get\_view('MYVIEW'). Thanks a lot

# Answer
> 0 votes
I have solved my issue. Changed the type to view block and then I did `views_embed_view()`

Works fine

---
Tags: views, ajax, uri
---


# Question
Title: How to fetch 10 10 records in json format using views
I am working on views(D7) for providing JSON web services ... I am using **JSON\_data\_document** module My question is How to get the data returned from the views in ten,ten records.

Example : consider mysql query

```
select *  from table limit $variable,10 ;

```

so if `$variable is 0` it gives 0 - 10 records and again when webservice is called (developer passes $variable as 11 ) it should give next ten (11 - 20) records. and so on

Is this possible in drupal using views ?

Is there any special module ?

please help !!!

# Answer
Maybe Services? Create views with pager by 10 items per page and read this article from 19 punkt - how to fetch your view.
> 2 votes

# Answer
If you append ?page=1 to your views page url you should be able to fetch records 11-20. Make sure your view has paging enabled.

I personally prefer the Views Datasource (Views JSON) module for retrieving JSON information about nodes/users through views. This approach definitely supports ?page=1 when appended to your Views Page Display (JSON Data Document) url path.
> 2 votes

---
Tags: views, services
---


title: Save fields when creating user?

text:
# Question
Title: Save fields when creating user?
I've added some custom fields in "Account Settings" at *admin/config/people/accounts/fields*. But, those doesn't appear on the "Add user" menu on *admin/people*, and appear on user edit page *user/%uid/edit*.
I need to have them on the account creation page too. By using `hook_form_alter()` I can add the fields on the form. But, I need them to be saved when the user gets created. I understand that fields can be added to a user only on successful creation of the user by `user_save()`. So, I think I need to write a validation (after successful user creation) to save the fields for the newly created user. How do I do that?

# Answer
> 0 votes
The field should be visible if you check the checkbox which says: **Display on user registration form.** on *admin/config/people/accounts/fields/FIELD* near the top.

If you don't want the field on the standard user registration form which is visible to visitors, you could always use `hook_form_alter()` to hide that field there.

This way, Drupal will handle the validation and saving of the field for you.

---
Tags: 7, hooks, users
---


title: How do I use views_pre_execute

text:
# Question
Title: How do I use views_pre_execute
I am trying to run a subquery through views and found this call. I cannot get it to work. Here is how I am using it

```
function module_name_custom_views_pre_execute(&$view) {
    if($view->name=="view_name") {
            if($view->build_info['query_args'][1]==0) {
            $view->build_info['query']="my subquery";

                //echo ($view->build_info['query'] );
                //var_dump($view);
            }
    }
}

```

Without to test it I tried replacing the $view-\>build\_info\['query'\] with the query generated in the view. Instead of a view result I get a blank page. Any other query I put in there myself results in a blank page as well.

I am writing the queries like so:

$view-\>build\_info\['query'\]="SELECT nid FROM node WHERE node.status='1'";

So I am not assigning any array objects values but rather writing the query in as if I would in any other db call. Should I build the query through the means of creating an object? So something like this to start:

```
["build_info"]=> array(3) {
    ["query"]=> object(SelectQuery)#752 (21) {
        ["fields":protected]=> array(4) {
            ["nid"]=> array(3) {
                ["field"]=> string(3) "nid"
                ["table"]=> string(4) "node"
                ["alias"]=> string(3) "nid" }
        ["node_created"]=> array(3) {
            ["field"]=> string(7) "created"
            ["table"]=> string(4) "node"
            ["alias"]=> string(12) "node_created" }
        ["og_og_membership_label"]=> array(3) {
            ["field"]=> string(5) "label"
            ["table"]=> string(16) "og_og_membership"
            ["alias"]=> string(22) "og_og_membership_label" }
        ["node_title"]=> array(3) {
            ["field"]=> string(5) "title"
            ["table"]=> string(4) "node"
            ["alias"]=> string(10) "node_title" } }

```

Is there is another way to implement a subquery in views?

Using Drupal 7 Views 3

# Answer
Also checkout http://drupal.org/sandbox/Fabianx/1184598 as this is adding a subquery to a view; which is exactly what your trying to do.
> 2 votes

# Answer
There are tons of pre\_execute() examples here http://drupal.org/node/409808 that might help.
> 1 votes

# Answer
You will have to make db\_select() query object (In Drupal 7 Views 3 you can not use simple SQL query any more). For further detail on "Dynamic queries" go to this link.

http://drupal.org/node/310075

Thanks
> -2 votes

---
Tags: views, hooks, database
---


# Question
Title: How do I reference an image from text/description field?
In some cases, I am entering some text and an img src tag in descriptions and text fields on my content pages rather than use an image field, for example the *Header* field on a view.

I cannot work out the location to use. I thought images/imagefilename.jpg would do the job, but alas no. I also want to avoid the old http://hostname.com/images/imagefilename.jpg for vairous reasons.

My images are in themes/mytheme/images.

# Answer
Unless the location of your Drupal install changes (sub directory versus root directory), the easiest way would be to use a relative path from the site root to the image.

```
<img src="/sites/all/themes/mytheme/images/imagefilename.jpg" />

```

You could get the file path with a PHP snippet. Note that the PHP filter module needs to be enabled, and the PHP code text format selected, for this to work.

```
<?php $path = base_path() . path_to_theme() . '/images'; ?>
<img src="<?php print $path; ?>/imagefilename.jpg" />

```
> 2 votes

# Answer
Typically your images would live in your /sites folder, especially under a theme.

The two most common paths would be:

or

Depending on whether you are using a site-specific folder or the all folder to host your themes folder.

The easiest way to determine the correct path would be to mimic the path for the css files also in your theme folder and included in the http header when viewing the rendered html source in a web browser.
> 0 votes

---
Tags: media
---


# Question
Title: Is it possible to address a single item of a field collection in pathauto?
I'm making sort of a slideshow for a customer

The slideshow has a field collection which has itself several fields that contain the actual content of the slides (headline, text, image, alt text, image caption)

And the slideshow is a node which uses several fields: title, teaser texts, teaser title texts, links to other pages etc.

The customer wants the slides to have individual URLs which I want to be created with pathauto module. The token which I use for a normal node (on admin/config/search/path/patterns) is like this `[node:title]-[node:nid]`. This works ok

But how about the token for a individual slide? If I administer the fields for my field collection (admin/structure/field-collections/field-pages/fields), there is no such default field like URL-alias.

Do I need to use the token hooks to create new tokens? But how? How can I then add them to the URL-alias? I suggest with hook\_presave? Could it be done?

# Answer
> 0 votes
I managed it now like this in a custom module. What I do is add a new argument to the system path, so `node/<nid>` becomes `node/<nid>/<slide_num>`

Can it be made better?

```
/**
 * implements hook_pathauto_alias_alter()
 * alters the alias of a newly created slideshow node
 */
function coco_slideshow_pathauto_alias_alter(&$alias, &$context) {
        // print_r(array($alias, $context));
    if ($context['module'] == 'node' && $context['type'] == 'slideshow'
        && ($context['op'] == 'insert'
            || $context['op'] == 'update')
        ) {
            $node = $context['data']['node'];

            module_load_include('inc', 'pathauto');
            module_load_include('inc', 'path');

            // get default path alias from patterns
            // this will be start of url alias
            $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
            $path = pathauto_clean_alias(token_replace($pattern, array(
                'node' => $node,
            ), array(
                'sanitize' => false,
                'clear' => FALSE,
                'callback' => 'pathauto_clean_token_values',
                'language' => (object) array('language' => $node->language),
                'pathauto' => TRUE,
            )));

            $pages = field_get_items('node', $node, 'field_pages');
            if (!empty($pages)) {
                $slide_id = $pages[0]['value'];
                $slide = field_collection_item_load($slide_id);
                if (!empty($slide)) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    $headline_text = $headline[0]['safe_value'];
                    if (!empty($headline)) {
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");
                        // alias is replaced with new one
                        $alias = "{$path}-{$path_text}";
                    }
                }
            }
    }

}

/**
 * implements hook_node_insert()
 *
 * creates aliases for each slide in slideshow node type
 */
function coco_slideshow_node_insert($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i > 0) {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}

/**
 * implements hook_node_update
 */

function coco_slideshow_node_update($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i == 0) {
                            $save = array(
                                'source' => "node/{$nid}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            $temp = drupal_get_path_alias("node/{$nid}", $node->language);
                            path_delete(array('alias' => $temp));
                            // print '<xmp>' . print_r($save,1). '</xmp>';
                            path_save($save);
                        } else {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_delete(array('source' => "node/{$nid}/{$id}"));
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}

```

---
Tags: 7, entities, tokens, path-aliases
---


title: Overhead of using Panels

text:
# Question
Title: Overhead of using Panels
Panels is one of the most useful modules for Drupal and many websites make use of it. However I always have been cautious using it because of its processing overheads. I want to know is there any benchmark or article about Panels efficiency on the net?

Thank you.

# Answer
This is the only thing I recall seeing, at DrupalCon San Fran in 2010. Sam Boyer, a maintainer of Panels, discusses benchmarks a bit in this video: http://sf2010.drupal.org/conference/sessions/state-panels-3-and-more-what-you-love at about the 29 minute mark. It's not really a great benchmark test, but gives some idea into what page manager is running/processing.
> 4 votes

# Answer
Here's another benchmark Performance Panels.

> Conclusions
>
> Panels is, in general, about 20% quicker than Block. Until you add in some Views \>blocks. Then big ouchy things start to happen (we haven't investigated why that \>is yet). Those big ouchy things *only* affect Block and not Panels. So all of a \>sudden Panels becomes about 100% quicker than Block
> 2 votes

---
Tags: panels
---


# Question
Title: Importing large content with Feeds and cron
I've used the migrate module in the past, it's great to import large amounts of content but it's pretty complex. This time I'm trying Feeds and Feeds\_SQL to import from a mysql tables. It imports fine when I kick it off with the import UI. However it will give an Ajax error after importing a few hundred records.

I try to import using cron. That's where it gets confusing to me:

I select "periodic import" -\> "as often as possible", uncheck "import on submission" and check "process in the background".

I then start the import using the UI, it imports some nodes and then stops.

When I manually run "feeds\_cron" nothing happens. When I manually run "job\_scheduler\_con" it showed "Finished processing scheduled jobs (0 sec s, 1 total, 0 failed)." in teh logs and imported more records (but not all). When I run it again it shows "Finished processing scheduled jobs (0 sec s, 0 total, 0 failed)." and nothing gets imported.

Do I have the correct settings? How are the "periodic import" setting and the "feeds cron" and "job scheduler cron" related?

Is there a setting somewhere that controls how many nodes are processed each time?

# Answer
Are you running the actual site cron? If not, run it.

As for the Ajax errors when running a manual import, are you sure that it isn't continuing to import despite these? My large imports will time out the browser connection when I manually import in feeds, *but* they will actually still continue to process.

Also, could you try changing your setting from "As often as possible" to "Every 30 minutes", to ensure the crons aren't running over each other?
> 3 votes

---
Tags: 7, feeds
---


title: Getting the profile2 user fields?

text:
# Question
Title: Getting the profile2 user fields?
i am writing a simple multistep form using ctools on drupal 7. Everything seems to work but i have a one last problem before i finish the task. How can i access the custom user fields (or fieldset i am not sure about the terminology). I've tried to do that by using the function below but it doesn't works and the property is always empty;

```
function helper_get_default_value_from_profile($fieldset, $key){

  $uid      = helper_is_user_logged_in();
  $account  = user_load($uid);
  $profile  = profile2_load_by_user($account, "cv");

  if(!property_exists($profile, $fieldset))
    return 0;

  if(empty($profile->$fieldset))
    return 0;

  $fieldset_ref = $profile->$fieldset;
  $id           = $fieldset_ref["und"][0]["value"];
  $fieldset_data = field_collection_field_get_entity($id);

  if(!property_exists($fieldset_data, $key))
    return 0;

  if(empty($fieldset_data->$key))
    return 0;

  $user_prop = $fieldset_data->$key;
  return $user_prop["und"][0]["value"];
}

```

# Answer
> 2 votes
It seems like you want to retrieve the value of a single field from a field collection. And that the field collection you want to retrieve a field from is a field of a 'cv' profile2.

The returned value of `profile2_load_by_user($account, "cv");` is a `Profile` entity object. When `$fieldset` is the (machine) name of a field collection field, then you can retrieve its value using `$items = field_get_items('profile2', $profile, $fieldset)` (see `field_get_items()`). This will return an array of field collection values (or `FALSE` if there is no value for the field). The values are arrays containing a `value` entry which is the entity id of a field collection entity. You can load the field collection entity for an ID using `field_collection_field_get_entity()`. Finally, using `$key` as field name, you can retrieve the values of one of this field collection entity's fields using `field_get_items()` again.

```
$items = field_get_items('profile2', $profile, $fieldset);
if ($items) {
  $item = reset($items);
  if (!empty($item['value'])) {
    $field_collection = field_collection_field_get_entity($item);
    if ($field_collection) {
      $items = field_get_items('field_collection', $field_collection, $key);
      if ($items) {
        $item = reset($items);
        return !empty($item['value']) ? $item['value'] : 0;
      }
    }
  }
}
return 0;

```

---
Tags: 7, users
---


title: Enable <small> tags in CKEditor?

text:
# Question
Title: Enable <small> tags in CKEditor?
I have the CKEditor module installed, and it has a place to configure the allowed tags, but the list of allowed tags that you are allowed to... allow is very anemic. Is there a way to stop it from stripping tags (or any other tag for that matter)?

# Answer
This answer is for future reference

Checkout the WYSIWYG Filter

> The WYSIWYG Filter module provides an input filter that allows site administrators configure which HTML elements, attributes and style properties are allowed. It also may add rel="nofollow" to posted links based on filter options. It can do so with no additional parsing on user input. That is, it may apply nofollow rules while parsing HTML elements and attributes.
>
> The filter is based on whitelists that can be defined from the filter settings panel. Rules for HTML element and attributes are defined using the same syntax of the TinyMCE valid\_elements option.
>
> HTML attributes related to DOM events (on\*) are not allowed for security reasons (to prevent XSS, etc.).
>
> The following elements cannot be whitelisted due to security reasons, to prevent users from breaking site layout and/or to avoid posting invalid HTML. Forbidden elements: applet, area, base, basefont, body, button, embed, form, frame, frameset, head, html, iframe, input, isindex, label, link, map, meta, noframes, noscript, object, optgroup, option, param, script, select, style, textarea, title.

Please refer to the project page for more details.
> 2 votes

# Answer
If you go to admin/config/content/formats/ you can select the text\_format that ckeditor module is being used on and then adjust the relevant filters for the text format. The one you will want to look at is Limit allowed HTML tags where you can add exceptions for whichever you like.
> 1 votes

---
Tags: 7, wysiwyg
---


title: Setting up file sharing in Drupal 7

text:
# Question
Title: Setting up file sharing in Drupal 7
I would like to set up simple file storing and sharing (for educational purposes) for my users. I considered creating Profile2 profile and put data uploads files there. But it seems little clumsy.

Now i have idea to set up content types "File" Which will contain title and File upload field. That way they could possibly be able to "send" those nodes to anyonther somehow.

I could create listing of user files with views or else.

I am also using User Relationships module.

Question: What would you suggest, what would be best method to achieve this ? Is there mechanism for user to "send" node to another (User Relationships) ? What is the danger of having extreme number of nodes that user can produce this way ? Is there an alternative ?

Thanks

# Answer
> 3 votes
I suggest using Privatemsg module it had a nice attachment field and now it is fieldable that means you can add highly customizable file fields.

Thou Privatemsg module will work not as content type but more like internal messaging tool I also suggest checking out Notifications which depends on Messaging module. It will send emails upon creation or edit of chose content for all users you chose. You may also look into Team Notifications module which will allow your users to create subscriptions for others. Which is integrated with Organic groups module (OG). OG is best way for grouping and allowing users to group themselves yet if you are looking for a simple solution this may not fit due to it\`s extensive functionality which results in fairly complex results.

---
Tags: nodes, users, files
---


title: How to have multilingual custom 404?

text:
# Question
Title: How to have multilingual custom 404?
I have a multilingual Drupal 7 site for which I have set up a translated 404-page accessed at `mydomain.com/404` and `mydomain.com/en/404`. In the Drupal settings for 404-page I enter just the path `404`.

However, when visiting a non existant URL on the English version, the default language is still being used.

What did I miss?

# Answer
> 8 votes
With i18n module pack, there is a module for translating settings, like front page and 404 pages. This means you can setup your 404 page per language, fx `node/1` for `en` and `node/2` for `fr` etc.

# Answer
> 2 votes
Another way to achieve this is with a single page with different text sections per language using Language Sections.

---
Tags: 7, i18n-l10n
---


title: nested xml views export

text:
# Question
Title: nested xml views export
I use drupal6 and views2. I need to create xml file using views. This can be done easily using any xml export module but I am not able to create deeper nested xml output like:

```
    <itemslist>
     <items>
      <item>
       <item_nbr></item_nbr>
       <item_pic></item_pic>
      </item>
     </items>
    </itemslist>

```

Can anybody point me to the right direction? Thank you.

# Answer
> 2 votes
The best way for creating data output from Drupal is by relying on Services it will give you XML-RPC or REST server which will be capable of outputting data in precisely the way you want. I will lay out in steps:

1. Installing Services module
2. Creating an endpoint and firring up a server.Here is simple guide how to do that.
3. To format Service output you will need to create a simple module or rely on contributed modules.

Writing a module may seam bit tricky for a beginner so I suggest using modules like Services Views which will let you add a Service type view page or use Services Entity API or Services SearchAPI.

---
Tags: views, entities, importing-exporting
---


# Question
Title: Views group different number of divs of a view by wrapping them
I have a views block that is displayed in the content section of a node. What I need is wrapping the rows of the views block by divs. I have a list of 10 divs like so:

```
<div class="row-1">Some Text here</div>
<div class="row-2">Some Text here</div>
<div class="row-3">Some Text here</div>
<div class="row-4">Some Text here</div>
<div class="row-5">Some Text here</div>
<div class="row-6">Some Text here</div>
<div class="row-7">Some Text here</div>
<div class="row-8">Some Text here</div>
<div class="row-9">Some Text here</div>
<div class="row-10">Some Text here</div>

```

Now I want to wrap the first 3 divs, div 4 to 8 and div 9 and 10 in a separate wrapper div like so.

```
<div class="wrapper-1">
<div class="row-1">Some Text here</div>
<div class="row-2">Some Text here</div>
<div class="row-3">Some Text here</div>
</div>
<div class="wrapper-2">
<div class="row-4">Some Text here</div>
<div class="row-5">Some Text here</div>
<div class="row-6">Some Text here</div>
<div class="row-7">Some Text here</div>
<div class="row-8">Some Text here</div>
</div>
<div class="wrapper-3">
<div class="row-9">Some Text here</div>
<div class="row-10">Some Text here</div>
</div>

```

How would I edit my views.tpl.php? Thanks!

# Answer
> 1 votes
Here is what worked for me. Mind that I only got it to work in an unformatted list format in views.

```
<?php
  $currIx = 1; // This will be our incremental index variable. Let's make it 1-based to maintin consistency with your example.
  $currWrapperIx = 1; // Wrapper counter
  $wasOpen = FALSE; // This variable will be used later as a flag to watch for properly closing wrapper divs.
?>

<?php if (!empty($title)): ?>
  <p class="<?php print $title ?>"><?php print $title; ?></p>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php switch ($currIx){
    // List the row indices that are supposed to begin a new wrapper.
    case 1:
    case 27:
      if($wasOpen == TRUE){ // Close current wrapper div before opening a new one.
        print "</div>\n";
        $wasOpen = FALSE;
        $currWrapperIx ++; // Increment the index for next wrapper's class.
      }
      // Open a new wrapper div
      print "<div class=\"wrapper-{$currWrapperIx}\">\n";
      $wasOpen = TRUE;
      break;

    default:
      // For other row indices do nothing.
    }
  ?>
<!--<div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>-->
  <div class="<?php print $id ?>"><?php print $row; ?></div>
<!-- </div>-->

  <?php $currIx ++; ?>
<?php endforeach; ?>

<?php
    // Close the last wrapper.
    if($wasOpen == TRUE){
      print "</div>\n";
      $wasOpen = FALSE;
    }
?>

```

Kudos go out to @Artur. Great support. Many thanks.

# Answer
> 0 votes
Sure thing criscom. Below is a very rudimentary piece of code.

```
<?php
  $rows = array(
    1 => "row1",
    2 => "row2",
    3 => "row3",
    4 => "row4",
    5 => "row5",
    6 => "row6",
    7 => "row7",
    8 => "row8",
    9 => "row9",
    10 => "row10",
  );
?>

<?php
  $currIx = 1; // This will be our incremental index variable. Let's make it 1-based to maintin consistency with your example.
  $currWrapperIx = 1; // Wrapper counter
  $wasOpen = FALSE; // This variable will be used later as a flag to watch for properly closing wrapper divs.
?>

<?php foreach ($rows as $id => $row): ?>
  <?php switch ($currIx){
    // List the row indices that are supposed to begin a new wrapper.
    case 1:
    case 4:
    case 9:
      if($wasOpen == TRUE){ // Close current wrapper div before opening a new one.
        print "</div>\n";
        $wasOpen = FALSE;
        $currWrapperIx ++; // Increment the index for next wrapper's class.
      }
      // Open a new wrapper div
      print "<div class=\"wrapper-{$currWrapperIx}\">\n";
      $wasOpen = TRUE;
      break;

    default:
      // For other row indices do nothing.
    }
  ?>

  <div><?php print $row; ?></div>

  <?php $currIx ++; ?>
<?php endforeach; ?>

<?php
    // Close the last wrapper.
    if($wasOpen == TRUE){
      print "</div>\n";
      $wasOpen = FALSE;
    }
?>

```

Sorry, I did not bother to make it pretty-print, but the source of the generated page has the div structure you asked for. The code is abstract and has dummy rows array, so you can test it by simply pasting it in an empty PHP file and trigger it outside Drupal. Anyway you should get the idea.

### Update

You used the PHP code from view-view.tpl.php. This is a template file with a broader picture on a view's output structure. In this file you don't have any control over the traversal (the foreach loop). It just says `print $rows` and that's it, meaning "print out the loop, whatever it looks like." What you need is to specify how the loop is generated - that is: open your view, open the Theming information and pick one of the tpl in the **Style** group (where tpl's contain the word **unformatted**). There you'll be able to mess with the loop. Remove my code from the former file and move it to that file. Rescan templates.

---
Tags: views, theming
---


# Question
Title: Creating a contextual filter for a view based on month and day
I've created a content type that represents a past events. I've added an extra date-field to this content type that indicates the date of the event. I'm trying to create a calendar that groups events by day and month, but ignores the year in which the event happens.

e.g. when going to site.com/calendar/\[month\]/\[day\], I'd like to get a list of all events that happened on the given day of the given day, irrespective of the year in which they happened.

This seems impossible with the default tools, as they always expect a year to filter on. How can I customize these filters?

# Answer
You will find the Date module useful for this. Date contains a number of sub-modules, including Date Views. Enable the Date Views module (and its required modules) and you will have what you need in Views.

Here's a link to the module:

http://drupal.org/project/date
> 2 votes

# Answer
Take a look at the `Archive` view, which is provided with Views by default. Change the contextual filter from `Content: Created year and month` to just `Content: Created month` (with `Content: Created day` if necessary). If you have trouble, look at the settings the `Archive` view provides by default.
> 0 votes

---
Tags: 7, views, datetime, tokens
---


# Question
Title: Alter Entity Reference View Widget available options
I have 2 content types business, locations, programs and services.

At program level we select all the services associated with that program.

At business level we select the programs the business is associated with.

At the location level based on the programs selected we give the option to sub select the services.

Now the services entity reference is displayed via Entity Reference View Widget. All I want to do is alter or unset certain options based on the choices made at the business level in terms of program selection.

I tried working at the views level to pass it as an argument but was unsuccessful. Then tried the node form alter but the unset option still shows up but without the checkbox.

Tried to alter it using hook\_field\_widget\_form\_alter as well but was not successful.

It looks like it implements a preprocess function entityreference\_view\_widget\_preprocess\_widget but I am not able to override it.

Looking for pointers if anyone has come across similar problem.

# Answer
Ending up using hook\_views\_pre\_render(&$view). So I did something like this

```
function contractor_programs_views_pre_render(&$view) {
  if ($view->name == 'location_services' && $view->current_display == 'entityreference_view_widget_1') {
    // added my logic to get the service options
    if (!empty($services_options)) {
        $services_options = array_keys($services_options);
        if (!empty($view->result)) {
          foreach($view->result as $key => $value) {
            if (!in_array($value->nid, $services_options)) {
              unset($view->result[$key]);
            }
          }
        }
      }
  }
}

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Views exposed taxonomy filter - show only terms within results
I have a block display with an exposed 'term' filter using BEF links filter. I have the need to reduce the terms to display only the ones that show within the blocks results.

For example I have 'term1', 'term2', 'term3' - then if within the results there is only 'term1', 'term2' - I need to remove 'term3' from the list of filter links.

I realize that the filter is built before display so I am having difficulty grasping how the filter can be modified depending on what is in the display.

Any help is much appreciated.

# Answer
> 1 votes
Have a look at views\_hacks. Specifically refer to Views Selective Exposed Filters (views\_filters\_selective)

# Answer
> 0 votes
I am interested in the option, as well. Just getting to that issue on a new project. Hard to believe that it is a built-in feature at filter level. But, would be a good feature request for the BEF module -- perhaps you could add it to issue queue.

---
Tags: taxonomy-terms, views
---


# Question
Title: Why do I get a fatal error when clicking on the permissions tab in admin/people?
Steps to reproduce:

1. Log in as administrator
2. Click on `People`
3. Click on the `Permissions` tab

This navigates to `admin/people/permissions`. Here is the complete source code for that page:

```
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2048 bytes) in /.../includes/common.inc on line 6300

```

Why am I getting this error and what can I do about it?

**Notes**:

* my `php.ini` file contains the following line: `memory_limit = 128M`
* `.../sites/default/settings.php` contains the following line: `ini_set('memory_limit', '512M');`
* If I go to `Reports/Status report` and scroll down to `PHP memory limit`, it says `128M`

# Answer
> 1 votes
If you are running multisite, you probably need to modify your settings.php on each sites.

---
Tags: 7
---


# Question
Title: let the user choose role upon registration
I'd like to let the front-end user to choose user role upon registration.

When the register form submit, I'd like it to redirect to the respective profile page concerning with their chosen role.

I use profile2 module and profile2 registration path module.

Is there any existing module for that ?

Thanks in advance!

# Answer
If you love custom coding and if you already have a custom module, I would recommend to do this with a custom module rather than using Profile 2 and other related modules. I personally prefer to write custom modules because it will let you get exactly what you are looking for. But you still need to use Auto Assign Role module to let user choose a user role on registration.

My solution is to show/hide the respective profile fields upon user role selection on the registration form. It would not redirect to the respective profile page.
You can create profile fields at **admin/config/people/accounts/fields** and you can export them to the registration form, but they cannot be created by role. What you would need to do is to show/hide each field by role from hook\_form\_alter and use #ajax attribute.

Here is an code snippet for this purpose. I did not test the code. Just for example.

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'user_register_form' || $form_id == 'user_profile_form'){

        $form['autoassignrole_user']['user_roles']['#ajax'] = array(
          // #ajax has two required keys: callback and wrapper.
          // 'callback' is a function that will be called when this element changes.
          'callback' => 'ajax_form_alter',
          // 'wrapper' is the HTML id of the page element that will be replaced.
          'wrapper' => 'replace_field_div',
          // Don't show any throbber...
          'progress' => array('type' => 'none'),
         );

        # This profile field will be shown or hidden when the respective "user_roles" is selected
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#prefix']     = '<div id="replace_field_div">';
        $form['field_first_name']['und'][0]['value']['#suffix']     = '</div>';

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['autoassignrole_user']['user_roles']) && $form_state['values']['autoassignrole_user']['user_roles'] == {rid_here}){
            # when the respective user roles is selected, show this field and set required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'textfield';
            $form['field_first_name']['und'][0]['value']['#required']   = TRUE;
        }else{
            # when the respective user roles, hide this field and remove required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
            $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        }
    }
}
/**
 * Callback for user_roles
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['field_first_name'];
}

```

You may notice that you have to use `['und'][0]['value']` for the profile field to tweak its attributes. If you are not sure about this, you can print $form for debugging purpose:

```
dpm($form); // if Devel module is enabled
echo '<pre>'; print_r($form); echo '</pre>'; // if you don't have Devel module

```

If there is another better solution, please post it and it will be appreciated.
> 4 votes

# Answer
checkout the Auto Assign Role.

> The Auto Assign Role serves three primary purposes. The first is to provide an automatic assignment of roles when a new account is created. The second is to allow the end user the option of choosing their own role or roles when they create their account. The third is to provide paths that will trigger a specific role when an account is created. The administrator has full control over these functions and can have them working together or independently of each other.
> 2 votes

---
Tags: users
---


# Question
Title: Filter for landscape format images in views
I am working with Views 3 and Drupal 7 and created a view to display a list of images from a given content type in a slideshow. For layout reasons, images in portrait format don't work. Is there any way to filter for "width \> height"?

# Answer
> 0 votes
One simple solution
in given content type, add a CCK (select list) field having option "width \> height". select this field when the image is landscape. then in views add this filter too.
by doing this, only images that are "width \> height" will be shown

---
Tags: 7, views, media
---


# Question
Title: Fallback to local images when Cloud Files breaks?
I'm using the Cloud Files module which uses the Rackspace Cloud Files PHP API to store all uploaded files on Rackspace Cloud Files (a CDN). It all works very well.

However, today, Rackspace itself had an outage related to their API and it caused my entire site to break. I absolutely can't have this happen when my site is finally live. Is there any way to keep the files locally as well as in Cloud Files so that if there is a problem I can flip a setting in the admin pages and it'll start using the local files so that the site continues working while Rackspace works on the problem?

# Answer
In javascript, you can listen to the image's onerror event listener.

set the source as normal. in onerror, set this.src to your local image path:

```
<img src="//somecdn.com/cat.jpg" onerror="this.src='/localpath/cat.jpg';" />

```

you could use jquery to loop over all images on the page and add the onerror event listener
> 6 votes

---
Tags: 7, cdn
---


# Question
Title: How to make a word/pdf type doc clickable
Good day

I have created a view, but am not sure how to make the documents type clickable. At the moment you click on the label it works, but not when you click the type. See attached, second example is the desired results and first one is the current results. I would like to take away the label and leave just the type and make it clickable.

On the other hand, how can I determine the document size and display it on the table as per second example.

# Answer
> 0 votes
I know its not a complete answer, but may help. Icon:

```
$icon = theme('file_icon', array('file' => $file));

```

File size:

```
format_size($file->filesize);

```

---
Tags: 7, views
---


title: db_insert() for CCK

text:
# Question
Title: db_insert() for CCK
I've created a custom module in D7, wich gothers info from user via form.api. Next, I've created a Custom Content Type 'questions' where I setup fields according to my form.

How do I save data to the CCK?

Note: I've tryed db\_insert(), but it refers only to 'node' which nsert one or more records to the node table.

```
    $nid = db_insert('node') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
  'created' => REQUEST_TIME,
))
->execute();

```

# Answer
> 3 votes
You should never insert into the node (or any other entity table) directly, there's a fully-fledged API for handling such things. At the moment you're bypassing a lot of the core goodness that the node module offers, and you're likely to run into problems (you're not updating the revision table for example).

`node_save()` is the best tool for the job here:

```
$node = new stdClass;
$node->type = 'the_type';
$node->language = LANGUAGE_NONE;

node_object_prepare($node);

// Add a field
$node->field_some_field[$node->language][0]['value'] = 'Some value';

// Save the node
node_save($node);

// The node is saved by this point so the nid is available.
$nid = $node->nid;

```

---
Tags: 7, database
---


# Question
Title: Ask services "Which user am I?", as defined by session id?
Scenario: An external service wakes up. This could be a remote Drupal site running a cron , a mobile application being started or something completely different.

The service has a session id from it's last interaction with a Drupal site running Services.

How does this service go about asking the Drupal site: "**Based on this session ID, who am I?**"?

For a regular user on the Drupal site, /user will tell you who you are. However, when accessing \[endpoints\]/user through Services, you get an *index* of all users, instead of a specific user object.

If possible, please include json as the content type for any code examples.

# Answer
This service resource simply return an object representing the currently authenticated user:

```
/**
 * Implements hook_services_resources().
 */
function MYMODULE_services_resources() {
  $resources['MYMODULE'] = array(
    'actions' => array(
      'whoami' => array(
        'help' => 'Get an object referring to the currently authenticated user.',
        'callback' => '_MYMODULE_whoami_service_resource',
        'access callback' => 'services_access_menu'
      )
    )
  );

  return $resources;
}

/**
 * Resource callback
 */
function _MYMODULE_whoami_service_resource() {
  return $GLOBALS['user'];
}

```

Once enabled you should be able to access the resource at http://site.com/\[endpoint\]/MYMODULE/whoami.json.
> 2 votes

---
Tags: services
---


# Question
Title: How can I insert a block into each page of a view if the page is loaded via ajax?
I am trying to insert a SimpleAds block for each page of a View. But pages are loaded via AJAX using infinite pager. How can I insert a SimpleAds block into each dynamically loaded page of results?

# Answer
You want to add a javascript such one below to either your custom module or theme (would recommend module). This will react on a view that has a class view-infinitestack, so replace it to match yours view.

Where the debugging code is (console.log) you can add whatever JQuery you need. Eg. ajax call to fetch new content and inject it in another div, sidebar, or anywhere else on the page just by using JQuery, etc...

```
(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('.view-infinitestack', context).ajaxSuccess(function(){
        // add your js here to refresh a block
        console.log('success');
      });
    }
  };
})(jQuery);

```
> 4 votes

# Answer
Checkout the block refresh module

> As the name implies, Block Refresh allows an administrator to configure a block to refresh it's content in a given number of seconds. Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".
>
> Current Features:
>
> * Automatically refresh a block in a set number of seconds (configurable per block)
> * Allow site visitor to manually refresh block (configurable per block)
> 1 votes

# Answer
If they have a common path, you can simply create a Block and tell it to only appear when the path matches. So for example, if your path was something like 'ads/\[date\]/\[title\]'.

In your block, tell it to only appear for ads/\*. That should achieve what your looking for.
> 0 votes

# Answer
It could be done using the tpl files.
Check the theme information you will find a common tpl file name place that block in "Display output" or "style output".

Its not the best way to do it, but you can do it in this way. :)
> 0 votes

---
Tags: 7, views, ajax
---


# Question
Title: How to disable the submit button after clicking?
Drupal doesn't seem to prevent multiple form submits, even on node pages. This QA suggests fixing it on the server side.

How could I disable the submit button after clicking?

Any other solutions?

# Answer
> 12 votes
It's only in dev but the Hide Submit module would do the trick. One of the features is:

> Hide (or disable) the submit button after it has been clicked

I've just installed it on a dev site and it seems to work well for node add forms; when you click the submit button it's hidden and replaced with a loading image and a 'Please wait...' message, before the form is finally submitted. I haven't tried it on any other forms though.

# Answer
> 10 votes
Here is solution for Drupal 7. Code is simplified version of Hide Submit module.

This code works fine even with "Add more" buttons and AJAX forms.

```
Drupal.behaviors.hideSubmitButton = {
  attach: function(context) {
    $('form.node-form', context).once('hideSubmitButton', function () {
      var $form = $(this);
      $form.find('input.form-submit').click(function (e) {
        var el = $(this);
        el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
        return true;
      });
      $form.submit(function (e) {
        if (!e.isPropagationStopped()) {
          $('input.form-submit', $(this)).attr('disabled', 'disabled');
          return true;
        }
      });
    });
  }
};

```

# Answer
> 0 votes
The easiest way is to do a theme based javascript solution to disable the button after form submission. In the theme.info file, put your javascript file so it can be loaded by the theme api.

```
scripts[] = js/themename-script.js

```

Now in the themename-script.js add to the Drupal.behaviors.themename section to look like the following:

```
Drupal.behaviors.themename = function()
{
  $('.node-form').submit(function(){
    $('#edit-submit').attr("disabled", "disabled");
    $('#edit-preview').attr("disabled", "disabled");
  });
}

```

So the flow is as follows:

1. Theme loads the javascript
2. The Drupal.behaviors.themename is fired on page load
3. On the form submission of the node add form (class based in the above example, it can be customized on the type of form) disable the submit buttons (submit and preview) so it cannot be clicked again

I am sure if there is some ajax processing that the above could be dangerous and the form submission could never be done again if an error is caught in the form\_api validation so do test this and customize to meet your needs. I disabled both buttons since you could still click the preview button while the submit button was disabled. Obviously your milage my vary.

---
Tags: 7, forms
---


title: Show content on specific page

text:
# Question
Title: Show content on specific page
Am I able to add the following field to a content type, so that each piece of content I create can be conditioned to a page?

Or is there a module to extend Publishing Options, where by it adds all the pages I have created (just like 'Promote to Front Page')? If not, why is no one doing this? As a new user to Drupal this seems like it would be a handy operation. (I have already tried this module but it doesn't achieve the results I'm after).

If none of these solutions are available, what would be the best alternative way of doing this?

# Answer
First, you start with defining what are the rules of showing this content to the user. There are many ways how to deal with such a thing, but it all depends on the rules. I do recommend to create such rules, otherwise you will run into unmaintanable mess.

**If you have less than 10 or so occurences**

You can use the bean module (http://drupal.org/project/bean) to create specific block types with fields (similar way like creating content types). These blocks you can then expose via the default blocks UI and set the visibility there or you can use context.

**If you have more than 10 occurences**

You better define rules (logic), when such special content should appear. This way you can have just one logic easily maintainable (which is your goal).

*Reference on node?*

One way could be, that you create a content type for this content, and add any of the node reference fields (references, relations modules,...) (in case you want to display the content on specific nodes). This way you can always assign a content to another content and then create a block view that will take the argument from current nid and pass it over so you can display all content that has a reference with the same nid or you can attach the view to the entity via eva view.

*Path?*

I am not seeing any module available so you will have to create your own solution. This might help to get you started

1. Add a long text field to the content type - this field will allow you to enter path or multiple paths, one path per line
2. Create a custom module that will be using that field to match the path by using the function drupal\_match\_path. You can for example create a block, that will output matched content
3. You can place this block where you want the linked content appear (main content region, sidebar,...) via Drupal blocks UI, or context,... depends what you are using.

This could be a performance killer, if you will have a lot of content that Drupal will need to run through and see if it matches the content visibility, so you should think about some sort of caching, etc...
> 1 votes

---
Tags: entities, nodes, 7
---


title: Gear menu unavailable

text:
# Question
Title: Gear menu unavailable
Haven't been on Drupal for a while and now I seem to be lost at some points. Please help me get on the right track ;-)

I decided to build a theme based on the Stark theme and found out that the contextual menu gear widget does not appear. It's definitely a theme issue, because the widget comes up for the very same block when I switch the theme to, say, Garland.

What could be the reasone?

# Answer
> 1 votes
The contextual links are being exposed via contextual module. just by looking into the module, you would find the function contextual\_preprocess.

```
 $variables['title_suffix']['contextual_links'] = array(
      '#type' => 'contextual_links',
      '#contextual_links' => $element['#contextual_links'],
      '#element' => $element,
    );

```

So my first guess would be, that you are missing in the block.tpl.php or page.tpl.php, etc... templates to output the $title\_suffix variable?

```
<?php print render($title_suffix); ?>

```

---
Tags: theming
---


# Question
Title: print all the titles of a content type by php
I created a content type: "period".

Then, I created instances of this content type.

Now I would like, on a page tpl.php put the instructions, to print all the titles of the instances that I put on this content type. is it possible?

# Answer
> 4 votes
I think the "best" way (most future-proof etc.) would be to use an `EntityFieldQuery`:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'period');

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
  foreach ($nodes as $node) {
    // Do something with $node->title
  }
}

```

There are other options but they either involve deprecated methods or going directly into the node/revision tables, which can be a pain.

If you need this list in page.tpl.php make sure you don't put the code directly in the template file (it's bad practice and can cause problems with caching). The best place would be in a preprocess hook in your theme's template.php file, or a module file.

---
Tags: 7
---


# Question
Title: How would I monitor if a new entity had been saved?
I am creating a module that I want to run when an entity is saved. I have used rules in the past but the overhead on the module means that I cannot use it. Is there another way that I can do this? Thanks

# Answer
If you need it to run for all entities, then your module can implement `hook_entity_insert()` for new entities and `hook_entity_update()` for changes to existing ones.

If you just need to target specific ones (node, user, etc), then most of the modules that implement entities also have `insert` and `update` hooks.
> 3 votes

# Answer
`hook_entity_insert()` sounds like what you're after.

> Act on entities when inserted.
> 2 votes

---
Tags: entities
---


# Question
Title: How do I filter the "admin/content" page through it's url?
As the content overview page ("admin/content") has filtering capabilities, I'm trying to allow my users to access the filtered content through an url.

For example, if I want to see a list of contents of type "Article", I would like to access "admin/content/article" or a similar url, and get the contents page with the filter already applied.

Is there any way to do this?

# Answer
> 2 votes
By default this is not possible. Easiest I can see would be to create a view - if you have views module installed - that has the same path which will override the default Drupal content screen.

Then you can either create argument for the content type as part of url and/or expose filters and since the filters are being passed via get parameter, you will be able to construct an url to point to the filter selection.

Which is almost what administration views module does. You might want to extend these views with arguments, filters, etc...

Other option would be to create custom functionality that would "hook" into the default functionality.

---
Tags: nodes
---


# Question
Title: How can I upload a CSV file and expose it in a "views table" for Drupal 7?
I am looking to create a simple table with 3 fields (columns) but at least 25 rows of possible entries. Then I want to display this in a views table (with pagers etc.) - I have done this by creating a content type with 3 custom fields, then filling out 25 of these custom content types (nodes) - then exposing all 25 nodes in a views table to get these results. However- there should be a simpler way to simply upload a CSV table that is already formatted (in Excel or Spreadsheet or text file) in rows and columns and simply use views to display the data in a simple table.

This would greatly reduce the amount of unnecessary published content as well as the workload to create a simple, searchable table from views.

Any other ways to make this work without hacking into the Drupal Database?

# Answer
> 1 votes
As far as I know the short answer here is you can't. Views is pretty much a query building machine.

The next best thing would be to create a script and/or use some views plugin to mass import your nodes from the CSV document and then present them to a view.

And I am proposing a scripted solution in case your nodes are more than 25. Else you might as well do it by hand :)

---
Tags: views
---


# Question
Title: Does superfish module support multiple languages?
Does superfish module support multiple languages in drupal 7? From the CMS, I seem to be able to translate each menu item into english and french. But Superfish is only outputting the english version of the menu. So does superfish handle multiple languages? If it does, how do I enable it?

# Answer
> 0 votes
At time of writing this response, the answer is NO. superfish doesn't have multilingual support for drupal 7. I couldn't find a patch. So i stopped using superfish.

# Answer
> 2 votes
Heh, it looks like they've released a version of Superfish with what was supposed to be just a temporarily disabled support for translations.

You can either

1. apply patch found at http://drupal.org/node/1112928 or
2. use an older version of Superfish

# Answer
> 2 votes
It seems that i18n is supported, or at least improved using this patch.

# Answer
> 1 votes
I've tested first with version 7.x-1.8 and it didn't work, the superfish menu was returned with both language of the site, but with version superfish-7.x-1.9-beta4 it worked.

# Answer
> 0 votes
Version superfish-7.x-1.9-beta4 worked.

---
Tags: 7, i18n-l10n, navigation
---


# Question
Title: User's homepage depending on their organic group
Is there a way to set the homepage of a user depending on their organic group. So when a user clicks the site logo, they will be redirected to something like /test-page/%group. When I created a panel page it specified that I could not use % which would have been perfect.

I am using Drupal 7.

# Answer
> 2 votes
There is a module (Frontpage) that allows to set a different front page for anonymous users, and authenticated users.

The module allows third-party modules to alter the page to which the users are instead redirected, or to alter the structure array used to render the page.

As alternative, you can create a custom module that, using code similar to the one used by Frontpage, redirect users to a specific page, basing on specific criteria.

The module should implement hook\_menu() and associate a menu callback to, for example, http://example.com/frontpage; the page callback of that menu item should simply verify a condition is verified, and then redirect the users to a specific URL.

The code skeleton could be something similar to the following:

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_frontpage_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function mymodule_frontpage_view() {
  // These variables can be useful to redirect the users
  // to specific pages, basing on the language currently set for
  // the content, or on the fact the user is logged in.
  $langcode = $GLOBALS['language_content']->language;
  $logged_in = user_is_logged_in();
  $usergroups = og_get_groups_by_user($user);
  $group = og_load($gid);
  $groupnode = $group->etid;
  $redirectpath = 'node/'.$groupnode->nid;
  drupal_goto($redirectpath);

}

```

# Answer
> 0 votes
Here is my idea how to do this with contrib modules only:

1. Use *Views* and *Views Field* modules to show the OG group as a view inside the frontpage view in step 2
2. Create the frontpage View that will show the OG group of the current user Use relationship: Content: Author to filter the user group only Use view field to show OG group fields inside the main view Limit the main view to 1 record only
3. Use System: Site information: (admin/config/system/site-information) to replace frontpage with the view created in step 2

* Use field: *Default front page* to redirect to your new frontpage view

# Answer
> 0 votes
In the end I used rules links because I wanted it to redirect the user to a panel page that ends with %node. Then I used visibility rules on the rules link for it to show depending on the current user logged in's role. Then I create a view with one record which displays that rules link and then placed it in a block.

So Depending on the users role, that "Home" link will show. When clicked, that user will be redirected to their group.

# Answer
> 0 votes
If you are using OG 7.2 you can try out the OG homepage module. The module basically does what @mohit\_rocks outlined.

I made this module a while back and just recently published it on Drupal.

# Answer
> -1 votes
There is programmatical way to do this and even more :) Drupal 7, actual code called from page.tpl.php

```
    //get unique user id
    $user_id = $user -> uid;
    //get id-s of groups where user is a member, from og_membership drupal table
    $og_check = db_select('og_membership', 'n')
            ->fields('n')
            ->condition('etid', $user_id, '=')
            ->execute()
            ->fetchCol($index = 4);

  //if user is multiple group member, use first index [0], 1 is GID
 // (group id, it is defined in OG table in drupal database
    if ($og_check[0]==1) {
    $logo_link = 'http://your-site.com/whatever-start-page-for-group';
    } else {
     $logo_link =  'http://your-site.com/normal-start-page';
    }

```

and then print $logo\_link inside a href that surrounds logo... it is pretty specific case, but i need to do this way because targeted group page has nothing to do with actual group page of type group... hope it helps someone

---
Tags: 7, organic-groups
---


# Question
Title: What's wrong with the way I use variables in my function?
I have a function that looks like this:

```
function mymodule_privatemsg_message_validate($message) {
  $uid = $vars['message']->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid !== '1') {
    if ($uid !== '3') {

      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
    form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }
}

```

However, I received a comment that "As side note, you are using $vars, but that variable has not been initialized from the function, nor is a function's parameter." I don't understand what this means or what I'm doing wrong. Could someone explain this to me?

# Answer
The parameters given to hook\_privatemsg\_message\_validate() are `$message`, and `$form` which has a default value of `FALSE`.
`$vars` is not a parameter passed to the function, nor is a local variable defined from the function. As consequence of this, the value of `$vars` is `NULL`. When you try accessing `$vars['message']->author->uid`, PHP would give you two warnings:

* Undefined variable: vars
* Trying to get property of non-object

The first warning is because the variable is not defined from the function. If your code would have assigned a value to `$vars` the warning would not appear. It would also work if `$vars` is defined as global (with `global $vars;`), and it was already initialized from another function.
The second warning is because every PHP variable that is not define get an automatic value that is `NULL`. `$vars` is `NULL`, and so is `$vars['message']`, and `NULL` is not an object.

The result is that `$uid` is set to `NULL` too.

The following code is also wrong.

```
  if ($uid !== '1') {
    if ($uid !== '3') {
      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
        form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }

```

With `$uid !== '1'` you are saying to PHP to check if `$uid` is a string with a value that is different from `'1'`. If `$uid` is set to 1 (the integer), the following code would print `"different"`, not `"equal"`.

```
$uid = 1;

if ($uid !== '1') {
  print "different";
else {
  print "equal";
}

```

Differently, the following code prints `"equal"`.

```
$uid = 1;

if ($uid != '1') {
  print "different";
else {
  print "equal";
}

```

Also the following code will print `"equal"`. (To the reader, the task to understand why. `;)`)

```
$uid = '1a';

if ($uid != 1) {
  print "different";
else {
  print "equal";
}

```

What you meant to write is the following code, as the user ID for a user object is an integer, not a string.

```
function mymodule_privatemsg_message_validate($message) {
  $uid = $message->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid != 1 && $uid != 3) {
    if (empty($message->thread_id) && strlen($message->body) < 200 ) {
      form_set_error('[body][value]', t('My custom message.'));
    }
  }
}

```

I am not sure if `$message->author` is a property defined for `$message`, but I guess that is what you really need.

As side note, I would rather avoid checking the user ID for a user object, and take any action basing on that value. In Drupal, it is better to check if the user has a permission, using code similar to the following one.

```
if (user_access('permission to check', $account)) {
  // The user has the permission.
}

```

`$account` is an user object.

If you have just a user ID, then you can use the following code.

```
$account = user_load($uid);
if ($account && user_access('permission to check', $account)) {
  // The user has the permission.
}

```

The reason for checking the permission instead of user IDs is maintainability of the code. Imagine what happens if you have 100 users, and just 50 of them should see that error message: You should check the value of `$uid` is not the user ID for those users that should not see the error message. If they have not consecutive values (as it happened in your case, where the user IDs were 1 and 3), you should check each value singularly.

As side note, `user_access()` always return `TRUE` for the user #1. In fact, the function contains the following code.

```
function user_access($string, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

  // ...
}

```

Notice the control statement uses `$account->uid == 1`, not `$account->uid === '1'`.
> 3 votes

# Answer
For a variable to be available in the scope of a function, it needs to have been initialised (or it needs to have been initialised in the global scope and imported into the local function using `global`).

At the moment there's nothing declaring or passing the `$vars` variable in...it hasn't been initialised, thus you get the warning.

You're passing a variable to the function called `$message`, which suggests your code should be:

```
$uid = $message->author->uid;

```

The confusion with `$vars/$variables` might be caused by the fact that it's sort of the standard name for the only argument passed to theme functions, e.g.

```
function MYTHEME_preprocess_node(&$vars) {
  // Use $vars

```
> 4 votes

# Answer
If you look at the type signature for that hook, it is

```
function hook_privatemsg_message_validate($message, $form = FALSE) {
}

```

`$vars` is not a function parameter, nor have you declared it as being a `gloabl`. Using it as you have should make PHP complain (one of the various undefined variable notices). As it stands, `$uid` would therefore be undefined when you try to extact something from `$vars`.
> 2 votes

---
Tags: privatemsg
---


# Question
Title: $user->uid is always 1 when running automated tests
In my automated tests, I create some users.

```
  debug('moderator_user: '.$this->moderator_user->uid);
  debug('editor_user: '.$this->editor_user->uid);

```

outputs

```
'moderator_user: 2'
'editor_user: 4'

```

So I would think that

```
global $user;
$this->drupalLogin($this->editor_user);
debug('currently logged in as '.$user->uid);

```

would output

```
'currently logged in as: 4'

```

but instead it shows,

```
'currently logged in as: 1'

```

It seems to be correctly logging user 4 because

```
$this->drupalLogin($this->editor_user);
$edit = array(
  'title' => $this->randomName(),
);
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($edit['title']);

debug('Draft was created by user with uid '.$node->workbench_moderation['current']->uid);

```

yields

```
'Draft was created by user with uid 4'

```

So what's going on?

# Answer
It happens exactly what described in the documentation page for DrupalWebTestCase::drupalLogin().

> Please note that neither the global `$user` nor the passed-in user object is populated with data of the logged in user. If you need full access to the user object after logging in, it must be updated manually. If you also need access to the plain-text password of the user (set by `drupalCreateUser()`), e.g. to log in the same user again, then it must be re-assigned manually. For example:
>
> ```
>   // Create a user.
>   $account = $this->drupalCreateUser(array());
>   $this->drupalLogin($account);
>   // Load real user object.
>   $pass_raw = $account->pass_raw;
>   $account = user_load($account->uid);
>   $account->pass_raw = $pass_raw;
>
> ```
> 2 votes

---
Tags: users, testing
---


# Question
Title: Views Contextual Filters with Wildcards URLs
I have a view with two page displays. The first page uses a contextual filter for the UID, which is provided with a default value for the user that is currently logged in to the site. One of the fields displays an order ID, and I have a second Global: Custom Text field which displays a link that appends the order ID to last path component of the URL.

The second page display uses a wildcard within the path of page settings, that matches the scheme of the link generated in the first page display. When the argument is provided in the preview everything works as expected, however when the URL is accessed via browsing I only see a blank page.

Does anyone have any ideas of why this may be happening or have additional information regarding using path wildcard and contextual filters. Thanks in advance for any possible advice or tips.

# Answer
It seems that the error had to do with URL that was used in the path.

When I originally had the issue I was using "account/page/%" , but after removing account so that it read "page/%" everything began to work as expected.
> 1 votes

---
Tags: 7, commerce, views
---


title: WSOD after installing Pressflow 6

text:
# Question
Title: WSOD after installing Pressflow 6
I installed Pressflow on my Drupal 6 website by replacing core files. I only kept .htaccess, robots.txt and sites folder.

After that I got a lot of PHP errors, even after I change php.ini's error reporting.

So I checked Apache logs.

I had APC running on my site already and I noticed the following error happening frequently:

\[apc-warning\] Unable to allocate memory for pool.

It disappeared after I change APC memory to 16MB (it was 30MB) and restart Apache.

Although I can now load a few pages, I'm getting a white screen when trying to load home page and some other pages. Also, some regions of the page aren't showing up properly.

I tried clearing cache too.

Is there anything I'm missing?

# Answer
> 0 votes
My first step here would be try again. If you still get issues and there is nothing in the logs try increasing the memory limit.

Also there are some pressflow changes in htaccess, replace that roo.

---
Tags: 6, wsod
---


title: Node or static page generation

text:
# Question
Title: Node or static page generation
I am currently working on a project where I have 2 databases: the internal site database, and an external database that contains a table with establishment information I want to display as pages on my site.

The external database can still be modified from another application.

How do I go about doing this? Should I create a module to generate static pages, or nodes? What are the differences, or implications of choosing either option?

# Answer
What approach you want to use depends on the remote database and how dynamic the information is as well as how much data you expect to display.

If the remote DB is easy to work with and you don't need to do anything interesting with the data you might integrate with it using a custom module working directly against the remote database.

If the data needs to integrate with typical Drupal stuff (Views, Panels, Pages, Fields) then you might want to pull the data into nodes. This would still probably mean a custom module. I believe the Migrate module (http://drupal.org/project/migrate) could be a good help here.

How current the data needs to be is also a consideration. Should it checked for new content every time a certain page is visited or is it fine to run it on a cronjob in the background. Like every 3 hours?
> 1 votes

# Answer
What you describe is similar to what the API module does; the difference is the source used to generate content, which in the case of the API module is the source code of Drupal and other modules.

The API module creates nodes for each documentation page just to allow commenting on those pages. Nodes are not used for showing the documentation pages; in fact, if you try visiting http://api.drupal.org/node/27228, you are redirected to http://api.drupal.org/api/drupal/modules!taxonomy!taxonomy-term.tpl.php/7.
> 0 votes

---
Tags: nodes, sessions, database
---


title: jQuery UI theming

text:
# Question
Title: jQuery UI theming
I want to use in my module custom jQuery UI theme from the themeroller. What is the best way to do it?

# Answer
> 6 votes
Assuming you are using the jquery\_ui module, all you have to do is:

* Build a custom download for jQuery UI including your custom theme from ThemeRoller and copy it under the jquery\_ui folder, following the instructions in the module's README.txt
* Alternatively, you could just build your custom theme, download it, and copy it to jQuery UI's theme directory

EDIT:

However, since Drupal 7 already ships with the latest jQuery UI, all you gotta do is download your custom jQuery UI theme and include it using one of the following methods:

* Copy the directory to your theme's folder and include the css file in your theme's .info
* Create a custom module, and implement hook\_init() and use drupal\_add\_css() to add your custom stylesheet:

function mymodule\_init() { $options = array( 'group' =\> CSS\_THEME, 'every\_page' =\> TRUE, 'weight' =\> 9999 ); drupal\_add\_css(drupal\_get\_path('module', 'mymodule'), 'mymodule.css', $options); }

# Answer
> 3 votes
If you are adding the UI via `drupal_add_library()`, you can change the style using `hook_library_alter()`. For example:

```
/**
 * Implements hook_library_alter().
 */
function YOURMODULENAME_library_alter(&$libraries, $module) {
  unset($libraries['ui']['css']['misc/ui/jquery.ui.theme.css']);
  $libraries['ui']['css']['path/to/your/custom/theme/jquery.ui.theme.css'] = array();
}

```

# Answer
> 3 votes
For Drupal 7, the stock Seven theme does this (repository link) (abridged):

```
function seven_css_alter(&$css) {
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    $css['misc/ui/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'seven') . '/jquery.ui.theme.css';
  }
}

```

Modify accordingly—i.e. replace "seven" with the name of your theme, and point the path to your jQuery UI theme's CSS file.

# Answer
> 2 votes
I recommend to use the jQuery UI theme module which manages multi THEMEROLLER generated UIs and attached these UIs to Drupal themes. Then set the jquery UI CSS classes for elements in Drupal with the modules such as block class/ node class/ webform css, etc.

---
Tags: 7, javascript
---


# Question
Title: I have muliple webforms in my site, but want to disable all webforms after user makes a submission
I'm stuck. I have a site that has many users. Each user is allowed to log in and has access to a certain number of webforms (depending on their role status). Each webform contains a product that they receive for yearly award. They can pick from any of the products/forms that their user role allows.

The problem lies when they submit the form/product that they would like, the other forms are still active, which would allow them to submit another form etc etc.

I need to deactivate ALL webforms for that user when they submit their form/product choice so they cannot submit multiple products from the same user.

Please help.

B

# Answer
make a user role `user has submitted survey`. use `hook_webform_submission_insert` or `hook_webform_submission_update` (what you use depends on if you allow Drafts) -- and change whatever role they have by default in your site, to `user has submitted survey`. Dont allow this new role to access any forms.
> 0 votes

---
Tags: users, webforms
---


title: how to hide Body Label from webform?

text:
# Question
Title: how to hide Body Label from webform?
I have created a webform, but the Body label shows on the page. How do I remove that label from the form?

# Answer
> 5 votes
Go to "Manage Display" tab in content type page. Hide label there

---
Tags: 7, webforms
---


# Question
Title: Display page created using panel programatically
I am using Drupal 7 and Panel module.

I have created custom page using panel module. **page-welcome**

I want to render this page on the following url **user/%user/my-profile**

Is there any way to print page programatically..

# Answer
> 2 votes
You should be able to set the path to /user/%user/my-profile within Panels. For an example of this, look at the "User edit template" override provided with Panels, which, if enabled, overrides /user/%user/edit.

To set the path in Panels, go to /admin/structure/pages, choose the page you wish to edit, click **Basic** under **Settings**, and set the **Path**.

The help text there states the following:

> The URL path to get to this page. You may create named placeholders for variable parts of the path by using %name for required elements and !name for optional elements. For example: "node/%node/foo", "forum/%forum" or "dashboard/!input". These named placeholders can be turned into contexts on the arguments form.

---
Tags: panels
---


# Question
Title: How to change "add to comment" in comment form?
When CCK was not in core, as in Drupal 6, and you selected a node type for comments on other node types, the comment form would say the name of the content type instead of comment. In this case, I want the comment form to say 'Add New Review' instead of 'Add New Comment'. Does anyone know how to do this through a module or configuration?

# Answer
Create a seperate .tpl file for comment-wrapper named **comment-wrapper.tpl.php**.

To create a seperate template file for node specific comment wrapper you can create using **comment-wrapper-contenttype.tpl.php** copy the code from core **comment-wrapper.tpl.php** and change the title in the code given below.

While copying from core **comment-wrapper.tpl.php** don't forget to remove the validation which is meant for forum node types only.

```
<h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>

```
> 8 votes

# Answer
You can do it by implementing `hook_node_view_alter()`, in your module or theme(template.php).

```
function myThemeOrModule_node_view_alter(&$build) {
  if ($build['#node']->type == 'page') {  //extra check for content type (optional)
    $build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');
  }
}

```
> 8 votes

# Answer
You can use the "strings override" module to change the text.
> 3 votes

# Answer
Open your settings.php file and under 'To override specific strings on your site ...' add the following:

```
$conf['locale_custom_strings_en'][''] = array(
  'Comments'      => 'Reviews',
  'Add new comment' => 'Add new review',
);

```

Make sure you have permission to edit settings.php.
> 2 votes

# Answer
You could do it from the comments-wrapper.tpl.php (or check comments.tpl.php too) file in the comments module (/modules/comments)
> -3 votes

---
Tags: 7, comments
---


# Question
Title: Advance search between two content types that are linked by entity reference fields
I have "linked" 2 content types (Type A and Type B) by a field using the entity reference module. They are "linked" by the other node's ID number. For example, the entity reference field would have an input that says: "Select the node ID which is related to this content". Now I would like to implement a smart search.

For example, if someone searches for Type A, the search should also return the content of Type B that is "linked" to Type A based on that entity reference field. Can this be done with search or Views? In quasi-SQL, it would be something like:

```
"SELECT * FROM TypeA, TypeB WHERE TypeA.field_A=TypeB.nid"

```

# Answer
In Views this called "Relationships".

Create view that show "Type A", then in filters add "Type B" to be also allowed. Then add relation on field that you use for entity reference and made this relation required.

Now "Type B" content will be also displayed in view if related "Type A" is match search criteria.
> 1 votes

---
Tags: 7, views, search
---


# Question
Title: What module controls Commerce Kickstart 2 add to cart popup?
I have installed the demo store Commerce Kickstart 2. Going through and changing things here and there somehow I've affected the popup functionality. It no longer fires when adding something to your cart. I'm thinking I may have just turned off the module that controls this? Or maybe it's a setting I clicked off?

# Answer
> 4 votes
From Commerce Kickstart 7.x-2.0-rc3 and up, the module is Commerce add to cart confirmation (Previously this functionality was a part of the base product feature and couldn't be disabled).

---
Tags: commerce
---