# Question
Title: Responsive image gallery with unique URL per image?
I've been tasked to create a carousel that would have **a unique URL per panel**.

The panel would have to contain multiple pieces of info (each piece a link), and so would be views based. the panels would have to be able to rotate.

Royal slider seems like it may be up to the task: http://dimsemenov.com/plugins/royal-slider/

My question is - are there any recommendations for other modules? module combos? custom script?

I'm using D7.23

Thanks!

# Answer
Give a try to Flexislider module:

> Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

* Touch enabled nagivation
* Keyboard navigation
* Configurable slide animations
* Multiple sliders per page

Demo available here: http://www.woothemes.com/flexslider

> Library available at: https://github.com/woothemes/FlexSlider

And as far as the unique URL per panel thing is concerned I guess that depends upon how you creating the structure for slider, i.e while creating the structure for slider you can define the unique **id** attribute for each `li` as following:

```
<div class="flexslider">
  <ul class="slides">
    <li id="UNIQUE-ID1">
      <img src="slide1.jpg" />
    </li>
    <li id="UNIQUE-ID2">
      <img src="slide2.jpg" />
    </li>
    <li id="UNIQUE-ID3">
      <img src="slide3.jpg" />
    </li>
  </ul>
</div>

```

---

> Drupal also have the royalslider library integration which integrates the royal slider library
> 1 votes

# Answer
If you can style the slider yourself, then usually Views Slideshow is the most flexible way to go. It uses cycle.js by default but if you're good with Drupal and php code you can create a plugin for your Royal Slider.
> 0 votes

---
Tags: media, javascript
---


# Question
Title: How can I alter (theme) the default content feed?
How can I alter (theme) the default content feed on the front page (the list of node teasers) so that my 'thumbnail' image style is used instead of my 'medium' style for the images contained in the nodes.

All I can think of is to create my own `page--front.tpl.php` file or use `is_front` in `node.tpl.php`. Either way it means creating a custom listing for the front page.

Thanks.

# Answer
The best way to do this if you're running stock D7 is in config: you'll want to change the default field dislpay settings by clicking "manage display" on the Article content type in admin/structure/type.

Click the gear icon to adjust the display type:
> 0 votes

---
Tags: theming, feeds
---


title: Image styles are not getting created

text:
# Question
Title: Image styles are not getting created
Our image styles are not getting created on one of the Drupal 7 sites in a multi-site installation. They are created for at least one of the other sites that uses the same Drupal 7 core.

Symptoms: Upon uploading an image to a node, the image preview does not get displayed (depending on the browser, a broken image placeholder may display). The image is not created in the file system either. I have verified file system ACLs. Both sites use the same .htaccess.

# Answer
As per image style (imagecache) images are not being created, changing the theme and reverting back fixed the problem. Very strange - it would be nice to know what the cause was!
> 0 votes

---
Tags: 7, media
---


# Question
Title: How do I get the timezone form reference on a date field?
In Drupal 7 I have a date field in a content type that has the Time zone handling option set to "Date's time zone". Setting this option will render a drop down list of time zones in your date field.

I am trying to replace the list of core time zones with a smaller list for just the United States. I found this post which works perfectly for overriding the timezone drop down list on the user profile page. However, I have not been able to figure out how to get a reference to the timezone select list on a date field.

The timezone reference on the user profile field is:

```
 $form['timezone']['timezone']['#options']

```

If you print the $form variable to the screen you can clearly see the time zones in the above reference.

What I can't figure out is where the timezone options are in the form variable for a date field. I would expect them to be in somewhere in

```
 $form['field_event_dates']['und'][0]

```

I do see a default value for the timezone at

```
 $form['field_event_dates']['und'][0]['#default_value']['timezone']

```

but I can't find "options" in there.

Any ideas where the "options" for the time zone are set in the form variable?

# Answer
Use **hook\_date\_timezone\_process\_alter** in your custom module to do the magic, see below example and adapat if for you needs

```
function MODULENAME_date_timezone_process_alter(&$element, &$form_state, $context) {
  // add some logic here
  // keep only the needed values
  // dsm($element['timezone']['#options']);
  $element['timezone']['#options'] = array(
    'Africa/Abidjan ' => 'Africa/Abidjan',
    'America/Detroit' => 'America/Detroit',
  );
}

```
> 3 votes

---
Tags: 7, datetime
---


# Question
Title: How to unpublish all nodes of a user after is assigned a role?
I am interested on this scenario: After a user is assigned a role,all his published nodes get unpublished. I am interested in doing this with rules and VBO. I tried but no luck. I used :Event:User profile is update Action:Load all node with VBO. Seems I am missing something.Anyone help? thanks

# Answer
> 1 votes
I finally found how to do this with VBO . Here is a video which helped me. http://drupalize.me/videos/using-vbo-load-list-objects-rules I hope it helps someone else. THanks!

# Answer
> 1 votes
I would instead create a Views Loop using the Views Rules module. You can create a view and have the rule loop through all the rows that the view outputs.

Edit:

> For Example, I want to send an e-mail to all user's attached to a node registration. So I needed to do the following:
>
> 1. Create a view with a Rules Display. Field: User E-mail. Contextual Filter: NID (Screenshot: https://i.stack.imgur.com/csci1.jpg).
> 2. In the Views Rule Settings - Parameters: I specified the parameter's label and name, that wil need to match the Views Loop Data selector (Step 4) for the Views Contextual filter. (Screenshot: https://i.stack.imgur.com/pLZKn.jpg)
> 3. In the Views Rule Settings - Row Variables: I specified which field should be enabled for Rules, and how it should be passed back to Rules. (Screenshot: https://i.stack.imgur.com/g9FhM.jpg)
> 4. I then created a Views Loop in my Rule matching the Parameters and Row Variables in my view (Screenshot: https://i.stack.imgur.com/ewUfS.jpg)
> 5. I then created the action "Send mail" under the Views loop using the now available token that was specified in the View. (Screenshot: https://i.stack.imgur.com/NObZJ.jpg)

And that's it. If you want to test your output rather than your unpublish action. I would recommend using the action "Show a message on the site".

In your case your contextual filter is most likely your UID and NID as your field. I used my example as a proof of concept.

Edit 2:

Exported View:

```
$view = new view();
$view->name = 'waiting_list_user_list';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Waiting List User list';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Registration */
$handler->display->display_options['relationships']['registration']['id'] = 'registration';
$handler->display->display_options['relationships']['registration']['table'] = 'users';
$handler->display->display_options['relationships']['registration']['field'] = 'registration';
$handler->display->display_options['relationships']['registration']['label'] = 'User Registration';
/* Relationship: Registration: Registration to Node */
$handler->display->display_options['relationships']['registration_related_node']['id'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['table'] = 'registration';
$handler->display->display_options['relationships']['registration_related_node']['field'] = 'registration_related_node';
$handler->display->display_options['relationships']['registration_related_node']['relationship'] = 'registration';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['label'] = '';
$handler->display->display_options['fields']['mail']['alter']['trim_whitespace'] = TRUE;
$handler->display->display_options['fields']['mail']['alter']['strip_tags'] = TRUE;
$handler->display->display_options['fields']['mail']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['mail']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'registration_related_node';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Registration: State entity */
$handler->display->display_options['filters']['state']['id'] = 'state';
$handler->display->display_options['filters']['state']['table'] = 'registration';
$handler->display->display_options['filters']['state']['field'] = 'state';
$handler->display->display_options['filters']['state']['relationship'] = 'registration';
$handler->display->display_options['filters']['state']['value'] = array(
  'waitlist' => 'waitlist',
);

/* Display: Rules */
$handler = $view->new_display('views_rules', 'Rules', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_parameter'] = array(
  'nid' => array(
    'enabled' => 1,
    'type' => 'integer',
    'label' => 'nid',
    'name' => 'nid',
  ),
);
$handler->display->display_options['rules_variables'] = array(
  'mail' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'token',
    'label' => 'User: E-mail',
    'name' => 'mail',
  ),
);

```

Exported Rule

```
{ "rules_waiting_list_e_mail_after_registration_deletion" : {
    "LABEL" : "Waiting List E-mail after Registration Deletion",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "REQUIRES" : [ "rules", "rules_i18n", "registration" ],
    "ON" : { "registration_delete" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "registration:state:name" ], "value" : "complete" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "registration:entity-id" ] },
          "PROVIDE" : { "entity_fetched" : { "node_id" : "node_id" } }
        }
      },
      { "VIEW LOOP" : {
          "VIEW" : "waiting_list_user_list",
          "DISPLAY" : "views_rules_1",
          "USING" : { "nid" : [ "node-id:nid" ] },
          "ROW VARIABLES" : { "mail" : { "mail" : "User: E-mail" } },
          "DO" : [
            { "mail" : {
                "to" : [ "mail" ],
                "subject" : "test",
                "message" : "Test",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
Here is the view

```
$view = new view();
$view->name = 'published_cars_of_a_user';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Published cars of a user';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'car' => 'car',
);

/* Display: Content pane */
$handler = $view->new_display('panel_pane', 'Content pane', 'panel_pane_1');
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::flag_node_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);

/* Display: Rules */
$handler = $view->new_display('views_rules', 'Rules', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_parameter'] = array(
  'uid' => array(
    'enabled' => 1,
    'type' => 'integer',
    'label' => 'Content: Author uid',
    'name' => 'uid',
  ),
);
$handler->display->display_options['rules_variables'] = array(
  'nid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Content: Nid',
    'name' => 'nid',
  ),
);

```

And here is the rule

```
{ "rules_unpublish_all_emporos_expired_nodes" : {
    "LABEL" : "Unpublish all emporos expired nodes",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "published_cars_of_a_user",
          "DISPLAY" : "views_rules_1",
          "USING" : { "uid" : [ "account:uid" ] },
          "ROW VARIABLES" : { "nid" : { "nid" : "Content: Nid" } },
          "DO" : []
        }
      }
    ]
  }
}

```

---
Tags: rules, views
---


# Question
Title: How to programmatically determine if the cron is running
Is there any way programatically to determine when the cron is running (and if possible, what tasks are being run)? I've explored some options online that are bound to drupal\_cron\_run(), but no examples on how to listen for this method being used, as it is intended to start the cron.

# Answer
In Drupal 7:

**To determine if the current page request is a request for cron:** in other words, "is my code being called during cron"?

If you're running cron through cron.php, this is probably sufficient:

```
return strpos($_SERVER['REQUEST_URI'], 'cron.php') !== 0;

```

A more reliable way to determine a cron would be through introspection (e.g. debug\_backtrace()), but that would entail a much greater degree of overhead.

**To determine if any cron request is still running, across all Drupal threads and pageloads:** in other words, "is any process running cron anywhere?" * Note that this method will fail if cron is stuck.

Drupal will programmatically set a variable called `cron_semaphore` while the cron is running. This variable is deleted once cron has completed. You can check for the presence of this variable to determine whether cron is currently active or not:

```
if (variable_get('cron_semaphore', FALSE)) {
  // cron is running
}

```

You can see the specific use of `cron_semaphore` in the documentation of drupal\_cron\_run().

The 'tasks being ran' will be implementations of `hook_cron`, which you can find using:

```
foreach (module_implements('cron') as $module) {
  $function = $module . '_cron';

  drupal_set_message($function . '() is being ran');
}

```
> 8 votes

# Answer
There is a variable you can check which is called `cron_last`. It will be a timestamp of the last completed cron run.

So, something like `variable_get('cron_last')`
> 1 votes

---
Tags: cron
---


# Question
Title: Adding Google Remarketing Script tags to Drupal 7 website
I need to find a way to easily add google remarketing script tags to my Drupal 7 website. If there is a module that can do this easier and faster then that's what I need.

# Answer
> 1 votes
I think you are looking for the Google Adwords Remarketing module. Here is a quote about it (from the module's project page):

> Adds the Google Adwords Remarketing web statistics tracking system to your website.
>
> NB - Google now has another (easier) method for using Remarketing tags. If your Adwords account is linked to your Google Analytics account you can enable the tag by installing the Google Analytics module and ticking a tick box under the Google Analytics Drupal admin page - see attached image.
>
> This tick box causes a slight alteration in the GA tag which is needed by Google Remarketing.

---
Tags: 7
---


# Question
Title: CSS to define where a image is located on each Node
Short version: How do you use CSS to define where a image is located on each Node?

I AM NOT TALKING ABOUT IMAGE STYLES: https://drupal.org/documentation/modules/image#styles

Long version of my question:

I have created a content type call image\_content, in which I can create a node and upload a image to that node. That works great! but now what? I mean if load 10 images one one node, the are lined up hortizonaly, and thats pretty ugly. How can I use CSS to change the style of the images per node.

Now I understand, I could create a photo gallery, but I want more control of how each image is displayed. Example my background looks like a empty room. On node created by the image\_cotent, I might want a image1 far left, and image2 far right. Basic CSS understanding can do this, but how would I do this node? The reason is I might want the images on node2 have a left-margin of 50px, but images on node1 to be margin-right-0px

Does this make sense?? PLEASE provide example if you can!

# Answer
If you look at the body tag in view source or firebug you should be able to see a list of CSS classes assigned to class attribute; Ex. `class="html not-front page-node page-node-1"`

So you should be able to style each node different than other nodes based on the node ID

CSS example:

```
/* node 1 styles */

body.page-node-1 .title {
  color: #333;
  background-color: blue;
}

body.page-node-1 .field-name-field-image {
  position: absolute;
  left: 100px;
  top: 100px;
}

/* node 2 styles */

body.page-node-2 .title {
  color: #000;
  background-color: yellow;
}

body.page-node-2 .field-name-field-image {
  position: absolute;
  left: 200px;
  top: 200px;
}

```

I hope this will help you.
> 0 votes

---
Tags: nodes, theming, media
---


# Question
Title: select paged nodes by using selectNode of drupal 7 service module?
i'm developing a mobile apps call the drupal service, i'want to get paged nodes of relative taxonomy\_term, selectNodes seems can help

http://domainABC.com/my\_services/taxonomy\_term/selectNodes/

But how do i call page 2 of the nodes of the taxonomy\_term (suppose 25 nodes per page)?

i looked the source code (taxonomy\_resources.inc) but still don't have idea to do ,

```
    function taxonomy_service_select_nodes($tid = '', $pager, $limit,  $order) {
      $result = taxonomy_select_nodes($tid, (bool)$pager, $limit, $order);
      foreach ($result as $nid) {
        $node = node_load($nid);
        if ($uri = services_resource_uri(array('node', $nid))) {
          $node->uri = $uri;
        }
        $nodes[] = $node;
      }
      if (empty($nodes)) {
        return services_error(t('No nodes were found with tid @tid', array('@tid' => $tid)), 404);
      }
      return $nodes;
    }

'actions' => array(
        'selectNodes' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/taxonomy_resource'),
          'help'   => t('This method returns all nodes with provided taxonomy id.'),
          'access arguments' => array('access content'),
          'callback' => 'taxonomy_service_select_nodes',
          'args'     => array(
            array(
              'name'         => 'tid',
              'type'         => 'string',
              'description'  => t('The vocabulary ids to retrieve, separated by comma.'),
              'source'       => array('data' => 'tid'),
              'optional'     => FALSE,
            ),
            array(
              'name'         => 'pager',
              'type'         => 'int',
              'description'  => t('Whether the nodes are to be used with a pager (the case on most Drupal pages) or not (in an XML feed, for example).'),
              'source'       => array('data' => 'pager'),
              'optional'     => TRUE,
              'default value'=> TRUE,
            ),
            array(
              'name'         => 'limit',
              'type'         => 'int',
              'description'  => t('Maximum number of nodes to find.'),
              'source'       => array('data' => 'limit'),
              'optional'     => TRUE,
              'default value'=> FALSE,
            ),
            array(
              'name'         => 'order',
              'type'         => 'int',
              'description'  => t('The order clause for the query that retrieve the nodes.'),
              'source'       => array('data' => 'order'),
              'optional'     => TRUE,
              'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
            ),
          ),

```

The callback function

```
function taxonomy_service_select_nodes($tid = '', $pager, $limit,  $order) {
  $result = taxonomy_select_nodes($tid, (bool)$pager, $limit, $order);
  foreach ($result as $nid) {
    $node = node_load($nid);
    if ($uri = services_resource_uri(array('node', $nid))) {
      $node->uri = $uri;
    }
    $nodes[] = $node;
  }
  if (empty($nodes)) {
    return services_error(t('No nodes were found with tid @tid', array('@tid' => $tid)), 404);
  }
  return $nodes;
}

```

Anyone know?

# Answer
> 0 votes
(post)

The url link should be

http://domainABC.com/my\_services/taxonomy\_term/selectNodes?page=1

parameter:

tid=1

problem fixed.

---
Tags: services
---


# Question
Title: Why nodes aren't always deleted on cron?
I have this code in my module\_cron function (I need to delete old unpublished nodes).

```
include_once './modules/node/node.module';
$nids = db_query("SELECT nid FROM node where status = 0 AND UNIX_TIMESTAMP()-changed>172800 LIMIT 2000");
while ($result = db_fetch_object($nids)) {

  echo  "Deleting node ".$result->nid."<br>";
  node_delete($result->nid);
}

```

It always outputs node ids, but it rarely actually deletes nodes. In fact it seems to totally stop deleting them until I login to admin panel. What am I doing wrong? Is there any way to always delete nodes?

# Answer
Check this "Running cron as an authenticated user" in http://drupal.org/node/23714 it might be useful for you.
> 1 votes

# Answer
Here's one solution:

```
  include_once './modules/node/node.module';
  $nids = db_query("SELECT nid FROM node where status = 0 AND UNIX_TIMESTAMP()-changed>172800 LIMIT 2000");
  global $user;
  $orig_uid = $user->uid;
  $user->uid = 1;
  while ($result = db_fetch_object($nids)) {

      echo  "Deleting node ".$result->nid."<br>";
      node_delete($result->nid);
  }
  $user->uid = $orig_uid;

```
> 1 votes

# Answer
There might be the issue with the permissions. Please check the permissions of deleting the desired content type's content as cron might be running as anonymous user.
> 0 votes

---
Tags: 6, cron
---


# Question
Title: How can a div at the top of the page coexist with Adminstration Menu?
I want to place the Page execution times at the top of the page. I first tried it in a block as mentioned in this question, but the code for the block executes before the page is fully rendered, resulting in the wrong time.

Devel places the Page execution time is place in a div class `.dev-query` and I tried placing it at the top of the page.

The problem is it gets obscured by `Admin menu` and after reading a few solutions such as this one on stackoverflow 1 and stackoverflow 2 and I wonder if someone has `been there and done that` in relation with `Admin menu`

# Answer
> 2 votes
One way of doing that with the CSS is as below:

```
.dev-query {
    position: fixed;
    top: 33px;
    width: 100%;
    left: 30px;
    color: #000;
    z-index: 100;
}

```

I have tried that and it seems to be working for me.

---

Another way of doing this with the JS I have mentioned here is somewhat like below:

```
<div id="page-execution-time-custom"></div>
<script>
(function ($) {
  // Jquery onload function.
  $(document).ready(function(){
    // Display the page execution time in the custom wrapper as below.
    var page_execution_time = $('.dev-query').text();
    $('#page-execution-time-custom').text(page_execution_time);
  });
})(jQuery);
</script>

```

---
Tags: 7, routes, theming
---


# Question
Title: How do I update commerce product display nodes based on SKU (of the referenced product)?
I would like to update the product display nodes with taxonomy terms based on the SKU of the referenced product of each node. Is that possible, programmatically?

1. I know the SKU.
2. I need to find the product by the SKU of a product display. 1.I update the taxonomy term of the product display accordingly.

I tried to use `EntityFieldQuery` without success.

If someone could possibly give me an idea on the best approach to do this in DrupalCommerce, or provide a link to the documentation I have missed, it is greatly appreciated. I have lost a day or two googling the wrong questions, apparently.

# Answer
> 2 votes
Although an old thread, for the benefit of others looking, this could be done easily using views\_bulk\_operations (VBO). No coding required.

* Install VBO.
* Create a View of product display nodes.
* Add a relationship to commerce product.
* Add a batch update operations field to the View.
* Enable the "Modify entity fields" option in the VBO field settings.
* Add an exposed filter for the product SKU
* Save
* Use the batch update operation to check and set the relevant taxonomy term reference field.

# Answer
> -1 votes
I believe you can do this just fine using feeds and commerce feeds. The sku is commonly used as the unique id.

---
Tags: 7, nodes, commerce
---


# Question
Title: Drupal 7, superfish menu hidden in garland theme
I am using the default theme `garland` in `Drupal 7.23` with a `superfish` menu put on the `first sidebar` block . (the side on the left).

But when I try to open the menu, and on my content block I have a view or a nivo slideshow block the menu is hidden. Where should I put the z-index? (tried on the theme and on the menu but nothing worked)

Thank you

# Answer
> 0 votes
In `page.tpl.php` page search with keyword menu,

```
 <div id="main-menu" style="z-index:99">

```

you can put style `z-inex` here.

---
Tags: theming
---


# Question
Title: Why bootstrap navigation button does not expand?
I am trying to created a simple responsive theme using bootstrap but got stock at navigation bar in Drupal 6 and basic theme. Here is the navbar that I've put in page.tpl.php:

```
<div class="navbar navbar-default navbar-fixed-top">
  <div class="container">
<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">MySite</a>

 </div>
  <div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Tutorials</a></li>
</ul>
  </div>
</div>

```

I have removed all the native css and js files. Instead I have placed bootstrap.css, bootstrap.min.js and jquery-1.10.2.min.js into the theme and defined them for info and template.php. In the rendered page source I can see that all the 3 are loaded.

When I shrink the window, the navigation links collpase to button but then the button does not respond to on click to expected and show links. I also tried the very bootstrap example navbar but the button and drop-down menus does not work either.

What could be wrong here?

Can see in the source of the page that all the three are loaded.

# Answer
The problem is in JavaScript: you should not include jQuery (and generally other libraries) through your theme.

Bootstrap requires newer versions of jQuery (I think v1.8+) and you should use jQuery Update module to upgrade it on your site.
> 2 votes

---
Tags: javascript, theming, navigation
---


# Question
Title: How can I create a bulk node creation interface?
I have a request for an interface where nodes with a small amount of required fields (for example, a title, date, and a node reference) would be able to be created in bulk on one screen.

I am imagining some kind of editable table view/grid with each row representing an individual node.

What would be the best approach to implementing something like this?

# Answer
> 4 votes
The Multi Node Add module might provide what you need.

# Answer
> 2 votes
This is great... there is a D6 & D7 version http://drupal.org/project/slickgrid

Edit: I highly recommend trying this its the most awesome thing!! You even get your field widgets in popups when clicking on the cells.

A couple quick tips (D7) Be sure to also install http://drupal.org/project/title so you can reset the title (make it a field), Basically with this editor you can only edit actual fields, so same goes for location module, you'll need to use the field option rather than node option.

# Answer
> 0 votes
You can use `devel` module and in sub module exist another module named `Devel generate` you can use it to genereate bulky , content type , vocabulary, taxonomy and ....

This is perfect way to create bulk, it also support local module

---
Tags: 7, nodes
---


title: User Reference For a Particular role

text:
# Question
Title: User Reference For a Particular role
I am using Drupal 7 . and in a content type i created a field with user\_reference, which is working fine.

And while creating a content it shows all users.

Now i want to show only User with particular role..

Does anybody tell me how to do this. Is there is any module avialable for this

# Answer
> -1 votes
For User Reference Module, In Field settings -\> already roles are defined know.. **User roles that can be referenced**

# Answer
> 3 votes
I would use the Entity Reference module (rather than user reference). I would then create a view (display: entity reference) filtering only Users with that desired role.

In the field settings you can choose the designated View under "Entity Selection" - "Mode": "Views: Filter by an entity reference".

This is at least how I solved this problem in the past. I hope this helps.

---
Tags: 7
---


# Question
Title: Why would the body field's language not save as the same language as the node?
I am having a problem where the user is creating new nodes and entering body text, but setting the nodes to "language neutral" for the language. Yet when it saves the node the body field's language gets set to English. Why would this be happening? What would cause this?

On this site we have both English and French enabled and configured. This site is D7 running i18n.

This is similar to Empty body in node edit page except that I want to know how the field would get a different language than the node in the first place.

# Answer
> 4 votes
By default, drupal sets 'und' as the field language, that is LANGUAGE\_NONE. So, when you `print_r($node)`, you will see a field with something like `$node->field_name['und'][0]['value']`

Now, when you enable translation on this field, the 'und' will get replaced by the language code and somehow the `$node` structure would look like `$node->field_name['en'][0]['value']` where 'en' is the language code. Your body field will now have 'en' as the language and won't be empty anymore when rendered

For your question above :

> I am having a problem where the user is creating new nodes and entering body text, but setting the nodes to "language neutral" for the language. Yet when it saves the node the body field's language gets set to English. Why would this be happening? What would cause this?

Check default language of your site, if its set to English, then probably Language Neutral will take your site's default language.

---
Tags: 7, entities, nodes, i18n-l10n
---


# Question
Title: Move fields into fieldset with field_collection module doesn't work
I have a node, inside this node I have a field\_collection with one checkbox and 2 fields inside it. I want to move these two fields inside a fieldset to show/hide entire fieldset depending of the checkbox value.

```
function mymodule_form_testtype_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_test_collection']['und'][0]['surround_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Sorround fieldset'),
        '#tree' => FALSE,
    );
    $form['field_test_collection']['#tree'] = FALSE;
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'] = $form['field_test_collection']['und'][0]['field_collection_first'];
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'] = $form['field_test_collection']['und'][0]['field_collection_second'];
}

```

But when I try to submit the form these two values are not saved. I tried to remove the original fields using

```
unset($form['field_test_collection']['und'][0]['field_collection_first']);

```

or hide them with

```
$form['field_test_collection']['und'][0]['field_collection_first']['#access'] = 0;

```

I also tried the "cheat" to move back these two fields in the *validate* function

```
function mymodule_article_form_testtype_node_form_validate(&$form, &$form_state) {
    $form_state['values']['field_test_collection']['und'][0]['field_collection_first'] = $form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'];
    $form_state['values']['field_test_collection']['und'][0]['field_collection_second'] = $form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'];
    unset($form_state['values']['field_test_collection']['und'][0]['surround_fieldset']);

    $form['field_test_collection']['und'][0]['field_collection_first'] = $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'];
    $form['field_test_collection']['und'][0]['field_collection_second'] = $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'];
    unset($form['field_test_collection']['und'][0]['surround_fieldset']);
    $form['field_test_collection']['und'][0]['field_collection_first']['#access'] = 1;
    $form['field_test_collection']['und'][0]['field_collection_second']['#access']  = 1;
}

```

With a dpm($form\_state) in the *submit* function I can see correct values in their places, but after it they're not saved.

Any idea? Thank you

# Answer
> 0 votes
I found the solution. It seems values from fields inside the field\_collections are not managed as other Drupal form values.

This is the code to achieve the result:

```
function mymodule_form_testtype_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_test_collection']['und'][0]['surround_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Sorround fieldset'),
    );
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'] = $form['field_test_collection']['und'][0]['field_collection_first'];
    unset($form['field_test_collection']['und'][0]['field_collection_first']);
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'] = $form['field_test_collection']['und'][0]['field_collection_second'];
    unset($form['field_test_collection']['und'][0]['field_collection_second']);
    $form['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_form_submit($form, &form_state) {
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_first['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first']['und'][0]['value'];
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_second['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second']['und'][0]['value'];
}

```

---
Tags: 7, entities
---


# Question
Title: Load jquery action on link menu click/node load
So what I would like to do is great a sliding door effect for my drupal site using jquery-ui action. Does anyone know of examples or a module for this?

Also I would like the action to execute on two triggers. -open close sliding door on "menu link to new node click" -close sliding door once node is loaded

I've seen example for what I want to do and I know that you can insert jquery-ui. All I need to know is where do I need to insert the jqurey-ui. Examples would be great!

# Answer
It depends on what page you need to add the script, adding jquery\_ui is fairly straightforward if you know which component it is.

You should add the following line in the template.php (changing the ui.autocomplete to what you need)

```
drupal_add_library('system', 'ui.autocomplete');

```

The following page is extremely useful https://drupal.org/node/171213

Update as described in comments

```
function MY_THEME_preprocess_html(&$variables) {
    if(arg(0)=='node' && arg(1) === 3)) {
        $node = node_load(arg(1));
        drupal_add_js('system', 'ui.autocpmplete);}
       }
    }

```
> 1 votes

---
Tags: nodes, javascript, rules
---


# Question
Title: re-saving users with default field collection items
I wanted to post to @Clive comment on How can I quickly re-save all users on my site? and ask about how to do this for fields in a field collection but couldn't because I've never posted to this site before so I had to ask a new question. He provided the following code to run as a php script in VBO on all users:

```
$items = field_get_items('user', $entity, 'field_name');
if (empty($items)) {
   $entity->field_name[LANGUAGE_NONE][0]['value'] = 1;
}
user_save($entity);

```

This solution works great for a single field of a user. I need a similar solution for setting default field values in a field collection after importing users.

I migrated 6000+ users and have set default values for fields in a field collection after the fact that don't show up unless I re-save a user account. I want to bulk re-save all 6000+ users so that the default field collection fields are saved and are visible. It's almost identical to the original question except the field is not just a singular field associated with the entity -- the field(s) in question are part of a field collection. How do I access the fields from my default field collection to then force re-save of users?

Is the proper way to access field data through entity\_metadata\_wrapper? If this is the case, how do I get/set the values of fields in a field collection that I want to associate with users using this wrapping class?

# Answer
This finally worked for me -- may it save someone hours of headaches:

```
// load the user
$userwrapper = entity_metadata_wrapper('user', $entity);
// apparently you have to create the field collection entity
$fieldCollection = entity_create('field_collection_item', array('field_name' => 'field_yourCollectionName'));
// attach your field collection to the user
$fieldCollection->setHostEntity('user', $entity);
// set the value of one of your fields in your field collection - in my case it's a boolean
$userwrapper->get('field_yourCollectionName')->field_fieldNameInYourCollection->set(0);
// save the entity
$userwrapper->save();

```
> 1 votes

---
Tags: users, views
---


# Question
Title: Dynamic profile2 fields - User can add more fields while registration
how to add dynamic user registration fields . I need a phone number field which can be added by users during registration by pressing "add more" button as many times he wants .

Is it possible ? or any other approach ?

thanks

# Answer
I think you can use the Field Collection module.
> 0 votes

---
Tags: users
---


title: Attaching css to blocks

text:
# Question
Title: Attaching css to blocks
Why do we use **$block\['content'\]** while attaching css or js files to block ?

```
$block['content']['#attached']['css'][] = drupal_get_path('module',
                                          'mymodule' . '/mymodule.css');

```

What does that 'content' mean ?

# Answer
A block array has a 'subject' and 'content' key, it's just a convention. See `hook_block_view()` for details:

> **Return value**
>
> Either an empty array so the block will not be shown or an array containing the following elements:
>
> * subject: The default localized title of the block. If the block does not have a default title, this should be set to NULL.
> * content: The content of the block's body. This may be a renderable array (preferable) or a string containing rendered HTML content. If the content is empty the block will not be shown.
> 3 votes

---
Tags: 7, blocks
---


# Question
Title: what is the difference between using drupal_add_js and ['#attached']
What is the difference between `drupal_add_js()` and `$form['#attached']['js'][]` ?
When is the purpose of using each of the above functions?

(I mean I know that it is used to attached js to say form if used inside form but when is `drupal_add_js` used and when is `$form['#attached']['js'][]` used ?)

# Answer
> 9 votes
If you are using `drupal_add_js()` in your form building function, you are attaching JavaScript to a page, and that's it.

If you are using `$form['#attached']['js']`, other modules may interact, test and change it as they need, using `hook_form_alter()`. That's the way you should choose every time your JavaScript is functionally related to particular form.

Other than that, they are functionally the same.

**Note** that it is usually better to use JavaScript libraries than plain JavaScript files, as they allows you to declare versions, keep relations between JS and CSS, manage dependencies, well, they are generally way more powerful.

Of course then you should use `$form['#attached']['library']` when your JavaScript Library is functionally related to particular form, and only use `drupal_add_library()` when no form is in any way related to library's function.

---
Tags: 7, javascript
---


title: eCommerce system with simple order form

text:
# Question
Title: eCommerce system with simple order form
I need a food order system to embed in my drupal 7 website. I added the screen shot of the design here:

I don't want a full eCommerce system.User can select items and the items will be listed in the order list.They can edit the no of items from remove items form the order list.After send an order the order will be stored in db and the site admin can view it on the admin part.From he can process it manually.There is no payment system for it and this is only to track the order and deliver it manually.

Can you please suggest me better way to accomplish it.

thanks in advance.

# Answer
I had to do something similar to this in the past, where the website client wanted users to be able to mark items as favorites, and then email that list of favorites to the client for pricing and further information. Rather than building a whole e-commerce setup, I used webform and webform view.

Here is the basic setup:

1. Create 'food item' content type or whatever will be most appropriate for each of your food items
2. Create a view that displays the food item nodes.
3. Create a webform that collects user information (such as contact information when submitting an order
4. Embed your food item view in that webform using the webform view module.

When people then fill out the form, they can select which 'food item' nodes they, want, the quantity, or any other custommizations that you can create using the webform (special requests, delivery method, anything you'd like). They will also enter in any relevant contact information and send it to you as a standard webform.

Webform view has great documentation. It can be a little confusing the first time you try to use it though, so I suggest you follow exactly the documentation in webform view to get an idea for how this module works, and then modify it accordingly for your food item view.

I liked this method too as then the food items are their own content type, so if you do want to do something with e-commerce for real in the future, you should be able to migrate those nodes to products for something like drupal commerce.
> 2 votes

---
Tags: ubercart, commerce
---


# Question
Title: changed theme -> Logged out -> No log in field shown :(
I cant find the log-in or registration fields on my wellcome page after i changed my theme and loged out myself.

How can i make the log in field visible again?

thank you for help.

# Answer
> 1 votes
You can go to the following path: http://www.yoursite.com/?q=user/login

---
Tags: users
---


# Question
Title: Altering views exposed form - Adding select list separator causes error
**Problem**

I want to break the select list on my exposed form into chunks using select list dividers.

However this breaks my search.

Any attempt to search with values from that select list removes all results and attempts to navigate to the next page display the following error:

"An illegal choice has been detected. Please contact the site administrator"

What is going on?

**Set-Up**

I have an exposed view form. It has a select list field as one of the filter options.

There are a lot of options in the select list, so I've reordered it (away from alphabetical) to leave the five most popular at the top. This seems a little random so I then altered the form to add in un-selectable dividers. (see top picture)

How to add separator option in Form API 'select' element? (this is for creating forms, I put it into a form alter)

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'views_exposed_form') {
      'Most Popular' => array (
          1 => 'China',
          2 => 'Thailand',
          3 => 'Japan',
          4 => 'Spain',
          5 => 'Saudi Arabia',
      ),

      'Countries' => array (
          6 => 'Afghanistan',
          7 => 'Aland Islands',
          8 => 'Albania',
          9 => 'Algeria',
          10 => 'American Samoa',
          ..
       );
    }

```

Is it somehow appending "Most Popular" or "Countries" onto the select list data value, invalidating the select list and throwing errors?

Allowed values in my select list looks like:

```
China|China
Thailand|Thailand
Japan|Japan
Saudi Arabia|Saudi Arabia
Spain|Spain
Afghanistan|Afghanistan
Aland Islands|Aland Islands
Albania|Albania

```

**EDIT --**

Alfred-Armstrong's answer has fixed the first problem. I now get search results. But the form alter is still breaking my ability to change pages.

This does however depend on what I search for. If I choose a country it works otherwise it breaks on a blank search.

Any more insight would be fantastic.

**EDIT--2**

Thanks again to Alfred I figured out what the other problem was. I was getting slightly different paths in my views with and without `hook_alter_form`.

The reason is I have two exposed forms for the same view. This means I have two views with the same path and both have exposed forms. One is on the home page the other on the search page.

The exposed forms have the same `$form_id`, so I when I alter one using `hook_form_alter` I alter the other. However I'd altered one exposed form in the views UI and not the other and because they have the same $form\_id Drupal tries to pass data between them but can't.

# Answer
> 2 votes
The key values in the field are strings but in your altered version they are numbers. Change 1 to China etc.

---
Tags: 7, views, forms
---


title: Rewrite results "read more" link death

text:
# Question
Title: Rewrite results "read more" link death
**My rewrite result settings:**

**My general settings:**

the "read more" link from the teaser doesn't redirect me to the article, When pressed, it redirects me to the main page (current one).

When leaving the "more link path" empty, it should redirect me to the blogpost (article).

Some values I've tried for "link more path":

```
[path]
[node/id]
[node:title]
[title]

```

Is this not working because I also got the "URL aliases" module installed? Which cleans my url like this:

```
www.mysite.com/blog/awesome-article-about-ducks

```

instead of this:

```
www.mysite.com/blog/node/41

```

# Answer
> 2 votes
There are 2 ways to do this.,

Step :1

> 1. Add the nid to the views and exclude it from the display.
> 2. Place this nid before all fields in the views. Only by placing it above the all fields, we can get this as a token in the replacement.
> 3. Now use node/\[nid\] as the path to link.
> 4. This will worl

Step : 2

> 1. Add content:link as a field.
> 2. Add set the nid in the replacement pattern.

Difference between the 2.

> Step:1 shows the read more only when the length is greater than the trim value. Else it will not show.
>
> Step:2 will show the read more in all the cases. Even the body is empty it will show read more, but this will not happen in step 1.

---
Tags: 7, nodes
---


# Question
Title: Nested OR and AND condition with db_select
How can I convert the following query with db\_select

```
SELECT *
FROM 'my_table'
WHERE
(condition1 < "value1" AND ((conidition2 > "value2") OR (condition3 < "value3")))
  OR
(condition4 < "value5" AND ((condition6 < "value6") OR (condition7 < "value7")))

```

I am trying with

```
$query = db_select('mytable');

$query->condition(
          db_and()->condition("condition1","value1")
                 ->condition(
                             db_or()->condition("condition2","value2")->condition("condition3","value3")
                             ));
$query->condition(
          db_and()->condition("condition4","value4")
                 ->condition(
                             db_or()->condition("condition5","value5")->condition("condition6","value6")
                             ));

  $query_debugg = $query->__toString();
dpm($query_debugg);

```

issue is with the "AND" in between where is should be "OR", it is expected I know.how can I change it

Output String

```
SELECT
FROM
{mytable} mytable
WHERE ( (condition1 = :db_condition_placeholder_0) AND( (condition2 = :db_condition_placeholder_1) OR (condition3 = :db_condition_placeholder_2) ))AND( (condition4 = :db_condition_placeholder_3) AND( (condition5 = :db_condition_placeholder_4) OR (condition6 = :db_condition_placeholder_5) ))

```

# Answer
with help of question pointed by @molot I could make it work, here is the code

```
$query = db_select('mytable');
$db_or = db_or();
$db_or->condition(
  db_and()
    ->condition("condition1","value1")
    ->condition(
      db_or()
        ->condition("condition2","value2")
        ->condition("condition3","value3")
));
$db_or->condition(
  db_and()
    ->condition("condition4","value4")
    ->condition(
      db_or()
        ->condition("condition5","value5")
        ->condition("condition6","value6")
));
$query->condition($db_or);

$src = $query->__toString();
dpm($src);

```

and here is the output

```
SELECT
FROM
{mytable} mytable
WHERE (( (condition1 = :db_condition_placeholder_0) AND( (condition2 = :db_condition_placeholder_1) OR (condition3 = :db_condition_placeholder_2) ))OR( (condition4 = :db_condition_placeholder_3) AND( (condition5 = :db_condition_placeholder_4) OR (condition6 = :db_condition_placeholder_5) )))

```
> 2 votes

# Answer
In Drupal, conditions are `AND` by default. It's easier to use objects directly, in my opinion:

```
$left_condition = new DatabaseCondition('AND');
$left_condition->condition( ... ); // add what you need

$right_condition = new DatabaseCondition('AND');
$right_condition->condition( ... ); // add what you need

$condition = new DatabaseCondition('OR');
$condition->condition($left_condition);
$condition->condition($right_condition);

```

But you can use `db_and()` and `db_or()` if you prefer.
> 4 votes

---
Tags: database
---


# Question
Title: Selecting First Name of Billing Address in Rules with Data Selector?
How do I use data selector for Billing Address \> First Name in Rules for Commerce?

I want to use the order owner's first name in automatically generated emails.

For example:

> Hey **Scott**,
>
> Thanks for your order...

# Answer
> 9 votes
The solution likely depends on the billing customer profile's address field using a split first and last name field instead of the combined "full name" field. I've noticed on my Commerce site that there appears to be a bug in Address Field (hope to fix soon) that prevents a full name field from being split up into first and last name fields or vise versa.

Assuming your customers are entering first and last name separately, then all you have to do is drill down from the order through the profile to the first name on the address field. To do this using a Rules data selector, you'd first need to add two "Entity has field" conditions - one to ensure the commerce-order entity has the commerce\_customer\_billing field and a second to ensure the commerce-order:commerce-customer-billing entity has the commerce\_customer\_address field. IF those are in place, using the data selector you can drill down to the following token:

commerce-order:commerce-customer-billing:commerce-customer-address:first-name

The problem comes when you actually want to embed this value in the body of an e-mail. Right now, as far as I can tell, there is no chain of tokens (replacement patterns in Rules UI parlance) that will drill down to the first name using that same pattern. Looking in the code for addressfield.module, I don't see any token related code. This may just need to be opened as a feature request for the Token module.

# Answer
> 8 votes
Found the solution. My rule was already sending an email but I could not see any token for the customer first and last name.

1. Add a condition "Entity has field" \> commerce\_customer\_billing
2. Add an action "Fetch entity by id":

Entity type \> Value: Commerce Customer Profile

Identifier \> Data selector: commerce-order:commerce-customer-billing:profile-id

Provided variables
Variable label: Customer Billing Profile
Variable name: customer\_billing\_profile
3. Add an action "Send email"
(if you installed Mime Mail module for sending email within Rules you can choose "Send HTML e-mail" like I did)

Use those tokens for first name and last name:
\[customer-billing-profile:commerce-customer-address:first\_name\]
\[customer-billing-profile:commerce-customer-address:last\_name\]

Note that it's taking the first and last name from the order itself NOT in the address book or profile. So if a user change its name in his address book it won't update in the order. I tried it.

I was inspired by a rule set found here:
https://gist.github.com/ogredude/3956560

---
Tags: 7, commerce, rules
---


# Question
Title: How do I redirect user_view_page to user_profile_form?
I do not really need the user\_view\_page on my site and I want to redirect calls to user/%user to the user\_profile\_form. I only want this change for regular users, not for administrators.

I already tried to accomplish this with hook\_menu\_alter, but that would change it for all users including the administrator.

How can I do this?

# Answer
If you don't want to use the Rules module, you can mimic its behavior/do it yourself inside of hook\_init(), eg something along the lines of:

```
function YOURMODULE_init() {
  global $user;

  if (arg(0)=='user' && is_numeric(arg(1)) && !(arg(2)) { // eg user/# and not user/#/edit

    if ( /* whatever logic you need to determine this is not an admin */ ) {

      if ($user->uid==arg(1)) { // same user...
        drupal_goto($_GET['q'] . '/edit');
      } else {
        // either ignore it and allow standard Drupal permissions to deal with it or go someplace else, do a drupal_access_denied() etc
      }

    }

  }

  // any other module init stuff here...

}

```

You didn't specify what you want to happen if a user tries to look at another user's page but you can deal with that situation easily above as well.
> 0 votes

# Answer
I've solved this problem in the past with the Rules module.

Event: User Account page is viewed

Condition: User has role(s)

Action: Page redirect Parameter URL:\[account:edit-url\]

I created the rule and added the screenshot here: https://i.stack.imgur.com/oONeT.jpg

Here is also the exported rule:

```
{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_view" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "[account:edit-url]" } } ]
  }
}

```

I hope this helps!
> 0 votes

---
Tags: users
---


# Question
Title: Is there a way to remove a menu item from the active trail without removing it from the menu parent?
I'm a relative newcomer to Drupal and I'm not sure how to handle this. On this page:

http://staging.stvincentdepaul.net/volunteer

You can see that Volunteer is highlighted in the main nav but so is Today. If you hover over those L1 links, you'll see that each one has a Donate and Volunteer button. These are all part of the main navigation menu in the admin section so each Donate and Volunteer button falls under each L1 link. The Today section was the last to have Donate/Volunteer added so it is attaching the active-trail class to that link since it can only have one.

Is there a way to keep those Donate/Volunteer links in the menu but not part of the active trail?

# Answer
This is a common headache. I keep meaning to write a contrib module to address this by letting users define a "canonical" menu item in the event there are several menu items that point to the same page in the same menu.

That said, there are some workarounds you can use.

The best option is to use the Redirect module. You create a redirect to your Donate and Volunteer pages then put the redirects in the menus.

So if your volunteer page is at /volunteer and donate is at /donate, then you can create two redirects. One called /go-volunteer and another called /go-donate which redirect to their respective pages. Then you'd put /go-volunteer and /go-donate in the menu which, when clicked, will take the user to the appropriate page.

Since they're redirects, they won't trigger the active trail.
> 3 votes

---
Tags: navigation, routes
---


# Question
Title: How do I separate custom template from the administration theme?
I have made a custom template for the user\_profile\_form. I made a module and in the module I added the hook\_theme function:

```
function myuser_theme() {
  $items = array();

  $items['user_profile_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('module', 'myuser'),
    'template' => 'user-account-form',
  );

  return $items;
}

```

This works as suspected but the theme is also applied in the administration theme. How can I have a custom template for the profile form and retain the original layout from the administration theme?

# Answer
> 0 votes
You can sniff the user's role and/or permissions and then conditionally change the template.

You can test permissions with `user_access('view the administration theme')` and depending on the result, assign your custom template.

---
Tags: theming
---


# Question
Title: Caching Drupal 7 using boost module and Varnish, yet still getting a "MISS"(
I'm trying to do a little test, so I installed Drupal7 w/ following modules (expire, boost, varnish, purge, rules and token). I'm using`varnish-3.0.4-1.el5.centos.x86_64` in front of `httpd-2.2.15-29.sl6.x86_64`.

I added following into my `settings.php`:

```
// Add Varnish as the page cache handler.
$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap. This needs
// to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

```

and I set following settings for varnish module inside of Drupal7:

```
# drush -r /usr/share/drupal7/ -l XXXXX vget varnish
varnish_bantype: "1"
varnish_cache_clear: "2"
varnish_control_key: "XXXXX"
varnish_control_terminal: "XXX.XX.XXX.XX:6082"
varnish_flush_cron: "0"
varnish_socket_timeout: 100
varnish_version: "3"
#

```

yet I keep getting `MISS`

```
# curl -I XXXXX
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
X-Powered-By: PHP/5.3.3
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Thu, 24 Oct 2013 14:42:21 +0000
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: "1382625741"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Content-Type: text/html; charset=utf-8
x-url: /
x-host: XXXXX
Accept-Ranges: bytes
Date: Thu, 24 Oct 2013 14:42:21 GMT
X-Varnish: 1527289503
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXXXX
X-Cache: MISS

#

```

even though it seems like if I go to `Configuration`-\>`Performance` and then enable `Caching`, I'd end up with a HIT, yet `Status Report` would say following message (after enabling `Caching`) `Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.`

*** UPDATE ***

this is after enabling `boost`, as you see `Cache-Control:` *IS* in there, yet still getting `MISS` from Varnish(

```
$ curl -I http://XXXXX/node/1
HTTP/1.1 200 OK
Server: Apache/2.2.15 (Scientific Linux)
Last-Modified: Mon, 28 Oct 2013 15:53:48 GMT
ETag: "802449-1da7-4e9cf1b11461e"
Accept-Ranges: bytes
Content-Length: 7591
Cache-Control: max-age=1209600
Expires: Mon, 11 Nov 2013 15:55:46 GMT
Content-Type: text/html; charset=UTF-8
x-url: /node/1
x-host: XXXXX
Accept-Ranges: bytes
Date: Mon, 28 Oct 2013 15:55:46 GMT
X-Varnish: 1527308733
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: XXX.XXXXX.XXX
X-Cache: MISS

$

```

What am I doing wrong?

# Answer
Pay attention to the `Cache-Control` header returned from Drupal:

```
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0

```

If `Cache-Control` is set to `no-cache`, Varnish will respect it by default. Either you must force caching from within Varnish in `vcl_fetch` or (much better), make Drupal deliver the proper header (`Cache-Control: public, max-age=X`). The simplest way to achieve the latter is to enable "Cache pages for anonymous users" in *Administration » Configuration » Development* and also set "Expiration of cached pages". You can hard-code those settings using:

```
$conf['cache'] = 1;
$conf['page_cache_maximum_age'] = 3600; // 1h

```

You also may force the `Cache-Control` header by adding it explicitely using a custom module by implementing `hook_exit`. A reasonable save implementation looks something like this:

```
/**
 * Implements hook_exit().
 *
 * @see drupal_serve_page_from_cache()
 */
function MYMODULE_exit($destination = NULL) {
  // If the client sent a session cookie, a cached copy will only be served
  // to that one particular client due to Vary: Cookie. Thus, do not set
  // max-age > 0, allowing the page to be cached by external proxies, when a
  // session cookie is present unless the Vary header has been replaced or
  // unset in hook_boot().
  $vary_header = drupal_get_http_header('vary');
  $max_age = !isset($_COOKIE[session_name()]) || isset($vary_header) ? variable_get('page_cache_maximum_age', 0) : 0;

  if (drupal_page_is_cacheable() && $max_age && $destination == NULL && !headers_sent()) {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . $max_age);
  }
}

```

Also note that due to the fact that boost will also add a `Cache-Control` header, you still need to introduce some VCL logic in `vcl_fetch`. The following fragment will force Varnish to still store pages in the cache, even when they were delivered using boost with `Cache-Control no-cache`:

```
sub vcl_fetch {
  if (beresp.http.X-Cached-By ~ "Boost") {
    set beresp.ttl = 1 h;
  }
}

```
> 7 votes

---
Tags: 7, caching, proxies
---


# Question
Title: How an user set his own password while creating account
When a user creates an account he is only asked for a username and email.

I also want him to set his own password when he creates an account. how can i manage that as admin?

Thank you!

# Answer
Maybe this module is for you: User registration password
> 1 votes

# Answer
I like the logintoboggan module. It lets you change a ton of settings for user registration including the one you're looking for and letting users login with their email as well as their usernames.
> 1 votes

---
Tags: users
---


# Question
Title: How to implement ORDER BY SUBSTRING in db_query
I am migrating comments from a Drupal 6 site into Drupal 7 - but I am importing into the Reply module https://drupal.org/project/reply because the comments were on a Profile node in Drupal 6 but now I'm using Profile2 entities in D7.

I am trying to connect to my legacy database and so far my query is like

```
$query = $this->sourceDbConnection()
  ->select('node', 'n')
  ->fields('n', array('nid', 'title', 'uid',))
  ->fields('c', array('cid', 'pid', 'nid',  'uid', 'subject',
    'comment', 'hostname', 'timestamp', 'status', 'format',
    'thread', 'name', 'mail', 'homepage',
));
$query->innerJoin('comments', 'c', '(n.nid=c.nid)');
$query->where('(n.type=:type)', array(':type' => $this->LEGACY_CONTENT_TYPE));

```

However, I wish to add an ORDER BY to the query similar to how it is used in the `comment_render` function https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment\_render/6 i.e. `ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))` and I don't know how to do this.

# Answer
> 1 votes
`SelectQuery::orderBy()` isn't particularly picky, you can just tack this on to the end of your code:

```
$query->orderBy('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))');

```

With the rest of your code that produces

```
SELECT n.nid AS nid, n.title AS title, n.uid AS uid, c.cid AS cid, c.pid AS pid, c.nid AS c_nid, c.uid AS c_uid, c.subject AS subject, c.comment AS comment, c.hostname AS hostname, c.timestamp AS timestamp, c.status AS status, c.format AS format, c.thread AS thread, c.name AS name, c.mail AS mail, c.homepage AS homepage
FROM
{node} n
INNER JOIN {comments} c ON (n.nid=c.nid)
WHERE  ((n.type=:type))
ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) ASC

```

---
Tags: database
---


# Question
Title: Drupal 7 in subfolder behind reverse proxy, login not working
I'm trying to run a Drupal 7.12 site behind an nginx reverse proxy, so that it shows up in a sub-folder to the primary domain (company.com).

Nginx is handling all incoming traffic to http://company.com, and Drupal is installed on another server with Apache. We want the content from Drupal to show up under http://company.com/drupal/.

For nginx, there is a proxy\_pass specified like this:

```
  location /drupal/ {
    proxy_pass http://drupal.company.com/;
  }

```

For Drupal, I have set

```
$base_url = http://company.com/drupal;

```

This works fine to browse the content, Drupal is generating correct links, etc.

But when I try to login `/drupal/user`, I get the login form, but the action parameter for the form is set to "/user" - it seems that Drupal is forgetting to apply the base\_url here.

Any ideas how to solve this issue? Help appreciated...

# Answer
As I understood, the `#action` on the page `/user` is generated by request\_uri, the default action of each form, except for few form that are block (check if the user\_login block has the same problem).

I can advise you, to check your PHP config in Report -\> Status report and then click on the PHP version an try to find the REQUEST\_URI information, this can be different from what you are expecting (I guess /drupal/user).

To fixe it, I see only two solutions, submit an issue (or check if that issue already exists) or the second its to use the hook\_form\_alter and replace the `#action` by something like that.

```
$form['#action'] = url(current_path(), array('external' => FALSE));

```
> 1 votes

# Answer
You can find the solution at https://drupal.org/node/244593

In essence you rewrite $\_SERVER\['REQUEST\_URI'\] in settings.php.
> 1 votes

---
Tags: users
---


# Question
Title: How to run the Flags module after the Rules module?
As a sequence on this question, I'd like to deduct 2 User Points when a user's **first** reaction on an Article is deleted (I mentioned my flag 'First reaction' there). I created a Rule 'Reaction removed' with the following settings:

*EVENTS:* After deleting a comment

*CONDITIONS:*

* Comment is flagged Parameter: Flag: First reaction, comment: `[comment]`, User on whose behalf to check: `[comment:author]`

*ACTIONS:*

* Grant points to a user Parameter: User: `[comment:author]`, Points: -2, Points category: Reaction, Operation: Delete, Moderate: Automatically approved
* Unflag a Node: Parameter: Flag: Commented on a node, Node: `[comment:node]`, User on whose behalf to flag: `[comment:author]`, Skip permission check: false

I thought it looked all right, but it doesn't work, because apparently the comment is always handled as if it's unflagged, even when it's stored in the database as flagged with 'First comment'!

This is the Rules evalution log:

```
0 ms Reacting on event After deleting a comment.
11.674 ms Evaluating conditions of rule Reaction removed. [edit]
15.543 ms The condition user_has_role evaluated to FALSE [edit]
28.531 ms The condition flag_flagged_comment evaluated to FALSE [edit]  <--- going wrong here
28.547 ms AND evaluated to FALSE.
28.575 ms Finished reacting on event After deleting a comment

```

What went wrong and how can I solve it?

# Answer
> 2 votes
The problem arises because the Flag module runs before Rules, so it has already removed the flag before Rules performs its test. One way to deal with this is to install Modules Weight which will allow you to adjust the relative priorities of modules so Flag runs after Rules.

---
Tags: 7, rules, comments, flags, userpoints
---


# Question
Title: When no terms are chosen as filters in a view all results are returned
I have a view with exposed filters that are taxonomy terms. These are multiple select.

When none of the options are selected the nodes are not filtered by that vocabulary so everything is returned. But what I need to happen is only noes not tagged with any of those terms be shown. Can this be done?

# Answer
So you want the inverse of a search? Or have I misunderstood?

If thats what you mean I think you can change that inside your view settings.

Go to Structure \> Views \> *edit your view*

Then select your filter criteria and edit it. I think you need to check the following check box.
> 0 votes

---
Tags: views
---


# Question
Title: Can't get form_state['values'] from a form on a custom checkout pane
I created a custom checkout pane with Drupal Commerce so if a user checkouts as anonymous they can create an account on the checkout completion page. The problem is that when in my form's submit function the form\_state values are not passed and I get an undefined index error. Here is the code for the checkout form:

```
function commerce_checkout_complete_registration_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

      $form['new_email'] = array(
        '#type' => 'textfield',
        '#title' => t('Email'),
        '#element_validate' => array('_validate_the_email'),
      );

      $form['pass'] = array(
        '#type' => 'password_confirm',
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Register'),
        '#submit' => array('commerce_checkout_complete_registration_pane_checkout_form_submit'),
      );

      global $user;
      if($user->uid == 0){
        return $form;
      }

    }

```

And here is the submit function:

```
function commerce_checkout_complete_registration_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  dpm($form_state);
  $email_address = $form_state['values']['new_email'];
  syslog(1, $email_address . 'TEST');
}

```

# Answer
> 1 votes
The function "commerce\_checkout\_complete\_registration\_pane\_checkout\_form" needed to have the $form variable passed as a reference, &$form.

---
Tags: 7, forms, commerce
---


# Question
Title: how to make node data available in the page.tpl.php
I want to be able to print the contents of my node tpl up into the outer page region, accessible via the page.tpl.php (or an override). How exactly can I do this?

I originally thought about doing a variable\_set in the node.tpl and then getting it in the page.tpl. However, if this would work, I would need to be able to create a template. I tried page--node--gallery-photo.tpl.php, but it doesn't seem to be the correct override.

What this the best way to do what I need to do here?

# Answer
> 1 votes
If you are on Drupal 7 you can edit your theme's `template.php` and add (or edit) the function

```
function <YOUR_THEME_NAME>_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

The same task in Drupal 6 is accomplished by adding/editing in template.php

```
function <YOUR_THEME_NAME>_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $variables['template_files'][] = "page-" . $variables['node']->type;
  }
}

```

Then you can add `page--<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php` (or `page-<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php` in Drupal 6) to your theme. Remember to clear the theme cache.

---
Tags: theming, 7
---


# Question
Title: How to pass Views contextual filter via URL?
I want to pass some values to my view via contextual filters in the URL. What GET naImes do I use? There seem to be no clue given, just this "The contextual filter values is provided by the URL".

If I have to construct that URL, how do I find out what GET var names do I need to pass so they are recognized?

# Answer
> 13 votes
Contextual filters aren't passed in separate variables, they are part of the path. If your view path is xxx/yyy then to have a filter value of nn the path would be xxx/yyy/nn.

# Answer
> 12 votes
Use Provide default value in the contextual filter.

also you can use php code for getting the value from url

# Answer
> 6 votes
If you want to pass arguments via GET in the URL you can use BEF module for this.

For example: `mydomain.com/your-view-path?field_a=valuea&field_b=valueb`

With Better Exposed Filters you need to add exposed filters (not contextual filter), check the expose this filter option and the GET variable name is below in more options. Then if you don't want to show the filter you can hide it in Better Exposed Filters Settings.

Don’t forget to enable Use Ajax option if your view is a block display.

The exposed filter style setting must be set on Better Exposed Filters instead of Basic.

It is very useful with view blocks.

---
Tags: views
---


# Question
Title: Why does drush rsync require a local site?
It's clearly documented that `drush rsync` requires one of the sites to be local. I'd like to understand why this restriction is in place. I have configured site aliases to work with `ssh`, and I'm able to ssh into a system and then launch `drush rsync`. Why can't do that?

# Answer
Drush just performs the following in commands/core/rsync.core.inc:

```
$exec = "rsync -e 'ssh $ssh_options' $options $source $destination";

```

This isn't compatible with rsync daemons, as stated in the rsync manual:

> you must not specify the --rsh (-e) option.

Now, if you want to use drush to rsync between two remote environments, you'll need to install Drush on the source, then:

```
drush rsync @remote.source @remote.target

```
> 6 votes

---
Tags: drush
---


# Question
Title: Drush makefile downloading 7.x Dev instead of stable
I have drush makefile that I use to kick off new Drupal installs:

**my\_profile.build**

```
core = "7.x"
api = "2"

projects[drupal][version] = "7.x"
; ... grab install profile

```

When I run `drush make my_profile.build` it downloads the 7.x-dev version of core instead of stable. I knew that I code force the download of dev versions with `projects[drupal][version] = "7.x-dev"` but how do I make sure that it only downloads the *stable* version of a project? My drush version is 5.7.

# Answer
To always specify the latest major version of Drupal, just use

```
projects[drupal][version] = 7

```

For modules and themes, just omit the version. For example:

```
projects[views][type] = module

```
> 4 votes

# Answer
Just put the exact version in the makefile:

```
projects[drupal][type] = core
projects[drupal][version] = "7.23"

```

Since it's auto selecting `-dev` (which isn't the default `stable` is) it sounds like your `drush.rc` file is tweaked to make `-dev` a default option ...
> 0 votes

---
Tags: drush
---


title: How to tell travis that test is failed?

text:
# Question
Title: How to tell travis that test is failed?
I am trying to integrate travis test bots to my module. Travis can run the test correctly, in console log, I can see drush run-test discover pass and fail assertions, but the final result is still passed. Is there any trick to tell Travis know that the test is fail?

My test code is: https://travis-ci.org/andytruong/at\_demo\_travis/builds/12999422

Thank you

# Answer
The test-run is outputting XML and reporting success on the generation, which is useful for Jenkins, but not Travis CI.

```
drush test-run --xml 'Andy Truong'

```

Change that to

```
drush test-run 'Andy Truong'

```

And you should be set.

For reference, see https://drupal.org/project/travis\_ci\_drupal\_module\_example and https://travis-ci.org/sonnym/travis-ci-drupal-module-example
> 2 votes

---
Tags: testing
---


title: Open form module from popup

text:
# Question
Title: Open form module from popup
I have a basic module that I made for a survey/email collection form for a site I'm building. I'm very new to drupal and drupal development and I'm trying to figure out how to open this module on the front page after a click on a button inside of a popup of some sort, I was thinking jquery modal or something of the sort. I can't figure out heads or tails from it and don't even know where to put anything. So far I just have the module files survey.info and survey.module. Do I have to modify theme files or what? Sorry for being so green but the development files online aren't very cut and dry.

# Answer
Welcome to Drupal!

Take a look at https://drupal.org/project/modal\_forms \- this performs the functionality that you've described and works with https://drupal.org/project/webform which you can use to build the survey.

I also recommend taking a look at https://drupal.org/project/examples to learn more about module building in general; it includes many practical examples.

If you want to use an existing form, check out the tutorial at http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 that describes how to use CTools Modal with existing forms.
> 2 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Drupal 7 inserting space before inline HTML tags upon rendering
Whenever I try to use `<a>`, `<em>`, `<sup>`, or `<sub>` tags (or probably any other inline tag), Drupal inserts a space before the HTML tag. This does not happen within the node but rather upon the HTML rendering.

For instance:

`234<sup>2</sup>` in the body field

is rendered as

`234 <sup>2</sup>` on the page

Any idea why this would be or what I can do to eliminate the space that is being added? I have TinyMCE installed on the site, but (long story) it is disabled so that I input everything in raw HTML.

# Answer
> 0 votes
If you use "Full HTML" text input rather than "Filtered HTML", then Drupal won't parse or modify your markup.

---
Tags: input-formats, theming
---


# Question
Title: Snippet to hide the editing of one vocab
I need a snippet that hides/omits the editing of a certain vocab on the node/edit form of a certain content type if they are not in a certain role. All the access modules are too heavy for just this small requirement.

# Answer
You will need to create a custom module with:

Drupal 6:

```
/**
 * implements hook_form_alter()
 */
MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'type_node_form') {

    global $user;

    // Check to see if $user has does not have the administrator role.
    if (!in_array('administrator', array_values($user->roles))) {
      //to turn all vocabularies off
      $form['taxonomy']['#access'] = FALSE;

      //turn off a single vocabulary *BELOW*
      //if you select 'tags' from your vocabulary settings
      if(issset($form['taxonomy']['tags']) {
        $form['taxonomy']['tags']['vid'] = FALSE;
      }
      else {
        //if you do not selet 'tags' from your vocabulary settings
        $form['taxonomy']['vid'] = FALSE;
      }
    }
  }
}

```

So there is 3 options, depending how your vocabularies are setup. You must subsitute 'vid' for the vocabulary id.

Drupal 7:

inside hook\_form\_alter() like

```
if ($form_id == 'type_node_form') {

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['name_of_field']['#access'] = FALSE;
  }
}

```
> 2 votes

# Answer
drupal 6

in hook\__form\_alter if role and content-type i set

$form\['taxonomy'\]\['vid'\]\['#access'\] = FALSE;

this seems to hide without removing and validates.
> 0 votes

---
Tags: 6, taxonomy-terms
---


# Question
Title: Printing outout of a view in to a field in user profiles
I have created a view which prints only usernames of registered users .

In user registration there is field named "father username" . i want that field to be populated as a list from the above view .

i used view reference , but it just shows all the views in the site .

any clue ? thanks :)

# Answer
I'll make an assumption, and answer based on the assumption. The assumption is that the field "Father username" is an entity reference field, and you want to use the view of registered users to populate the options for that field.

If that is so, you need to create an "entity reference" view display, then refer to that view display in the field settings of the "father username" field.
> 1 votes

---
Tags: views, users
---


# Question
Title: Using Panels and Views to Display Information from Entity Reference
I'm currently work on a site that manages retail stores and visits made by salespeople to those stores.

I have the following two content types:

**Store:**
contains basic store information: address, phone number, etc

**Sales Survey:**
date of sales call
salesperson
general info gathered on call
**Entity Reference to the Store**

I'm currently working with panels to create a custom display for the store content type and I would like to include a section showing the 5 most recent sales calls made to that store and the information about that call.

I've been trying to create a content pane in views to include in the panel for the store node display, but I can't figure out how to access all **Sales Surveys** that *reference* the store that is currently being displayed.

Any thoughts?

I'm using:
Drupal 7
Panels3
Views 3
Entity Reference

Let me know if I can provide further clarification, I think part of my problem is just in wrapping my mind around all the things I'm trying to bring together and I'm still very new to Drupal. Maybe I'm going at this in the wrong way?

Any help is appreciated!

# Answer
First, you need to create a view (probably block display) of the sales surveys, with a contextual filter. Create a new view of Sales surveys, with a block display. Add whatever fields you want to the display. Then, open the "advanced" tab, and add a contextual filter:

* choose the field that you've named as the entity reference to the store
* provide a default value -\> "content ID from URL"

Once you save that view, go into panels, and add that view to the page you are creating for the stores.
> 1 votes

---
Tags: views, panels, entities
---


title: Display the full URL of the home page?

text:
# Question
Title: Display the full URL of the home page?
Is it possible to display the full, absolute URL of the home page in Drupal 7, like www.example.com/The-best-example-possible ?

I'd like to display the full URL of the home page, not just the hostname.

# Answer
In Drupal 7, The front page is normally set via `system_site_information_settings()`. It is an unaliased URL, so it is best to use the API. I would do it as:

```
$home = url(variable_get('site_frontpage', 'node'), array('absolute' => TRUE));

```

In Drupal 8, there is a special route `<front>` that you can use with the `Url()` object

```
use \Drupal\Core\Url;

$home = Url::fromRoute('<front>')->setAbsolute()->toString();

```

However, in most circumstances you don't need to explicitly render out `Url()` objects as strings; you can just use the object itself.
> 5 votes

# Answer
```
global $conf, $base_url;
echo $base_url . '/' . variable_get('site_frontpage', 'node');

```

For details, see https://api.drupal.org/api/drupal/developer!globals.php/global/base\_url/7 and https://api.drupal.org/api/drupal/includes!path.inc/function/drupal\_is\_front\_page/7
> 2 votes

---
Tags: 7, uri
---


title: Metatag won't work for homepage?

text:
# Question
Title: Metatag won't work for homepage?
The Metatag Module inputs (Such as Description, Abstract, ETC, and that includes Page Title) won't trigger on the home page.

I already read in a forum thread that didn't give an in-program solution. I assume it's a solved problem, because it affects almost any site.

How can one solve it?

# Answer
> 1 votes
According to https://drupal.org/node/1848184#comment-6801690

> Check if you have the code for the main content on the homepage .tpl file:
>
> `<?php print render($page['content']); ?>`

---
Tags: 7, meta-tags
---


title: Render a field in node_preprocess

text:
# Question
Title: Render a field in node_preprocess
I need to order my field in a node\_preprocess to display it in a ul.

I have this field:
body,
field\_cover\[image\],
field\_gallery\[2 imgs with title..\],
field\_video \[a link list.. rendered with videojs module\],
field\_video\_desc \[a text field..\]

I need to render they in 2 lists:

```
function mytheme_preprocess_node(&$variables){

  $rendered_field = mytheme_field_HTML($variables);

  $element = array (
     $rendered_field['field_cover'],
     $rendered_field['field_gallery_0'],
     $rendered_field['field_gallery_1'],
     $rendered_field['video'] );

  $text = array (
     $rendered_field['body'],
     $rendered_field['field_gallery_0_title'],
     $rendered_field['field_gallery_1_title'],
     $rendered_field['video_desc'] );

  $variables['elements'] = theme_item_list(array('items' => $element, 'type' => 'ul'));
  $variables['texts'] = theme_item_list(array('items' => $text , 'type' => 'ul'));
}

```

but I need to write mytheme\_field\_HTML() function and I don't understand how, using Field API, I can retrive the HTML according the default field display used in the current node.

How can I achieve this?

# Answer
> 1 votes
What about leaving the rendering of fields by Drupal and putting your list directly in the template?

Depending the condition about your node rendering, can be based on 1 particular node, or by content type, ... you can use a separate `tpl` file. For example, if its for a content type `gallery`, you can create a `node--gallery.tpl.php` in the `templates` folder of your activated theme.

Inside the tpl, you can create an HTML structure like this:

```
<!-- content node part -->
<div class="content"<?php print $content_attributes; ?>>
    <ul>
        <li><?php print render($content['field_cover']); ?></li>
        <li><?php print render($content['field_gallery_0']); ?></li>
        <li><?php print render($content['field_gallery_1']); ?></li>
        <li><?php print render($content['video']); ?></li>
    </<ul>
    <ul>
        <li><?php print render($content['body']); ?></li>
        <li><?php print render($content['field_gallery_0_title']); ?></li>
        <li><?php print render($content['field_gallery_1_title']); ?></li>
        <li><?php print render($content['video_desc']); ?></li>
    </<ul>

    <!-- remaining unrendered fields -->
    <?php print render($content); ?>
</div>

```

---
Tags: 7, entities, theming
---


# Question
Title: Why is $base_url = http://{$_SERVER['SERVER_NAME']} in settings.php? Will this cause any problems?
I saw this on a legacy website and I am not sure why our sys-admin insists on doing it this way. While most things are working fine, I wonder how will this affect the site, for example, I know the $\_SERVER is not defined on cli and every time I execute a drush command it gives me `parse_url(http:///example): Unable to parse URL in drupal_settings_initialize() (line 718 of [warning]
path/to/includes/bootstrap.inc).`

# Answer
If the site is served by a single application server and that name will never change, then this isn't wrong, but not the way I would do it.

If you want to use SERVER\_NAME and avoid issues if it's not initialized:

```
$base_url = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';

```

Or, instead of empty quotes, specify the server name if it doesn't change.
> 1 votes

---
Tags: configuration
---


# Question
Title: What is the difference between Pantheon DROPS and vanilla Drupal?
Is it just the added config wrappers, or is the Drupal site code itself changed? Are there any changes to Drupal module and filesystem compatibility compared to a more traditional Drupal hosting environment?

# Answer
> 10 votes
Pantheon's variant of Drupal is openly hosted on GitHub:

https://github.com/pantheon-systems/drops-7

The main variation that matters is in `drupal_settings_initialize()`:

https://github.com/pantheon-systems/drops-7/blob/master/includes/bootstrap.inc#L720

This is how Pantheon runs sites without making users handle DB or Redis credentials. This change is now in Pressflow as well.

The other material addition is an apachesolr integration package and a way for the site to query the Pantheon API. Those are in modules/pantheon.

The good news is none of this will prevent a site from working anywhere else. The changes are all designed to revert to normal when not on Pantheon.

---
Tags: 7
---