# Question
Title: How can I get the content of a mini panel that is limited to admin-only access using a scheduled rules component?
I'm using Rules to e-mail myself the content of a Mini Panel, which contains several views that are restricted to admin-only access.

I am using a component (Action set) that consists of two actions:

* **Send e-mail**
* **Schedule component evaluation** (re-schedule the same component to be evaluated the following day)

For **Send e-mail**, the body of my message looks like this (based on this code):

```
<?php $block = module_invoke('panels_mini', 'block_view', 'admin_user_role_statistics'); print $block['content']; ?>

```

When I first triggered this component (using a rule that I created to trigger the component for the first time by viewing a user profile), I was logged in as an administrator, so the e-mail I received shows all of the content of the mini panel as I expected. However, the following day, when the scheduled component was evaluated, the body of the e-mail message was blank, presumably because it was not sent by an admin user.

I re-enabled the rule to trigger the component and tried it as a non-admin user: the message body was empty. I then tried it as an administrator: the message had the full content.

So, what can I do to make sure the component is evaluated as if triggered by an admin user?

# Answer
> 2 votes
The problem seems to be an anonymous user triggering the component and since you want an admin user to run the component, you will have to *impersonate* the admin user.

Try this code inside your components to *impersonate* the admin user :

```
global $user;
// Save the current user
$current_user = $user;
// Save user session
$current_session = drupal_save_session();
// From now on we don't want to save the session, since it would be unsafe
drupal_save_session(FALSE);
// We impersonate admin user
$user = user_load(1);
// Do wathever needs to be done.
// ...
// Now let's restore the triggering user and session.
$user = $current_user;
drupal_save_session($current_session);

```

# Answer
> 2 votes
This page has more detail about how to set up rules scheduler to run as admin. (Wouldn't it be nice if someone made a module to solve this problem?)

---
Tags: rules
---


title: How to use Hansel Module?

text:
# Question
Title: How to use Hansel Module?
I was asked to use the Hansel breadcrumbs module to derive the breadcrumbs in a site, but I hardly understood the flow of the module. I cannot get a clear picture even from the modules documentation. I would appreciate any help to clarify my doubts about this module.

* I have removed a custom breadcrumb module, and installed the Hansel breadcrumbs module.
* I want to create breadcrumbs in specific page like Home-\>Bussiness-\>Faq and so on.

How is this possible with the Hansel breadcrumbs module?

# Answer
"Switch on node type" is like a `switch($case){}` statement in PHP (and other languages).

After selecting "Switch on node type" in Hansel, you will need to provide the \*machine\_name\* of the node-type in the "Name" field that Hansel presents. For instance, you can enter one of the following in the "Name" field:

* `article` -- will target Article nodes
* `blog_entry` -- will target Blog Entry nodes
* `webform` -- will target Webform nodes
* `<default>` (for remaining node types)

If it were in code, it would look something like:

```

switch($node->type) {
  case 'article':
    // Make an article crumb
    break;
  case 'blog_entry':
    // Make a blog-entry crumb
    break;
  case 'webform':
    // Make a webform crumb
    break;
  case '<default>':
    // Do something for everything else...
    break;
}

```

"Switch on path argument" works the same way... but, instead of providing a node-type in the "Name" field, you should enter the path-argument you're targeting, such as:

* `node` (to control breadcrumb on pages with a path like node/\*)
* `taxonomy` (i.e. for taxonomy/term/\* pages)
* `admin` (i.e. admin/\* pages)
* `blogs` (i.e. blogs/\* pages)

```

$path_arg_1 = arg(0);

switch($path_arg_1) {
  case 'node':
    // Make a crumb for node/* pages
    break;
  case 'taxonomy':
    // Make a crumb for taxonomy/* pages
    break;
  case 'admin':
    // Make a crumb for admin/* pages
    break;
  case 'blogs':
    // Make a crumb for blogs/* pages
    break;
}

```

It seems Hansel can only target the first path-argument. Also note that `<default>` seems to only work for "Switch on node type".

To create **Home-\>Bussiness-\>Faq-\>How To Tie a Tie** (assuming Business is a tax-term and Faq is node-type):

1. **First Rule (for the breadcrumb's head, i.e. "Home" link)**
2. Create a rule with the name `start`, and leave "Parent" set to `<root>`
3. Under "action with breadcrumb", select "add a single link"
4. Set "Action" to "switch", then click "next"
5. Enter "Home" as your link name, then set path to `<front>`
6. Select "switch on url argument" and click "save"
7. **Second Rule (for the breadcrumb's tail, i.e. node-title: "How To Tie a Tie")**
8. Create a rule with the name `finish`, and leave "Parent" set to `<root>`
9. Under "action with breadcrumb", select "add link to current page"
10. Set "Action" to "leave", then click "next" and "save"
11. *So far, these two rules will get you: Home-\>How To Tie a Tie*
12. **Third Rule (for the second crumb, i.e. taxonomy term "Business")**
13. Create a rule with the name `node`, and set "Parent" to `-start`
14. Under "action with breadcrumb", select "add term path"
15. Set "Action" to "switch", then click "next"
16. On the next page, select the vocab containing the "Business" term
17. Set "Switch on" to "node type" then click "save"
18. **Fourth Rule (for the third crumb, i.e. node-type "Faq")**
19. Create a rule with the name `faq` (for node type "FAQ"), and set "Parent" to `--node`
20. Under "action with breadcrumb", select "add link to nodetype"
21. Set "Action" to "Goto rule", then click "next"
22. On the next page, configure the "Path" as desired
23. Set the "Goto Destination" to `-finish` then click "save"
> 4 votes

# Answer
In my opinion at the current state hansel is way to complicated and limiting, I ran into multiple problems:

* dealing with taxonomy
* entity reference
* token issues (which was more a problem to token itself and entity reference)
* addind a custom link to something based on little logic and a given field (php processing is for switch only, not for action why? besides it is a bad idea to use php in that way anyway)
* ordering problems of added terms.

Actually I spend dealing 5 hours messing around with hansel to end up writing a custom breadcrumb building within one hour.

It is too complicated for a site builder / non developer and too limiting for a developer. see http://drupal.org/node/805874 for further reference and discussion.

roundup: do not use it, maybe take its code as a reference for building a own module:

```
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $theme_registry['breadcrumb_original'] = $theme_registry['breadcrumb'];
  $theme_registry['breadcrumb']['function'] = 'my_module_get_themed_breadcrumbs';
}

function my_module_get_themed_breadcrumbs() {
  $breadcrumbs = my_module_get_breadcrumbs();
    if (is_array($breadcrumbs)) {
      return theme('breadcrumb_original', $breadcrumbs);
    }
    return theme('breadcrumb_original', $original_breadcrumbs);
}

function my_module_get_breadcrumbs() {
  $links=null;
  switch (drupal_strtolower(arg(0))) { // node/$x, taxonomy/$x ...
    case 'node': // node/$x
      if (is_numeric(arg(1))) {
        if ($node=node_load(arg(1))) {
          switch ($node->type) {
            case 'article':
              _my_module_link_taxonomy($links, $node, 'field_tags');
              _my_module_link_node($links, $node);
              break;
          }
        }
      }
      break;
    default:
    case 'taxonomy':
    case 'admin':
    case 'user':
      //extend by your own rules
      return null;
      break;
  }

  $breadcrumbs=array();
  $i=0;
  $last_item_number=count($links);
  $last_item_link = variable_get('my_module_breadcrumb_last_item_link', TRUE);
  foreach ($links as $key => $link) {

    if (is_array($link)) {
      switch ($link['href']) {
        case '<none>':
          $breadcrumbs[$i] = check_plain($link['title']);
          break;
        case '<front>':
          $breadcrumbs[$i] = ($last_item_link || $i != $last_item_number) ? l($link['title'], '') : check_plain($link['title']);
          break;
        default:
          $breadcrumbs[$i] = ($last_item_link || $i != $last_item_number) ? l($link['title'], $link['href']) : check_plain($link['title']);
      }
    }
    $i++;
  }
  return array('breadcrumb'=>$breadcrumbs);
}

function _my_module_link_node(&$links, $node, $key=null) {
  if (is_null($key)) {
    $key=$node->nid;
  }
  $links[$key] = array(
    'title'=>$node->title,
    'href'=>'node/'.$node->nid,
  );
}

function _my_module_link_taxonomy(&$links, $node, $field) {
  // check if the node has classification settings
  if (!empty($node->{$field})) {
    $tids=array();
    foreach ($node->{$field}['und'] as $tid) {
      $tids[$tid['tid']]=$tid['tid'];
    }
    $terms=taxonomy_term_load_multiple($tids);

    if (!empty($terms)) {
      // find a term with parent items, taxonomy_get_parents_all() will
      $term=null;
      foreach ($terms as $term) {
        $parents=taxonomy_get_parents_all($term->tid);
        if (count($parents)>1) {
          // notice $parents contains the parents
          // notice $term contains a term with a parent item
          break;
        }
        $term=null;
      }

      // no hierarchical term found, take the first one from array
      if (is_null($term)) {
        $term=reset($terms);
      }

      $link = array();
      $link[$term->tid] = array(
        'title' => $term->name,
        'href' => 'taxonomy/term/' . $term->tid,
      );
      #$parents = taxonomy_get_parents_all($term->tid);
      foreach ($parents as $parent) {
        $link[$parent->tid] = array(
          'title' => $parent->name,
          'href' => 'taxonomy/term/' . $parent->tid,
        );
      }
      foreach (array_reverse($link) as $tid => $value) {
        $links[$tid] = $value;
      }
    }
  }
}

```
> 1 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Imported views from other site that didn't have any Master display in the UI. How to remove Master display from Views UI?
I wanted to reuse some View I built on older site which is using EVA module and contextual filters and so on. So I just re-imported it to my new site and now from nowhere there's that Master display showing up (while on older site its not shown) when editing view and the view cannot be saved because it gives me error:

```
'Display "Master" uses fields but there are none defined for it or all are excluded.'

```

The problem is that I don't need that master display at all. How is that it popped up from nowhere?

# Answer
> 2 votes
A view will always have a master display. You can set it to not display on the views settings page at 'admin/structure/views/settings'. To get rid of the error you are seeing, just a add field to the master display, or set the display to show content instead of fields.

# Answer
> 1 votes
The master display is what used to be called "default" in previous versions of Views. Sounds like there are some conflicts in its settings. You can change how it's set up by going to admin/structure/views/view/MYVIEW/edit/default where MYVIEW is the machine name of your view.

---
Tags: 7, views
---


# Question
Title: Question regarding hook_user_presave() and setting roles
When a new user is created, either via admin or by normal user registration, I need to assign a custom role to that user. It works fine, but I'm not convinced I've checked the user status enough.

In my hook\_user\_presave() implementation, I check to make sure the administration role isn't set, and uid isn't 1. To set my role:

```
if ($account->uid == 1 || array_search('administrator', $account->roles))
        return;

$account->roles[] = 'my_custom_role';

```

I only want to do this if it is a brand new user being created/inserted. The documentation says hook\_user\_presave() is called if the user is being updated. What is the best way to check if this is a brand new user creation? Would uid be set to 0?

# Answer
The documentation for hook\_user\_presave() says the hook is invoked when an user account is updated, or created, not just when the user account is updated.

If you look at user\_save(), you will notice that `$account->is_new` is set before invoking `hook_user_presave()`, when the user account is being created. If the account is being updated, `$account->is_new` is not set, and `$account->original` contains the user object before any changes.

In Drupal 8, `$user->is_new` will be replaced with Entity::isNew().
> 2 votes

# Answer
It looks like the $account-\>is\_new flag is how to test. I've been testing and it seems to be the way to go.
> 1 votes

# Answer
`hook_user_presave()` is fine, just pay attention to `$account->is_new`. And save fields in the `$edit` variable in the usual format, ex:

```
if ($account->is_new) {
  $edit['field_time'][LANGUAGE_NONE][0]['value'] = (string)time();
}

```

`$edit` is passed as reference and so you don't need to do anything else.
> 1 votes

# Answer
Try hook\_user\_insert which is called only when saving a new user. Also, make sure that $account-\>uid is set. If uid is set, that means some save function( user\_save() ) is called before.

Also, try in\_array() instead of array\_search. You just wanted to check if the role is in the array, which in\_array does out of the box.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Prevent clicking on view tab when editing a node
I was wondering anyone knew of a module that would warn people when clicking on the view tab if they have made changes to a node, but didn't save it. For example, I've seen a few times where people would click on the edit tab to edit the node, then when finished, click on the view tab at the top next to it. This doesn't save the page, and they loose everything they just worked on.

Any thoughts on how to warn people to click "save" first before navigating away?

# Answer
> 2 votes
See the content lock module:

> Features
>
> * Concurrent editing:The user gets notified when he tries to edit a node, which is edited by someone else. He cant enter the edit mode.
> * By node type: Configure content\_lock to lock only specific nodes.
> * By format: Configure content\_lock to lock only specific input formats.
> * No losing content by accident: User gets notified, if he wants to leave a edit form by abnormal conditions (close browser/window/link click). If the user confirms to leave, the edit lock gets automatically removed by an ajax call. You can disable this behavior in the admin menu.
> * No forgotten locks: The user gets notified when he forgets to unlock a node. He/she will be asked to click on a link to unlock this node.
> * Views integration: Show all open locks using any filters, as you have a views integration.

---
Tags: nodes
---


# Question
Title: module_invoke/module_invoke_all with multiple arguments
I know enough D7 to be dangerous. I'm stumped, however, as to how to call one module from another. In this case, I want to call the simplenews module's subscribe\_user hook from a custom module I'm creating. I'm having difficulty passing the multiple arguments either as a string or an array. Here are the variables the hook accepts:

```
$mail = 'test@test.com';
$tid = 1;
$confirm = TRUE;
$source = 'unknown';
$preferred_language = NULL;

```

Can someone please help me call this properly?

```
module_invoke('simplenews', 'subscribe_user', $args);

```

# Answer
use

```
simplenews_subscribe_user($mail, $tid, $confirm, $source, $preferred_language);

```

or

```
module_invoke('simplenews', 'subscribe_user', $mail, $tid, $confirm, $source, $preferred_language);

```

module invoke is parsing all given arguements and handles them to the called function.

see php documentation regarding passing variables by reference, if that might bug you someday: http://php.net/manual/en/function.call-user-func-array.php#refsect1-function.call-user-func-array-notes
> 4 votes

---
Tags: 7, hooks, emails
---


# Question
Title: How to automatically upload a file on form submission
I have created a form with a file attachment field. I have noticed that users will attach a file but sometimes forget to hit the upload button. I would like the form to automatically upload the file when the form submit button is pressed (if a file has been selected to upload).

I have seen a similar answer answer to this at https://drupal.stackexchange.com/a/31453/4471 but that is a slightly different use case then what I am after. I would have thought that submitting a form would automatically upload attached files as default behaviour.

I am working with Drupal 7 by the way.

Thanks.

# Answer
> 1 votes
If a file has been selected in a file upload field, it will be uploaded on form submit regardless of whether the "Upload" button has been pressed.

---
Tags: 7, forms
---


# Question
Title: How to Redirect search form to search api views
I'm struggling to redirect the core search form /search/node/\* to the search api views /s\* .

I took a look at but nothing happens ...

```
http://api.drupal.org/api/drupal/modules%21search%21search.module/function/search_box_form_submit/7

also tried
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#action'] = 'search';
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
  else if ($form_id == 'search_box_form' || $form_id == 'search_theme_form') {
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
}

function MYMODULE_search_form_submit(&$form, &$form_state) {
  $default = search_get_default_module_info();
  $form_state['redirect'] = str_replace("$default[module]/", '', $form_state['redirect']);
}

```

Tried different modules ... but they don't pass the results.. Also tried to add the search form from views on the front page and managed to get it wrong .. all sorts of errors.

Cheers

# Answer
> 0 votes
The following code will work when saving a node...

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

  if ($form_id == 'business_node_form') {
    // redefine our submit handler
    $form['actions']['submit']['#submit'][] = 'myfunction_form_alter_redirect';
  }
}

function myfunction_form_alter_redirect( $form, &$form_state ){
  $form_state['redirect'] = 'home';
}

```

# Answer
> 0 votes
try this function:

```
/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }
  else {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
  }
}

```

---
Tags: views, forms, search, redirection
---


# Question
Title: How do I redirect users to a predetermined url after login?
I have a view in Drupal 7 that lists PDF files. I want to keep track of the users that open that file; so I want that, if they are not logged in when they click, they are sent to the login/sign up page. I have already accomplished this using two views with different permissions, but the problem is that, after they sign up, they are redirected to the user profile page, as opposed to the PDF file.

How can I accomplish this?

# Answer
All forms in Drupal support a internal destination parameter.

When you link to the user or user/register form, you can add ?destination=\[url\]

```
user/register?destination=node/1

```

Since you display the files-list with Views, you will need to re-write the files link to include the destination parameter. If you output the link with l(), you can add the extra url data in l's third parameter like

```
l('Sign in to View', 'user', 'destination=node/1');

```
> 8 votes

# Answer
The Login Destination module is for all types of logins and registrations. The project pages says, "It is also possible to keep users on the currently visited page after logging in or out."

I haven't used it before, but I hope it solves your problem.
> 6 votes

# Answer
You can do this with rules. Use the after login event and add an action to transfer the user to the page.
> 2 votes

---
Tags: users, files
---


# Question
Title: Make the order available in checkout pane callback when viewing
I've overridden the payment pane callback in the checkout page (using hook\_checkout\_pane\_alter), and I want to modify the form inputs in the pane based on the order total. However, the order object is empty when the callback is called with the "view" operation parameter.

How do I make the order available in the callback function?

# Answer
You might need to use an order pane instead.
> 0 votes

---
Tags: ubercart
---


# Question
Title: Ubercart Numerical Attributes Not Respecting List Position Settings
I have an attribute option select box field that has numerical options, like this:

```
LENGTH
1
1.5
2
10
100

```

However, this is how the options are displaying on the front-end view of the product:

```
LENGTH
1
1.5
10
100
2

```

As you can see, it is sorting anything that starts with a "1" before anything that starts with a "2". I need it to be in literal numerical format.

Any ideas on how I can make this work the way I need it to?

Thanks!

# Answer
Ubercart manages options twice. First in the overall (global) attributes, which may be applied to any individual product, then in the realm of the individual product. Since the product may have only a subset of the global options selection, once you have applied an attribute to a product, you are able to select which options apply, and re-order the sort order for that product. The default sort in Drupal is alphabetical.

Edit your product, go to the options tab, and set the options order the way you want to see it. The select list will respect the order you set. (And yes, this will require you to repeat the process for every product.)

EDIT:

One possible way to brute force the ordering is with direct access to the database.

First go to /admin/store/products/attributes and open the options list(s) for your attribute(s). Drag and drop to get the options in the correct order, then save.

Then run the following query (after backing up your database in case it blows up):

```
UPDATE uc_product_options p JOIN uc_attribute_options a ON p.oid=a.oid SET p.ordering = a.ordering;

```

Just be aware that if you ever edit the attributes on a product, they will re-order with the selected options at the top, and the unselected options at the end of the list. You WILL have to double check the order before saving, as the selected attributes will probably be in alphabetical order.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: how to add "access callback" function to a path defined by a view?
I'm using Drupal 7, Views 3, and `hook_menu_alter`

```
function MYMODULE_menu_alter(&$items){
  $items['client/place/%'] = array(
    'access callback' => 'custom_function',
  );
}

```

to override the view visibility (access), also flushing caches, but this doesn't seems to work, can somebody give some light about how to solve this, is this the right way to override path defined by a view ?

thanks in advance

# Answer
Reminder: Views module allows you to set the access from Views UI

If you want to create your own logic; this is how your code should look like:

```
function MYMODULE_menu_alter(&$items){
  $items['client/place/%']['access callback'] = 'MYMODULE_custom_callback';
}

function MYMODULE_custom_callback(){
  $isValid = false;

  /* your logic */

  return $isValid;
}

```

Make sure your module is called after the Views module. Usually Views module wight is 10; so your module wight should be 11 or more.

Also, don't forget to clear your cache.
> 10 votes

---
Tags: 7, views, routes
---


# Question
Title: "Content Type Edit/Add" gives Whitescreen, no errors loged, what to do?
I am running a Drupal Commerce Kickstart 1 on top of it (D7)site on localhost/xampp (1.7.7).

Now: When I go to Content Type (/admin/structure/type), and click Edit on a given type or New Content Type, i get the white screen or a server 500 error. I can access manage fields and manage display on the same page. When I go to drupal error logs, there is no trace of the error. Neither can I find a trace of the problem in /opt/lampp/log/error\_log. Tried to increase allowef script time / php memory limit in php.ini - no result.

The site works without problems on a remote testing server, and has been working without problems for a long time locally. So most probably it's local configuration, but I am not sure what to do.

Maybe some of you have an idea about what can I do?

# Answer
> 1 votes
OK, resolved. Thanks for your help, Triskelion - thanks to you, I understand xampp better. There were two things 1) xampp giving no error messages. After looking in vain for error messages, I upgraded to xampp 1.8.0, and when I tried to get to the page that caused problems, I got a full error message.

```
 Additional uncaught exception thrown while handling exception.Original ODOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = 'theme' OR (type = 'module' AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of /opt/lampp/htdocs/twotrees/includes/module.inc). Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] => 1 ) in filter_formats() (line 409 of /opt/lampp/htdocs/twotrees/modules/filter/filter.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 209 of /opt/lampp/htdocs/twotrees/includes/session.inc).

```

Still, no messages in error\_log. Where should I look for them?

2) I searched through the web, and found similar problems for example \[http://drupal.org/node/1542432\]. It turned out this is a XAMPP mysql memomry limit problem. I changed the value 'max\_allowed\_packet' to 100M in 'my.cnf'.

My site works now. I was really scared!

---
Tags: nodes, commerce, database, wsod
---


# Question
Title: how to show html content when select box item selected
i have a select box called Delivery method and it has two options Drop off and pick up..,i want to load few extra html fields like size ,pick up address to the page when user select pick up method,what is the best way of doing it drupal..

# Answer
> 1 votes
In custom form you can use ajax API for this. You can find the sample code from here

When you are using node form then use conditional\_fields module for this purpose.

# Answer
> 1 votes
Did you read up on the FAPI Ajax Framework in D7? You make a Form using the drupal Form API. It has `#ajax` callbacks that can make use of client-side JS `$commands` to update the DOM clientside.

> When responding to Ajax requests, the server should do what it needs to do for that request, then create a commands array. This commands array will be converted to a JSON object and returned to the client, which will then iterate over the array and process it like a macro language.

---
Tags: 7, forms
---


# Question
Title: View Shows Latest Members - How to Limit Count by Last 3 Months
I created a view that shows all recent members. Right now it shows members, from the newest to the oldest. I want to limit this view to show only the last 3 months of latest users.

# Answer
In your views 'Filter criteria' add another filter and choose 'User: Created date' and choose an operator which suit your needs, An example shown below. It will list users that are created between last 90 days
> 3 votes

---
Tags: views, users
---


# Question
Title: Why are these file errors show up on the site - I have "none" selected in admin
I'm getting errors like these show up on the site with setting "Error messages to display" set to "none":

```
File temporary://fileGhQKBK could not be copied, because the destination directory public://css is not configured correctly.

```

Why do they still show up on the site?

# Answer
> 2 votes
The "Error messages to display" setting only controls whether or not PHP errors/warnings/notices/etc are shown - that particular message is a 'standard' message displayed using `drupal_set_message()`, with `error` as the second parameter.

This happens in includes/file.inc, line 891.

```
drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $original_source)), 'error');

```

Since there's nothing actually throwing an exception the PHP error handling never comes into it, and the message is displayed as normal.

---
Tags: 7
---


# Question
Title: To view the database field data in the admin page custom module
How to show the data from the database in the admin page of custom module. The listed data should be edited/deleted/view.

Please say what Hook is to be used in the.inc file

# Answer
> 0 votes
There are plenty of ways to get your fields in a page. You can try

Views OR Data

If you prefer some coding you could try theme\_table or theme\_item\_list

I would do it by `theme_table` if i prefer coding.

> Returns HTML for a table.

Read HowTo: Create Simple Tables

```
<?php
  $header = array('Node ID', 'Title', 'Type', 'Terms', 'Created', 'Published', 'Sticky', 'Promoted');
  $rows = array();
  $no_yes = array('No', 'Yes');

  $results = db_query("SELECT * FROM {node} ORDER BY promote DESC, sticky DESC, created DESC");

  while ($node = db_fetch_object($results)) {
    $termlist = taxonomy_node_get_terms($node->nid);
    $terms = array();
    foreach ($termlist as $key => $value) { $terms[] = $value->name; }
    $rows[] = array($node->nid,
                    l($node->title, 'node/'. $node->nid .'/edit'),
                    $node->type,
                    implode(' | ', $terms),
                    format_date($node->created),
                    $no_yes[$node->status],
                    $no_yes[$node->sticky],
                    $no_yes[$node->promote],
                );
   }
  return theme('table', $header, $rows);
?>

```

**To get Edit/Delete work you should write your own code if its not nodes.**

---
Tags: forms
---


# Question
Title: AJAX / AHAH 'Add More' Button on Unlimited Cardinality Fields Conflicts with Custom Submit Handler
I have a node add form with some integer text fields that have unlimited cardinality, which causes an AJAX 'Add More' button to be displayed for those fields. The form also has a custom submit handler that is defined in a custom module.

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

$form['actions']['gaylord_submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add Gaylord'),
  '#submit' => array('inventory_stocking_ticket_form_gaylord_submit'),
  '#executes_submit_callback' => TRUE,
  '#name' => 'edit-gaylord-submit',
  '#limit_validation_errors' => array(),
);

function inventory_stocking_ticket_form_gaylord_submit(&$form, &$form_state) {
if ($form_state['clicked_button']['#id'] == 'edit-gaylord-submit') {
  node_form_submit($form, $form_state);

//do custom stuff here

}
}

```

Here's my problem: If the custom submit handler function is defined inside the hook\_form\_alter function & there are no unlimited cardinality fields, everything works great, node is created or modified, form values are saved, & my custom submit handler stuff is performed. If, however, I have a field with unlimited cardinality & my custom submit handler function is defined inside the hook\_form\_alter function, I receive an error: `PHP Fatal error: Call to undefined function inventory_stocking_ticket_form_gaylord_submit() in /hosting/somesite/com/htdocs/cms_sandbox/includes/form.inc on line 1464` & a white screen of death. If I move the custom submit handler function outside of the hook\_form\_alter, there's no error even with unlimited cardinality fields, the node is created or modified, & my custom submit handler stuff works, but field values are not saved.

I've further discovered that commenting out the code that creates the AJAX 'Add Another' button in core's field.form.inc makes everything work, even with the submit handler inside the hook\_alter & unlimited cardinality fields. Of course there's no 'Add Another' button now, defeating the purpose of having unlimited fields.

I have two questions:

1. What is causing the conflict & PHP error when the submit handler inside the hook\_form\_alter is combined with unlimited cardinality fields?
2. Why won't the custom submit handler save field data when it is defined outside of the hook\_form\_alter?

If I could solve either of these problems I'd have what I needed. Any help is hugely appreciated.

# Answer
> 0 votes
Solved both questions.

1. It's a hack, but I was able get everything working by including the custom submit handler function by putting it in an external .inc file & using a require\_once line in the custom module outside any function therein to include it. This still fails when I make fields required & bypass the requirement with the custom submit button (data not saved); however, I don't need this because I figured out #2.
2. The real problem was that I was making fields required, then needed to bypass validation of 'required' status when using the custom submit button. I was doing this by using `'#limit_validation_errors' => array(),`. The problem is that unvalidated values are removed from `$form_state['values']` when using `#limit_validation_errors` and therefore not saved, which is why everything worked with the custom submit except saving the data input into required fields. See https://drupal.org/node/763376

To solve this, I lifted & modified some code from a patch to the Save Draft module (the patch).

My custom module now includes the following:

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

$form['actions']['gaylord_submit'] = array(
  '#type' => 'button',
  '#value' => t('Add Gaylord'),
  '#submit' => array('inventory_stocking_ticket_form_gaylord_submit'),
  '#executes_submit_callback' => TRUE,
  '#name' => 'edit-gaylord-submit',
//  '#limit_validation_errors' => array(), //values in required fieldsnot saved with this
  '#skip_required_validation' => TRUE, //add new property to custom submit button
);
$form['#after_build'][] = 'inventory_after_build';
}

function inventory_after_build($form, &$form_state) {
  // Check that the form has been submitted.
  if ($form_state['process_input']) {
    // If the gaylord_submit button was pressed.
    if (!empty($form_state['triggering_element']['#skip_required_validation'])) {
      _gaylord_submit_remove_required($form);
    }
}
return $form;
}

function _gaylord_submit_remove_required(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      _gaylord_submit_remove_required($elements[$key]);
    }
  }
  if (!empty($elements['#required'])) {
    $elements['#required'] = FALSE;
  }
}

function inventory_stocking_ticket_form_gaylord_submit(&$form, &$form_state) {
if ($form_state['clicked_button']['#id'] == 'edit-gaylord-submit') {
  node_form_submit($form, $form_state);

//do custom stuff here

}
}

```

And it works perfectly! A new property is added to the custom submit button. An after\_build function is called that checks if the form has been submitted by the custom button with the new property, & if so, calls a function that recurses through all the form fields & removes the #required property from any that have it. All other form validation is preserved. And the data input into the (formerly0 required fields is saved.

Maybe this will help someone. Cheers.

# Answer
> 0 votes
try this:

```
function formalter_form_alter(&$form, $form_state, $form_id) {
  // override the default submit
  $form['#submit'] = array('inventory_stocking_ticket_form_gaylord_submit');
  // include the default submit and your custom submit
  //$form['#submit'][] = 'inventory_stocking_ticket_form_gaylord_submit';
}

function inventory_stocking_ticket_form_gaylord_submit(&$form, &$form_state) {
  if ($form_state['clicked_button']['#id'] == 'edit-gaylord-submit') {
    node_form_submit($form, $form_state);

    //do custom stuff here

  }
}

```

# Answer
> 0 votes
This may be relevant: form\_load\_include. Including external files needs to be done differently in form code because of caching.

---
Tags: forms, ajax
---


title: How to theme Panels properly?

text:
# Question
Title: How to theme Panels properly?
I am using Page Manager and Panels, providing custom node panels with selection rules by type (e.g. one panel variant for article-, one panel variant for blog-content type). This works smooth so far, styling is also neat. But, how can I get more power over the rendering of elements?

There are multiple ways to render specific elements: adding fields, using token, using a custom view only rendering specific fields, using rendered node entity with view mode. using custom panel content with placeholders etc.

What is the best approach here? It would be great to have the ability to add a custom (something) pane element that can be styled in a \*.tpl.php.

My current approach would be using display suite, creating view modes for different parts / panel regions and using theme hook suggestions for adding custom node.tpl.php for each view mode. It would not need to invoke views, which is pretty much a overkill?! rendering, additional queries...) and can use already cached entities.

```
function mytheme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_left') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_left';
  }

  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_right') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_right';
  }
}

```

I am not sure how well this will be cached and how much resources it will consume. Any advice would be grateful.

# Answer
As the official doc says you can do something like

> panels-pane\_node-title.tpl.php
>
> panels-pane\_panel\_node\_title.tpl.php
>
> panels-pane-node-title.tpl.php
>
> panels-pane-node\_title.tpl.php

After some search i have found that the suggestions are not detecting by panels, and i end up in this preprocess function.

```
function MYTHEME_preprocess_panels_pane(&$vars) {
// get the subtype
$subtype = $vars['pane']->subtype;

// Add the subtype to the panel theme suggestions list
$vars['theme_hook_suggestions'][] = 'panels_pane__'.$subtype;

return $vars;
}

```

After a long search in forums i found this too,

```
<?php
function THEMENAME_preprocess_page(&$vars) {
    global $theme_path;
    if($panel_page = page_manager_get_current_page()){

        $target_menu = 'menu-sixth-form-college';
        $current_path = menu_get_item();

        $target_menu_links = menu_load_links($target_menu);
        foreach($target_menu_links as $links) {
            $link_paths[] = $links['link_path'];
        }
        $preferred_link_paths = $link_paths;
        // if the current link is inside menu_load_link
        if(in_array($current_path['href'], $preferred_link_paths)) {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
        if($panel_page['name'] == 'page-sixth_form_college') {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
    }
?>

```

**Theme and Cache.**

When it comes to caching, i believe Drupal will handle template caching for you as normal page cache. If your dont think it work you can do something like

```
<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>

```
> 11 votes

# Answer
The best and easiest way to add custom content to panels and theme it your way is, make custom content panes, add your code using the filter mode as php filter, and encapsulate your custom php/html content into custom div tags.

Now to theme this custom content pane, all you have to do is add your custom css rules for this div tag into your local.css

If you have any specific requirements, please state them here.
> -2 votes

---
Tags: views, panels, caching, display-suite, chaos-tool-suite
---


# Question
Title: Problem with specialchars/tokens sent by email with rules module
I'm using rules module in D6

I have an encoding problem in the email's body sent by a rule while using tokens:

```
Name : [node:field_company_nid-title]

```

In the email, it appears like that:

```
Name : L'entreprise exemple

```

With php it works :

```
echo htmlspecialchars_decode( $string )

```

but i'd rather to use tokens !

Thank you for help

# Answer
> 0 votes
The good way is to use the -raw output :

```
[node:field_company_nid-title-raw]

```

---
Tags: 6, rules, tokens
---


title: ahah and fieldset 'collapsed' state

text:
# Question
Title: ahah and fieldset 'collapsed' state
On my drupal 6 site I have the following fieldset in one of my forms ($cur\_div\_wrapper\_name is a variable I have set to be "share\_opp\_with\_rep\_div"):

```
$form['add_rep_share_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Share with Rep'),
    '#prefix' => '<div id="' . $cur_div_wrapper_name . '">',
    '#suffix' => '</div>',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
);

```

As you can see, the fieldset is collapsible and has a state of collapsed by default.

Inside of this fieldset I have two selects. One of these selects ("share\_with\_rep") changes it's values when the other select ("share\_with\_rep\_region") is changed. I utilize ahah and the ahah\_helper module to make this work.

```
$form['add_rep_share_fieldset']['share_with_rep_region'] = array(
    '#type' => 'select',
    '#title' => t('Region'),
    '#options' => $regions_lov,
    '#default_value' => $default_share_opp_region,
    '#ahah' => array(
        'event' => 'change',
        'path' => ahah_helper_path(array('add_rep_share_fieldset')),
        'wrapper' => $cur_div_wrapper_name,
    ),
);

```

$regions\_lov is a variable containing an array of options for this select.

```
$form['add_rep_share_fieldset']['share_with_rep'] = array(
    '#type' => 'select',
    '#title' => t('Sales Rep'),
    '#options' => $rep_user_lov,
    '#default_value' => $default_share_opp_rep,
);

```

$rep\_user\_lov is a variable containing an array of options for this select.

The user has to un-collapse the fieldset in order to see the two selects. When I change the "share\_with\_rep\_region" select the other select ("share\_with\_rep") changes automatically. This works fine.

My problem is that the fieldset does not keep it's un-collapsed state after changing the "share\_with\_rep\_region" select, and the user has to click on the fieldset again to un-collapse it and choose a value for "share\_with\_rep".

Does anyone know if it's possible to pull the collapsed state of the fieldset and remember it so the user does not have to click it again to view the contents after changing the "share\_with\_rep\_region" select?

Thank you!

# Answer
> 1 votes
I'd do something along the lines of checking the value of share\_with\_rep\_region before defining the collapsed state of your fieldset. i.e.:

```
// whatever the default value of the select is before
// the user has interacted with it in any way
$default_value = '';

// set collapse true
$collapse = TRUE;

// assuming you're passing $form_state into your form definition, if not, do so
if ($form_state['storage']['add_rep_share_fieldset']['share_with_rep_region'] !== $default_value) {
    $collapse = FALSE;
}

$form['add_rep_share_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Share with Rep'),
    '#prefix' => '<div id="' . $cur_div_wrapper_name . '">',
    '#suffix' => '</div>',
    '#collapsible' => TRUE,
    '#collapsed' => $collapse,
);

```

I hope this shows the basic idea behind what I'm trying to say: $collapse = true by default, IF the user has interacted with the form in any way, $collapse = false

---
Tags: ajax, forms
---


# Question
Title: Admin custom module not displaying in theoverlay
How to show the data fetched from the database in the overlay of the admin custom module. The data are retrieved but not showing in the overlay. Kindly help me out

# Answer
> 0 votes
There is Overlay Paths

> This is a simple module that enables site builders to use the built-in Overlay for non-admin pages.

Refer

Working with the overlay

https://drupal.stackexchange.com/a/8265/4471

# Answer
> 0 votes
You need to implement hook\_admin\_paths to let Drupal know that your page is an admin page. This will ensure it is displayed in the overlay.

# Answer
> 0 votes
You could also give a path on this page in your hook\_menu() like

```
admin/config/YOURPAGE

```

and with the appropriate permissions it will show in the admin theme automatically

---
Tags: 7
---


title: Go to page section after redirect

text:
# Question
Title: Go to page section after redirect
I wanted to provide feature where non-logged in users can click on "Rate" button, which will lead them to login and after login they come back to the page. Upto this, it is working fine.

But I want user's to go to particular section of page, `div with id = "id1"`.

How can I achieve this?

-- Many thanks for your time.

This is what I have tried:

```
$destination = drupal_get_destination();

$options = array( 'query' => $destination,'fragment'=>'div_id');

print l('Review', 'content/login', $options);

```

# Answer
> 2 votes
This works for me...

```
$destination = drupal_get_destination();
$destination['destination'] .= '#div_id';
$options = array( 'query' => $destination);
print l('Review', 'content/login', $options);

```

---
Tags: 7, users, redirection
---


title: Boost plus Cloudflare

text:
# Question
Title: Boost plus Cloudflare
Can we use Boost together Cloudflare?

I am curious whether using both can be enabled on the site, and whether doing so will actually improve performance.

# Answer
I currently use Boost and Cloudflare together on a medium sized site, I don't have any current performance figures to show you but there is a substantial improvement in performance and scalability by using the boost module with the cloudflare service. I don't use the cloudflare module itself as it only allows you to submit Spam reports & ban/whitelist IP addresses.

I use the boost module and have then setup my account on cloudflare.com to cache static assets like images etc Boost on its own does a great job of serving more pages faster. However as my site has a lot of static assets and that is primarily why i use the cloudflare service.
> 4 votes

---
Tags: performance, caching, files
---


# Question
Title: Propagate changes inside module.install schema to database
Using schema module, I was able to easily describe tables that I included in Drupal DB, by creating .install files to appropriate modules.

Now i have updated field descriptions for each field defined in schema, inside those .install files. How do I get those (and even more complex) changes to be propagated to DB ?

I do not care for module versions/update functions, as these modules are internal (used only for this site)

# Answer
> 2 votes
During development this might be appropriate. If you make mistakes in the schema you may just want to start from scratch again. To do this you need to completely uninstall and reinstall the module. drush can make this faster.

This is dependent upon you implementing hook\_uninstall which drops the schema - read deletes all data. 'drop table' in sql.

```
/**
 * Implements hook_uninstall().
 */
function hottopicsnotify_uninstall() {
  drupal_uninstall_schema(HOTTOPICSNOTIFY_VOTING_TABLE);
  drupal_uninstall_schema(HOTTOPICSNOTIFY_STATE_TABLE);

  variable_del(HOTTOPICSNOTIFY_CONTENT_TYPES_VAR);
  variable_del(HOTTOPICSNOTIFY_EDITORIAL_GROUP_VAR);
}

```

With Devel module installed run this on the command line:

```
* drush devel-reinstall -y hottopicsnotify

```

Without:

```
* drush dis -y hottopicsnotify
* drush pm-uninstall -y hottopicsnotify
* drush en -y hottopicsnotify

```

---
Tags: 7, database
---


title: "Content manager: broken/missing"

text:
# Question
Title: "Content manager: broken/missing"
After upgrading to Drupal 7, all the pictures of the items have disappeared. In the View UI editor, I cannot add an image content and it says "Content manager: broken/missing".

Help?

# Answer
"broken/missing" means that Views can't find the field. If you hover over the "broken/missing" link you can look at the address and get a hint of which field it's supposed to be. Once you know which field it is you can remove the broken handler and re-add it to the views output. If it's not available something has gone wrong with the field migration (I assume you did migrate the fields).
> 0 votes

---
Tags: 7, views, upgrading
---


# Question
Title: Sharing variables between node preprocess and page preprocess
Both of my preprocess files use the $vars array. I assigned a new element to the $vars array in page preprocess but I can't access this variable in node preprocess. I tried doing it the other way around and had the same problem. How can I get around this?

# Answer
The node object itself can be used to share information across these two functions. In your template\_node\_preprocess() override do something like:

```
$node = $variables['node'];
$node->my_data = my_data_function();
$variables['my_data'] = $node->my_data;

```

Then in template\_preprocess\_page() override write:

```
if (!empty($variables['node'])) {
  $variables['my_data'] = $variables['node']->my_data;
}

```
> 4 votes

# Answer
I think that would be useful to have this piece of code here. This is how you can pass variables from page to node. in `THEME_preprocess_page`

```
if(isset($vars['page']['content']['system_main']['nodes'])){
    $keys = array_keys($vars['page']['content']['system_main']['nodes']);
    $vars['page']['content']['system_main']['nodes'][$keys[0]]['#node']->variable_name = value;
}

```

In `node.tpl.php` you can `print $variable_name`
> 0 votes

---
Tags: 6, theming
---


# Question
Title: How to set an action to unpublish a comment with rules?
The rules modules has default actions setup to unpublish nodes but not comments. Do I need to use PHP to unpublish a comment?

# Answer
> 8 votes
If you choose the action "Set a data value" and a comment is visible to the action (e.g. because the triggering event is "After saving a new comment") then the data selector will let you choose

```
comment:status

```

which you can then choose to set to "Published" or "Unpublished", or (via a data selection) to another available value.

# Answer
> 1 votes
I had this same issue using Flag module and this solution worked out great for

the data source was *flagged-comment:status* in case anyone comes across this

# Answer
> 0 votes
Make sure you have nodecomment module downloaded and enabled. If node comment module is there, then you will get comments as the first option in rules trigger.

---
Tags: 7, rules
---


title: Page Title in drupal

text:
# Question
Title: Page Title in drupal
In my drupal site some places the page titles are not shown.that are the term or a block but not a page.how can i show that title

# Answer
You can show a custom title on each page with the function drupal\_set\_html\_head("your title"). You call that function in a custom module with a preprocess hook.
> 0 votes

# Answer
You can add or alter a page title with drupal\_set\_title('My custom page title !')
> 0 votes

---
Tags: 7
---


# Question
Title: How to use contextual filters to a View for use as a sort criteria?
I want a View with a default sort criteria that can be overridden by a contextual filter. For example, the URL might end like this: `?sort=popular`. `popular` would be associated with one field and `recent`, the default, would be associated with another field.
This is on Drupal 7 and Views 3.

# Answer
> 0 votes
you can use "exposed filters", they will use url name/value pairs similar to contextual filters. If you don't want to show the exposed filter to the visitor you can hide them.

# Answer
> 1 votes
I am not sure how this translates to Drupal 7 and Views 3, but I have done the following with Drupal 6 and Views 2 using hook\_views\_query\_alter

```
function mymodule_views_query_alter (&$view, &$query)
{
    if ($_GET["sort"]) {
        $sort = check_plain(trim(strtolower($_GET["sort"])));

        switch ($sort) {
            case "title":
                $query->orderby = array("node.title ASC");
                break;
            case "order":
                $query->orderby = array("node.nid DESC");
                break;
            case "somefield":
                $query->orderby = array("node_data_field_somefield_field_somefield_value ASC");
                break;
        }
    }
}

```

The trick is to make the views w/ the sorts, and look at the SQL, and use this to update your code.

# Answer
> 0 votes
In Drupal 7, query will look in following way:

```
$query->orderby[] = array('field' =>'node_title', 'direction' => 'DESC');

```

---
Tags: views
---


# Question
Title: Node Access Product Module (nap) - Really embarrassing error message
I have built an Ubercart site, using the Node Access Product module, that sells only two products, one of which is access to a single node. Everything works correctly, but after the customer makes a successful purchase the following errors are repeated all the down the completed order page:

"Notice: Trying to get property of non-object in nap\_save\_purchase() (line 1508 of /home/mysite/public\_html/sites/all/modules/nap/nap.module)"

and

"Notice: Undefined index: type in drupal\_write\_record() (line 7025 of /home/mysite/public\_html/includes/common.inc)"

I have been everywhere looking for an answer. Can anyone help?

# Answer
> 1 votes
This error is thrown when an object is empty, and you attempt to determine the value of a property. In this case the following code is responsible:

```
 // Go through each of the products purchased.
  for ($i = 0; $i < count($product_nodes); $i++) {
    // Easy referencing.
    $node = &$product_nodes[$i];
    $settings = nap_get_nap_settings($node->nid); <- Throws error

```

My guess is that $product\_nodes is empty.

Try wrapping the for loop as follows:

```
 // Go through each of the products purchased.
  if (!empty($product_nodes)) {
    for ($i = 0; $i < count($product_nodes); $i++) {
      // Easy referencing.
      $node = &$product_nodes[$i];
      $settings = nap_get_nap_settings($node->nid);

      ..rest of loop code ...

    } //End of for loop
  }

```

This should work. You should also bring this up as an issue on the project page.

# Answer
> 0 votes
2 things.

* Somewhere in your code your saving something with a column `type` in a database table. It's probably in `nap_save_purchase()`. The field is blank when you save the record to the DB. fix that.
* You have all error messages likely going to the screen on your live website. You can hide Notice messages in your settings.php file with like `ini_set('error_reporting', 'E_ALL ^ E_NOTICE');`

---
Tags: ubercart, users
---


# Question
Title: How to customize the user profile page with views
I've got a view I want to embed in a user profile page (A list of nodes that are associated with the user). The view is already working correctly.

Is the best way to do this to simply make a region in the theme that shows up only on the user profile page and then add the block view to that region?

To complicate this more, I have some pagination that should work with the view that is in date form (they could click "january 2012" or "february 2012" or just "2012" and is separated from the main view by some other content/markup. Do I somehow make two views? One for the content and the other to manage the links back to the page for which the main view can determine which content to show?

# Answer
I think adding the view into a region is the simplest way to do this. The main problem with this would come if you wanted to show the view 'inside' the rendered user. There are a couple of modules that could also help with this:

EVA (Entity Views Attachment) \- This module allows you to create a view that becomes a field in an entity. You can then enable it in the field display area for the user entity.

Panels \- This is a hefty module and probably overkill for what you need. Unless I was using it elsewhere I probably wouldn't use it for this.
> 2 votes

# Answer
* Create a view and add a "page" display.
* Use "user/%" as the page path.
* Add a contextual filter "user uid" and select "provide default value" user ID from URL.

You are done. This view overrides each user's profile page.

You can also add another display "attachment" to this view. Or add another views block as a view area into the footer of that view.
> 6 votes

---
Tags: users, views
---


# Question
Title: taxonomy-term--vocabulary.tpl.php still shows tagged content
I'm trying to show on my taxonomy term page only what's in *taxonomy-term--myvocabulary.tpl.php*, but :

* If I enable **the taxonomy/term/% view**, what's in my **template is not displayed**
* If I enable **the term panel page**, what's in my **template is not displayed**
* If I disable that view and that panel, what's in my template **is displayed**, but **content tagged with that term is also displayed**.

EDIT: My template outputs several lists of content, uses APIs and webservices, I can't really explain here what it's made of, it's 350 lines of code :) Anyway, I'm sure the content of it is not related to solving that problem.

**Q: What do I have to do to avoid processing and displaying of that tagged content ?**

# Answer
> 0 votes
As I now think I know what you want, here's what I'd do: use Page Manager to override the default display, then add the rendered Entity display for Taxonomy. That should then pull in your custom template,

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


title: hide titles based on page type?

text:
# Question
Title: hide titles based on page type?
I want to disable titles from showing on main content pages, but have them show still on blog post/article pages. I was using a CSS rule #page-title to hide them, and was thinking of working from that, but it doesn't work as well in dynamically generated pages. Comparing a post page to a main content page, I don't see any difference in the preceding css classes and ids.

How could I quickly change this behaviour?

I'm working on a self-built custom theme that doesn't have a lot of editing done to it.

# Answer
> 1 votes
Take a look at the classes in the body tag, and I am sure you will find what you need to build the right CSS.

Hint: body.SomeClass #page-title { display:none; }

# Answer
> 2 votes
If these are different content types, you could create a separate node-*\[type\]*.tpl.php file for each, leaving out the title in one of them.

http://drupal.org/node/1089642

# Answer
> 1 votes
under `node.tpl.php` remove the element including the php if statement:

```
<?php if (!$page): ?>
  <h2 class="title"><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
<?php endif; ?>

```

assuming you are using the blog module, under `node-[type].tpl.php` (which can be found via `$node->type`) simply keep the element and php if statement.

FYI - this was the default node template from zen. yours may look different.

# Answer
> 0 votes
Or just hide it:

```
  <?php if (!$page): ?>
  <h2<?php print $title_attributes; ?> style="display:none"><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>

```

---
Tags: 7
---


# Question
Title: Adding $terms to the byline in node.tpl.php for Drupal 7 and Acquia Prosper & Fusion Framework
I'm trying to add the taxonomy term for a blog post to node--blog.tpl.php for the Fusion Framework and the Acquia Prosper Theme, but I've run in to some trouble and I'm not sure why it's not working.

The goal is to have the authorship line look like this:

By Blog Author | Posted Thursday March 14, 2013 | Filed under \[Category Taxonomy Term name\]

Here is the code I've got in there currently:

```
<?php if ($display_submitted && isset($submitted) && $submitted): ?>
<div class="submitted terms terms-inline"><em>By</em> <?php print $name; ?> | <em>Posted</em> <?php print format_date($node->created, 'custom', 'l F j, Y'); ?> <?php if $terms: ?> | <em>Filed under</em> <?php print $terms; ?><?php endif; ?></div>
<?php endif; ?>

```

I've tried several different things, but I can't get anything to work. I'm thinking it should a simple fix, but I've not been able to make it work.

The tpl.php file tells me that $terms should be available to me as a variable, but I've tried everything I can think of to no avail. I'd appreciate any help you can offer!

# Answer
> 1 votes
If you look at the Drupal 7 documentation for the variables available by default in the node.tpl file, $terms is **not** on the list: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

If you want to display additional variables in your template files (from what's already there by default), you should make sure that these *additional* variables are actually being set in your template.php file first.

So, go into your theme's directory and find the file called **template.php**. Does it have one of the following preprocess functions, in which it adds additional variables for your template file:

* THEME-NAME\_preprocess\_node() or
* THEME-NAME\_preprocess\_node\_blog() (assuming your content type's machine name is 'blog')

If either of those exist in your theme's template.php file, look to see if the $terms variable is being set in a statement that should start with

```
$variables['terms'] = ...

```

If that is not happening in the template.php file, then the variable is never being set and will be empty.

If your theme's preprocessing isn't somehow prepping that variable for you, however, you can still try printing out your tags this way:

```
 <?php print render($content['field_tags']); ?>

```

Where you can substitute 'field\_tags' with any field you have on that node. :-)

---
Tags: 7, theming
---


# Question
Title: HTTP Basic auth on specific Drupal paths?
I want to use HTTP Basic authentication on a group of paths in my Drupal site (e.g. /folder/\*). The paths are all menu callbacks that don't have actual page content.

I tried to use Secure Site but I don't see a way to specify the restricted pages. It seems to just assume that /admin is the only restricted path you would want, unless you wanted to force authentication on your whole site.

How would I go about forcing HTTP Basic auth on particular paths that don't have nodes aliased to them and that aren't admin pages?

# Answer
In order to do this, I ended up hacking the Securesite module to add an option for forcing auth only on user-specified paths. I used `drupal_match_path()` and basically just cut and pasted this code from Cache Exclude to do the path matching:

```
$pages = trim(variable_get('cacheexclude_list', ''));

// If the current page is one we want to exclude from the cache,
// set the page caching to false temporarily.
if (strlen($pages) && (drupal_match_path($_GET['q'], $pages) ||
                     drupal_match_path(drupal_get_path_alias($_GET['q']), $pages) )) {
  drupal_page_is_cacheable(FALSE);
  return;

```

Adapting that and inserting it into securesite.inc, specifically into the `_securesite_forced()` function allowed me to specify my own paths. I plan to submit a feature request with patch to the project on d.o.
> 1 votes

# Answer
I think you are looking for Sharing authentication with HTTP-Auth which describes using the Drupal user tables to supports Apaches http auth system. You will probably have to hard-code the paths in your menu, or within your page content. Then set up Apache to use http auth on the particular directories.

EDIT:

To use this technique in the Drupal environment, you would define http auth for individual directories in the apache Auth.conf file like:

```
<Directory /usr/local/webroot/d7.example.com/folder>
...Auth directives ...
</Directory>

```

where /usr/local/webroot/d7.example.com is your drupal root. This allows you to protect individual directories, while maintaining drupal authentication for your site.
> 1 votes

---
Tags: security, users
---


# Question
Title: How can I add variables from a preprocessor function to be used in an unformatted view template?
The variables I'm adding in my preprocessor function are not visible in the template for the *unformatted* view I've written. This seems to work fine if the template is formatted (the default).

That is, in template.php I set some variable `$foo` in the preprocessor…

```
function themename_preprocess_views_view(&$vars) {
  // Do view-specific preprocessing in here because of http://drupal.org/node/939462
  if ( $vars['view']->name === "viewname" ) {
    $vars['foo'] = 'bar'; // set $foo to be used in viewname templates
  }
}

```

…such that I can use it in views-view--viewname.tpl.php, `<?php echo $foo; ?>`. This works just fine.

However, **`$foo` is undefined in views-view-*unformatted*--viewname.tpl.php**.

Why is this? How can I store the results of my preprocessing in a variable I can then use in the template for my *unformatted* view?

Doing the preprocessing in a function specific to the unformatted view doesn't work because

* such a function, `themename_preprocess_views_view_unformatted__viewname()`, will not be called due to a bug, and
* working around the bug by defining its behaviour in, or calling it from, `themename_preprocess_views_view()` doesn't work

+ as above, where I seem to make changes to `$vars` that should be accessible in all viewname view templates,
    + nor can it be repeated specifically for the unformatted view templates because there's nothing in `$vars` that can be used to discriminate the unformatted from the default view.

Any help?

# Answer
> 5 votes
Your problem is that the output for the view is built up from the inside-out. So, the views-view template already has the processed results from the views-view-unformatted template.

You should just be able to implement a `template_preprocess_views_view_unformatted()`, and do a manual check:

```
function mytheme_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];

  if ($view->name == 'viewname') {
    $variables['foo'] = 'bar';
  }
}

```

I don't typically use unformatted output, but I do it somewhat often at the field level.

---
Tags: views, theming
---


# Question
Title: Rules reaction: "After updating an existing user account" reacts on user login
I have a rule that I use to create a group node for user when user gets a new role. A group node was created for the user when she got the new role but unfortunately a group keeps getting created for the user whenever she logs in. Not sure of what is going on. How do I fix this? Thanks!

# Answer
What event are you using to trigger the node creation? It sounds like maybe there's a "User has logged in" event somewhere in the chain.

The Rules module can be flakey. (I love it but it drives me crazy sometimes.) If you can't figure it out, you could try to preempt the problem by adding a check to the event where you create the group node to see if a group node already exists before adding one.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: How do I collect an end date when creating a Date field in code?
This is my field definition:

```
'ms_date' => array(
            'field_name' => 'ms_date',
            'type' => 'datetime',
            'cardinality' => 1,
            'settings' => array(
                'cache_count' => '4',
                'cache_enabled' => 0,
                'granularity' => array(
                    'day' => 'day',
                    'hour' => 'hour',
                    'minute' => 'minute',
                    'month' => 'month',
                    'second' => 'second',
                    'year' => 'year',
                ),
                'timezone_db' => 'UTC',
                'todate' => '',
                'tz_handling' => 'site',
            ),
        ),

```

and the instance definition:

```
 'ms_date' => array(
        'field_name' => 'ms_date',
        'entity_type' => 'node',
        'bundle' => 'ms_core',
        'label' => $t('date'),
        'widget' => array(
            'active' => 1,
            'module' => 'date',
            'settings' => array(
                'increment' => 15,
                'input_format' => 'm/d/Y - H:i:s',
                'input_format_custom' => '',
                'label_position' => 'above',
                'text_parts' => array(),
                'year_range' => '-3:+3',
            ),
            'type' => 'date_text',
            'weight' => '1',
        ),
        'settings' => array(
            'cache_count' => '4',
            'cache_enabled' => 0,
            'granularity' => array(
                'day' => 'day',
                'hour' => 'hour',
                'minute' => 'minute',
                'month' => 'month',
                'second' => 'second',
                'year' => 'year',
            ),
            'timezone_db' => 'UTC',
            'todate' => '',
            'tz_handling' => 'site',
        ),
    ),

```

I'm using these structures with field\_create\_field and field\_create\_instance respectively.

Currently the "Collect an end date" textfield is missing when I create this field. How do I enable it?

# Answer
You just need to set the `todate` under the `settings` array, I believe the 2 options available are

```
'todate' => 'optional',

```

and

```
'todate' => 'required',

```
> 3 votes

---
Tags: entities, nodes
---


# Question
Title: What is the correct token for a multi value field?
Oke, so I have this multi value field in drupal 7 and I want to use it's values in a custom php snippet in the rules module.

I found the Array Tokens module to generate an array of the values, but that is for Drupal 6.

Then I found Architecture RFC: Field token architecture, which makes me assume I could use \[node:field-name:0\] or \[node:field-name:value:0\] to read the first entry, but I either replaces nothing of throws an error (I have tried various combinations).

Could someone tell me:

1. What is the right way to read a token with it's delta value?
2. How to get the delta of the fields so I can start a for loop?

# Answer
> 0 votes
Since the rules module gives you access to the $node object (if triggered on 'after saving content'). I managed to use it like this `$node->field_myField['und'][0]['value']`. Where `0` is the delta and `und` (probably) the language.

Since this looks like a multidimensional array I assume one could use a foreach on `$node->field_myField['und']`, but I did not test this.

---
Tags: rules, tokens
---


# Question
Title: extra 'field_' prepended to fieldnames in views $rows (Drupal 7)
I created a field "myfield". I then created a Drupal 7 view and selected the field 'field\_myfield'. (As expected the system prepended 'field\_' to my fieldname.) When I call `dsm ($rows)` to look at the row data that gets passed to my custom template, I see that the field is now called 'field\_field\_myfield'. Why is a second 'field\_' prepended to the fieldname? Should I assume all fieldnames in $rows will have 'field\_field\_' prepended?

# Answer
> 0 votes
The drupal field api enters fields in the database with the `field_` prefix (to avoid conflicts with other existing tables). If you use field in your name as well, it will become `field_field_...` in the database.

And since views loads the fields directly from the database, the prefix is there as well.

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


# Question
Title: How to display multiple taxonomy fields in a view
I have a view that display data from nodes (it's a listing of books). Next to each rows, I need to display some icons that represent different category per book. Per example, a book could have the categories "For young adults, comic, black-white".

All the categories are in a taxonomy, and when the node is created, we select the ones we need.

Now displaying the field of the categories in the view doesn't work if I have more than one category selected.

I created a relation, allowing me to retrieve the images, but it only displays the first category selected.

How would I be able to display all of them ?

Thanks!

# Answer
> 3 votes
If you are willing to use Display Suite then you can get the kind of result you are asking for with configuration only (but with some limits on flexibility). The other alternative would be to do something with Views PHP.

The steps for configuring Display Suite to show taxonomy terms as images (from an image field you've added to the taxonomy) are:

1. Create a view mode for your taxonomy (or reuse, say, the tokens view mode). This view mode needs to show just your image image field. You can format it here, e.g. to a thumbnail or whatever works for you.
2. Create a view mode for your content type (or content types if more than one is involved). You could use the standard teaser view mode or add a custom one for this purpose. Add the fields you want from your node and also add the term reference field.
3. For the term reference field select the Rendered taxonomy term FORMAT option. This then gives you a choice of view mode for rendering the term. Select whatever you used in step 1.
4. In you View select Show: Content | Teaser under the FORMAT section. (If you've made a custom view mode, then replace 'Teaser' with the name of your custom view mode.)

By using the Content option you lose some of the flexibility of using the Fields option Views. If that's an issue you may need to go the Views PHP route. Although, if it's a case of doing the sort of thing that Views does with Rewrites, you may be able to do some or all of by using Display Suite code fields or block fields.

This approach, of course, also allows you to use the images for taxonomy terms (single or multiple) in your default view mode as well. If you're new to Display Suite, this might be a fairly tricky configuration task - but once you're used to DS it's a pretty quick job.

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


# Question
Title: Omega Theme: how to change the stacking order of each region for each layout?
I´m starting my first theme with Omega. I´ve read the documentation, and managed to understand how it works. My problem here is that I don´t know how to stack regions in different order for each layout. I know that I can hide some regions with css and the different css files provided by the omega subtheme, but how to change the order?

Let me explain with an example:

I have this in my wide and tablet (normal) layout:

> HEADER SECTION:
>
> User Bar First -- User Bar Second -- Branding
>
> CONTENT SECTION: ...
>
> FOOTER SECTION: ...

For my mobile version I have this:

> HEADER SECTION:
>
> User Bar First
>
> User Bar Second
>
> Branding
>
> CONTENT SECTION: ...
>
> FOOTER SECTION: ...

And I want it to be:

> HEADER SECTION:
>
> User Bar First
>
> CONTENT SECTION: ...
>
> User Bar Second
>
> Branding
>
> FOOTER SECTION: ...

Any idea on how to do that? Thanks!

# Answer
The browser, not the server, knows the width of the layout. So you cannot change the stacking order on the server side and move the regions or zones up and down without having the browser talk back to the server, which Omega doesn't do.

You could use Javascript to move things around, which is painful. You could also duplicate the content you want to be in the different places, and then hide it or display it with `display: none` and `display: block`. But then you are outputting multiple copies of the content and lengthening page load time.

Here's a similar discussion about (not) changing stacking order in Omega: http://drupal.org/node/1343798.
> 4 votes

# Answer
The following is an example of selective region/zone display as show on this comment from Dan Halbert to how to change the stacking order for mobile layouts. It shows how to use the CSS display attribute to hide the header zone in the mobile layout.

> * Put this in global.css:
>
> ```
> .zone-header { display: none; }
>
> ```
> * Put this in mytheme-alpha-default.css:
>
> ```
> .zone-header { display: block; }
>
> ```
>
> The header zone will be visible in all but the mobile layout. You can imagine variations on that: If you wanted to hide in the narrow layout, but not in normal and wide, you could put the `display: block` in mytheme-alpha-default-normal.css and mytheme-alpha-wide.css.

See also Additive content / display:none problem.
There are some good comments on this on Display problem.
> 1 votes

# Answer
The answer can be found here: http://drupal.org/node/1343798#comment-7180142
> 0 votes

---
Tags: theming
---


# Question
Title: No Schema type for mysql type datetime error while creating view to show webform submissions
I am attempting to display webform submitted data in view. For that I have used Webform MYSQL Views and Data module. And I am referring tutorial from here: http://drupal.org/node/1658784. The problem is when I created MySQL views for given webform, it has created view with `Submitted` column as `datetime` field.

Now when I go to `Structure > Data Table > Adopt Tables` and selects the created view, it is giving error of "no Schema type for mysql type datetime".

I googled for it, but didn't find any solution yet, any suggestion how can I overcome this error.

-- Thanks for your time.

# Answer
> 4 votes
You likely already resolved this, but I just ran into the same issue. Here's how I resolved it:

I applied the patches to the Schema module listed here: http://drupal.org/node/1237974.

This got rid of the error, but because i had a db\_prefix on my tables, I could not adopt them. In order to get that working, I tried the patches here (http://drupal.org/node/894074#comment-6459584). It didn't work for my view, so I logged in via PHPMYAdmin and removed the prefix dr\_ from the webform view (instead of dr\_webform\_myviewname, it's now webform\_myviewname). This allowed me to adopt it.

I'm not saying it was pretty, but it is working now.

KMT

---
Tags: 7, webforms
---


# Question
Title: Is there a module that creates a jquery-like bar that displays system messages at the top of the page?
Is there a module that creates a jquery-like bar that displays system messages at the top of the page. (exactly like the large, red bar on this site (stack exchange)?

# Answer
> 2 votes
You could have a look at the "Purr Messages" module \- I haven't used this myself, so I don't know if it allows for the messages being displayed at the top - it says it creates a "jquery popup," which I suppose means an absolutely positioned div which either fades out or you can click away with your mouse.

I did something similar to this this on one site by simply editing `page.tpl.php` \- but it sounds like you want a module, & not coding advice.

# Answer
> 0 votes
You can also check out the Absolute Messages module. I have used it many times. Here is a quote about it (from the module's project page):

> Displays system messages in fully themeable colored horizontal bars on top of the page, similar to Stack Overflow / Stack Exchange network notifications.
>
> Features:
>
> * when messages are displayed content is pushed down respectively, so that nothing is covered and everything could be still interacted with,
> * alternatively, messages could be fixed to the top of the browser's viewport, so they will always remain visible regardless of scrolling,
> * each message has its own "Dismiss" (close) icon,
> * optional "Dismiss all" icon is displayed if total number of messages exceeds value defined in module settings,
> * messages could be dismissed automatically after a specific time - configurable in module settings for each message type separately,
> * hovering mouse cursor over messages resets dismiss timer,
> * provides option to re-show all already dismissed messages,
> * provides option to display only first n lines of each message, with remaining part shown after clicking on the message,
> * provides separate permissions to administer and to access Absolute messages,
> * full control over output with template files,
> * uses standard jQuery library without other modules or plugins dependencies,
> * falls back to standard Drupal's way of displaying messages when JS is not available (or when user does not have access absolute messages permission granted),
> * provides option to skip "has\_js" cookie checking, which disables fallback to standard Drupal messages if no JS has been detected (for example in case of Pressflow, which dropped "has\_js" cookie completely),
> * displays devel messages as standard Drupal messages.

---
Tags: 7, javascript
---


# Question
Title: Including files in template.php. failed in some cases (when using some contrib modules)
In template.php, in `theme__preprocess_page` function, I am including files (as my template.php grew big, I decided to separate some operations for readability) like this:

```
 function THEME_preprocess_page(&$variables) {
// .. skipped non-related code
 include  $_SERVER['DOCUMENT_ROOT'] . "/" . path_to_theme() . "/template_includes/file1.inc";

}

```

But sometimes some contrib modules complain about this. Currently I have an issue where Print module gives the following message:

```
Warning: include(): Failed opening
'/var/www/drupal/sites/all/modules/contrib/print/template_includes/file1.inc' **for inclusion** (include_path='.:/usr/share/php:/usr/share/pear') **in THEME_preprocess_page() (line 80 in** /var/www/drupal/sites/all/themes/THEME/template.php).

```

What causes paths mess?

# Answer
If you read the docs for `path_to_theme()`, there is this tidbit:

> It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.

The Print module invokes preprocess functions within its own preprocesss functions (look at the code), so I think that is why yours is getting called with a scope other than your theme.

You should really do your include as

```
include drupal_get_path('theme', 'YOURTHEME') . '/template_includes/file1.inc';

```

or

```
include dirname(__FILE__) . '/template_includes/file1.inc';

```

There is debate in the Drupal community which is best.

Personally, I think including code within a function is a really bad practice, and would recommend splitting out whole functions into separate file(s), and doing the include at the top. If you go that route, then you using the second form is best.
> 2 votes

---
Tags: theming
---


# Question
Title: Node paths with custom prefix based on taxonomy
I have a "category" field attached to the "article" content type that is a taxonomy term reference. I want to setup path auto to create a path wich is prefixed based on the category. My problem is that i.e.: I have a category called "Interesting facts", path auto will create a path **/interesting-facts/node-title** but I want to have **/facts/node-title** And I could change the taxonomy term to "Facts", but the taxonomy term index page would show "Facts" too, but I want it to remain "Interesting facts".

So basically I want to customize prefixes, without changing the taxonomy terms. Is that possible?

# Answer
> 1 votes
Create a new field on the Category Taxonomy called something like "Title Prefix" and then use this Field to create a custom path for the article

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


title: Migrate CSV source serial

text:
# Question
Title: Migrate CSV source serial
I am using migrate to import Commerce Products from a CSV file. The CSV file doesn't have its own serial so I am using csvrownum but that obviously won't work if there are already products -- I will be migrating constantly from the CSV files and so I need a real serial. So the big question is, how do I tell Migrate to generate its own serial? `prepareRow` feels too late because it seems I need to supply MigrateSQLMap a key field.

Here's a rough version of the constructor of the class:

```
public function __construct() {
  parent::__construct();
  $this->description = t('Test CSV');

  $columns = array(
    array('product_name', 'title'),
    array('url', 'url'),
    array('price', 'price'),
  );

  $this->source = new MigrateSourceCSV('/tmp/test.csv', $columns, array('header_rows' => 1));

  $this->destination = new MigrateDestinationCommerceProduct('commerce_product', 'product');

  $this->map = new MigrateSQLMap($this->machineName,
    array(
      'csvrownum' => array(
        'type' => 'int',
        'not null' => true,
      ),
    ),
    MigrateDestinationCommerceProduct::getKeySchema('commerce_product')
  );

  $this->addFieldMapping('product_id', 'csvrownum');
  $this->addFieldMapping('title', 'title');
  $this->addFieldMapping('field_url', 'url');
  $this->addFieldMapping('commerce_price', 'price');
}

```

# Answer
> 4 votes
Meanwhile I got this figured out. The second argument of `MigrateSQLMap` is a field =\> schema array and you can fill in those fields in `function prepareKey($source_key, $row)` as necessary, say

```
function prepareKey($source_key, $row) {
  $row->vendor_id = $this->vendorId;
  return parent::prepareKey($source_key, $row);
}

```

**Note**: `prepareRow` is too late, you want `prepareKey`.

# Answer
> 2 votes
You do not need to map the `product_id` explicitly. You should be able to just drop this line:

```
$this->addFieldMapping('product_id', 'csvrownum');

```

On the other hand, you are going to need a SKU, and relying on `csvnumrow` as the external ID means that you cannot ever remove any product from the CSV, just add some more at the end... I would highly recommend finding a reliable external ID.

---
Tags: commerce, migrations
---


# Question
Title: Is there a way to dynamically resize remote images in drupal 7?
Part of the site, I'm making has a YouTube video gallery. I want to display the thumbnails in list format but I need to resize them first. Using theme('`image_style`', etc) would be the simplest solution but it seems to only work on local files. Is there a way to get this to work with remote files?

# Answer
> 4 votes
Try out Imagecache External module

> Imagecache External is a utility module to allow you to use imagecache(D6)/image derivatives (D7) with external images.

---
Tags: 7, media
---


# Question
Title: How do I get Drupal to use my themes page.tpl.php template for the front page?
I'm writing a new Drupal theme. I have a html.tpl.php and a page.tpl.php (soon to add a set of node.tpl.php's for each different content type). I want my page.tpl.php to be used for every page, including the front page — every page is going to have exactly the same layout, so I don't need a page-front.tpl.php.

When I visit www.example.com/node/whatever, my page.tpl.php is applied.

When I visit www.example.com (the front page), my page.tpl.php is completely ignored — I'm assuming that Drupal is looking for page--front.tpl.php, not finding it, and then ignoring my page.tpl.php.

How do I get Drupal to use my themes page.tpl.php template for the front page?

**edit**:

Apparently my front page isn't even being counted as a node?!? The below code will die on any page except for the front page:

```
function cefmap_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        die;
    }
}

```

How do I get my front page to be treated as a node like any other node?

**edit**:

Think I've worked this out, and it's really dumb of me. I set that node to "be the front page" through structure, menus, main menu and then set the path for the *link* to be "\<front\>".

Of course, that just changes the link in the menu to be "/", without changing the actual path of the node. So I don't actually have a node at "/", and so I don't get to have a page template or a node template applied.

# Answer
> 0 votes
This was pretty dumb: I set that node to "be the front page" through structure, menus, main menu and then set the path for the link to be "".

Of course, that just changes the link in the menu to be "/", without changing the actual path of the node. So I don't actually have a node at "/", and so I don't get to have a page template or a node template applied when I visit "/".

The proper way to set the front page is to go to configure, site information and then set the "default front page" there.

# Answer
> 3 votes
It is page--front.tpl.php - note the double dashes.

The cascading matches my understanding. page.tpl.php should be called if there are no higher priority page templates. You need devel themer to work this out http://drupal.org/project/devel\_themer. It will print out on the screen the template matches.

Details are in the drupal theming guide. in this section:

```
page--[front|internal/path].tpl.php
base template: page.tpl.php

```

# Answer
> 2 votes
You can put this code into your template.php:

```
function yourtheme_preprocess_page(&$vars) {
 $vars['theme_hook_suggestions'][] = "page";
}

```

If you really want to use page.tpl.php for all

# Answer
> 1 votes
Hi i think drupal will take the page.tpl.php with out any code.

Look at the bartik theme structure. Here page.tpl.php is used in front page also.

# Answer
> 1 votes
page--front.tpl.php for the theming the front page and page--node.tpl.php for rest of the pages

---
Tags: theming
---


# Question
Title: List Nodes/Content Type Items with same tags as current
On the node page I'd like to add a linked list of other nodes tagged with the same tag/taxonomy term. How can this be achieved? Via Views?

Any help will be highly appreciated

# Answer
> 4 votes
There's a module that does that for you: Similar by Terms. But you can also do this with Views using Contextual Filters & Relationships. This comment on Drupal.org explains it quite well:

> Its really easy in D7. Coding is not at all required.
>
> Taxonomy is a field in D7. I will explain how to create a Related Content block using Views.
>
> Create an argument by adding the taxonomy field on which you want to find the related nodes. Select "Provide default argument". Argument type = "Taxonomy Term ID from URL" Remove tick from "Load default argument from term page" Tick the "Load default argument from node page, thats good for related taxonomy blocks." To remove duplicates you have to follow the following points.
>
> Open "Query settings" in the "Advanced Settings". Tick "Distinct". This gives you a perfect "Related Articles" or "Related Nodes" using Views.

# Answer
> 2 votes
Ok, a bit frustrating due to lack of documentation and me being relatively new to Drupal. So here we go:

```
#Let's find out what term is used
$my_node_tag = $node->field_your_field_used_in_node['und'][0]['tid'];

#Get the array of nodes IDs
$nodeid = taxonomy_select_nodes($my_node_tag, FALSE);

#And here we go
$counter = 0;
foreach($nodeid as $nid) {
    $node = node_load($nid);
    $alias = drupal_get_path_alias("node/$nid");
    print '<div class="title"><a href="' . base_path() . $alias.'">';
    print $node->title;
    print '</a></div>';
    $counter++;
}

```

Lovely. Not sure how efficient this is, but it works.

# Answer
> 0 votes
Not really needed to install other module when we can achieve this using core ones see this tuto to fond out how.

---
Tags: taxonomy-terms
---


# Question
Title: Flagging users as spam and giving a reason for doing so
I am creating a community site using Drupal7. The users of my site should be able to report other users as *spam users*. For this I am using the Flag module. I have created a flag called *Report User for Abuse*, and placed it on the user profile so that other users may report the user by clicking on the flag.

**I want that the flagging user should give a small summary for the reason he or she is reporting the other user as spam etc.**

Once this was done, I created a view for the site admin which shows him/her all the *reported users*. The admin may then see the reason, verify it and take appropriate actions. Am I going in the right way about this or is there any other way as well?

# Answer
> 6 votes
Why not use the Flag Note module.

> Extends the Flag Module to allow users to enter a note when they flag a piece of content and eventually build a flag history.
>
> Usage examples:
>
> * flag nodes or comments for abuse providing a descriptive reason
> * flag users as friends leaving a hint
>
> It's possible to opt to keep old notes even when the content gets unflagged

# Answer
> 1 votes
Try this module Flagging Form. It says

> you could now attach fields to Flags, this module, Flag forms, provides a form for filling out these fields.

---
Tags: 7, users, flags, advertising
---


# Question
Title: How to show images below a select box according to the value?
Let's say I have a select box with values : 1, 2, 3, 4, 5, 6. Every value has it's own image, which I want to display as a description below the select field. Any Drupal / AJAX way to show this?

By the way this is NOT a custom form. This is a node creation and edit form.

# Answer
> 0 votes
As far as I know there are no ready made solutions for this, and you will need to write a custom module. The way to do this would be to implement hook\_form\_alter to modify the select element and add a #ajax property.

If you've never written a module with hook\_form\_alter then this article might be of help: very-introduction-drupals-hookformalter

And here are some relevant questions on Drupal answers:

---
Tags: 7, nodes, forms, ajax
---


# Question
Title: Can I filter the list of candidates used by the menu system to determine the menu trail?
I have a site with a menu structure like so:

```
- a
- b
  - 1
  - 2
- c
  - 1
  - 2

```

Now lets say that I have a node that both b2 and c2 point to (I'll call it node/4). When the user clicks either link, I want the site to display as a click on c2. That is to say that the main menu item for c should be highlighted, and the secondary menu for c should be displayed. And of course, the content of node/4 should be visible.

What actually happens is that the node/4 content is displayed, but both b & c main menu items are highlighted and the secondary menu for b is displayed.

I've investigated, and found the `menu_link_get_preferred` function in core/includes/menu.inc. This function builds a list of candidates that can match the current path, and places them into an array keyed like this:

```
$candidates[MENU_ITEM_LINK_PATH][MENU_NAME]

```

My problem is that I have two link candidates that match the same exact criteria:

```
$candidates['node/4']['main']

```

and so I cannot control which one ends up in the candidates array. Ideally I would like to have a way of flagging the c2 link so that it was not treated as a candidate. I had thought that this would make a good module, but I cannot see a way of interrupting the execution of the function.

The bit of code I would like to alter is (D7 version, D8 is very similar):

```
// Sort candidates by link path and menu name.
$candidates = array();
foreach ($query->execute() as $candidate) {
  $candidate['weight'] = $candidate['link_weight'];
  $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
  // Add any menus not already in the menu name search list.
  if (!in_array($candidate['menu_name'], $menu_names)) {
    $menu_names[] = $candidate['menu_name'];
  }
}

```

In an ideal world I would have added an extra field to the database, so that a $candidate would be discarded on a certain flag. Any ideas how I could achieve this?

# Answer
> 1 votes
Unfortunately `menu_link_get_preferred` does not sort it's results. If two items match the same paths, it will just return the first result returned by the database. There is an ongoing issue about this: drupal.org/node/1649062

You can workaround this by ensuring the menu you want was added first in the database, but that's not a sustainable way of addressing this. The order might change after you restore a backup, when you compact your database, or after the next Drupal update if they address the issue.

If you cannot work around the issue another way, I think patching core with the patch provided in the issue is safer. The patch sorts the preferred links by mlid, which means you need to create the preferred menu item last (but unlike the workaround before, this will still work even if your database gets re-written).

---
Tags: routes
---