# Question
Title: Deploying code to multiple front end servers
We have a situation where we have multiple load balanced servers pointing to a common database.

In the normal run of things this works fine and gives redundancy, scalability etc.

However we are finding deployment to be a bit of a chore.

We are using features extensively and are trying to automate deployment. Deployment at the moment is not very reliable.

In a simplified form the deploy script for each server has two stages

1. Update Files
2. Revert Features (which will manage dependencies, settings changes etc)

Are there any best practices for deploying across multiple servers without causing them to be in an inconsistent state?

As far as I can see if you deploy steps 1 and 2 to server A it will cause server B to break, if you try step one on both servers before proceeding to step 2 they will both be broken for a while.

# Answer
You should probably look into Aegir, which is by far the most flexible and powerful Drupal site management/deployment system. It is able to manage 'platforms' that span acros multiple web heads, or 'clusters', as well as a variety of other configurations.

I'd suggest having a read through of their community documentation which is generally pretty good, as well as reading through mig5's excellent overview and introductory article and some of his other articles like this one.

You can also get good support in the #aegir IRC channel.

It'll be a bit of a workflow change, which can definitely take some time to get your head around, but once you're there you won't look back.
> 6 votes

# Answer
Which part of the deployment process is a chore/unreliable?

If it's the "update server A then B/inconsistency" problem, what about putting up the maintenance page for the duration of your pushes? Maintenance page up, update code on both web heads, run update.php on *one* of them, maintenance page down. That's pretty easily scriptable.

Another option: depending on the kind of site you run, you could create a "read-only mode" that kicks all users offline and disables login/register. Clone your DB to a second DB on the same db box, clone your front end to a new docroot, do your updates there, then symlink Apache's docroot to the new front end docroot. Workflow is something like:

1. Read only mode on
2. SELECT current\_db INTO new\_db
3. cp -R current\_docroot new\_docroot
4. new.yourdomain.com ==\> /new\_docroot
5. update code into new\_docroot
6. update.php
7. symlink /new\_docroot ==\> current\_docroot
8. Read-only mode off.
> 3 votes

# Answer
At our company we maintain A LOT of Drupal sites, our current setup goes something like this:

* Every site's codebase has it's own git repo
* New features not likely to be stable enough for the next release get their own feature branch in git

The above I would say is fairly common for most Drupal sites.

What we do special at our company is debian package the sites for deployment using a custom drush command - 'Drush Debian Packaging'.

Drush Debian Packaging provides a Drush command for building Debian packages of Drupal sites as a means of deploying Drupal sites to Debian or Ubuntu servers.

Drush Debian Packaging utilizes the Drupal hooks system to build a Debian package that best fits your sites needs. Features include:

* Automatic virtual host configuration for Apache2 and Nginx webservers
* Cron setup in /etc/cron.d
* Automated code deployment with partition split for sites/default/files
* Automated configuration through the dpkg debconf settings tool
* Automated deployment process
* custom Git VCS handler for building packages from Git

What does this mean?

To build a release:

```
cd /path/to/drupal-root
drush dh-make

```

To deploy a release, first SCP the .deb to all web servers in the cluster. Then on all web servers run (you can use the linux package cssh to type the command to all servers in the farm at the same time):

```
sudo dpkg -i drupal-site-yoursitehere.2011.05.25-1.all.deb

```

On one web server run:

```
cd /path/to/drupal-root
sudo -u drupal-site-yoursitehere drush updb && drush fra -y && drush cron

```

Done

Of course to roll back this is now trivial from a codebase point of view, simply install the previous version of the .deb to all web servers and rollback the database.

Happy to answer any questions about this
> 3 votes

# Answer
It will depend on the changes you're making, as Entendu suggests. What proportion of code updates can be run without causing errors if the database isn't updated yet? For anything that's not dependent on database updates (and maybe you can change the development process a bit to make this more common) there isn't really anything special to do. I assume you want to do deployments with minimal downtime, otherwise this would just take some basic sync operations. In this case there will always be some window of time with unwanted effects (even if it's just having the site in read-only mode) but I would think it could be fairly small most of the time.

You can do basic optimization like setting up a "new" directory on each server ahead of time and then switching them all over to point to the new directory at the same time (maybe using symlinks like in Entendu's answer) so you can get all the servers switched to the new files within 5-10 seconds.

That leaves the issue of database updates. If they're the kind that has to be done from one server only, you might want to put the others in maintenance mode or adjust the load balancer to not use them while this happens. Of course if they can't be done while users are active on the site you'll just need to have everything in maintenance mode but for simple updates this might be something you can do in about 30 seconds or less.

It may be worth having different deployment scripts for different types of changes, so you can run the minimal process needed whether that's just copying files, running a small database update, or doing a major database change.

If you can optimize your file and database updates and look at whether there are simple changes you can make to the way things are developed, that could take you closer but I don't know if any of this is new to you :)
> 2 votes

# Answer
Aegir is useful managing a network of sites. I used it to deploy and manage over 2000 sites for a single client.

Your question suggests that you want to manage a single site with multiple webheads. If that is the case Aegir may be less useful for you. Instead I'd suggest you look at using a file system that supports networking. Not only does this ensure your code is kept in sync it means your uploads are available on all nodes.

Historically people have used NFS which allows the file system of one server to be shared with other nodes. Unfortunately this introduces a single point of failure, because if the NFS server locks up or dies your site can't be served.

If you are willing to compromise a little on io performance in favour of a more reliable server, then I would recommend GlusterFS. I have used in a few production environments. It isn't perfect but it is better than NFS. Gluster allows the webhead to always read locally and the writes are then replicated to the other nodes.

In terms of your deployment strategy you should have drush as the first tool on your list. With drush you should be able to automate the steps of your deployment. You should consider adding Jenkins to the mix so you can track your deployment jobs and identify patterns if things fail. Capistrano can be useful for automating the steps involved in the deployment. If you do things properly you can make it so your users never even know that you did a deployment.
> 0 votes

---
Tags: deployment
---


# Question
Title: Taxonomy Access Control Change Default Behavior
From Taxonomy Access Control Documentation

> **Users with multiple user roles:** Allow/Ignore/Deny options are interpreted only within one user role. When a user belongs to multiple user roles, then **the user gets access if any of his/her user roles have the access granted.**
> In this case, permissions for the given user are calculated so that the permissions of ALL of his user roles are "OR-ed" together, which means that Allow in one role will take precedence over Deny in the other. This is different from how node access permissions (for multi-category nodes) are handled within one user role, as noted above.

This is a default behavior of the TAC. But is there a way to change this behavior so that the it is **AND-ed** instead of **OR-ed** or in other words a Deny in any of the roles would deny access to the content even if the other role has Allow permission.

The use case is as follows. Let us Assume there are Two Taxonomy called Grade and Subject. And all the contents are tagged with with both the terms.

A student logged in with a role of **Grade 1** and **Science** should only be able to see the contents tagged with both **`Grade 1`** and **`Science`**

The way to go about it should ideally be set allow permission to the **Grade 1** role to access all with the **grade 1** Term and deny for rest of the roles in the grade category such as grade 2 grade 3 etc.

Similarly Set allow permission for **Science** and Deny for the rest of the subjects.

With the current setup if you give the role Grade 1 and Science. the student would be able to see all the subjects in Grade 1 and all Grades in science.

Is there a way to accomplish this.

# Answer
One option I found was to use the `hook_node_access` this function has three inputs

1. `$node` The Node object on which the operation is done
2. `$op` The Operation being done on the Node could have three values **view, update or delete**
3. `$account` the user object.

The taxonomy access control stores the access information in `taxonomy_access_term` which has the following fields **tid** \- taxonomy term ID, **rid** \- the role ID, **grant\_view, grant\_update, grant\_delete, grant\_delete, grant\_create, grant\_list**

All the grant columns can have the following values

* 0=\>Ignore
* 1=\>Allow
* 2=\>Deny.

Used the following function to override the `hook_node_access`

```
    function custom_node_access($node, $op, $account) {

        if ($op == 'view')
        {
        // Get all the tids into the $tids array
            $tids = array();
            $tids[] = $node->field_class[$node->language][0]['tid'];
            $tids[] = $node->field_subject[$node->language][0]['tid'];

        // Get all the role ids into the $roles variable
            $roles = array_keys($account->roles);

        // Create the query to get the `grant_view` with a value 1 if all the
        // roles have grant permission then the result would have 2 records.

            $query = db_select('taxonomy_access_term' , 't');
            $query->condition('t.tid', $tids, 'IN');
            $query->condition('t.rid', $roles, 'IN');
            $query->condition('t.grant_view', 1);
            $query->fields('t', array('grant_view'));
            $result = $query->execute();

        // if the result is less than two then we deny access other wise we
        // ignore it so that let the node_access control take over.

        if ($result->rowCount() < 2)
        {
                return NODE_ACCESS_DENY;
            }
      }
      return NODE_ACCESS_IGNORE;
    }

```

This works well node displays. But the problem would be that since the hook\_node\_access is bypassed by the list queries this will not work, Might have to add the node\_access tag to all the queries which would become a performance issue.

The second method was to use the `hook_node_access_records_alter` and `hook_node_grants_alter`

the `hook_node_access_records_alter` edits the grant realms before writing it to the `node_access` table when creating or editing a node.

```
function custom_node_access_records_alter(&$grants, $node) {

  // Store the grants to a temp variable

  // create a new varible to store the new gid
  $gid = "";

  // Loop through the grants
  foreach ($temp as $key => $grant)
  {
    if ($grant['grant_view'])
    {
        // if the grant_view is set to 1 then append the gid
        // after adding a padding 0 to the left so that we get
        // a 2 digit number
        $gid .= str_pad($grant['gid'], 2, "0", STR_PAD_LEFT);

    }

  }

  // After completing this loop the new gid would look something like 040506
  // which means the role id 4, 5, and 6 has access to the page. and since we have
  // added it together we can make sure that it is individualy not valid
  // has to work together.

  // Rewrite the grant values with the new gid.
  if($gid_view != "")
  {
    $grants = array();
    $grants[0] = array();
    $grants[0]['realm'] = 'taxonomy_access_role';
    $grants[0]['gid'] = (int)$gid;
    $grants[0]['grant_view'] = 1;
    $grants[0]['grant_update'] = 0;
    $grants[0]['grant_delete'] = 0;
    $grants[0]['priority'] = 1;

  }

}

```

The next step would be to override the `hook_node_grants_alter` function.

```
function custom_node_grants_alter(&$grants, $account, $op) {

  // we only want it to work with the view.
  if($op == 'view')
  {
    $gid = '';

    // loop through the roles of the user
    foreach($account->roles as $rid => $role)
    {
        // we do not want the role id 2 as it is the id of the authenticated user.
        if ($rid >2)
        {
            // generate the gid we created in the hook_node_access_records_alter
            // so if the user has all the roles we set to the node then we would
            // get the same gid other wise the gid would be different and access
            // would be denied
            $gid .= str_pad($rid, 2, "0", STR_PAD_LEFT);
        }
    }

    // Over write the grants array.
    $grants = array();

    $grants['taxonomy_access_role'][0] = (int)$gid;

  }
}

```

**Note : There are few assumptions made here**

1. We only have the taxonomy access control module as access control module other than the core access control system. If there are more then we have to check and make changes to the function accordingly.
2. We are only checking for the view grants and not bothered about the rest of the grants.
3. Maximum number of roles that a user would have is 5. The gid is of the type int so it can accommodate a maximum value of 10 digit.
4. Each role would have only one allow per taxonomy term and rest of it would be deny.
> 1 votes

---
Tags: taxonomy-terms
---


title: where and how to manually apply patch?

text:
# Question
Title: where and how to manually apply patch?
> **Possible Duplicate:**
> How do I apply a patch file?

It is obvious latest colorbox plugin needs patching because even with drush install it is not working to load images and I've been at it all day, literally.

So found this http://drupal.org/files/patch-colorbox-1\_3\_21-2.patch which is recommended for the drush install of colorbox plugin with only the one colorbox folder.

But where and how do I patch it?

Very kind volunteers have been trying to help throughout the day but I am yet to get this fixed.

# Answer
> 0 votes
You could either do it through the patch program or git. you have a good documentation here

Or do it manually.

```
  --- colorbox.module.old   2013-01-17 12:36:37.000000000 -0700
    +++ colorbox.module 2013-01-17 12:35:46.000000000 -0700
    @@ -80,9 +80,9 @@
         'download url' => 'http://www.jacklmoore.com/colorbox',
         'path' => 'colorbox',
         'version arguments' => array(
    -      'file' => 'colorbox/jquery.colorbox-min.js',
    +      'file' => 'jquery.colorbox-min.js',
           'pattern' => '@ColorBox v([0-9\.a-z]+)@',
    -      'lines' => 1,
    +      'lines' => 2,
         ),
         'files' => array(
           'js' => array(

```

What this says is in the colorbox.module file and find the line which says

```
'file' => 'colorbox/jquery.colorbox-min.js',

```

replace that with

```
'file' => 'jquery.colorbox-min.js',

```

and find the line with

```
'lines' => 1,

```

and change that to

```
'lines' => 2,

```

@@ -80,9 +80,9 @@ this tells you that you would be looking some were near line number 80.

---
Tags: drush, javascript
---


# Question
Title: How can I get the term ID out of the hierarchical select theming function?
I'm attempting to add a link to flag each term output by hierarchical select in a views template.

Here's the relevant code from hs\_taxonomy.module:

```
function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');
  dpm($variables);

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($lineage);
    $line  = '<span class="lineage-item lineage-item-level-' . $level . '">';
    $line .= drupal_render($item);
    $line .= '</span>';
    dpm($item);
    $items[] = $line;
  }
  $output .= implode($separator, $items);

  return $output;
}

```

And here's the output of `dpm($item)`:

Based on the flag module documentation, I tried to add the link like this: `$line .= flag_create_link('hobbies', $term->$item['#options']['entity']['tid']);`

But that gives this error: **Fatal error: Cannot use object of type stdClass as array in /mysite/sites/all/modules/contrib/hierarchical\_select/modules/hs\_taxonomy.module on line 880**

How can I get the tid of the term being output?

# Answer
> 3 votes
The entity is a `stdClass` object, you need to use the `->` accessor:

```
flag_create_link('hobbies', $term->$item['#options']['entity']->tid);

```

---
Tags: theming, taxonomy-terms
---


# Question
Title: How to get selected value in option id value in drupal form api
Hi hello please help how to get dynamically selected option id value (i.e #options=\>0=\>'bala',1=\>'kumar')

for example (1001-\>india,1002-\>usa) like that stored in select option value (india, usa like that) , but i want to fetch the id value(1001, 1002) of selected value of id value from option? that value to be store in $key variable, please help me

```
$query_state=db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_name]=t($state_record->State_code);
}

$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

// here values are popup in select option component but corresponding value of state in city select option not visible

 $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name','State_Code'));
$query_city->condition('State_Code',$key,'=');

$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach ($city_results as $city_record) {
  $options_city[$city_record->District_Code]=t($city_record->District_Name);
}

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '<div id="divaroundseconddropdown">',
  '#suffix' => '</div>',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state1"]' => array(
          'value' => $options_state,
      ),
    ),
  ),
);

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

```

# Answer
> 1 votes
Try the following code:

```
function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

```

Hope this helps you!

---
Tags: forms
---


title: Problems with form api and #tree

text:
# Question
Title: Problems with form api and #tree
I'm trying to create a form element with an array of child inputs. How is the below example incorrect in D7, I'm getting this error:

```
Fatal error: Cannot create references to/from string offsets nor overloaded objects in C:\wamp\www\water-uk\www\includes\common.inc on line 6518

array(3) {
  '#tree' =>
  bool(true)
  '#type' =>
  string(8) "fieldset"
  'first' =>
  array(6) {
    '#type' =>
    string(6) "select"
    '#options' =>
    array(8) {
      'All' =>
      string(8) "Show all"
      [0] =>
      class stdClass#470 (1) {
        ...
      }
      [1] =>
      class stdClass#468 (1) {
        ...
      }
      [2] =>
      class stdClass#469 (1) {
        ...
      }
    }
    '#size' =>
    NULL
    '#default_value' =>
    string(3) "All"
    '#ajax' =>
    array(5) {
      'callback' =>
      string(38) "_listing_blocks_select_tax_depth_js"
      'wrapper' =>
      string(18) "tax-select-wrapper"
      'method' =>
      string(6) "append"
      'effect' =>
      string(4) "fade"
      'event' =>
      string(6) "change"
    }
    '#required' =>
    bool(false)
  }
}

```

# Answer
> 1 votes
You appear to be using `stdClass` objects for the values in your options array. Drupal expects a string for each of the options.

You probably have code like:

```
foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item;
}

```

when you need to have something like

```
foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item->name;
}

```

---
Tags: 7, forms
---


# Question
Title: 500 HTTP error on "Manage Display" tab after changing layout with Display Suite! What should I do?
I changed the layout to "One column" with Display Suite on a given content type's "Manage display" tab, which has many (~30) fields. I'm also using Field group module with multiple groups.
After saving, DS has set some group's parent elements to "Disabled". OK, I changed it, I dragged these to the enabled part, and after saving, I got a 500 HTTP-code when going to "Manage display" tab after a long waiting time!

What should I do? Can I simply uninstall Display Suite module? Will it reset the display to my original settings and field orders?

Thank you for any kind of ideas!

---

EDIT

**Uninstalling the module did NOT solve the problem**.... I'm in a real big trouble, because I don't know how to reset the display... Any ideas?

# Answer
Had the same issue, deleting the rows corresponding to my problamtic content type from the table "field\_group" solved it. This way I didn't lose my entire field group settings.
> 2 votes

# Answer
OK, uninstalling the Field group module solved the problem. It seems like Display Suite and Field group are not in a very good relation with each other... Maybe I'll post an issue related to the problem on drupal.org, because DS should be prepared not to "explode" a field\_group, so each groups should stay together, and put to "Disabled" section together, or in no wise.

I think a possible solution until then could be that I create the new layout with Display Suite first, and **after that**, I create the field\_groups, and take care that I don't move parent elements separately to "Disabled" section, because it can cause trouble.
> 1 votes

# Answer
At the beginning of the message you posted is "MySQL server has gone away" which means that MySQL timeout limit was not enough (example: it waited too long for the server to respond).

You can change that the following way (basically you can replace 300 \[5 mins\] to any higher value you want):

```
ini_set('mysql.connect_timeout', 300);
ini_set('default_socket_timeout', 300);

```

This is from here.

Check this article and this thread.
> 1 votes

---
Tags: 7, nodes, display-suite, entities
---


# Question
Title: Drupal Commerce Export Orders in CSV format
How can I export Order details along with custom line item fields data in CSV format?

# Answer
You can use Views and Views Export modules.

Views Export provides you with a Export display, you do the filter in the view and in the end it will return a link where the orders can be downloaded in csv format.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: What token can I use for the taxonomy hierarchy?
I have a vocabulary with 3 levels and a content type with a term reference to that vocabulary. When I create a node of that type, I choose a term in the deepest level of the vocabulary. I installed the Pathauto module and I'd like to use *\[node:field\_category:level-1\]/\[node:field\_category:level-2\]/\[node:field\_category:level-3(deepest)\]/\[node:title\]* as pattern.

The problem is that I can't find the right token to achieve this.

How can I achieve this?

# Answer
> 4 votes
*\[node:field-yourfield:parents:join:/\]/\[node:title\]* works for me, where *yourfield* is the name of your reference field.

You have to go to *Configuration » Search and metadata » URL aliases Settings*; under *Punctuation* change *Slash* to *Do nothing*, to avoid slashes are removed from the path alias.

---
Tags: 7, taxonomy-terms, path-aliases, tokens
---


# Question
Title: overlay does not work after enabling my custom module
I am using latest Drupal 7.

I just noticed my admin overlay is not working.

First I thought its due to Jquery Update contrib module installation however that not it. Its apparently due to my custom module, overlay works if I uninstall my module.

My module consists of few basic hooks like hook\_menu, hook\_form, etc and a simple js file with delete confirm popup code in it.

Also in Home » Administration » Structure » Content types » Basic page, in manage fields tab, 'select a widget' select list (dropdown) shows all options. It is suppose to show options according to field type selected.

```
$(function() {
 $(document).ready(function () {

  $(".del-link").click(function () {
   var answer = confirm("This action will delete this record?")
    if (answer){ // if yes is clicked on the confirm box.
     var del_record_id = this.id; // get record id that needs to be deleted.
      window.location = "/delete_url/" + del_record_id; // go to url which trigs the delete function and the record is deleted.
    }
  });

  $("#edit-my-form-field").click(function () {
    $("#edit-my-form-field").is(":checked") ? $("#show-hide-div").hide() : $("#show-hide-div").show();
  }); // end of click function.

 }); // end of  $(document).ready(function ().
}); // end of $(function().

```

Has anyone come across similar issue?

# Answer
> 1 votes
I figured (googled) it out. :)

I added my custom js in my custom module's info file instead of using drupal\_add\_js in my module directly.

```
scripts[] = my_module.js

```

and added drupal behaviors in my js file as well, so now my custom js looks like below

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

// my js code

 }
};
})(jQuery);

```

I spent many hours figuring this out but it was as simple as could be be.

Hope this helps someone! :)

# Answer
> 0 votes
did you wrap your code in a closure? if it is Drupal 7 you should wrap everything like nya:

```
(function($) {
  // Your custom code here.
})(jQuery);

```

Just throwing the $ around like that in the global scope is cray.

---
Tags: 7, modal-dialogs, javascript
---


title: Add class to views row using a template

text:
# Question
Title: Add class to views row using a template
I'm using Views 3 with Drupal 7. I'm trying to dynamically add a class to the "views-row" line of a view based on the node type. I have a view with a relationship which is duplicating items when a relationship exists. I thought by adding a class for the node type into the views-row line I could hide the field in the row. I'm not sure whether I should be overriding views-view-unformatted.tpl.php or views-view-fields.tpl.php, to add the class and how I can extract the node type from the data to add it into the the classes for that line.

I'd be grateful for any guidance.

Ben

# Answer
Views itself will tell you which file to use as a template. Go to the config page for the relevant view and choose *Theme: Information* under **Other**. This will print out a list of potential templates; the template shown in bold is the one that is in use.

To get the node type, you can use the `dpm()` function of the devel module. For example, if you have devel enabled, you can simply insert `dpm($row)` in the template file, load a page containing the view in your browser, and then dig through the output.
> 1 votes

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


title: Alter checkboxes values in a webform

text:
# Question
Title: Alter checkboxes values in a webform
How can I alter the key/value items of a checkboxes component in a webform?
I've followed this answer and I successfully altered a select list component for both render and submission.
I'm trying to do the same with a multiple choice component, but although the form is rendered correctly, the values are not saved on submission.
This is my code:

```
function my_form_webform_client_form_30_alter (&$form, &$form_state) {
    $form = mycustom_form($form);
}

function mycustom_form($form){
     $form['#validate'][] = 'mycustom_webform_validate_form';
     $form['#submit'][] = 'mycustom_webform_submit';
     dpm($form['submitted']['code']['#options']); // ('0'=>'a value', '1'=>'another value');
     $codes = array('foo', 'bar');
     foreach ($codes as $key => $value) {
        $form['submitted']['code']['#options'][$value] = $value;
     }

return $form;
}

function mycustom_webform_validate_form($form, &$form_state) {
dpm($form_state['values']['submitted']);
// selecting all checkboxes I get all the four values
}

function mycustom_webform_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state, true) . '</pre>');
// only 'a value' and 'another value' are submitted
}

```

**UPDATE**
I even tried to add some values to the initial form and manipulate them programmatically.
The submission result is like no manipulation was done.
I update my code for a better explanation.

**UPDATE 2**
I've tried dumping the submitting form.
I updated my code with the results.

**UPDATE 3**
I confirm that removing the "Multiple" flag from the component, causes the issue to be fixed.
Unfortunately I need a multiple answer, so I can't remove it.

**UPDATE 4**
This is another solution I'm trying, using hook\_webform\_select\_options\_info():

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

   if (function_exists('_mycustom_users_options')) {
        $items['code'] = array(
        'title' => t('User codes'),
        'options callback' => '_mycustom_users_options',
      );
 }

  return $items;
}

function _mycustom_users_options() {
  $output = array();
  $codes = mycustom_user_codes(); // <- these values are based on logged user
  foreach ($codes as $key => $value) {
    $output[$value] = $value;
  }
  return $output;
}

function mycustom_user_codes() {
      $result = // a db query based on user id;
      while($usercode = db_result($result)){
         $output[] = $usercode;
      }

      return $output; // array({[0] => 'a value', [1] =>'another value'})
}

```

# Answer
> 1 votes
I've just tested the following code out locally and it "works", with the exception that when I view the submission results as an administrator, I see the original keys and not the keys that were altered when the form was displayed (which is what I would expect).

```
function my_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_12') { // yours is different
    // 'options' is the component name for a multiple-checkbox component.
    $form['submitted']['options']['#options'] = array(
      1 => 'Foo',
      2 => 'Bar',
    );

    $form['#submit'][] = 'my_custom_submit';
  }
}

function my_custom_submit(&$form, &$form_state) {
  dpm($form_state);
}

```

`dmp($form_state)` showed me that the checkbox I had picked was indeed the one that was checked, and when I look in the database in `webform_submitted_data` I can see that the record shows the proper value that I checked:

```
nid sid cid no data
12  12  2   0  2

```

where `data = 2` shows the checkbox that I picked in my altered options (I picked "Bar").

Since the subsequent *submission display* is going to show the keys as they currently exist, it's showing me that I picked the original value for option #2. If I change that to "apples" in the component and then refresh the submission, it shows the 2nd option as "apples". So I could follow this up with another `hook_webform_submission_render_alter()` or `hook_webform_submission_load()` to change the *options* being displayed on submission view so as to be appropriate to who the user was that filled out the webform.

My suggestion would be to instead build your own form, since it sounds like you have more than one dynamic aspect for what you need, and store the data that will be dynamic as a serialized array in a 'data' column in your own table.

# Answer
> 0 votes
Your `$codes` array is zero-based. This is usually bad, and can mess up the submitted values (especially if you check the 0-keyed option). Here's something from the Form API docs, for #checkboxes:

*The #options array can not have a 0 key, as it would not be possible to discern checked and unchecked states.*

This applies both to form generation (where you created the checkboxes for "a value" and "another value"), and to the form altering, submission etc. So a solution would be to manually specify the keys of your `#options`, like

```
$codes = array(
    "foo" => "foo",
    "bar" => "bar"
);

```

Or, if you want numerical,

```
$codes = array(
    1 => "foo",
    2 => "bar"
);

```

Just avoid the 0 key for checkboxes.

**EDIT:** I see that in hook\_form\_alter() you did, indeed, use `foo` and `bar` for keyes. Anyway, you have a 0 key when generating the checkboxes, so my observation stands, even if it might not fix the issue. I can't comment on your question (which would have been more appropriate for my observation), so I'll leave this "beware of 0-key" warning as an answer, to be visible.

# Answer
> 0 votes
Since webform3 there is hook\_webform\_select\_options\_info() for setting select ( or multiple choice ) options programatically.

I have been able to achieve this effectively in drupal 7 but there is a tutorial for drupal 6 and 7 here http://www.anexusit.com/blog/how-create-pre-built-list-webform-drupal-67

The tutorial that I followed to get me going on drupal 7 is here http://eureka.ykyuen.info/2012/04/11/drupal-7-dynamic-select-options-for-webform/ and gives more detail on how to setup the webform ( which should be very similar ).

This should prove to be a much cleaner way of achieving what you are looking to do rather than altering the form and attempting to hack it back into webform.

# Answer
> -1 votes
YOu need to pass `$value` by reference not by value, you should do it with `&$value` read more.

```
foreach ($codes as $key => &$value) {
              $form['submitted']['code']['#options'][$value] = $value;
            }

```

# Answer
> -1 votes
```
$codes = array('foo', 'bar');
foreach ($codes as $key => $value) {
  $form['submitted']['code']['#options'][$value] = $value;
}

```

could be written as:

```
$form['submitted']['code']['#options'] = array('foo', 'bar');

```

---
Tags: 6, webforms, forms
---


# Question
Title: template preprocess override not respected
I'm using Drupal 7.

I have a template preprocess function overridden in my `template.php` as

It does not alter the output as desired.

When I comment out (or delete) the original preprocessor (`template_preprocess_views_exposed_form(&$vars)`) in the contrib module's `theme.inc`, the overridden preprocess function then takes effect as it should.

What do I have to do to get my preprocess to work without having to hack a contributed module?

Here is the offending code:

```
function ncmr_preprocess_views_exposed_form(&$vars){
  $form = $vars['form'];

  if ($form['ncmr_days_only']) {
    $form['ncmr_days_only']['value']['day']['#options'] = array(
      '' => 'Select Day',
      '5' => 'April 5',
      '6' => 'April 6',
      '7' => 'April 7',
    );

    $form['ncmr_days_only']['value']['day']['#printed'] = FALSE;
    $form['ncmr_days_only']['value']['month']['#value'] = 4;
    $form['ncmr_days_only']['value']['month']['#printed'] = FALSE;
    $form['ncmr_days_only']['value']['year']['#value'] = 2013;
    $form['ncmr_days_only']['value']['year']['#printed'] = FALSE;

    $vars['widgets_ncmr']['filter-field_session_date_value']->widget = drupal_render($form['ncmr_days_only']['value']);
  }
}

```

# Answer
Try the following...

```
function THEME_preprocess_views_exposed_form(&$vars, $hook)
{
        if ($vars['form']['#id'] == 'FORM_ID')
        {
              // blah blah
        }
}

```

This way you shouldnt override the core stuff, thus not affecting your code either.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Where to place the admin screens for a module
When developing a module with an admin-area, what are the guidelines for menu-placement?

There is `admin/settings/*`, `admin/structure`, `admin/content` and so forth.

From what I can see, most modules follow arbitrary guidelines and often clearly content-related pages end up in `admin/settings/foobar`, or pages that have little to do with the architecture of the site end up under `structure`.

What are rules-of-thumb? What are the guidelines?

For example, I have a module that renders a tag-cloud, and I have some settings that allow manipulating how this module renders its pages. Settings such as "what vocabularies to include" and "amount of tags to render".

From a user POV, I would expect the first setting under `admin/structure` yet the other one under `admin/config/user-interface`. But I'd rather keep them together; since I believe a user (1) installs and then (2) immediately configures this type of module, once.

# Answer
> 2 votes
There is a handbook page that covers where you should place these menu items.

See Information architecture

I won't copy and paste the info here as it is too long. You also don't provide any info on what your module is about, so I can't even paste a excerpt that pertains directly to your issue.

The handbook page should be considered the canonical source for this info.

EDIT:

While these are guidelines, I don't think that they are very cut and dry. I would personally place the menu where the other two major tag cloud modules (Cumulus and TagCloud) place theirs: admin/config/content and keep them both in the same spot (one as a child item of the other)

---
Tags: routes
---


# Question
Title: Show 4 input file fields on my node add image page
I have a content type with an image field; the user can insert a maximum of 4 images. I need both the node add and edit form to show 4 input file elements, not only 1.

# Answer
> 4 votes
When you add a field there is an option to set number of items. You can set the number to 4 and you would have 4 input elements on the page.

# Answer
> 1 votes
If you want to get fancy and your server supports it, you can use the Plupload integration module.

---
Tags: 7, forms, media
---


# Question
Title: What is the benefits of Panels for a themer?
I've never thought much of Panels, as I have always been comfortable with writing my own themes.

However, I have seen a lot of articles advocating the virtues of Panels (from Lullabot & Active Lamp), so I thought it would be time to revisit it, especially as Panels is going to be in Drupal 8.

I've played around with it extensively and I've even watched this helpful screen cast series. But I can't see what the benefits are.

I usually build websites where non-technical people can edit the nodes. Usually each node form will have several fields where the user can add all the content for that page.

To get the most out of Panels, it seems you have to split your pages into separate nodes that hold 1 piece of content and then use the Panels to bring the separate nodes together. This might be fine if you are creating a site that is only to be edited by a web designer.

However, it creates an issue when you give the site to a non technical person to add content. Most non-technical people would like to do all their page creation on a single screen. If they have to create lots of different nodes and then let Panels bring them altogether, it seems to be confusing for them.

I know Panels has better performance and better support for context compared to Blocks. However, it seems to add a lot of complexity and abstraction.

I can see how it would be incredibly useful for a non-themer, but I can't see what the benefits are for someone who can theme.

Could someone enlighten me. Thanks!

# Answer
> 10 votes
One large advantage of Panels is that you can have wildly different layouts for pages, depending on your needs. In this context, layouts can mean both content and styling.

On the content end, you can have your main node-being-viewed piece, and add in different things. For example, you can add in views into sidebar areas that show/link to related content. You can also add in blocks, and have a lot more flexibility than what come stock with Drupal (though D7 really improves things).

On the styling end, the biggest advantage is being able to choose different layout templates for each page and variant. Other modules, like Context can do similar things, but I find it much easier to do with Panels.

With the sites we build, all pages are Panel pages (no exceptions). From the client's perspective, having adequate training and inline help greatly helps with them being able to keep the site alive (and nearly all of our clients are non-technical).

A side effect of using Panels is that you get a lot of features that cTools provides, which can be a huge benefit when you need to retrofit a site. In a lot of ways, we have found using Panels pages for everything really aids with future proofing a site.

# Answer
> 0 votes
One way to use panels is the way you describe: create a node with panels and put in content from other nodes. Yes, that is a bit unwieldy.

**Better:** You can also add fields to a node content type, panelize it, and place the fields into the panel layout. In this case, you might add col1 and col2 text fields, and users could enter their content into body, col1 and col2, which would display automatically into the panel you have set for that node.

Suggestion: Use the Panelize Module, rather than using Node panel, which is deprecated. The panels docs are unclear on which panel method you want to use. Panelize let's you add a panel to any node for any content type. Then you get layout plus all the other panels benefits.

---
Tags: theming, panels
---


# Question
Title: How to add html to title output of taxonomy terms in Drupal 7?
I just cant figure it out. How can change the title output of a term? I have a content type which displays the selected terms. The term is displayed as a link. How can I change this:

```
<div class="field-item even">
    <a href="/category/fe-sub">FE-Sub</a>
</div>

```

to something like this:

```
<div class="field-item even">
    <a href="/category/fe-sub">
        <strong>FE-Sub</strong>
    </a>
</div>

```

Edit: I tried it out with `mymodule_preprocess_field(&$variables)` but you may not enter html, it will print "-Element

```
function proposals_preprocess_field(&$variables) {
    if (isset($variables) && isset($variables['items']['0']['#options']['entity_type']) && $variables['items']['0']['#options']['entity_type'] == 'taxonomy_term') {
        $variables['items']['0']['#title'] = '<b>'.$variables['items']['0']['#title'].'</b>';
    }
}

```

renders link text:

`<strong>term title</strong>` instead of **term title**

**EDIT:** here is how i made it work: in your template.php:

```
function yourtheme_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';

  foreach ($variables['items'] as $delta => $item) {
    // allow html
    $item['#options']['html'] = TRUE;
    // set html
    $item['#title'] = '<span class="label label-info">'.$item['#title'].'</span>';

    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] .'>' . $output . '</div>';

  return $output;
}

```

# Answer
To make changes to the taxonomy term out put you can use the below function. This is taken from the batrik theme so you would use the function `mytheme_field__taxonomy_term_reference`

To change the markup of the term change #markup the defualt value would be

```
<a href="/drupal7/class/class-1" typeof="skos:Concept" property="rdfs:label skos:prefLabel">term name</a>

```

change that to

```
 $item[#markup] = '<a href="/drupal7/class/class-1" typeof="skos:Concept" property="rdfs:label skos:prefLabel"><strong>term name</strong></a>'

function batrik_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] .'>' . $output . '</div>';

  return $output;
}

```
> 1 votes

---
Tags: 7, taxonomy-terms, theming
---


# Question
Title: Performance: is preferable to use Rules or node_presave/node_save/other hook ?
we know that via hook\_\* we can make everything, but my question is about the use of Rules vs hook\_*. At high level performance programming hook\_* is better that rules, but if we consider a normal level performance ?

In a site where you have installed rules (like a commerce) is better to use hook\_\* or I can create a rule that exec an PHP function? In the first way (hook\_\*) I need to remember in which module an FooBar thing happen (say does something before node's saving, hook\_node\_presave) but I have max performance; second way is via Rules module where I have all rules in one path and I can crete a Rules that is "called" when "condition" "before saving new node of node type XYZ" appair.

Which is better in a normal site ? Or in a site more than normal ?

M.

PS: sorry for my bad english.

# Answer
In practice, it is far easier to debug a hook than a rule that includes a PHP function. So, not only are hooks faster, they are easier to maintain and less likely to present security risks.

You do not need to remember "in which module foo happens" if you put all your hooks in a single custom module for the site. Unless you have an extremely large number of tweaks, using a single module (and version controlling it!) is probably the easiest way to do this.

Regardless of the size of the site, if you want to write custom PHP, you should use a custom module, not rules.
> 3 votes

---
Tags: 7, performance
---


# Question
Title: Adjust number of posts that appear on front page
I currently only have one story that posts to the front page. How do I add more?

I know it's a really n00by question but I have google and visited many different links and they all say to go to the content administration page... but then where?

# Answer
> 2 votes
On Drupal 7: mysite.com/admin/config/system/site-information

Set the **Number of posts on front page** option to your liking.

---
Tags: nodes
---


# Question
Title: Is it possible to reference a field to a node, and also to a user?
My question: Is it possible to reference a field to a node, and also to a user?

I want to keep track of scores scored by users while playing a boardgame. So, I'll need a reference between nodes (boardgame) and users. I'm using the "entity reference" for this.

With the module field\_group and field\_group\_multiple, I can make rows with user field, score field, etc... But the problem here is: the score field is linked to the node, not to the user. (So if I want to make a view and get all scores scored by a player, this will be not possible.)

# Answer
I found an answer. The modules entity\_reference and field\_collection are what I needed. field\_collection makes a collection that has a reference to the node, and also to the user\_reference. An awesome module!
> 1 votes

# Answer
\**EDIT This would probably be best as a module then. You could either create separate views of each player or game instance and use view\_embed\_view() function or You could use a noad\_load() to grab the information as well.

http://api.drupal.org/api/views/views.module/function/views\_embed\_view/7

http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_load/7
> -1 votes

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


title: How to add link to node add form

text:
# Question
Title: How to add link to node add form
I wanted to add link besides editor in add post form that will linked to some static page in the page or it may be link for just some java-script purpose.

Is there any drupal module available to solve this or please suggest how can I proceed to get this done.

-- Thanks for your time

# Answer
> 1 votes
you can add to the node element in a module and call these in your template. e.g.

```
mymodule_node_view()
{
  $node->mylink = '<a href="">Link</a>';
}

```

Then in the node.tpl.php

```
print $node->mylink;

```

---
Tags: 7, nodes, navigation
---


title: Passing url arguments to views

text:
# Question
Title: Passing url arguments to views
I've created a landing page/portal content type and created a series of views for it. However I have run into a problem, i'm not sure how to pass arguments from the urls to the block views on these portal pages.

Basically, if a user goes to http://mysite.com/portal/action I want action which is a taxonomy term to be used as an argument for the block views on the page. Any ideas?

EDIT: To help clarify I am trying to create a page which pulls in information from other parts of my site based on a taxonomy term, so for example http://mysite.com/portal/action would go to a page which contains blocks displaying things like latest news posts in the action catgeory etc.

So far I have created a content type called portal that lets the author set the topic of a portal and then a series of text boxes to add some custom content to the page.

I then set up a view with a series of displays which creates the blocks that pull in information from other parts of the site such as news, and also turned the custom fields made during the creation of the content type as blocks on that page.

My issue is setting up the arguments within this view so that it changes based on the url. So if i created a horror portal page at mysite.com/portal/horror the content would be those items tagged with the horror taxonomy term.

Hope this makes sense?

Edit 2 Solved: Thanks everyone for your help. I ended up adding the following code to the provide default field

```
    if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(arg(1));
if ($node) {
return $node->title;
}
}

```

# Answer
I hope the said page is a view page in itself and you are passing a argument to that page.

If that is the case then you should check "Provide Default" value when you add the view and then select the required property from the dropdown. You would have something like get term id from url or what ever your argument is. Select that and it showup as you want.

If you need more clarification it would be good if you can export the view you have created or explain how you have created the view.
> 3 votes

# Answer
Can you not just use views contextual filters for this? Contextual filters allow you to filter content based on parameters in the URL.

Here's an example of how Contextual filters would work:

http://www.metaltoad.com/blog/using-drupal-contextual-filters-views
> 2 votes

---
Tags: views, 6, blocks, uri
---


# Question
Title: Programmatically assign permisions to role
I have a custom module and with hook\_permission() I create module's specific permissions. Is there a hook (hook\_role\_permission) in which I can create a module specific role and assign it's permissions?

I don't want to put these in custom\_module.install file because I don't want to reinstall the whole website.

# Answer
You don't need to re-install the whole website just to make a change to your .install file...you can just implement `hook_update_N()` instead.

```
/**
 * Description of the update.
 */
function MYMODULE_update_7100() {
  // Perform some tasks. From the comments it looks like you have the logic you need.

  return t('Tasks completed');
}

```

After adding that code visit update.php and follow the instructions (or run `drush updatedb`) to update the database.

The changes will then be applied, without having to reinstall your modules.

This hook is the best place for your code in this situation (in my opinion) as it will only need to be run once. The update system will make sure of that on your behalf, and if you need to make further changes you can just add another update function.

Please make sure you read through the docs fully before giving it a go, there are some caveats that you really should know. Basic stuff but quite important
> 2 votes

---
Tags: 7, users
---


title: Unrecognized migration

text:
# Question
Title: Unrecognized migration
I am using this example: https://gist.github.com/2596787 as a base for importing some static HTML to a Drupal 7 fresh install. Using `drush ms`:

```
Group:                Total  Imported  Unimported  Status  Last imported

HtmlfilesNodeMigration

HtmlfilesNode         2046   0         2046        Idle    2013-01-23 13:58:01

```

I can see that the Migration class seems to be setup. However when I go to run the migration from drush I get:

```
Unrecognized migration: HtmlfilesNodeMigration                           [error]

```

Trying through the UI, I get

```
Fatal error: Class 'HtmlfilesNodeMigration' not found

```

Any ideas, pointers etc would be a great help. I can post the info/module/inc files I am using if needed.

# Answer
I've made a bit of progress. I had created the HtmlfilesNodeMigration class outside of the actual hook\_migrate\_api function.

So instead of:

```
return $api;

}

class HtmlfilesNodeMigration extends Migration {
//code
}

```

I needed:

```
return $api;
class HtmlfilesNodeMigration extends Migration {

  }

}

```
> 0 votes

---
Tags: importing-exporting, migrations
---


# Question
Title: Adding extra parameter to hook function in custom module / get custom variable inside a hook from outside of that hook
I would be glad to pass an extra variable that is created outside to the inner function in my custom module. That inner function is a hook. But i can not pass variable as an pareamter of that function, or could I ?

Nice to have ;) :

```
$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
echo $foo;
}

```

As a workaround, i can wrap $foo in a function and do i this way

```
function process_vars () {
    $foo = 1;
return $foo;
}

function hook_tapir_table_alter (&$table, $table_id )  {
    echo process_vars ();
}

```

How could i go without function call to outside function ? Any clues? Thanx!

# Answer
You're already doing it the right way. You aren't in control of that particular hook so you can't control how it's invoked, and what parameters are passed.

Couple that with this information from the `drupal_alter()` docs:

> A maximum of 2 alterable arguments is supported. In case more arguments need to be passed and alterable, modules provide additional variables assigned by reference in the last $context argument:

And that means that in order to make changes to the arguments you'll need to patch the module that provides the hook.

You might want to consider `variable_get()` and `variable_set()` if the `$foo` variable is likely to change at all, or DB storage if it's something major.

But using a helper function to return that data is perfectly good practice; there are dozens of examples of the same in Drupal core itself.

Or....you *could* use the `global` keyword (emphasis because I wouldn't personally recommend it, it's not particularly good practice to pollute the global scope).

That would go something like this:

```
$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
  global $foo;
  echo $foo;
}

```
> 1 votes

---
Tags: hooks
---


title: Styling a Calendar View Page

text:
# Question
Title: Styling a Calendar View Page
I can't seem to get any templates to work with my Calendar View Page.

In the view settings, clicking Theme Information reveals some possibles but I've tried them all.

I'm not sure what to name my file to allow it to work as a theme template.

I'm not sure how to theme this Calendar! I only want to add a custom drop down menu above it!

# Answer
> 1 votes
You need to clear the cache before any templates you add will be recognized.

# Answer
> 0 votes
The one you are looking for it Display output. You can name it as the last entry in that row. and then click the **rescan button** so that it takes your template. the template should be placed in your theme folder.

There is a header variable being printed in there you can place the drop down some where there so that it is displayed in the header

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


# Question
Title: How to get Panels to override node with "no extras"
I'm having a problem with the node/%node use of Panels. I would like to display the body content of a node in one pane and all the extra fields which I have added into the content type in another.

The problem I'm hitting is the "no extras" option in the Pane settings makes no difference - all the fields (body and extra fields) are always displayed.

Searching around the web, nobody else seems to have this issue. Since it is what panels is supposed to be good at, I think I'm missing something. I've tried using the panels wizard and doing this manually. I had it working in Panels 1 in D5 :(

I'm using D7 and Panels 3.

Any suggestions gratefully received!

Edward

# Answer
> 1 votes
The problem is (I think) that when you added content (Whichever Variant -\> Content -\> Gear -\> add content) you clicked Node and then Node content. Node Content will display all of the content of the node (Title, Body, and all Fields). If you just want to display the body choose Node body.

Then in another Pane (Panel Biggest -\> Region -\> Pane Smallest) you can add your other fields.

Here's a video that talks about Panels and Panels Everywhere and can help show this in action.

http://www.youtube.com/watch?v=v6zMcfTxkhc

Hope this helps!

# Answer
> 0 votes
While you can do this with any panels module, the most direct usage of panels for layout of different fields in pre-existing nodes is via the Panelizer module.

---
Tags: panels, 7
---


# Question
Title: Can I use custom fields inside custom fields in Drupal 7?
I am making a custom field and would like to use other custom fields -- like the Link or Media fields -- inside it. Can I do this, and if so how do I determine what #type to include in my field definition?

For example, the pattern "Image + Linked Headline + Brief Description" happens frequently enough in my content that I am trying to create a custom field that combines these. But a lot of what I need already exists in both Link and Media plugins, and I'd rather not recreate that functionality if possible.

I have already tried using the Field Collection module for this, but can't because it does not support translation.

**Edited**

I think I have found my way around the Field Collection translation problem by switching to field translation instead of node translation. Field collection seems to be a little buggy there, especially for collections made prior to turning on entity translation, but so far it seems to be working.

A yes/no answer to this would still be interesting, though, for future custom-field development. The more I think about it, the more I think the answer is likely "no."

# Answer
Please let me know if I'm misinterpreting your question — essentially, you're asking how to group up fields of content that appear frequently together on your Drupal site? Without using Field Collection... hmmm...

Well, first potential option is the Field Group module. However, it may not be exactly what you want seeing as how you mentioned Field Collection. It may be worth looking into though. Not sure it supports translation though.

The next potential option I see is changing the actual Image entity through the File Type interface provided by the Media module. At this screen, you can actually adjust the Image entity to contain extra fields. In doing this, all you would need then is place the Image field in your content type. The user uploading an image via this Media field would then be prompted to add the linked headline and a brief description after uploading the image.

Because the Media module documentation does an AWESOME job of explaining how to modify an Image entity, here is the documentation page about managing/editing file types — scroll down to the start of the section "Manage the Display of Images (Manage File Types)". After adding these fields to your Image entity (or a new entity), you'll be able to manage the display like you would for a content type.
> 1 votes

---
Tags: entities
---


title: Display messages in bootstrap file

text:
# Question
Title: Display messages in bootstrap file
I have a file that I have bootstrapped and I am trying to print messages but I can't get it to work. Here is the code does anything look wrong (mysite was changed)?

```
<?php
define('DRUPAL_ROOT', '/home/mysite/public_html');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

<html>
<body>
 <div class="description">
  <?php global $user;

     print "Welcome " . $user->name;
     drupal_set_message(t("Don't panic!"), 'warning');
     print $messages;
  ?>
</div>
</body>
</html>

```

# Answer
> 3 votes
To get the list of the messages set with `drupal_set_message()`, you should call drupal\_get\_messages().

Drupal doesn't use any global `$messages` to store those messages. They are stored in `$_SESSION['messages']`, but you should really use `drupal_get_messages()`.

`drupal_get_messages()` returns an array; this means you cannot simply use the following code.

```
$messages = drupal_get_messages();
print $messages;

```

---
Tags: 7, bootstrapping
---


# Question
Title: How do I use views to override a taxonomy term page for only terms with a single vocabulary?
How do I configure a view to allow me override only term pages within a specific vocabulary without overriding all other term pages?

Edit: Due to the requirements of the project, this must be done with a view and not overridden with a custom tpl.

# Answer
I ended up using the Taxonomy Views Integrator module.

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.
> 8 votes

# Answer
If i were you I'd try the using the Pages module functionality combined with views for your display and contexual filters to show the taxonomy according to vocabulary. Simply enable the taxonomy template page(admin/structure/pages). The contexts comes set so all you have to do is create a View with a contexual filter to that the taxonomy page as a block field and place it on that page. you should be able to figure out the rest ;}
> 3 votes

# Answer
If what you are asking is how do you override

```
www.yoursite.com/taxonomy/term/138

```

when term 138 is of a certain vocabulary, but leave

```
www.yoursite.com/taxonomy/term/139

```

alone when it's not, you *should* be able to copy `taxonomy-term.tpl.php` from the taxonomy module's directory to your theme and modify it.

In it, it basically does this:

```
<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>
    <h2><a href="<?php print $term_url; ?>"><?php print $term_name; ?></a></h2>
  <?php endif; ?>

  <div class="content">
    <?php print render($content); ?>
  </div>

</div>

```

and you could change it to something along the lines of

```
<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>
    <h2><a href="<?php print $term_url; ?>"><?php print $term_name; ?></a></h2>
  <?php endif; ?>

  <div class="content">
    <?php if ($term->vid==VOCABULARY_IN_QUESTION): ?>
      <?php print views_embed_view(VIEWYOUWANT, 'default', $term->tid); // or any other content you want printed out instead of the default
    <?php else: ?>
      <?php print render($content); ?>
    <?php endif; ?>
  </div>

</div>

```

I say *should* because I only know D7 intellectually (if that lol) and don't have a test bed, but I've done similar with D6. There is a great tutorial Crazy Awesome Taxonomy Pages also based on D6 that might be of help in giving you some ideas you could "port" over to your D7 installation.

ADDITION: To your question of using the supplied default views: if you want to use them, you may have to enable them, grab the one your want for this specific case, eg, taxonomy/term/%, and clone/copy it and then disable the supplied one and then in the new cloned one, remove the page menu stuff so Views doesn't use it there anymore and is instead called directly from here. I can't think of a better way of explaining this but maybe someone out there can help :) Of course, if you write your own view, this isn't needed.
> 2 votes

# Answer
Perhaps the project taxonomy display would work for you. It integrates with panels and display suite, but does not require them. It may require some hooks to get the right effect; these would look a lot like @Jimajamma's custom taxonomy term template answer (which would also work fine).

It's too bad that panels is not an option. With panels, you could define your selection rules to filter on the taxonomy term's vocabulary, and just drop your existing view into the panel content. You could create a variant for the other vocabularies that output the standard taxonomy term display. This would be very fast to put together, wouldn't require any custom coding, and wouldn't have to affect any pages on the site except taxonomy terms. One of the other alternate solutions will probably work just as well, though, with perhaps just a bit more effort.
> 1 votes

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


# Question
Title: Where are these modules - "Views Slideshow: SingleFrame" & "Views Slideshow:ThumbnailHover"?
Were these integrated into some other modules? Cannot find a trace of them anywhere on drupal.org but they are used at many places, like in this tutorial: http://mustardseedmedia.com/podcast/episode42

Screenshot from the tutorial showing the Modules: http://www.tiikoni.com/tis/view/?id=0000d1a

# Answer
> 1 votes
They are packed with the Views Slideshow module.

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

# Answer
> 1 votes
This from a release outline for one of the 6.x versions:

Singleframe and Thumbnailhover have been combined into the Views Slideshow Cycle module. Singleframe and ThumbnailHover are still available, but are marked as legacy modules. They will be removed in the next major release. There is no migration path from singleframe/thumbnailhover to cycle.

See it here:

http://drupal.org/node/926932

---
Tags: views, 6, paging, javascript
---


# Question
Title: Content Strategy: Similar but unique content
I am building a Drupal 7 site and need some help with my content strategy. One type of content I regularly work with are workshop/conference pages. Each workshop/conference may have one or more of the following (proposed content type in parens)

* The workshop/conference (book page)
    + About (basic page)
    + Registration (webform)
    + Schedule (basic page)
    + Lodging information (basic page)
    + Transportation information (basic page)

The main benefit of this approach: we'll use a Book Navigation Block to have a menu for each workshop/conference sub-page.

However, I see several disadvantages:

* Two different workshops/conferences may require unique "Lodging Information" pages. Drupal won't let me title two different pages "Lodging Information" even though each belongs to a separate book. I could name each specifically, like
    + "Lodging Information Conference FOO 2013"
    + "Lodging Information Conference BAR 2013"
    + "Lodging information Conference BAZ 2013"
* Thinking long-term. . . Let's say in the future our site documents dozens/hundreds of workshops/conferences. The drop-down to select Book parent pages could get excessively long. If we don't stick with a good naming convention, this could be a bit overwhelming for content contributors.
* I don't like the Book navigation helpers near the footer of every parent/child page (table of contents on parent, previous/up/next buttons on all children pages). Editing the core Book module seems like overkill to remove this functionality. Perhaps there's a better way?

Using the Book Module brings up more questions than answers. Is a the Book Module the best approach to implementing a workshop/conference page?

# Answer
> 0 votes
I would agree with beth's post earlier, use a taxonomy to group all the different content types you are working with. For example, create a taxonomy vocabulary named "Conference". For EACH of the content types used to store information about the conference, add a field: Label: Conference Type: Term reference Form element to edit the data: Autocomplete term widget (tagging)

Now, when you are filling in the details using your different content types, tag your content with the conference name. Later you can filter display of that information by filtering on the taxonomy term.

---
Tags: 7, nodes
---


title: Calendar week views block dates

text:
# Question
Title: Calendar week views block dates
**Drupal 7.14 - Calendar Module 7.x-3.4**

Does anyone have an idea how to display the dates alongside the week days on the week views block?

# Answer
First you need to copy calendar-week-overlap.tpl.php from calendar/theme to your custom Drupal theme and add the following lines:

**Add this code before html code - after line 30**

```
$start_date = date_format($view->date_info->min_date, 'U');

```

**After line 40 `<th class="calendar-agenda-hour"> </th>` replace the following code**

```
 <?php foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>
    </th>
  <?php endforeach; ?>

```

**with this code**

```
<?php $i = 0; foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>, <?php print date('d/m/Y', strtotime("+$i day", $start_date)); $i++ ?>
    </th>
  <?php endforeach; ?>

```
> 1 votes

---
Tags: 7, blocks, datetime
---


# Question
Title: Calling node delete (node_delete_multiple) is not deleting all comments from database
When I do a query on the database (`SELECT * FROM comment c where c.nid = 119445765;`) I get a `12 rows in set (0.00 sec)`
The I call `node_delete_multiple(array(119445765))`. Then I go back to the database and perform the same query `SELECT * FROM comment c where c.nid = 119445765;`) I get a `5 rows in set (0.00 sec)`.

Now These may be replies to comments since this is a forum. However, how do I ensure they are deleted? Do I have to perform the query myself?

UPDATE:

I have stepped debug this issue here is my notes: 1. `node_delete_mutliple` -\> invokes `comment_node_delete`
2. `comment_node_delete` perform this query `$cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();` and it correctly returns all cids associated with the node.
3. `comment_node_delete` calls `comment_delete_multiple` which in turns calls `$comments = comment_load_multiple($cids);` **NOW** `comment_load_multiple($cids);` is not returning the correct number of comments. Surprisingly it is always ommiting comments by a certain user.

I am continuing to debug and will add more info,

**Update 2**

```
 $cids = db_query('SELECT cid FROM {comment}
 WHERE nid = :nid', array(':nid'  => 119318471))->fetchCol();
 dpm($cids); // Gives the correct number of $cids
 $comments = entity_load('comment', $cids, $conditions = array(), TRUE);
 dpm($comments); // Is an array with fewer comments than number of $cids

```

So the problem so far is in entity\_load.

**Note** I failed to mention that the database is migrated from another system and may contain some bad references.

# Answer
you should check the watchdog table to see if there are any errors. The function calls comment\_delete\_multiple and with in that functions deletes all the replies as well.

If there was any error during this process it would rollback to a specific point in this case I guess it would be during the delete process of child comments. Tne information would be stored in the watchdog table with type set to comment. This would give you a hint as to why it was not deleted.
> 1 votes

# Answer
OK, it is because of some incorrect migration of data. In other words, the problem lies with bad references in my database and not a drupal bug.
I traced down the problem to `CommentController`. In there there the method for building a query add additional joins:

```
protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
$query = parent::buildQuery($ids, $conditions, $revision_id);
// Specify additional fields from the user and node tables.
$query->innerJoin('node', 'n', 'base.nid = n.nid');
$query->addField('n', 'type', 'node_type');
$query->innerJoin('users', 'u', 'base.uid = u.uid');
$query->addField('u', 'name', 'registered_name');
$query->fields('u', array('uid', 'signature', 'signature_format', 'picture'));
return $query;

```

}

When commenting out the inner joins the comments were returned in from the entity\_load function. However, **since** the data was not migrated well, the uid associated with the comment does not exist. And hence the inner join with the user table was empty for that specific node. When I commentned it out I got this result (sample result):

```
... (Object) stdClass
cid (String, 9 characters ) 119410583
pid (String, 1 characters ) 0
nid (String, 9 characters ) 119318471
uid (String, 6 characters ) 983643
subject (String, 14 characters ) Re:
hostname (String, 0 characters )
created (String, 10 characters ) 1340215426
changed (String, 10 characters ) 1340215426
status (String, 1 characters ) 1
thread (String, 3 characters ) 02/
name (NULL)
mail (NULL)
homepage (NULL)
language (String, 3 characters ) und
new (Integer) 0
node_type (String, 13 characters ) comment_node_

```

Note name, mail.
> 0 votes

---
Tags: comments, nodes
---


# Question
Title: What is the difference between the Load and Render objects in Devel?
When viewing a Node in the Devel tab, what are these different objects Load and Render? How and where would I have access to them in the theme layer?

# Answer
The "Load" tab shows the output of node\_load(), while the "Render" tab shows the output of node\_view(). In the first case, the output is a node object; in the second case, the output is an array as accepted by drupal\_render().
> 7 votes

---
Tags: debugging
---


# Question
Title: How can I distinguish dynamic pages on a hook_menu?
```
function mymodule_menu_local_tasks(&$variables) {
   if ( request_path == 'yadda') :
   ....
}

```

I can do that.. but the problem is I want to include this for the tabs on `user/$id/edit` and I'd rather not do regex or check the beginning and end of the string...

Is there some way I can pull a variable that relates to that specific page type?

# Answer
You can tell if you're on a node page with `menu_get_object()`, but other than that it's difficult. `menu_get_object()` can return other objects than a node, but you need to know the type of entity before you call it (not much help in your situation). There's no generic solution that I know of in Drupal 7.

There is the `drupal_match_path()` function though, which you can use with wildcards, e.g.

```
if (drupal_match_path(request_path(), 'user/*/edit')) {
  // On a user edit page
}

```
> 3 votes

---
Tags: 7, uri, routes
---


# Question
Title: Can't login to Drupal after Varnish install (reverse proxy)
I setup Varnish for Drupal 7.x; when I go to settings.php to uncomment the following line, and I try to login as administrator, I am just redirected to the same page; nothing happens. No idea what could I have done wrong.

```
$conf['reverse_proxy'] = TRUE;

```

# Answer
> 2 votes
I'd like more details. To start, here's what I have in my settings.php:

```
/**
 * Varnish settings
 */
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
$conf['reverse_proxy'] = true;
$conf['cache'] = 1;
$conf['cache_lifetime'] = 0;
$conf['page_cache_maximum_age'] = 21600;
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';
//$conf['page_cache_invoke_hooks'] = false;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
$conf['omit_vary_cookie'] = true;
$conf['page_cache_invoke_hooks'] = FALSE;

```

All of that might not be necessary, like $conf\['page\_cache\_invoke\_hooks'\] = FALSE - but it's working for me

First, did you set Varnish to port 80 and Apache to port 8080? First try to access the site via http://example.com:8080 to see if Apache is still serving pages. Another way to check for servers working is by opening terminal via ssh and typing 'netstat -anp | grep httpd'. Here is my output:

```
netstat -anp | grep httpd
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      324/httpd

netstat -anp | grep varnish
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      24841/varnishd
tcp        0      0 127.0.0.1:6082              0.0.0.0:*                   LISTEN      24840/varnishd

```

You can see that apache (httpd) is working on :8080 and varnishd (d for daemon i.e. service) is running on :80 and :6082 where :80 is varnish and :6082 is its backend.

If you CAN see site on :8080 and you have varnish running on :80 and :6082 you should go to the varnish drupal config page via `http://example.com:8080/admin/config/development/varnish`

From there you should select the correct Varnish version set, the Varnish Control Terminal set to 127.0.0.1:6082, and your Varnish Control Key set. You can find this by seeing the output of the secret file. In CentOS you can do this by: `cat /etc/varnish/secret` \- this will give you a 30ish char long string to input. At the bottom of this settings page you will find "Status: Varnish Running" hopefully.

If you have all of this working and still can't get the site to show, it will be giving you an output noting Varnish and a Guru Meditation. This shows you that varnish is indeed running but just isn't configured correctly, most likely in your .vcl file. If no guru meditation and site not working, you probably haven't set the sysconfig correctly. Edit - again CentOS - `/etc/sysconfig/varnish` using vi or nano. I have the following uncommented:

```
// using Alternative 2, Configuration with VCL
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s file,/var/lib/varnish/varnish_storage.bin,1G \

```

Check that the .vcl file is correctly referenced and that the port (:6082) is the same as what you found with netstat above.

Finally, if you are getting the Varnish Guru Meditation the .vcl is the issue. In this case here's some of what I have for the .vcl:

```
BEGINNING OF FILE ->
backend default {
  .host = "127.0.0.1";
  .port = "8080";
  .connect_timeout = 600s;
  .first_byte_timeout = 600s;
  .between_bytes_timeout = 600s;
}

sub vcl_recv {
//TRY THIS AT BEGINNING ->
return(pass)
..
}

```

The `return(pass)` will pass EVERYTHING and thus Varnish won't actually be caching anything, but you can use for diagnosis. Remember after changing anything varnish related you need to restart varnish by: `service varnish restart` \- if you .vcl has any errors it won't restart.

# Answer
> 2 votes
Apparently your login/register pages are served by Varnish and your vcl configuration strips SESS cookie (seen in many examples). Here is what you should add to your vcl config (Varnish 2.x), in vcl\_recv function:

```
# Do not cache these paths.
if (req.url ~ "^/status\.php$" ||
    req.url ~ "^/update\.php$" ||
    req.url ~ "^/ooyala/ping$" ||
    req.url ~ "^/admin/build/features" ||
    req.url ~ "^/info/.*$" ||
    req.url ~ "^/flag/.*$" ||
    req.url ~ "^.*/ajax/.*$" ||
    req.url ~ "^.*/ahah/.*$" ||
    req.url ~ "^/user/.*$") {
    return (pass);
}

```

This will always pass 'user/' related pages to your backend (Apache/nginx/your web server of choice) and Varnish will never serve cached versions for this pages.

# Answer
> 0 votes
I guess varnish strips your session cookies. I guess you are using D7 or pressflow. Did you install the Varnish module?

---
Tags: users, proxies
---


# Question
Title: Why is my custom module giving a "page not found" message when using https?
I have a custom module that is a form. The first section in the hook\_form() function is

```
if (!$_SERVER['HTTPS'] == 'on') {
    drupal_goto('https://mysite/mymodule');
}

```

If I comment out this section, the form works as expected. If the https redirect is left as is, I get a page not found error. This occurs only for unauthenticated users. If I am logged in, the form displays correctly.

I am on Drupal 6

EDIT: I turned off caching on my Drupal site and the form works again. The caching must have broken my form. I will see if I can find a way to not allow the form to be cached by Drupal.

# Answer
```
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

```

or take a look at this article
> 0 votes

---
Tags: 7, hooks, ssl
---


# Question
Title: Which module will allow me to see the two buttons "Customize this page" and "Change the layout"?
When I use the Drupal distribution Openchruch, and I view a page as an administrator. There are two buttons in bottom: **customize this page** and **change the layout**

## Which module will let these two buttons appear?

# Answer
Panels and "Panels In-Place Editor" (sub-module of panels)
> 2 votes

---
Tags: panels, distributions
---


# Question
Title: Multiple forms and required fields affecting hook_form_FORM_ID_alter()
When creating a new content type, the $form\_id is correctly picked up in my module. Let's say in my example, my form is called the 'foo\_form'. The below hook\_form\_FORM\_ID\_alter function works fine when I go to add/content/foo-form

```
function MyModule_form_foo_form_alter(&$form,&$form_state,$form_id) {
  echo 'It works!';
}

```

The problem is that my content type has some required fields. If the user does not fill them in all out and submits, then the submission fails as expected.

The problem is that now on the error page telling the user that he or she needs to fill out the required fields, the $form\_id is no longer 'foo\_form', but instead named 'search\_block\_form' because on all my pages I have a search block on the left side bar. Now my hook\_form\_FORM\_ID\_alter() does not get invoked because my module is getting 'search\_block\_form' as its $form\_id instead of 'foo\_form'.

I tried using hook\_form\_alter(), which works globally, but because there are 2 $form\_id's on this required fields error message page, my MyModule\_form\_foo\_form\_alter() gets called twice (once for 'search\_block\_form' and 'foo\_form')!

How do I resolve this issue, other than exclude displaying the search form block when adding new content? How do I make 'foo\_form' the primary $form\_id???? I find this odd since if I go to add a new content, Drupal is "smart" enough to ignore the 'search\_block\_form' $form\_id.

EDIT: My code to test visibility about what $form\_id's are present before submitting and after submitted without filling in all the required fields.

```
function MyModule_form_alter(&$form,&$form_state,$form_id) {
  case 'search_block_form':
    //this one always shows up
    echo $form_id . "<br>";
  break;
  case 'foo_form':
    //does *not* show up when submitting form
    //with missing required field values
    echo $form_id . "<br>";
  break;
}

```

# Answer
To do form validation use the form API validation capabilities:

http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#validation

http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#validate
> 0 votes

# Answer
Use `hook_form_alter()`

and in that use a if condition

```
if($form_id == 'foo_form')
{
  //do your stuff
}

```

To target a specific node edit page you would use the following function

```
MY_MODULE_NAME_form_CONTENT_TYPE_NAME_node_form_alter(&$form, &$form_state, $form_id)

```

You can try out the following test to see if you the hook is working during the validation phase.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#description'] = 'a';

}

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#description'] .= 'b';
  dsm($form_id);
}

function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#description'] .= 'c';
}

```

This will add **a** **b** and **c** below the title.

The first two function would work on all the node add edit pages the last one would work on the Basic Page alone you can change the **page** to the name of your content type to test it with your content type.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: how do i create a subscribe or join group link in drupal 7?
I am trying to create a join or subscribe link for groups on my site but i don't know how to go about it (using views). I want to create something similar to this http://www.popsugar.com/community/suggest .

Any suggestions?

# Answer
> 3 votes
Use the field "Content: Group".

---
Tags: organic-groups
---


title: Unable to set custom breadcrumbs

text:
# Question
Title: Unable to set custom breadcrumbs
I've enabled the Custom Breadcrumbs module and given the administator (me) rights to create custom breadcrumbs. I am seeing this message on nodes, where it should allow me to set the custom breadcrumb:

Custom breadcrumbs have not been created for this test\_content\_type page. Use the Custom Breadcrumbs Administration Page to create a breadcrumb.

Going to this page the settings are as follows: Show only custom\_breadcrumbs where

```
Type is node

```

Where I see: Namesort descending Breadcrumb Type Operations No custom breadcrumbs have been defined.

What am I missing?

# Answer
From the custom breadbcrumbs README.txt:

> * Enable the module
> * Assign 'administer custom breadcrumbs' permission to those roles that should be allowed to add/edit/delete custom breadcrumbs.
> * Assign 'use php in custom breadcrumbs' to roles that should be allowed to use php to determine breadcrumb visibility.
> * Go to Administer \> Site building \> Custom breadcrumbs to add new breadcrumbs
> * Click "Add a new custom breadcrumb"
> * Choose the node type to create a breadcrumb trail for
> * For the titles, put each "crumb" one line after another (There is no need to put in "home"):
>
> Item 1 SubItem A SuperSubItem X
> * For the paths, put the path to each crumb starting after the domain name. Don't include a leading or trailing slash.
>
> item1 item-1/subitem-a item-1/subitem-a/supersubitem-x
> * Click save to save the breadcrumb
> * Visit the page and your breadcrumb should appear!
> 1 votes

---
Tags: breadcrumbs
---


title: How to call function by reference?

text:
# Question
Title: How to call function by reference?
I want to call `uc_stock` module by reference in my custom module. Actually I want to add and delete stocks. I have done this first using node\_presave and it works successfully, here is the code:

---

```
function my_module_node_presave($node){
  if($node->type == 'add_stock') {
    //drupal_set_message('stock_save :'.print_r($node,true));
    //drupal_set_message($node->field_reference['und'][0]['nid']);
    //$nid=16;
    //$p_node = node_load($nid);
    //drupal_set_message($p_node->field_product_stock['und'][0]['value']);
    $product = $node->field_stock_value['und'][0]['value'];
    drupal_set_message('product :'.$product);
    $nid = $node->field_reference['und'][0]['nid'];
    drupal_set_message('nid :'.$nid);
    $p_node = node_load($nid);
    $stock = $p_node->field_product_stock['und'][0]['value'];
    drupal_set_message('stock :'.$stock);

    $stock = $product + $stock;
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock;
    //$p_node = node_load($nid);

    //drupal_set_message($p_node);
   // drupal_set_message('node_load :'.print_r($p_node,true));

    node_save($p_node);
    //drupal_set_message('after saving product');
  }
 elseif($node->type == 'sold_stock') {
   $new_product = $node->field_sold_stock['und'][0]['value'];
   drupal_set_message('new product :'.$new_product);
  $new_nid = $node->field_stock_reference['und'][0]['nid'];
   drupal_set_message('new nid :'.$new_nid);
   $new_node = node_load($new_nid);
  $sold_product = $new_node->field_product_stock['und'][0]['value'];
   drupal_set_message('sold product :'.$sold_product);
   $product_sold = $sold_product - $new_product;
   drupal_set_message('product sold :'.$product_sold);
   $new_node->field_product_stock['und'][0]['value'] = $product_sold;
   node_save($new_node);
 }
}

```

---

Now I want to do the same thing as done in `uc_stock` module of Ubercart.

# Answer
I'm not sure if I understood your question correctly, but if you want to change the stock for a product you can simply call the `uc_stock_set()` function (where the product is in the $node variable, and the new stock is in the $stock variable)

```
$stock = 5;
uc_stock_set($node->model, $stock); // sets stock to 5

```

Or use `uc_stock_adjust()` to increase or decrease the stock by a certain amount

```
uc_stock_adjust($node->model, 1); // adds 1 to current stock, stock is now 6

```

---

I am assuming that you have

* Installed ubercart
* Activated the uc\_stock module
* Created a product, and set its SKU (model) to a certain value, say MODEL\_1
* Gone to the 'stock' tab on the edit node page of this product and activated the stock for MODEL\_1

At this point we have a product, represented by a node. This product has one (or many) associated SKUs. Each SKU has an associated stock stored in the database by uc\_stock.

Only once all of this is in place can we can go ahead and use the `uc_stock_set` and `uc_stock_adjust` functions.
> 1 votes

---
Tags: ubercart
---


# Question
Title: Forms - Save Draft and unique user access code to Resume (on any computer)
Is it possible for the site users to get a unique access code, so that they can resume the form from any computer?

I am currently using the Webform module for its "Save Draft" feature and am wondering if it is also able to provide an access code ...

# Answer
> 0 votes
You could always have users register accounts, use their passwords as the access code, and then use one of the revision management modules (Workbench, Revisioning/Workflow, etc.) to handle draft/publishing.

---
Tags: forms, webforms
---


# Question
Title: Placing a block next to the comments section
I have a problem that I have been working for hours now. Basically, I would like to place a block next to the comments div. So, in the footer of my page, I'd have all the user comments to the left and in the right side, I'd have my block. I know I have to do some realignment in the page.tpl.php, but I just can't get the comments div and the block div to appear side by side. Would appreciate any help on this.

Edit:

I added this in my template.php file:

```
/**
 * Custom function to render a block to manually position it in the node.tpl.php markup
 */
function mytheme_block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}

function mytheme_preprocess_node(&$vars) {
    //Add the related_by_term block to the variables array so that we can render it in our node.tpl.php file
    $vars['my_block'] = block_render('views', 'my_block-block_1');
}

```

And in my node.tpl.php, I added this after the comments section:

```
<?php print $my_block; ?>

```

But what I am getting is a memory limit exceeded error. Basically, the block\_render function is causing some problem. It's this line that is causing the problem:

```
_block_render_blocks(array($block));

```

Any input would be highly appreciated. Spending hours on this issue. Thank you...

# Answer
> 1 votes
The regions are usually printed in the page.tpl.php

And the comments are printed with in the node.tpl.php

You could follow the below steps to get a region with in node.tpl.php

1. Add a region in the .info file by adding `regions[custom] = Custom`
2. If you already have a preprocess\_node in you theme `template.php` then add the below code or else create a function in the `template.php` with the name `mythemename_preprocess_node(&$variables)`

$variables\['custom'\] = block\_get\_blocks\_by\_region('custom');

This would give you a variable with in the node.tpl.php named custom. This is a renderable array of the blocks with in the region.

Now in your `node.tpl.php` you would be having something like `<?php print render($content['comments']); ?>` above or below that you can add

Or you could wrap them in a DIV to suit your requirement.

What ever you add to The region custom would now be displayed near the comments

---
Tags: theming, comments
---


title: How to pass different arguments to view

text:
# Question
Title: How to pass different arguments to view
I am using profile2 field as user reference and also i filter results with an entity selection. The widget used is an autocomplete and i have a problem with it. If i type in the nid of a user the result returned is correct, but it does not work if i type in the name of the user or anything else related to it besides nid.

Example:

* for this url everything is fine ( returns the name of profile with nid == 1):

```
entityreference/autocomplete/single/field_test/profile2/profiletype/NULL/1

```
* but if i type "name" the result is null

```
  entityreference/autocomplete/single/field_test/profile2/profiletype/NULL/name

```

Is there any configuration that i miss ? Is it possible to change the behavior of autocomplete ?

# Answer
The answer was to modify the views query!
> 0 votes

---
Tags: views, entities, users
---


# Question
Title: 1 Better exposed Filters for 2 views blocks
I would like to make a page with 2 Views blocks. The views show the same content type, but in a different format.

Block A contains an OpenLayers map.

Block B contains a listing result.

I want to filter both Views based on taxonomy, but with one exposed filter block.

I've made one Better Exposed Filter for block A, but I don't know how to control both blocks with one exposed filter.

Can anyone help?

# Answer
> -5 votes
My solution is just to add a hook `mymodule_form_alter`.

# Answer
> 9 votes
You want to create an attachment view display and add it to your main display. For example, if you currently have the OpenMaps display working, create a listing display as an attachment and attach it to the OpenMaps display. Make sure you set "Inherit exposed filters" to "yes" to ensure both displays are using the same set of filters. In views 3 you can find this settings in the Attachment display settings:

---
Tags: views
---