# Question
Title: Conditional views exposed filters (using Search api views)
I have two views exposed filters,one dropdown field and a checkbox. I want,when the checkbox is checked the dropdown field to dissappear.When I uncheck the checkbox I want the dropdown field to appear again.

First I tried Views dependent filter,however it doesn't play well with Search api views.

Secondly I tried with javascript.I wrote this code and added it to the .js file of my theme.However it doesn't also work.How can I do this?

```
(function ($) {
  Drupal.behaviors.cdgi = {
    attach: function(context) {

      var $('#edit-field-level-of-telecommuting-1').prop('checked') = true;
      if ($('#edit-field-level-of-telecommuting-1').prop('checked') === true) {
        $('#edit-field-job-region-parents-all').hide();
      } else {
        $('#edit-field-job-region-parents-all').show();
      }
    }
  }
}(jQuery));`

```

# Answer
> 0 votes
I finally found the solution to my problem using this code:

```
$('your selects class or id').change(function(){
if($(this).val() == "publish_on"){
    $('.secret').fadeIn();
}
else{
    $('.secret').hide();
}

```

});

# Answer
> 1 votes
There is a slight change in the code.May be this can help you.

```
(function ($) {
  Drupal.behaviors.cdgi = {
    attach: function(context) {
     $(function () {
      $('#edit-field-level-of-telecommuting-1').click(function() {
        if ($(this).prop("checked")) {
          $('#edit-field-job-region-parents-all').hide();
        } else {
          $('#edit-field-job-region-parents-all').show();
        }
      });
     });
    }
  }
}(jQuery));`

```

check more info how to include js file

---
Tags: views
---


# Question
Title: Splitting up content fields into different regions
My situation is as follows: I have a content type Seminar, with fields A, B, and C. I have regions Header, Footer, Content, and Sidebar Left. There are some fields in Seminar I want displayed in the Content region, but also in the Sidebar Left region.

How do I go about doing this? Apologies if this has already been answered before. I am a developer and am not hesitant to dive into hook and preprocessor functions. I have the Views module installed, but have never used it (this is my first Drupal site, if you can't tell :P).

Cheers.

EDIT: This is for **Drupal 7**.

# Answer
> 11 votes
There is no easy out of the box way to add the content of a node to different regions on the page. There is multiple ways to tackle this problem.

**Non-coding way: Views & Blocks**

Create a view

* Type: Block
* Contextual Filter: Content: Nid
+ default value: grab from current page
* Fields: Whichever you want
* Filter:
+ Content Type: Seminar

(plus whatever additonal settings you want)

Then go to administrator block page Move the newly create view block, to the region you want it displayed. It should only display on the seminar node pages.

Repeat for all regions

**Coding Way with theme\_preprocess\_region():**

code would look something like this

```
MYTHEME_preprocess_region(&$variables) {
  if (isset($node) && ($node->type == 'seminar' )) {
     //add new variable here.
  }
}

```

This is for Drupal 7 only. Now its avaiable in your region.tpl.php.

# Answer
> 7 votes
The Display Suite module allows you to do this. You'll need to enable the Display Suite Extras module to expose theme regions as targets for node components. Information on how to do this can be found in the Add fields to a block page of the Display Suite documentation

# Answer
> 5 votes
I've had the same problem. The solution is quite easy. You can base the fact that in Drupal 7 we can define our own view\_mode, not only FULL and TEASER (as we know from oldest versions). So, define another view\_mode for using in your region: e.g. LEFTHAND. Drupal displays FULL view\_mode in content region. So, you have to say to Drupal to display LEFTHAND in Sidebar Left region.

1. In template\_preprocess\_page()

> `if ($vars['node']) {
> $vars['page']['sidebar_left'][] = node_view($vars['node'], 'lefthand');
> }`
2. In node.tpl.php add a new display for lefthand view mode

> `if ($view_mode == 'lefthand') {
> // render content fields here
> }`

# Answer
> 3 votes
If Display Suite seems like too much for you needs (It is a great module, but it might be overkill if you just need to relocate a few fields) there is a module for only this purpose -\> CCK Blocks.

I know it is called 'CCK' blocks, but it works with Drupal 7 (which brought the functionality of CCK to the core).

# Answer
> 1 votes
Slight change to @Patrik Lucan's answer, `if ($vars['node'])` was causing me problems on pages which weren't nodes, e.g. custom front page with block or views page.

Changed to:

`if (array_key_exists('node', $vars))`

Which seems to have solved the problem.

# Answer
> 0 votes
Meanwhile there's a module for this. From the module page:

> Field as Block provides an easy way to display one or more fields of the current node in a block.
>
> This module aims to be a light weight alternative to modules like Panels and Display Suite, or using Views to define a block which only retrieves one field.

---
Tags: views, theming, nodes
---


# Question
Title: How to export content to XML, CSV or RTF for print
I'd like to export a (views)-list of events to re-import it with Indesign or Pagemaker, so XML, CSV or RTF-format would be great. The list should be restricted to one, the current month (this is no problem with views or even views bulk operations). The important thing is: the events must be grouped by the event-day and their respective categories (concert, theatre).

I already tried the Views Data Export module, but there is no way of grouping the fields. So every "event" has all it's fields in one column.

Is there another module you could recommend or do i have to do this programmatically (which I can't unfortunately).

Thanks in advance for every hint...

**Update** Thanks to WestieUK i installed the Views Data Source module, which is working great, but not as expected. There's also no grouping of fields (at least not obvious).

So this is what i have:

```
<root>
    <events>
       <eventdate>21/7/2012</eventdate>
       <categorie>Clubland</categorie>
       <location>Club A</location>
       <title>Klanglabor</title>
       <time>21:00</time>
    </events>
    <events>
       <eventdate>21/7/2012</eventdate>
       <categorie>Clubland</categorie>
       <location>Club B</location>
       <title>Soundlabor</title>
       <time>21:00</time>
    </events>
</root>

```

I'd like to have it something like this:

```
<root>
   <eventdate date:21/7/2012>
       <categorie name:Clubland>
           <events>
              <location>Club A</location>
              <title>Klanglabor</title>
              <time>21:00</time>
           </events>
           <events>
              <location>Club B</location>
              <title>Soundlabor</title>
              <time>21:00</time>
           </events>
       </categorie>
    </eventdate>
</root>

```

Any ideas? If this can be achieved prorgammatically, like making a custom module (based on perhaps the Views Data Source module), I'd give it a try with your help!

Thanks!

# Answer
Views Data Source is pretty awesome for XML, the 7 release is in dev but we are using it on our D7 to create feeds for android / iphone apps and a intranet running D6.
> 3 votes

# Answer
I would advise to use Services module together with the Services Views

1. After installing the modules create the view with the fields in the sort order you need.
2. Define the needed end points
3. Get your XML by for example: http://example.com/rest/views/events
> 1 votes

# Answer
Under your `Format` , choose `Field`. Then keep the format `unformatted list`. Right next is the `settings`, there select `event date` as grouping field nr 1 and then select `categories` in grouping field nr 2.

Check `Remove tags from rendered output` on both options

Hopefully this should properly format your views display to what you are looking for.
> 0 votes

# Answer
Another option to consider for addressing these requirements is the Forena module.

You would use it's report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV or XML file. Did I mention it also comes with some interesting hooks?

Refer to Reasons for considering Forena to understand why I think it might be a good fit, especially because of this part in it:

> ... if you want to do **aggregation** or analytics, Forena is much more suited to address these requirements."

The Forena Video demos and tutorials contain quite some links to live demos.

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: 7, views, importing-exporting
---


# Question
Title: How to restrict a page to a group of people?
I am trying to figure out how I can lock down a page (part of my site) to a list of users that I have in another MySQL DB.

Ideally I would like to call the DB and see if the user has access each time they login. Is there any modules that would do this? Or has anyone done anything similar before.

# Answer
You can add the secondary database to Drupal by following this tutorial: https://www.drupal.org/node/18429

I would probably run a `hook_node_view` so that it's called before rendering the node and adding your custom logic there.
> 1 votes

---
Tags: database, taxonomy-terms, users
---


# Question
Title: Views show fields is set, but only "Content" options are available to select - why?
Simple question. I thought I knew views, but right now I'm stuck. All I want is a view with the body field of a certain content type.

I have "Fields" selected:

But when I go to add a field, my options are severely limited:

(There is no such thing as a "Content: Body" option to select.)

What happened to the rest of the categories in the Filter dropdown? I'm missing something obvious here...?

# Answer
> 2 votes
The `Content: Body` field should be there as long as it exists in the content type.

A couple things you can try in this order:

1. Ensure all permissions are set properly
2. Flush all caches
3. Flush the views cache at `/admin/structure/views/settings/advanced`
4. Disable views cache just to see if that's an issue
5. Update Views

Here's a current issue of the problem

---
Tags: views
---


# Question
Title: Want to process node edit in two different ways
On every node page there is an edit and submit, you can set when the edit is available and such.

So, what I want to do is this.

When a regular user uses the edit button(which I want to be available for all site users), I want it to open the node and allow someone to directly edit it. Just like when the owner edits it, it will open everything and allow the user to make changes. But instead of actually saving the changes to that node, I want it to create a new node that copies the old one and saves this other user's changes.

When a moderator or the creator of the node edits, I want it to edit the node directly and saves the changes to that specific node.

I need to either create two buttons that show up differently on page for certain users, or use the same button but use some form validation technique to check the permissions of who is submitting the form and do the above accordingly. Are there any ideas? Any help is greatly appreciated!! Thanks

# Answer
> 0 votes
You can use revisioning module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

Using this module when you edit a node, a new revision is created and it goes to modaration mode.

For more info check the module page

---
Tags: forms
---


# Question
Title: Is it safe and correct to run Drush under the same user account that the webserver runs on?
I've found following informaion:

> It's usually considered best practice to run Drush under the same user account that the webserver runs on (such as www-data). Some modules, such as XML Sitemap, Advanced Aggregator and cTools, often try to alter or generate files.

I also have some problem with Ctools cache.
I can use following command to run Drush under the www-data user:
`sudo -u www-data drush....`

But is it safe and correct to run Drush under the same user account that the webserver runs on?

# Answer
> 3 votes
In general, the answer is "yes", it is safe and correct. However, the specific answer here depends on (a) your security policy, and (b) what you want to do with Drush. Some people prefer to make the code files not writable by the web server. If you had a setup like that, then you would not be able to run `drush dl` as the webserver user.

The other thing of note here is that any time you run any Drush command, all Drush commandfiles are given the opportunity to alter the command's behavior. This means that it is generally NOT considered safe to run drush via `sudo` to root, unless you trust all of the code in your Drupal site to run as the root user. This is not generally a concern for `sudo -u www-data`, though, as you are already trusting the code in your Drupal site to run as the web user.

---
Tags: drush
---


# Question
Title: How to set up registration for event with parallel sessions?
I would like to set up the registration for an event. During the event there are various parallel sessions.

(I was thinking in using the entity registration module)

Needs / problems encountered: The (registered) user needs to chose the session he/she would like to attend (shouldn´t be possible to sign in for sessions given at the same time!) Each session has a maximum capacity.

Any idea how to achieve this?

Thanks in advance

# Answer
Make a node type for sessions, then add the registration field to it. You should make a small module which compares a time/date range/duration field on your session node types to ensure the user cannot register for sessions that are conflicting.

If you have multiple events on your site, consider making a node-reference field to another node type: "events". Then update your session conflict module to take events into account.

This is for Entity Registration (D7)
> 0 votes

---
Tags: users, entities
---


title: Drupal commerce price: allow null value

text:
# Question
Title: Drupal commerce price: allow null value
I have an e-commerce site with drupal commerce kickstart and I added an additional field called "list price" and setted it as Price field (the same type of the default price).

Now I'm trying to update some of these prices via drupal views and VBO but I can't set them to NULL, I have an error: "Integrity constraint violation: 1048 Column 'field\_list\_price\_amount' cannot be null"

But if I change that price manually via the standard windows and leaving the field empty, drupal accepts the update, why?!

Via VBO I can update normal prices (increase, decrease and more other things) but I can't reset them to its default values...

# Answer
> 0 votes
This would be because an empty value and NULL are two different things to a database. Deleting the value in the UI is not the same as setting it to be NULL. That field is stored in the database with the setting that I cannot be NULL and so the VBO operation is failing.

---
Tags: commerce
---


# Question
Title: Views 3 | How to programatically unset or add new value to a view's footer / header display?
I have added 1 view display into my view's footer via "`Global: View area | The view to insert into this area.`" and a regular "`Global: Text area`".

So my view has 2 footer displays, one being another view display and the other a normal text area.

Now I want to unset/hide either one of the footer display based on a condition, perhaps via hook\_views\_pre\_render()

I was expecting to find documentation on something like:

```
$view->display['MY_VIEW_DISPLAY_ID']->handler->handlers['footer']['FOOTER_DISPLAY_ID']->unset_display();

```

But obviously that is not the way to go. Is it possible to accomplish that via hook\_views\_pre\_render() or any other means? If so, how?

# Answer
The snap code below has been tested only on D7. In case this code does not work on D6, check out the comments on this post here.

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {

    // To find out the DISPLAY_NAME, FIELD_NAME and FIELD_VALUE use the devel module function
    // below to print them out.
    // Replacing 'footer' by 'header' works the same way.
    dpm($view->display_handler->options['footer']['DISPLAY_NAME']['FIELD_NAME']);

    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'FIELD_NAME', 'FIELD_VALUE');

    // In this case scenario you needed to unset the footer display.
    // For the embedded view display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'view_to_insert', '');
    // For the normal text area display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'content', '');
  }
}

```

---

Due to comments, to determine what views name and display came to this function, make next (of course, "devel" module should be enabled)

```
    function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
      dsm($view->name);
      dsm($display_id);
      if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {
...
      }
    }

```

And update views page.
> 10 votes

# Answer
Views 3 example of adding some text to existing header programatically:

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  $header_item = $view->get_item('default', 'header', 'text');
  $view->set_item_option('default', 'header', 'text', 'content', 'MY TEXT' . $header_item['content']);
}

```

Here is another example using `hook_views_pre_view`:

```
/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view') {
    // Unset: Global: Text area
    $view->display_handler->set_option('empty', NULL);

    /* Programatically update the 'No results behavior' by inserting another view. */

    // Example 1
    $options = array(
        'id' => 'view',
        'table' => 'views',
        'field' => 'view',
        'empty' => TRUE,
        'view_to_insert' => 'new_view:page',
    );
    $view->display_handler->set_option('empty', array('view' => $options));

    // Example 2
    $view->set_item_option($display_id, 'empty', 'view', 'id', 'view');
    $view->set_item_option($display_id, 'empty', 'view', 'table', 'views');
    $view->set_item_option($display_id, 'empty', 'view', 'field', 'view');
    $view->set_item_option($display_id, 'empty', 'view', 'empty', TRUE);
    $view->set_item_option($display_id, 'empty', 'view', 'view_to_insert', 'new_view:page');
  }
}

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: Views 2 - Embed a View inside Empty Text of another View
I want to embed a View (or a display of a View) inside another display of View when these view has no results. I figure out that I can embed a View inside the 'Empty Text' filed. I must say that I can show some php `echo "hello world";` using this 'Empty Text' filed, but when I try to embed a View, I can not embed a another View or display of View.

this is one example that I used, but without results:

```
$viewName = 'test_view';
$display_id = 'page_1';
print views_embed_view($viewName, $display_id);

```

# Answer
> 1 votes
In D7, Views 3 you can enable "NO RESULTS BEHAVIOR" which is under the "Advanced" tab. Here you can add "Global: View area" (or just "hello world" as a text area for testing) which will allow you to display a view when there isn't any results.

If you want this is code, you can always export the View after it is configured and see how it was done.

# Answer
> 1 votes
nMill's answer is great for Views 3.

I put together a solution that involves a bit more work for Views 2 (and there might be an even better way to do this). I'm using hook\_views\_pre\_render and the views\_embed\_view function to do this.

In your custom module, insert

```
function mymodule_views_pre_render(&$view) {
    switch($view->name) {
        case 'parent_view_name':
            if (empty($view->result)) {
                            $attachment = views_embed_view('view_to_insert', 'default');
                $view->attachment_after = $attachment;
            }
        break;
    }
}

```

Clear the cache and your new view should appear if there are no results in the parent view.

# Answer
> 1 votes
This has been added in Views 3 and can be found in 'No results behavior' where you can add 'View area' which would be inserted on empty results.

Here is example how to do it programatically by using `hook_views_pre_view`:

```
/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view') {
    // Unset: Global: Text area
    $view->display_handler->set_option('empty', NULL);

    /* Programatically update the 'No results behavior' by inserting another view. */

    // Example 1
    $options = array(
        'id' => 'view',
        'table' => 'views',
        'field' => 'view',
        'empty' => TRUE,
        'view_to_insert' => 'new_view:page',
    );
    $view->display_handler->set_option('empty', array('view' => $options));

    // Example 2
    $view->set_item_option($display_id, 'empty', 'view', 'id', 'view');
    $view->set_item_option($display_id, 'empty', 'view', 'table', 'views');
    $view->set_item_option($display_id, 'empty', 'view', 'field', 'view');
    $view->set_item_option($display_id, 'empty', 'view', 'empty', TRUE);
    $view->set_item_option($display_id, 'empty', 'view', 'view_to_insert', 'new_view:page');
  }
}

```

---
Tags: views, nodes
---


# Question
Title: Saving values of a multistep form into custom entity fields
I'm building a module that implement a multistep form based on a custom entity. The entity contains fields which are created by the install file.

I was able to create the steps and if I print the $form\_state\[storage\] array in the last step I can see all the values entered all along the form.

But when I submit the last step the entity is empty. This is what I have in the last\_step\_submit:

```
$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();
drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
$form_state['redirect'] = 'admin/organisations';

```

I know that I'm missing something but really I can't figure out what. I'm quite new in module developing and I'd appreciate any help.

# Answer
> 0 votes
After struggling for a couple of days I finally was able to store the values in the entity.

The first mistake was that I forgot to pass my entity ('organisation') as an argument in the primary hook\_form:

```
  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;

```

The second was that I had to build and save my entity each step with the code I attached in this question.

```
$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();

```

Now I have my custom entity with custom fields and a multistep conditional adding form!

This is the code if someone else need the same functionality. Primary form and submission functions:

```
function organisation_form($form, &$form_state, $organisation) {
  if ($form_state['rebuild']) {
      $form_state['input'] = array();
  }
  if (empty($form_state['storage'])) {
// No step has been set so start with the first.
   $form_state['storage'] = array(
      'step' => 'organisation_first_form',
   );
  }
// Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;
}

function organisation_form_submit($form, &$form_state) {
 $values = $form_state['values'];
 if (isset($values['back']) && $values['op'] == $values['back']) {
   // Moving back in form.
   $step = $form_state['storage']['step'];
   // Call current step submit handler if it exists to unset step form data.
   if (function_exists($step . '_submit')) {
     $function = $step . '_submit';
     $function($form, $form_state);
   }
// Remove the last saved step so we use it next.
$last_step = array_pop($form_state['storage']['steps']);
$form_state['storage']['step'] = $last_step;
  }
  else {
   // Record step.
   $step = $form_state['storage']['step'];
   $form_state['storage']['steps'][] = $step;
   // Call step submit handler if it exists.
   if (function_exists($step . '_submit')) {
      $function = $step . '_submit';
      $function($form, $form_state);
   }
  }
return;
}

```

This is one of the steps and its submission function.

```
function organisation_second_form($form, $form_state, $organisation) {
  $form['#parents'] = array();
  // These variables are needed to build field forms.
  $entity_type = 'organisation'; // Substitute with any entity type.
  $bundle_name = 'organisation'; // Substitute with the entity's bundle.
  $entity = $organisation;
  $langcode = LANGUAGE_NONE; // Substitute as appropriate.

  $field_name = 'hub_position_activities';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $field_name = 'hub_market';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('organisation_second_form_submit'),
    '#weight' => 499,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#weight' => 500,
  );
  return $form;
}

function organisation_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['hub_position_activities'])) {
      $form_state['storage']['hub_position_activities'] = $input['hub_position_activities'];
    }
    if (isset($input['hub_market'])) {
      $form_state['storage']['hub_market'] = $input['hub_market'];
    }
    $form_state['storage']['step'] = 'organisation_first_form';
  }
  else {
    $form_state['storage']['hub_position_activities'] = $values['hub_position_activities'];
    $form_state['storage']['hub_market'] = $values['hub_market'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    $form_state['storage']['step'] = 'organisation_third_form';
  }
}

```

And the last submission function.

```
function organisation_last_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  if (isset($values['back']) && $values['op'] == $values['back']) {
    $form_state['storage']['step'] = 'organisation_second_form';
    $form_state['rebuild'] = TRUE;
  }
  else {
    $form_state['storage']['hub_equipment_measurement'] = $values['hub_equipment_measurement'];
    $form_state['storage']['hub_equipment_software'] = $values['hub_equipment_software'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
    $form_state['redirect'] = 'admin/organisations';
  }
}

```

Perhaps there were easier way to achieve this goal but, so far, is the only one that worked for me. If anyone has better solutions I'm eager to know them.

Thanks to **Alex Weber** for his great tutorial on how to get the form for existent fields http://www.alexweber.com.br/en/articles/how-manually-add-entity-field-forms-custom-drupal-form and to **Bryan Jones** for his Multi-step form tutorial http://bryanjones.us/article/custom-multi-step-forms-drupal-7

---
Tags: entities
---


# Question
Title: How do import and save term lineage using feeds and Hierarchical select?
I have to import a number of nodes that only has the lowest term in the csv

e.g. Washington

However, in the taxonomy hierarchy it has United States \> Washington

I am using the Hierarchical select module for saving the term lineage however when I use feeds it tries to import the child term as the parent term and doesn't actually select anything.

How do I use feeds and Hierarchical select to import just the child term but save the entire lineage?

The closest I can come to is https://www.drupal.org/node/1319278 however the csv mush contain the lineage, whereas in this case we only have the lowest possible child term.

# Answer
I did some more research and testing decided to use the Term Set Lineage module so that it is set on import, then just changed to use the Hierarchical select module.
> 0 votes

---
Tags: feeds, taxonomy-terms
---


# Question
Title: How to minimize conflicts in hook_update_N implementations with multiple developers?
I work on a team with multiple developers and we use hook\_update\_N functions in a "miscellaneous" module to make updates such as module or theme enabling/disabling, performing miscellaneous database updates, one-off variable assignments, and more. We often encounter conflicts when having code reviews, since multiple feature branch pull requests get approved around the same time, many with hook\_update\_N implementations that use the same number (N). The process of resolving the conflicts is slow because each conflict has to be resolved in series.

One option would be to have each developer create their own "glue" module and put their hook\_update\_N implementations in that module's .install file, but it seems wasteful to run multiple modules as a workaround for this problem.

Anyone have a good solution to avoiding or minimizing the conflicts?

# Answer
> 0 votes
A low tech solution I can think of would be to set up a wiki page where developers can "reserve" hook\_update\_N numbers for that site, and set up a procedure that everyone has to go to that page first and check for the next available number before starting work on an update hook.

---
Tags: updating
---


# Question
Title: Using orderBy correctly with hook_query_alter
I have a hook\_query\_alter function that I'm using to edit my search.module results. It works ok so far. However, I'm having trouble adding an orderBy condition that I need. Here's the SQL I want added that I'm using successfully elsewhere in a custom module:

```
    ORDER BY ('fdfty.field_type_value' = 'Webinar'),
('fdfty.field_type_value' = 'Workshop'),
('fdfty.field_type_value'= 'Conference'),
fdfed.field_event_dates_value, n.title

```

That's accepted SQL for ordering by specific values. However, when I try to add something similar to my query\_alter function orderBy clause, like so:

```
$query->orderBy('fdft.field_type_value' = 'Conference');

```

Well, Drupal doesn't like the '=' sign being in there. Is there another way to include such normal SQL criteria in hook\_query\_alter?

Thanks!

Here's the complete code I'm working with in template.php:

```
// function for search results page to return correct results that meet business logic
function zen_pathfinder_query_alter(QueryAlterableInterface $query) {
    if (get_class($query) == 'PagerDefault') {
        foreach ($query ->getTables() as $table) {
            if ($table['table'] == 'search_index') {
                $query->leftjoin('field_data_field_event_dates', 'fdfed', 'n.nid = fdfed.entity_id');
                $query->leftjoin('field_data_field_type', 'fdft', 'n.nid = fdft.entity_id');
                $query->where('fdfed.field_event_dates_value >= CURRENT_DATE OR fdfed.field_event_dates_value IS NULL');
                    //->groupBy('fdft.field_type_value');
                $query->addField('fdft', 'field_type_value');
                $sql = 'CASE WHEN fdft.field_type_value = :first THEN 0
                WHEN fdft.field_type_value = :second THEN 1
                WHEN fdft.field_type_value = :third THEN 2
                WHEN fdft.field_type_value = :fourth THEN 3
                WHEN fdft.field_type_value = :fifth THEN 4
                WHEN fdft.field_type_value = :sixth THEN 5
                WHEN fdft.field_type_value = :seventh THEN 6
                WHEN fdft.field_type_value = :eighth THEN 7
                WHEN fdft.field_type_value = :ninth THEN 8
                WHEN fdft.field_type_value = :tenth THEN 9
                END';
                $query->addExpression($sql, 'my_alias', array(
                ':first' => 'Webinar',
                ':second' => 'Workshop or Training',
                ':third' => 'Conference',
                ':fourth' => 'Article or Report',
                ':fifth' => 'Blog',
                ':sixth' => 'Podcast or Webcast',
                ':seventh' => 'Newsletter or Magazine',
                ':eighth' => 'Tool',
                ':ninth' => 'Book or Workbook',
                ':tenth' => 'Certificate or Degree Program' ,
                ));
                $query->orderBy('my_alias');
                $query->orderBy('fdfed.field_event_dates_value');
                $query->orderBy('title');
            }
        }
    }
}

```

I keep getting a "Column not found: 1054 Unknown column 'my\_alias' in 'order clause" error when I go to the search page. So I ran dpm((string) $query); and the results are as follows:

```
      SELECT SUM(i.score * t.count) AS calculated_score
        FROM
        {search_index} i
        INNER JOIN {node} n ON n.nid = i.sid
        INNER JOIN {search_total} t ON i.word = t.word
        WHERE  (n.status = :db_condition_placeholder_0) AND( (i.word =
:db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND (n.type NOT
IN  (:db_condition_placeholder_3, :db_condition_placeholder_4,
:db_condition_placeholder_5))
        GROUP BY i.type, i.sid
        HAVING  (COUNT(*) >= :matches)
        ORDER BY calculated_score DESC
        LIMIT 1 OFFSET 0

        SELECT fdft.field_type_value AS field_type_value, CASE WHEN fdft.field_type_value =
    :first THEN 0
                        WHEN fdft.field_type_value = :second THEN 1
                        WHEN fdft.field_type_value = :third THEN 2
                        WHEN fdft.field_type_value = :fourth THEN 3
                        WHEN fdft.field_type_value = :fifth THEN 4
                        WHEN fdft.field_type_value = :sixth THEN 5
                        WHEN fdft.field_type_value = :seventh THEN 6
                        WHEN fdft.field_type_value = :eighth THEN 7
                        WHEN fdft.field_type_value = :ninth THEN 8
                        WHEN fdft.field_type_value = :tenth THEN 9
                        END AS my_alias
        FROM
        {search_index} i
        INNER JOIN {node} n ON n.nid = i.sid
        INNER JOIN {search_total} t ON i.word = t.word
        LEFT OUTER JOIN {field_data_field_event_dates} fdfed ON n.nid = fdfed.entity_id
        LEFT OUTER JOIN {field_data_field_type} fdft ON n.nid = fdft.entity_id
        WHERE  (n.status = :db_condition_placeholder_0) AND( (i.word =
    :db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND (n.type NOT
    IN  (:db_condition_placeholder_3, :db_condition_placeholder_4,
    :db_condition_placeholder_5)) AND (fdfed.field_event_dates_value >= CURRENT_DATE OR
    fdfed.field_event_dates_value IS NULL)
        GROUP BY i.type, i.sid
        HAVING  (COUNT(*) >= :matches)
        ORDER BY my_alias ASC, fdfed.field_event_dates_value ASC, title ASC

```

# Answer
You can use `SelectQueryInterface::addExpression` to add a CASE statement to the select and then order by that:

```
$sql = '
  CASE WHEN fdfty.field_type_value = :first THEN 0
       WHEN fdfty.field_type_value = :second THEN 1
       WHEN fdfty.field_type_value = :third THEN 2
  END';
$alias = $query->addExpression($sql, 'my_alias', array(
  ':first' => 'Webinar',
  ':second' => 'Workshop',
  ':third' => 'Conference',
);
$query->orderBy($alias, ASC);

```
> 4 votes

# Answer
Have a look at the API.

orderBy in Drupal doesn't accept operators. Instead it should be:

```
$query->orderBy('fdft.field_type_value', ASC);

```

I suggest either sorting by the key or weight of the field value (if there is one).
> 3 votes

---
Tags: theming, search, database
---


title: Use exposed filters to reorder nodes?

text:
# Question
Title: Use exposed filters to reorder nodes?
Just wondering whether I can use exposed filters to re-order a list of nodes rather than eliminating ones that don't fit the desired criteria.

E.g. If I filter for 'Monday' and have a list of nodes \[Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday, Monday\], then I would like the list of nodes to return as Monday, Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday.

At the moment my result when I filter for the term 'Monday', is just 'Monday'.

Any thoughts?

Cheers!

# Answer
Depending on your display requirements, you might be able to use a table format. When using a table format, you have the option to set columns to "sortable".

Format section:

Sorting settings:
> 2 votes

---
Tags: views
---


# Question
Title: Error in Views override template "Notice: Undefined offset: 1 in include()"
So I am theming a View with a template in my theme folder.

I am getting this error message:

"Notice: Undefined offset: 1 in include()"

This is the code:

```
<?php print ($fields["title"]->content); ?>

```

I've tried adding an IF statement like below (is my syntax correct???) and clearing the cache but the issue persists:

```
<?php if ($fields["title"]->content) { print ($fields["title"]->content); } ?>

```

P.S. the field is printing, it's just that there is an error message displayed in addition.

Also, by the way, I am using views-view-fields.tpl.php

# Answer
> 0 votes
You need to use `isset()` to avoid such notices:

```
<?php if (isset($fields["title"])) { print ($fields["title"]->content); } ?>

```

---
Tags: 7, views, theming
---


# Question
Title: Custom form with Date textfield with jQuery popup
I'm making a custom form and I would like to render a field that is just like the form that gets rendered for a Date with a jQuery Popup when editing a node.

I can't figure out how to build the array so that it will get rendered by drupal properly. I've tried a ton of different attempts, but this is what I've got currently:

```
$form['birthdate'] = array(
    '#title' => t("Offspring Birth Date"),
    '#id' => 'edit-field-filter-birthdate',
    '#type' => 'date_popup',
    '#default_value' => '2015-01-01 10:30:00',
    '#date_type' => DATE_DATETIME,
    '#date_timezone' => date_default_timezone(),
    '#date_format' => 'm-d-Y H:i',
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
);

$html = drupal_render($form);

```

The README.txt in the `date/date_popup` module says:

> To include a popup calendar in a form, use the type 'date\_popup':
>
> $form\['date'\] = array( '#type' =\> 'date\_popup': '#title =\> t('My Date'), .... );
>
> Set the #type to date\_popup and fill the element #default\_value with a date adjusted to the proper local timezone, or leave it blank.

However, all that ever gets rendered is just the `'#title'`.

What am I doing wrong?

# Answer
You need to initialize the form with `drupal_get_form()`:

```
$form = drupal_get_form('MYMODULE_birthdate_form');
$html = drupal_render($form);

function MYMODULE_birthdate_form($form, &$form_state) {
  $form['birthdate'] = array(
    '#type' => 'date_popup',
    // ...
  );
  return $form
}

```
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to do a URL redirect to the latest content?
This should be pretty simple, but what would be the best way to set up a 301 redirect to the latest post of a node type, for example.

For example: `example.com/blog/latest` -\> `example.com/node/*`

Ehat I was originally was doing was using views, getting the path of the latest post (+ random, also in views) and rewrite the results with a simple `<a href="[path]">Latest</a>`.

But, since I need to include this in email message, a URL is desired (as well as adding Google Analytics UTM Parameters).

What would be the simplest, site builder way to do this?

# Answer
> 2 votes
There seems to be a module for that.
Smart Node Links

---
Tags: redirection
---


# Question
Title: How to set a content type tile base on taxonomy field that user select?
I have ask in the past How to convert Content Type Title into Term reference?. Which someone suggest to used the Title Field UI in order to remove it the title and have a Term Reference field as my title field.

However, now I run into few problems where the title field is been expected like `admin/page`. So I was wondering if possible to set up the title field the same as the a term but automatically. I do not want the user re-type the field Title field, but at the same time I want to limit the user from choosing something that is not from the terms.

So how can I copy the taxonomy term that the user select and set up as title programmatically ?

**Update 1**

My content type machine name is `job_per_template` and taxonomy name is `field_job_title_template`. I have take the code from the answer below and I got this error.

> Integrity check for the imported configuration failed. Error message: The data type of the configured argument does not match the parameter's `<em class="placeholder">value</em>` requirement..

# Answer
> 1 votes
Do it with rules and the title module:

```
{ "rules_title_taxonomy_token" : {
    "LABEL" : "title taxonomy token",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--package" : { "bundle" : "package" },
      "node_update--package" : { "bundle" : "package" }
    },
    "DO" : [
      { "data_set" : {
          "data" : [ "node:title-field" ],
          "value" : [ "node:field-my-taxonomy-field:0:name" ]
        }
      }
    ]
  }
}

```

Be sure to change "package" to the name of your content type and be sure to use the proper field name for your taxonomy instead of field-my-taxonomy-field.

**As far as I know, the above only works with the Title module and the Title Field UI.**

---
Tags: taxonomy-terms
---


# Question
Title: Use Exposed Filter value in no result Global text
I'd like to use the value of the chosen Exposed Filter (=dropdownlist) in the Global text block when there is no result.

**In detail:** Exposed filter (which is a taxonomy list) has 3 values of provinces:

* Province 1
* Province 2
* Province 3

When there is no result using a chosen value, there should be a message (= global text, I presume), saying "Sorry, there are no addresses found in **Province 2**".

Is this feasible in Drupal views?

# Answer
1. set no result text area of view from advanced "No result behavior"
2. then edit your view using hook views\_pre\_render

Access your exposed input in same hook using :

```
$view->exposed_input['your field name']

```

then in same hook set these fields:

```
$view->empty['area']->options['content'] = "Set your message"; ( append exposed filter here)
$view->empty['area']->options['label'] = "Set your label"

```
> 0 votes

---
Tags: tokens, views
---


title: Path for images inside a block

text:
# Question
Title: Path for images inside a block
Right now I'm at "http://localhost:8080/drupal/xxxx/user/password" and I added an image inside a block like this "sites/default/files/background.jpg"

But I think is wrong because I'm at 2 paths "user/password" and it is not taken my images, in which way can I write the path to access to my images???

# Answer
You can display image using following URL:

`/drupal/xxxx/sites/default/files/background.jpg`

This is for your local setup. While migrating your drupal setup to production at root directory, your image url will break, because of directory change. To avoid this, you will need to change the path of image as below:

`/sites/default/files/background.jpg`

You can fix this broken your without changing the URL at production by using **Pathologic**. After Installing this module, you will need to enable Pathologic filter by checking **Correct URLs with Pathologic** in Text Formats e.g Full HTML. Then select **Correct URLs with Pathologic** tab from vertical tabs & **Path relative to server root (/foo/bar)** radio option. Add following values in the text area & save.

`/drupal/xxxx/
/`
> 3 votes

# Answer
The main idea is just to use this `"<?php echo base_path(); ?>"` That will give you the main path and then you can go with `"sites/default/....."`
> 1 votes

# Answer
I believe all you need to fix on that is change the URL to `/sites/default/files/background.jpg`
> 0 votes

---
Tags: media
---


# Question
Title: Drupal 7 custom module menu hook is not working
I have created D7 module called 'mymodule' and enabled it from module list page. But the menu created inside the mymodule\_menu() is not being called, instead redirects to 404 page.

Below is the mymodule.info file

```
name = my custom module
description = My module testing
version = 7.x
package = Custom Modules
core=7.x

```

Below is the mymodule.module file

```
<?php
echo 'Module is called';

function mymodule_menu() {

    $items['mydesk'] =  array(
      'title' => 'My Desk' ,
      'page callback' => 'show_mydesk',
      'access arguments' => TRUE,
    );
    return $items;
}

function show_mydesk() {
    echo 'show_mydesk';
}

```

Note: the echo 'Module is called' text is printing after enabled the module. Any help to find out where I have missed something.

Thanks Govind

# Answer
> 2 votes
You need to change `access arguments` with `access callback`.

Replace following code:

```
$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access arguments' => TRUE,
);

```

With:

```
$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access callback' => TRUE,
);

```

---
Tags: 7, routes
---


# Question
Title: "Locking" a node after a certain period of time
I'd like to be able to have nodes of a certain type "lock" after fifteen minutes, so that for the first fifteen minutes after a node of that type has been created its creator can edit that node, but after that fifteen minutes has passed only users with a specific permission can edit that node.

What's the best way to achieve this result?

# Answer
You could do something like this:

```
/**
 * Implements hook_menu_alter
 */
function MY_MODULE_menu_alter(&$items){
  $items['node/%node/edit']['access callback'] = 'MY_MODULE_check_node_access';
}

/**
 * Custom menu access callback for node/%node/edit
 */
function MY_MODULE_check_node_access($op, $node){
  global $user;
  // Note $op and $node are passed in default node_menu access arguments
  // Allow bypass by users with administer nodes permission
  if (($op == 'update') && (!user_access('administer nodes'))) {
    // Allow edit access to node author if within time limit
    if ($user->uid == $node->uid) {
      $limit = variable_get('node_edit_limit', (15 * 60));
      if ((REQUEST_TIME - $node->created) > $limit) {
        drupal_set_message(t('Edit time limit exceeded'));
        return FALSE;
      } else {
        return TRUE;
      }
    }
  }
  // Fallback to regular node_access checks
  return node_access($op, $node);
}

```
> 8 votes

# Answer
Module edit\_limit available for drupal 7 version since 2013-May-28 , just few days before David's answer. May be he was not aware of it that time.
Just few lines from modules page which is specific for OP's requirement.

> Node edit time limit
>
> Nodes can be limited to a given time frame. When this is used, nodes can only be edited within the time limit set by the site administrator, starting when the node is initially saved. This can be limited to a subset of content types.
> 2 votes

---
Tags: 7, nodes, users, workflows
---


# Question
Title: How to map url_alias table to node table?
I was trying to use some SQL to map the url\_alias field to my node field on the url\_alias.pid = node.nid field. However, it turns out that these are not apparently related, sometimes they are the same value and sometimes they aren't. As I'm looking through my mysql db I can see no connection between the url\_alias table and the node table.

The url alias is coming from the pathauto module. I just want to create links to my resources when the titles occur in a sql query in a custom module...this seemed the easiest way to do it.

Does anyone have any idea on which fields or tables the connections occur between these two entities?

# Answer
> 4 votes
They are not related because `url_alias` table contains all the URL aliases. You can use MySQL `CONCAT` to concatenate strings (fields or string literals).

```
$results = db_query("
  SELECT
    n.nid, n.title,
    a.source, a.alias
  FROM {node} n
  LEFT JOIN {url_alias} a
    ON CONCAT('node/', nid) = source
  ")->fetchAll();
foreach ($results as $result) {
  dpm($result);
}

```

---
Tags: nodes, path-aliases
---


title: Fetching nid in drupal

text:
# Question
Title: Fetching nid in drupal
Here I want to fetch the nid of matching child term id from my content type `product_categories`.

I used the below code.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'product_categories');
$query->propertyCondition('status', 1);
$query->fieldCondition('field_product_sub_cat', 'tid', $child->tid, '=');
$result = $query->execute();

```

I execute the above query and it displays correct results.But now I want to fetch the nid, I used below code but its not working.

```
 $childnid = $result->nid; //Area to explore
//print "<pre>"; print_r ((int)$childnid);
print $childnid;`

```

can anybody please help me ??

# Answer
> 2 votes
$result is in array of items.

Use this:

```
$first_nid = NULL;
if (isset($result['node'])) {
   $first_nid = array_shift(array_keys($result['node']));
}

```

---
Tags: database
---


# Question
Title: Drupal 7 Wildcard menu like txt-txt-% is not locating
I wanted to create wildcard menu like text-text-% in drupal 7.

But It works for if the menu is like text-text/% how can I make the above menu format to locate the action.

```
 $items['pin-code-%'] = array(
        'title' => 'Country list',
        'description' => 'Country pincode',
        'page callback' => 'country_pincode',
        'access callback' => true,
    );

```

# Answer
Wildcard menu items for root level is not supported. Partial match wildcards are not supported either.

You can, however, remap incoming requests to a proper menu router that Drupal supports by implementing `hook_url_inbound_alter`. Unless there is a strict requirement to use the path pattern you mention, I wouldn't go for this solution because this hook is executed to every request, including normal pages and Ajax requests.
> 1 votes

---
Tags: routes
---


# Question
Title: Module to convert a decimal amount of US Dollars to an equivalent amount of BitCoin
I am still new to Drupal and am looking for a module that does the following: convert a decimal amount of US Dollars to an equivalent amount of Bitcoin.

Is there such a module that can handle this or would I have to code this from scratch?

More info:

1. Accepts a decimal based argument in USD
2. Submitting the form sends a request to a 3rd party API to convert the dollar amount to BitCoin
3. Module should create a means to store any API connection details required to communicate with your API key in the database
4. Module should pull this value from the database when making a request to the API

# Answer
> 1 votes
It seems you're looking for the UC Bitcoin module

> This module provides an alternative 'payment gateway' that enables your clients to pay in the equivalent amount in BTC (Bitcoin currency)
>
> It does this by doing a current market exchange rate lookup of your stores default currency and then allowing an option to let people pay in the equivalent BTC amount.

---
Tags: 7
---


# Question
Title: Drupal 7 Commerce Stock Decrease stock when reverting cancel the order
I have used drupal commerce module. I have rules to increase stock when the order process is cancelled and decrease the stock after completed the order process.
When i cancelled the order status, the stock will be increased. It is fine.
When i trying to change the order status any of pending, processing, completed from cancelled, it didn't happened anything in my stocks.
But again when i changed status to cancelled, the stock will be increased.
So i want to write rule for "**decrease stock when reverting from cancel the order process**"
How to create rule for this edge cases?

# Answer
It can be done using hook\_default\_rules\_configuration(). Below is my code:

```
<?php
/**
 * implement hook_default_rules_configuration().
*/
function phponwebsites_default_rules_configuration(){
$rules = array();
$rules_export = '{ "phponwebsites_rules_decrement_stock_revert_cancel" : {
            "LABEL" : "Stock: decrease when revert canceling the order process (cloned)",
            "PLUGIN" : "reaction rule",
            "OWNER" : "rules",
            "TAGS" : [ "stock_control" ],
            "REQUIRES" : [ "rules", "commerce_ss", "entity" ],
            "ON" : { "commerce_order_update" : [] },
            "IF" : [
              { "data_is" : { "data" : [ "commerce-order:status" ],
                  "op" : "IN",
                  "value" : { "value" : {
                      "pending" : "pending",
                      "processing" : "processing",
                      "completed" : "completed"
                    }
                  }
                }
              },
              { "data_is" : {
                  "data" : [ "commerce-order-unchanged:status" ], "value" : "canceled"
                }
              }
            ],
            "DO" : [
              { "LOOP" : {
                  "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
                  "ITEM" : { "list_item" : "Current list item" },
                  "DO" : [
                    { "commerce_ss_decrease_by_line_item" : { "commerce_line_item" : [ "list-item" ] } }
                  ]
                }
              }
            ]
          }
        }';
   $rules['phponwebsites_rules_decrement_stock_revert_cancel'] = rules_import($rules_export);
 return $rules;
}
?>

```
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: How to alter the visibility of a menu tab for a page created in Views?
I have a View that is a primary tab on the user profile page. The user profile tabs look like this view | edit | menu-item-to-hide. If the person viewing the page is does not have role of admin or the owner of the profile page then they should not see the tab.

I assume that I use hook\_menu\_alter() but I'm not sure what the code should be.

# Answer
I created a mini module called helper.

In helper.info I put

```
name = "Helper"
description = "Provides custom support functions."
core = "7.x"

```

First we need to get the helper\_menu\_alter() to be called after views\_menu\_alter so we use hook\_module\_implements\_alter to pull the value of our module in the array and put it back in which will always be done at the end of the array.

```
<?php

function helper_menu_alter(&$items){
  $items['user/%/workbench']['access callback'] = 'helper_access';
  $items['user/%/workbench']['access arguments'] = array(1);
  $items['user/%/workbench/drafts']['access callback'] = 'helper_access';
  $items['user/%/workbench/drafts']['access arguments'] = array(1);
  $items['user/%/workbench/needs-review']['access callback'] = 'helper_access';
  $items['user/%/workbench/needs-review']['access arguments'] = array(1);
}

/**
 * Helper access callback.
 */
function helper_access($uid) {
  if ($uid) {
    if ($GLOBALS['user']->uid == $uid || user_access('view all unpublished content')) {
      return TRUE;
    }
  }
  return FALSE;
}

function helper_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move helper_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['helper'];
    unset($implementations['helper']);
    $implementations['helper'] = $group;
  }
}

```
> 6 votes

# Answer
Hook\_menu\_alter is called when the menu is being rebuild so you shouldn't use it for these situations.

Normally you should set the permission on your page view to only allow the roles you want to see that view. The menu system will handle hidding the tab for you when the user doesn't have the right permission.

The one thing that's weird is that you want to restrict on a role and if the user is viewing his own profile. In this case you do want to use hook\_menu\_alter but not to hide the menu tab but instead to replace the access callback with your own.

In your custom access callback you want to do something like http://api.drupal.org/api/drupal/modules--user--user.module/function/user\_view\_access/7

So essentially you want to do the logic on the access callback not on the hook\_menu\_alter.

You're going to run into issues with weights because I'm sure views run last.

To work around this you should implements hook\_module\_implements\_alter to designate your module to run after views only for the hook\_menu\_alter hook.

This doesn't required any weight changes and it helps resolve the problem where you might want your module to run before views in certain situations, yet after it in a different situation.
> 5 votes

# Answer
Easiest way is to write custom Access Callback with Views Access Callback module.
> 0 votes

---
Tags: routes, users
---


# Question
Title: What is the proper way to style pages in a new installation of a drupal theme?
I'm currently working on a new theme for a new drupal site, and have created a new subtheme of the adaptivetheme and am looking to modify it to match the two psd's I've been given (one for the main page, another for the content found in trhe rest of the site. Originally I was going to copy page.tpl.php over to the subtheme from the at\_core/templates directory and modify it's structure, but am wondering if that's considered best proactices drupal wise, ior if i should use modules like panel and views to build the style that I want that way?

So in a nutshell, which is the proper drupal way to style a new site; to use panel/views to match the design that you want, or to modify the tpl files, or a combination of both, or possibly something else that I might have missed?

# Answer
> 1 votes
Both or either are just fine, it really depends on what you want to achieve.

Panels will give you a UI in which you can move sections of the page around, but you will still need template files for the layouts if you don't want to use the standard ones.

Rearranging a template file is fine, but much less extendable via the UI.

In short, it's a matter of choice. I recommend trying both and seeing which fits your needs best.

Also, check out Omega 4.x, it's a beast of a theme with some extra layouts built in and a pre-built gemfile so that you can use SASS if you want.

# Answer
> 0 votes
Drupal has a very good Block Class module that allows you to add your custom classes through the drupal interface. Link to block class module

---
Tags: views, panels, theming
---


# Question
Title: How to create a list of nodes that the anonymous user has created and limit it by the current session (SID)?
Is there a way to create a list of nodes that the anonymous user has created and limit it only by the user's current session?

Basically I want the anonymous user to create a node under a specific content type and give that user a list of nodes (maybe using views) that he or she created only during the his or her current session on the site.

Anybody willing to help? I've been trying this the whole day and can't seem to get it done.

# Answer
> 0 votes
You should be able to use hook\_node\_insert to grab the nid of the node that is being created. Take the nid and add it to $\_SESSION. Then create a View that accepts NIDs as contextual arguments. You'll need to do some additional coding to grab those NIDs from the session and pass it to the View.

---
Tags: nodes, users, sessions
---


title: Boost Security_review compatibility

text:
# Question
Title: Boost Security_review compatibility
I had security\_review warning for boost cache folder.

I've changed cache folder location to "sites/default/files/cache"

And now I have no warning.

Is this solution correct and safe?

# Answer
From the point of view of the Boost module, it should be safe as well. Make sure you also regenerate the .htaccess for your site.
> 0 votes

---
Tags: security, caching
---


# Question
Title: How to send to redirect to a user after creating a node and display a message?
I want to be able to re-direct a user after creating a node of a specific content type and then display a message.

How can I accomplish this? Is the best way by using rules modules or custom module ?

With a custom module, I do not know what hook I would have to use in order to trigger after content type is been publish.

I know that I can use the drupal\_goto to redirect them + and used the drupal\_set\_message to create a notification.

On the another hand, I know that using rules can be used to accomplish some of all this work.

# Answer
The rules module can act on a "A new node has been created" event and has both "Page redirect" and "Display a message to a user" actions.
> 1 votes

# Answer
If you use modules like Ubercart or Drupal Commerce, you already have Rules module enabled. I'm not personally a fan of Rules module due to difficulties in migrating content and because the module is heavy to accomplish a few tasks.

You have few hooks you can implement.

* `hook_node_insert`/`update`\`: Executes on all node insert and update events, even the programmatic ones. Do **NOT** call drupal\_goto() in such hook because it can break a lot of things and the remaining hooks will not run.
* `hook_form_alter`: Go for this! Better yet you can improve the number of hook calls if you implement `hook_form_node_form_alter` (`hook_form_BASE_FORM_ID_alter`). You can check the node type inside the hook. If you implement `hook_form_alter`, make sure you validate the `$form_id`.

While in the form alter hook, add your custom submit handler, which can then set the form redirect destination and display the message.

```
<?php

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Validate node type and other conditions here.
  $form['#submit'][] = 'MYMODULE_SOME_APPROPRIATE_FUNCTION_NAME';
}

function MYMODULE_SOME_APPROPRIATE_FUNCTION_NAME($form, &$form_state) {
  $form_state['redirect'] = 'somewhere/you/want/to/redirect';
  drupal_set_message(t('Some message you want to display'));
}

```
> 1 votes

---
Tags: rules, redirection, status-messages
---


title: I am unable to save my content

text:
# Question
Title: I am unable to save my content
I have created a content type to apply for job. I have two roles, job posting and job hiring. When a user who has the role for job posting enters content, they get the `Access Denied` message when they try to save the content. Please see the attached screenshot.

How can I fix this?

# Answer
> 1 votes
Based on the URL partially hide in your second picture, the user is trying to access to the `node/add/need-a-freelancer`.

If you say the denied page is display when user click on the save button, so there is a problem during the submission of the content form.

The strange, in this problem, is that the same user can access to this URL for fill the form, but not for save it. But it's the same URL...

For resolve the problem, I would :

* Check if an admin User can submit and see a Need A Freelancer content.
* Double check your custom code where you play with permissions to display page (maybe something wrong in a hook, like in an alter or in a custom validate function).

Hope that helps.

# Answer
> 0 votes
Looks not the node is not saved (maybe it really is) but only not visible for the user role. So please test if the node really is not saved (f.i. with admin account and / or direct database access).

If so, add to the user(-role) the permissions to view the content type.

---
Tags: nodes
---


title: Getting the right TID with 2 parents

text:
# Question
Title: Getting the right TID with 2 parents
I'm trying to develop an script to upgrade nodes with a term reference.

But my source has 3 columns (copy to an in a db table) to the term tree, example:

fieldnames: ref1, ref2, ref3 fields: CAR -\> REDCAR -\> DARKRED

I can't use term name because it has is duplicates on the tree. Example: fields: CAR -\> REDCAR -\> DARKRED fields: BIKE -\> REDBIKE -\> DARKRED

How to get the right TID and verifying the tree with my DB table?

# Answer
Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree.

So I made my own function. (note I'm not a php pro)
TABLE
CAT1|CAT2|CAT3

```
function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('name', $node->cat3)
  ->propertyCondition('vid', 3)
  ->execute();

// check if has more than one
if (count($result['taxonomy_term']) > 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]->name == $node->cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
          }
        $a++;
        }
      }
      $c++;
    }
    $i++;
  }
} else {
  $mytid = array_shift($result['taxonomy_term'])->tid;
  // Found no multi parents...
}
}
}

```
> 0 votes

---
Tags: 7, taxonomy-terms, importing-exporting
---


# Question
Title: Should I use Spaces or Domain Access to share & separate content between subdomains?
*I realise that without the following additional information the title question is too broad.*

I have multiple sibling Drupal 7 sites with their own domains that I wish to consolidate into a single site, whilst to some degree retaining their apparent separateness. The rationale is discussed in this blog post, but to summarise:

* The sites have been developed in parallel and share many features
* Cross site search indexing would be much simplified by a single database
* Maintenance of a single site would be less costly
* Updates and new features could be rolled out simultaneously across sites
* The single, \[incidentally\] simplified and documented site would be easier to hand over to another developer

From the approaches considered in these two excellent but dated appraisals from Atchai and Palantir I had initially identified Spaces as my preferred, maintainable solution, but an apparent shift in usage, and seemingly low overall usage of Spaces leads me to question my assumptions.

Googling shows a dearth of **recent** articles on the subject, and d.o usage shows a decline in the weekly installs for the spaces module, which implies that people are taking a different approach.

Domain Access, however, is on the up:

Does anyone have any recent experience that would help?

# Answer
> 0 votes
I believe I have settled on an entirely different preferred solution - **multisite**.

For my particular situation, my priorities are derived from having to hand over the multiple site setup to another developer (with unknown resource/ability). I believe that with this in mind my question contained a couple of false assumptions, namely

* that a single site would be simpler to hand over to another developer
* that therefore maintenance costs would be lower than retaining multiple sites

The site will probably not have to share much content, and even fewer users, between sites so the main crossover is providing a shared search index. I have already solved this by separating the search functionality via aggregation (in an admittedly circuitous fashion). There are more powerful and efficient multiple site options involving Apache Solr or similar, but having separated search from the sites, these options are still open, and need only be implemented in one place.

A single site with multiple domains must necessarily make use of **Domain Access**, **Spaces**, **Organic Groups** or some combination of these. It may, therefore, be a single site, but it is not a **simple** site. Even if the documentation I provide with the site is perfect, the inheriting developer may encounter complications or complexities when maintaining or extending this more sophisticated site. Domain Access, though the most popular strategy, worried me particularly because of its interference with the core

I also found this article particularly useful in resolving my indecision. One aspect I had not considered with regard to a multiple domain site was the potential for path conflicts. I can certainly imagine a situation where both site1 and site2 have an /about path, and I cannot imagine an easy, maintainable way of getting round this within a multiple domain site without allowing drupal to create an ugly /about-0 path for site2. I find this distinctly unappealing, and it could cause some issues for existing paths.

I have always been quite reticent about using drupal's inbuilt multisite functionality to share a codebase between different sites (with different databases). For the purposes of updating etc it has often seemed simpler to me just to have separate codebases and manage shared code through version control, (because I can break a single site). In this handover situation, however, I think maybe a single codebase better communicates the absolute similarity of aspects of the different sites. As long as configuration is, as far as possible, captured in Features, there should be little confusion about the degree to which components and behaviours are shared between sites. The multisite codebase can easily be separated out into different sites later if required.

As a side-note, one advantage I had not previously considered for the multisite setup was the reduced amount of memory required to cache compiled PHP code (detailed here).

---
Tags: domain-access, subsites, 7
---


# Question
Title: How do I get rules to select a random node?
I'm working on my cron rule that will post to twitter every cron run. Thing is for this rule I need it to post a random node that either conforms to specific values in certain fields, or does something else if that value is false. I could use some help figuring this out.

Basically if The value of X=y I want the view to respond with one action, but if the value of X \<\> y then I want it to do another. And I need it to do this on random nodes of a sepcific content type.

Any ideas?

# Answer
See How to Use EntityFieldQuery, particularly the section "Random ordering".
> -1 votes

---
Tags: rules
---


# Question
Title: Outputting different class other than default for status messages
I'm trying to theme status messages, I want to change the HTML of the message.

Drupal default is

```
 <div class="message status">message!</div>

```

What I want to achieve is

```
 <div class="alert alert-success">message!</div>

```

I have used theme\_status\_messages to modify 'messages' but how can I modify the type (e.g. 'status'/'warning', etc)?

This is current code

```
function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"alert $type\">\n";
    if (!empty($status_heading[$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

I've changed this line

```
$output .= "<div class=\"messages $type\">\n";

```

to

```
$output .= "<div class=\"alert $type\">\n";

```

as you can see in my code above, but how can I change the options for $type?? I want my types to be alert-success, alert-error, alert-warning, rather than status, error, warning.

Anyone got an idea?

thanks!

# Answer
> 1 votes
This is just some good old PHP logic, is this what you're after?

```
function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );

  // Map our drupal statuses to bootstrap classes
  $bootstrap_statuses = array(
    'status' => 'alert-success',
    'error' => 'alert-error',
    'warning' => 'alert-warning',
  );

  foreach (drupal_get_messages($display) as $type => $messages) {
    // Grab the bootstrap class that corresponds to $type
    $bootstrap_class = $bootstrap_statuses[$type];
    $output .= "<div class=\"alert $bootstrap_class\">\n";
    if (!empty($status_heading[$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

You could even put the `$bootstrap_classes` and `$status_heading` arrays together. But I separated them for simplicity

---
Tags: 7, theming, status-messages
---


# Question
Title: Bootstrap framework - Sub-theme template.php not having any effect
I installed bootstrap framework for drupal and copied the sub-theme into my themes directory, renamed all the files accordingly and everything works fine, however any php code that i put in my sub-theme template.php file is not having any effect.

I tried adding google fonts, css files and some other functions to template.php but nothing works, even tho the code is valid.

I wonder what am i doing wrong? Should i be editing base theme template.php file, even tho it will get updated and deleted? Or is there some other reason why my sub-themes template.php has no effect?

# Answer
If you change in template.php then you have to clear the theme cache. Because the contents of the this file is cached in the database, so altering it will not be noticed by Drupal.

You can clear cache from here

Drupal 7: Administration \> Configuration \> Development \> Performance (**admin/config/development/performance**)

For more information visit Clearing the theme cache
> 1 votes

# Answer
Don't edit the files in the bootstrap base theme - they will get overwritten when you update to a new version just as you said. Only edit and add files to the subtheme.

About the changes not showing up: Is it possible that you are using the wrong theme hooks or no hooks at all? Just using functions like drupal\_add\_css() or drupal\_add\_js() wont work in the template.php unless you call them from a theming hook like template\_preprocess\_page().

Here is a good tutorial to preprocess functions: Implementing Preprocess and Process Hooks

If you want to generally add a css file to theme (not just to certain templates as you could with the preprocess functions) however, I would suggest adding them in the .info file of your subtheme:

```
#original bootstrap css files in your subtheme
stylesheets[all][] = css/style.css
stylesheets[all][] = css/jquery.cover.css

#custom sheet
stylesheets[all][] = css/YOURCSS.css

```

If you intend to use the less files bootstrap ships with hwever, there is no need to even do that: The bootstap subtheme supplies you with a number of less files you can compile into css for your theme using a programm such as crunch. The file you have to compile is the style.less file, which references all other less files. The output is a single style.css file, the one references above. You can either use the less files the subtheme provides or add new ones.
> 1 votes

---
Tags: theming
---


# Question
Title: This form was missing from the server cache on Drupal 8
On my site I do this:

I got a form with this field:

```
'myfile' => [
  '#title' => $this->t('MyTitle'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://myfolder',
],

```

And MyController:

```
$myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myclassform]');

```

This variable I pass to Twig template.

On my template:

```
{{ myform }}

```

Every is ok.

But when the page is cached I got this error when i upload a file:

```
An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.

```

I dont use memcache or CacheRoute, only drupal cache for anonymous user.

How I fix that? Is possible not cached the form?

# Answer
I fixed that prevent that drupal cached the page, this way, because the forms can't be cached:

```
// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

```

**EDIT:**

Recently was commited Add #cache\[max-age\] to disable caching and bubble the max-age

When `$build['#cache']['max-age']` is not set, permanent cacheability `(Cache::PERMANENT)` is assumed.

To indicate that a render array is not cacheable at all, set `$build['#cache']['max-age'] = 0` (i.e. zero seconds).

And to indicate that a render array is cacheable only for a limited amount of time, e.g. 5 minutes, set `$build['#cache']['max-age'] = 300; // 5 * 60 = 300`.
> 0 votes

---
Tags: forms, caching, 8
---


# Question
Title: How could I use both Rendered Entity and Fields in a view?
I like my *Rendered entity* style, but I want to add in just a couple of extra fields.

Under "Fields", it says

> The selected style or row format does not utilize fields.

Is this possible in any way?

# Answer
Figured out this IS possible, just have to switch things around.

Format to show *Fields* rather than *Rendered entity*. Then you have the option to use the rendered entity as a field. Something like this:

shows up in the Add fields list.
> 5 votes

# Answer
You would need to add the Field you want to add in the display of your entity itself, not in the view. If your rendered entity is one of the base entities of drupal (node/taxonomy term/...) you can use the UI to add or remove fields from their display.

To edit the display of a node for example go:

Structure \> Content types \> YOUR CONTENTTYPE \> edit display

You can not add fields to a rendered entity using views I am afraid.
> 0 votes

---
Tags: views
---


# Question
Title: A hook that would check if the module is enable?
**I'm not looking for hook\_enable (which would trigger when the module is been enable).**

I have a module that would work alone (lets call it custom\_module\_1) and I have another module which is an add-on (lets call it custom\_module\_2) to that module to the custom\_module\_1. I want to be able to have a different behavior on the custom\_module\_1 if the custom\_module\_2 is enable.

So I'm looking for a hook that would be be using on custom\_module\_1 and would check if the custom\_module\_2 is enable.

Or how can I check if there is a module enable as a function to have a different behavior on another module ?

# Answer
> 4 votes
`module_exists($module)` will do that for you. From the API:

> Parameters
>
> string $module: The name of the module (without the .module extension).
>
> Return value
>
> bool TRUE if the module is both installed and enabled, FALSE otherwise.

---
Tags: 7, hooks
---


# Question
Title: How to setup Page Cache to work with the Flag Module and Views?
I have a Site where Views are used to display flagged Nodes. When i turn on Cache Pages for anonymous Users, the anonymous Users only see the change in the Views until the cache is cleared. (If logged in no problem). What is the best Way to deal with this caching issue. I would prefer that all pages with views where item flags are updated would be recached. Is this possible ?

# Answer
> 1 votes
Similar to the first answer but not assuming your cache is in the database. (memcache, redis, apc, etc)

```
function hook_flag_flag($flag, $entity_id, $account, $flagging) {
  $view_name = '<view_name>';
  $display_id = '<display_id>';
  $cid = $view_name . ':' . $display_id . ':*';
  cache_clear_all($cid, $bin = 'cache_views_data', $wildcard = TRUE);
}

```

# Answer
> 0 votes
You can achieve this functionality using the Flag module hook\_flag\_flag, This hook will act on an object being flagged.

In this hook you need to clear the cache data for that particular view from cache\_views\_data table.

Below is the sample code,

```
function hook_flag_flag($flag, $entity_id, $account, $flagging) {
  $view_name = '<view_name>';
  $display_id = '<display_id>';
  $cid = $view_name . ':' . $display_id;
  if (db_table_exists('cache_views_data')) {
    db_delete('cache_views_data')
      ->condition('cid', db_like($cid) . '%', 'LIKE')
      ->execute();
  }
}

```

Usually views will set the cache ID based on the view name, display id and other data being passed.

Below is code snippet which prepares the cache ID for views result

```
$this->_results_key = $this->view->name . ':' . $this->display->id . ':results:' . md5(serialize($key_data));

```

So specify the cache ID accordingly in the delete query. However make sure to not to delete other entries in the cache\_views\_data table.

Hope this helps.

---
Tags: views, caching, flags
---


# Question
Title: How to install a module from an archive file with drush?
To install a module available on drupal.org, I do `drush dl modulename && drush en modulename`. However, when I have module available as an archive file on my local disk instead (`.zip` or `.tar.gz`), how can I still use `drush` to install it?

The archive file could come from downloading a sandbox project snapshot, from a self-developed "custom made" module or similar.

I know I could unpack the module into `sites/all/modules/`, then enable it with `drush en modulename`. But I'm looking for nice scriptable commands to do both these steps with `drush`. (Bit silly, but I like to keep a `drush` workflow.)

# Answer
You can use `drush make` to unpack a module named `your_module` from an archive file, as follows:

1. Create a `modulename.make` file containing:

```
core = 7.x
api = 2
; Install from local module archive file.
projects[your_module][type] = "module"
projects[your_module][download][type] = "file"
projects[your_module][download][url] = "file:///dir/your_module.tar.gz"

```
2. While in the Drupal root directory of your site, execute the Makefile and enable your module:

```
drush make --no-core -y your_module.make && drush en -y your_module

```

Alternatively, you can script this into one set of commands, using a temporary file instead of a separate Makefile. Again, to be executed while in the Drupal root directory:

```
#!/bin/bash
module="your_module"
makefile=$(mktemp)
echo "Created temp file $makefile"
cat << end-of-makefile >$makefile
  core = 7.x
  api = 2
  projects[$module][type] = "module"
  projects[$module][download][type] = "file"
  projects[$module][download][url] = "file:///dir/file.tar.gz"
end-of-makefile
drush make --no-core -y --verbose $makefile
drush en -y $module

```

(Bash named pipes or bash process substitution via `<(echo …)` cannot be used here to avoid a temp file. They create streams, which are non-seekable files that `drush make` fails to read from.)
> 2 votes

# Answer
First, you don't need to to type `drush dl modulename && drush en modulename` instead you can type `drush en -y modulename` and Drush is intelligent enough to know that you do not have the module and needs to be download it.

Second, if you have a Sandbox you can enable the module `drush en -y modulename` as long you have the module on your `site/all/modules`. If is a sandbox project from Drupal.org you probably would need to download it via git.

Just like the sandbox project as long you have it locally you can enable it via drush.

If you wish to download the module via drush you can find the answer at Is it possible to download sandbox projects with Drush?
> 1 votes

---
Tags: drush, installation
---


# Question
Title: Getting a list of nodes of a specific type (eg, forum) via REST API
I am using Drupal 7, with the Services module. I have the REST API enabled.

I have successfully done a user.login, and have retrieved the session id and session name, and then constructed the Cookie from same. I can successfully get a list of ALL nodes using this:

```
curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  http://myserver/rest/node

```

How do I get the list of nodes of a specific type? Eg, nodes of type=forum ?

I tried

```
curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  http://myserver/rest/node?type=forum

```

But that gave me the same list of all nodes.

---

**Edit**. this is what worked for me:

```
curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  'http://myserver/rest/node?parameters\[type\]=forum'

```

Thanks to burnsjeremy.

# Answer
> 2 votes
**Services 3.x**

You would use the parameters like this: http://localhost/endpoint/node?parameters\[type\]=node\_type

You can find out more how to use this by looking in the code (going off memory here): File: services/resources/node\_resource.inc function: \_node\_resource\_index

---
Tags: 7, services
---


# Question
Title: Is it possible to have multiple instances of the same field in one content type?
I understand that it is best reuse fields where possible and to avoid unnecessary duplication.

So is it possible to duplicate or reuse a field (or field instance) on the same content type?

For Example: A news article with both a cover image and an image gallery. Is it possible for both to use field\_image or must there be two distinct fields, such as field\_cover\_image and field\_gallery\_image ???

# Answer
The crux of the matter you stated as '..to avoid unnecessary duplication'.

Let your conceptual requirements dictate this and not your ideas of 'let's keep the database schema lean', or ideas of performance or something similar.

To take your own example from your comment. If you have different content types that serve the same purpose or that are grouped together somehow (ie all are products types that you group under a menu product catalog) and each product's type has a cover image that you want to show when you navigate to that product type listing, then re-using the cover image for each product type makes sense because it is conceptually similar.

On the contrary, re-using a product type cover image for a user image field would not make sense as it is conceptually unrelated, even though it might have the exact same database schema.

Not being able to re-use a field on the same content type makes sense from a conceptual point of view also. To have multiple fields all you need to do is set the multiplicity on the field, whether the field is 'simple', a field collection, or an entity reference. This already enforces a conceptual similarity.

Always design to your conceptual requirements first. This allows for:

1. better understanding of the design.
2. being able to easier adapt to changing future requirements
3. cleaner custom sql queries against the field's database if need be.
> 3 votes

# Answer
No, field instance is unique within a content type. See `field_create_instance`. Relevant code for checking uniqueness in that function:

```
// Ensure the field instance is unique within the bundle.
// We only check for instances of active fields, since adding an instance of
// a disabled field is not supported.
$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (!empty($prior_instance)) {
  $message = t('Attempt to create an instance of field @field_name on bundle @bundle that already has an instance of that field.', array('@field_name' => $instance['field_name'], '@bundle' => $instance['bundle']));
  throw new FieldException($message);
}

```
> 4 votes

---
Tags: entities
---


title: Node id from tid

text:
# Question
Title: Node id from tid
How to get the nid from tid, so I can used `node_load` function then used `Field_get_items` to fetch particular fields. I used `taxonomy_select_node()` first but it gives me nids of all nodes related to that tid but I want nids of a particular bundle(content type) so I can display contents only for that content type. Now I am using `Entityfieldquery`, here is my code:
`if(isset($_GET['tid'])){
 $id=($_GET['tid']);
 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node');
 $query->entityCondition('bundle', 'escorts_product');
 $query->propertyCondition('status', 1);
 $query->fieldCondition('field_description', NULL, $id, '=');
 $result = $query->execute();
 print "<pre>";print_r($result);`
Here I want to get my `field_description` from my content type `escorts_product` for a specific `$id=tid` but it gives me array structure for all tids not for a specific one I mentioned in argument?

# Answer
`$query->fieldCondition('field_description', NULL, $id, '=');`
line should be replaced like this and it will work,
`$query->fieldCondition('field_your_term_reference_field', tid, $id, '=');`
then you can get the nid easily.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Is it possible to add java script to webform?
I would like to have a field in module webform that uses javascript f.e that

```
 <script type="text/javascript">

var geocoder, location1, location2, gDir;

function initialize() {
    geocoder = new GClientGeocoder();
    gDir = new GDirections();
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        document.getElementById('d1').value =+drivingDistanceKilometers;
        document.getElementById('twojadres').value = '' + location1.address;

    });
}

function showLocation() {
    geocoder.getLocations(document.forms[0].address1.value, function (response) {
        if (!response || response.Status.code != 200)
        {
            alert("Przykro nam, ale wpisałeś niepoprawny adres. Spróbuj ponownie!");
        }
        else
        {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            geocoder.getLocations(document.forms[0].address2.value, function (response) {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else
                {
                    location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

</script>

```

It use js to calculate distance between address which should be get from webform field.

# Answer
An approach is to use hook\_form\_alter to alter the webform form and attach the custom JS.

```
/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webformCustomID')) {

    $form['#attached']['js'][] = drupal_get_path('module', 'custommodule') . '/custom.js';
  }
}

```

More info:
> 2 votes

---
Tags: webforms, javascript
---


# Question
Title: Add radio buttons and text field together to theme-settings.php
I want to integrate a CSS switcher into my theme, but without the Color module. So I want a radio button list, (or a select list, or dropdown, doesn't really matter), with a list of different styles, and then I also wanted a 'Custom' option, so that the user could input a hex code instead of picking a style.

I know how to create a radio list, but how can I add a 'custom' text field too? Any ideas?

And then... what would go in page.tpl.php if the user has selected 'custom'?

# Answer
> 0 votes
I think the select\_or\_other module is what you are looking for. it let's you create a select box or checkboxes with textfield as last option.

---
Tags: 7, theming
---


# Question
Title: restrict a field's content based on a selected taxonomy term
I have a content type with a number field and a field for a taxonomy. I'd like that, when the user creates a node of this particular content type, the value that appears in the number field changes to a preset depending on the taxonomy term chosen.

For example, The taxonomy term is a restaurant and the number field is a price, if the user chooses an specific restaurant the price changes depending on the restaurant chosen.

# Answer
> 0 votes
**option 1:**
use a hook\_form\_FORM\_ID\_alter `MYMODULE_form_node_form_alter(&$form, $form_state)` to add an ajax functionality on the taxonomy change event and populates the number field default value depending on the form\_state taxonomy value.

**option 2:**
Add your own javascript with taxonomy terms mapped to number values and when the taxonomy term changes, change the number values to the mapped value. This is pretty much same as above without requiring ajax.

---
Tags: 7, taxonomy-terms, nodes
---


# Question
Title: What's the proper way of working locally with freshly created features?
I have recently started to using Features, it was due time.

Once thing I started to wonder, is, once you created your feature locally, what's the best way to work with it. I first thought that creating the feature was enough and once it was there you could use it as such, but disabling the newly created feature doesn't remove everything the features exports, so it doesn't behave the same way as if you installed the same feature on a plain site.

Is that on purpose? If so why? What are the details I should consider for working with Features on the initial site.

# Answer
> 0 votes
## How features store settings

Features that are created locally have all there setting and content in the database as they where there before you export them to the feature, as an example if you created a view it will reside in the database even if you exported it to a feature.

as for features enabled on another site it will store every thing in the database when enabled except for ctools exports, which in this case even if you disable or uninstalled the feature those sittings will persist in the new site database, an example a strongarm (variable) will still be set even after you uninstall the feature.

as for settings using ctools exports they will not be added to the database unless you have override them, as an example if you had a view exported through features it will disappear if you have disabled the feature since it only exist in code.

## Conclusion

Features do not delete any thing in your database if uninstalled, except for true exportables that can only reside in code without the need to be in the daatabse to work.

## Suggested features workflow

When creating a feature on you local development machine it is a good thing to enable it to see if the settings in your database and the settings in the feature does match and be aware if they do change.

As for removing things added by the feature you can add a hook\_uninstall manually to your feature .install file and remove or delete what ever you like just like a proper module will do when uninstalled.

More info about this issue:

---
Tags: 7, features
---


# Question
Title: Getting rid of strongarm in features export
I exported a feature and it came wiht a bunch of strongarm configureation that I didn't want. I was able to delete most of it, but I wasn't sure about this part:

```
/**
 * Implements hook_ctools_plugin_api().
 */
function mymodule_ctools_plugin_api() {
  list($module, $api) = func_get_args();
  if ($module == "strongarm" && $api == "strongarm") {
    return array("version" => "1");
  }
}

```

Can I get rid of it altogether, or should I just have it return the version, for ctools?

# Answer
the short answer is yes you can delete it since you don't have any strongarm stored in this feature.

usually features add 3 pieces of code to any exported type:

1. the configuration it self in a file feature\_name.features.config\_group.inc or feature\_name.config\_group.inc
2. the include part in features feature\_name.features.inc
3. what are the content of the export in feature\_name.info

you can delete those manually and the feature will act as if they where never there, though removing a complete set of config group (e.g: remove all strongarm config) form the features UI will usually leave you with config file .config\_group.inc (1), and rarely with include settings in .features.inc, which you can delete them manually.
> 0 votes

---
Tags: features, strongarm
---