# Question
Title: How to make hook in custom module to execute only on condition
How to make contributed module hook execute only if conditions are met. Those functions seem to get automatically invoked. Environment is a custom module.

examples: 1.

```
if ($condition) {

   function mymodule_modulename_alter ($parameters) {
     //altering code here
   }

}

```

2.

```
    if ($condition) {
           //if condition is met, i call the function included in this custom module
           mymodule_modulename_alter ($parameters)
      }

  function mymodule_modulename_alter ($parameters) {
         //but this function will get auto-invoked! I want it run only if $condition is met.
       }

```

Thanks

# Answer
Let the hook be called, but put your operations(that your hook executes) inside your required condition.

```
function mymodule_modulename_alter($parameters) {
  if ($condition) {
    // Your code.
  }
}

```
> 3 votes

# Answer
I don't see a need to use variable\_get() or variable\_set(), rather, IMHO, I'd set this up somewhat like this inside your foo.module file:

```
<?php

function foo_is_whatever_condition() {

   return true or false based on whatever logic you define

}

function foo_WHATEVER_alter($parameters...) {

   if (foo_is_whatever_condition()) {

      // code for when the condition is true here

   }

}

```

Now, if I am missing out on why or how "conditions are not known to function inside" please add some more specific details here, because, unless it is some really odd edge case, few things are ever not known or knowable :)
> 1 votes

---
Tags: hooks
---


# Question
Title: What is the best way to set up demo for Drupal themes and live switch between them?
I want to set up demo for Drupal themes and live switch between them with top drop-down menu. Examples what i mean (navigate to the top bar and change theme live with a theme switcher):

http://themefuse.com/demo/wp/my-journey/

http://demo.themebrain.com/#anis

How can i repeat that with drupal, what is the best practice? The problem is: if i develop a theme on my localhost, then install on the server drupal with this theme enabled - that is simle. Then a develop second theme, and want to setup live preview with the same drupal installation BUT with another demo content.

So i need create another demo content BUT when the number of themes in development increase to 10-20 it will be a nightmare to remember what block or node is intended to appear with whith theme. Simple way is to setup different drupal each with one theme, BUT it's bad to accumulate the same code and db on the server.

In addition, i want to provide user with full drupal package (drupal setup with modules and database to import) to allow fast reproduce demo. So i don't want admin's interface clutter.

Possible modules i tried: http://drupal.org/project/themekey but it doesnot provide dropdown for switching http://drupal.org/project/switchtheme but it shows the same content, i need it to show nodes and blocks for some theme only.

# Answer
http://drupal.org/project/switchtheme is the one to use for that.

> Adds a block to allow users to switch between enabled themes.
>
> Themes can be given 'user friendly' names and access can be controlled by user role.

If you need to enable/disable blocks for certain themes, do so at `Admin > Structure > Blocks` for that theme.
> 2 votes

---
Tags: theming
---


# Question
Title: In D7 what is the correct way to create a page template that has HEAD elements specific to that page?
In Drupal 6 HEAD tags were part of the page.tpl.php. Now that that has moved to the html.tpl.php in D7, what is the correct way to create templates that need different data in head tags?

# Answer
> 2 votes
Use hook\_preprocess\_html ( e.g in template.php ) to modify the html.tpl.php variables.

For different JS or CSS, check the path ( e.g current\_path() == 'foo' ) and add with

Set the '`every_page`' option, and perhaps `preprocess` flag to FALSE.

---
Tags: 7, theming
---


title: Alternative to Views

text:
# Question
Title: Alternative to Views
Suppose we have numerous entities of types Alpha and Bravo. Alpha entities could easily be taxonomy terms and Bravo – content nodes. Bravo entities can reference multiple Alpha entities each; whereas, Alpha entities (taxonomy terms) are completely agnostic of any other entities.

The exercise is to aggregate all Alpha entities that are referenced together (by the Bravo entities) with a given Alpha entity.

**Example**: Alpha entity type is a taxonomy vocabulary containing Artists. Bravo is a Project content type. Sometimes Artists collaborate on Projects; therefore, some Projects have multiple Artists. An example of the aggregation in question would be to list all Artists that a given Artist has collaborated with (has been referenced in the same Project with).

I am building the information architecture for my first Drupal project, in which metadata and it's inter connectivity is important. I have achieved this aggregation using Views, but Views seems impractical for my uses. In many cases I want to list just Taxonomy term names like this:

> *Nirvana* has collaborated with: *Biggie Smalls*, *Lil' Wayne*, *Lil' Jon*.

(Of course, I wouldn't want my Taxonomy system to make jokes)

What aggregation solutions are there? Do you have tips? Have you done something like this?

# Why I'm looking for an alternative to Views:

The reason I find Views impractical for this use: my impression is that it's geared more towards heavier listing, like catalogs and is hard to squeeze into "lighter" roles (like the one in my example). If I am fooling myself, do correct me.

# Answer
If you're looking for a good core alternative to select entities, using custom queries, make sure you familiarize yourself with Entity Field Query (EFQ)

e.g, fetch 10 published article nodes with `field_my_field` value 'foo':

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_my_field', 'value', 'foo')
      ->range(0, 10)

$result = $query->execute();

if (isset($result['node'])) {
  // nids are here
  $nids = array_keys($result['node']);
  // nodes can be loaded as such
  $nodes = entity_load('node', $nids);
}

```

More EFQ info here
> 1 votes

# Answer
Views performance is OK, if you use caching. At least in this example, data won't change alot over the years. And if you preprocess, queries will be much lighter.

Suggested steps:

A. Outer view settings

1. Using your example, add a Term Reference field to the Projects content type, which will reference the Artists taxonomy (allow for multiple terms).
2. Make a view on the Artist taxonomy terms, then add an inner view as field (call it collaborators). The connection to the inner view is defined using the views\_field\_view module.

B. Inner view settings (picture below):

3. Make the inner view field-based, and set the term ID as it's contextual filter (under advanced settings). It should only show projects which add the term ID to their term reference field.
4. Change the fields of the inner view so it will only have one field - the term name, and don't provide default wrapper elements - to make it lighter. Also use a plain text formatter for the field so that there won't be any extra output - it will be even lighter.
5. Field settings of the 'Artists' field on the inner view: Open the collapsed 'multiple field settings' link on the field settings dialog and uncheck the option "Display all values on the same raw". Now each value will be on a separate row.
6. Add a new filter criteria to filter all terms whose id is equal to the contxtual filter we got as argument.
7. Go to the 'Query settings' under 'Advanced' and set the 'Distinct' option.
8. Also activate block caching.
> 1 votes

---
Tags: entities
---


# Question
Title: From where drupal get the template? if i don't have one
I've created a template with the following.

### myTheme.info

```
name = myTheme
description = Just my theme
core = 7.x
stylesheets[all][] = css/myCss.css

regions[test] = Test
regions[content] = Content

```

### template.php

```
// Empty file

```

### css/myCss.css

```
// Some styles

```

Drupal has position content and other blocks, but from where did he gets the template if mine is empty?

Also I get these errors:

> Notice: Undefined index: highlighted in include() (line 126 of Z:\home\test1.ru\www\modules\system\page.tpl.php).
> Notice: Undefined index: sidebar\_first in include() (line 138 of Z:\home\test1.ru\www\modules\system\page.tpl.php).
> Notice: Undefined index: sidebar\_second in include() (line 144 of Z:\home\test1.ru\www\modules\system\page.tpl.php).

It looks like it was used in the core template, but in my newly created template, I get this errors. Maybe I need to override some hooks? Which hooks should I override?

# Answer
> 1 votes
The variables for which you get those errors are the variables that Drupal uses to output the default regions a Drupal 7 theme should have, which are the following one.

```
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

```

The template.php file is not a template file; it's the file containing functions template files use.

When your theme doesn't define a template file, Drupal uses the one defined from the module implementing the theme function. For example, the Node module defines `theme_node()`; if your theme doesn't have the template file used by that theme function (node.tpl.php), Drupal will use the template file that is in modules/node/node.tpl.php.

# Answer
> 0 votes
If not provided by the theme, Drupal loads templates from the relevant module folder

1. Node
2. Comment
3. Block

etc...

also the 'system' module folder for some templates such as page.tpl. and html.tpl.php

Your undefined index errors are because your page.tpl.php is attempting to print out regions and variables that aren't defined by your theme.

---
Tags: theming
---


# Question
Title: How do you go without hierarchical taxonomy filters, when the site heavily relies on content browsing(multiple filters and sorting)?
I'm building classifieds site with drupal and got stuck on one major issue: I have 1 taxonomy vocabulary with parents, children, grandchildren and great-grandchildren, and can't find a way to build browser which would not restrict user's choices.

Over few days I found many drupal users stuck in the same place waiting for hierarchical taxonomy filters in views. this simple hierarchical select almost solves it, however in views it does not show child nodes when parent term is selected.

So what are the ways to go around this issue in drupal? Anyone built a site with hierarchical taxonomy vocabularies?

# Answer
This is unfortunately a big pain point with Drupal 7. On my site, I handled this with Views and Panels.

In my case, the hierarchies with places generated by the Location taxonomize module in the form of `country` / `state` / `city` or `country` / `city`.

To give you a rough idea of how I approached it: I overrode the taxonomy term path using Panels/Page Manager. I then added two variants in the following order:

1. a variant containing a content pane that aggregates countries and shows only those countries with 1 or more entries
2. a variant containing a content pane that takes a country as an argument/contextual filter and shows users having that taxonomy term as well as a list of states using the special Panels **related terms** (show children) block

Depending on the structure of your taxonomy and what you are trying to show, this can be an extremely complicated setup, but it is possible even without direct support from hierarchical select.
> 2 votes

# Answer
If you're using hierarchical select, make sure you set the 'save term lineage' setting.

That way, child nodes will be tagged with the parent and child taxonomy term(s) allowing them to show up in a filter on the parent term.

You might also be interested in faceted search and apachesolr
> 1 votes

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


# Question
Title: Which hook to allow specific users to add/edit/view comments?
Is there a hook that I can use that would give specific users permissions to add a comment, or edit their own comment? I was hoping there would be something like hook\_node\_access().

In my form, I have a select list with all the users that the submitter can choose. If the person is selected, then that selected person can comment on that specific node.

I looked at the comment access module, but that does not work since it is still being controlled by role permissions.

# Answer
There is no hook to do this. One possibility that doesn't require editing of the comment module is to change the comment status of the node depending on the current user using `hook_node_load`:

```
function MyModule_node_load($nodes, $types) {
    global $user;
    foreach($nodes as $node) {
        if(!user_has_access_to_node($user, $node)) {
            $node->comment = COMMENT_NODE_HIDDEN;
        }
    }
}

```

The hook will be called after the one in comment module, and will prevent users from posting comments unless `user_has_access_to_node` returns true.

The implementation of `user_has_access_to_node` would simply check if the current user is in the list of users allowed to edit the viewed node.
> 0 votes

---
Tags: 7, comments
---


# Question
Title: Migration Issue: New Site won't open -- server doesn't see file that is there
I am migrating a Drupal site from my localhost to the most current Bitnami Drupal AMI on Amazon:

* I uploaded the DB successfully.
* I moved the files correctly.
* I copied over the modules and libraries.

I got the WSOD, changed the error reporting and now, upon opening the site I get:

```
    Fatal error: require_once(): Failed opening required
'/opt/bitnami/apps/drupal/htdocs/sites/all/modules/views/includes/view.inc'
(include_path='.:/opt/bitnami/php/lib/php') in
/opt/bitnami/apps/drupal/htdocs/includes/bootstrap.inc on line 3066

```

But the file is in the proper spot, within the structure outlined by Bitnami:

```
/home/bitnami/apps/drupal/htdocs/sites/all/modules/views/includes

```

How do I convince drupal (or php) to use `"/home"` instead of `"/opt"?` I suppose I could just try a symlink but... that seems like such a kludge. I'd like to do it the "right" way.

Any suggestions?

# Answer
> 0 votes
If your files are all under /home instead of /opt you could just setup a virtualhost and point to the /home docroot

e.g, for apache, where www.example.com is your site domain name:

```
<VirtualHost *:80>
     ServerName www.example.com
     DocumentRoot /home/bitnami/apps/drupal/htdocs
     CustomLog /var/log/apache2/example-access.log combined
     ErrorLog  /var/log/apache2/example-error.log

     php_value memory_limit 256M
     php_value upload_max_filesize 128M
     php_value post_max_size 128M
     php_value max_execution_time "360"

     FileETag ALL

     <Directory /home/bitnami/apps/drupal/htdocs>
         RewriteEngine on
         RewriteBase /

         RewriteCond %{REQUEST_FILENAME} !-f
         RewriteCond %{REQUEST_FILENAME} !-d
         RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

         Options -Indexes
         AllowOverride All

         # Follow symbolic links in this directory.
         Options +FollowSymLinks

         # Customized error messages.
         ErrorDocument 404 /index.php

         # Set the default handler.
         DirectoryIndex index.php

         php_value magic_quotes_gpc                0
         php_value register_globals                0
         php_value session.auto_start              0
         php_value mbstring.http_input             pass
         php_value mbstring.http_output            pass
         php_value mbstring.encoding_translation   0

         # Requires mod_expires to be enabled.
         <IfModule mod_expires.c>
             # Enable expirations.
             ExpiresActive On
             # Cache all files for 2 weeks after access (A).
             ExpiresDefault A1209600
             # Do not cache dynamically generated pages.
             ExpiresByType text/html A1
         </IfModule>
         <IfModule mod_deflate.c>
         # Use mod_deflate to compress text content as required and supported by the client
         # Note that the frontend will automatically gzip content if supported using PHP functionality
         AddOutputFilterByType DEFLATE text/html text/javascript text/css application/x-javascript
         </IfModule>

     </Directory>

</VirtualHost>

<VirtualHost *:80>
    # Redirect non-www to www version of site
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

```

Add to **/etc/apache2/sites-available/example.conf**

Then, to enable:

```
sudo a2ensite example.conf
sudo service apache2 restart

```

---
Tags: installation
---


# Question
Title: What is the best way to start from scratch?
I have a drupal 7 instance at work, and one at home. I added content to both sites BEFORE installing the "menu breadcrumbs" module. On my Drupal instance at work the breadcrumbs don't work properly (they are skipping a level etc) while on my drupal instance at home, the same module works perfectly.

I've already tried uninstalling, and then reinstalling the module on my drupal instance at work, but didn't have luck getting it to work. Still skipping the breadcrumbs in between. What is the best way to fix this on my work instance? Should I delete all the content? If so, how? Is this likely to make any difference?

# Answer
This question is difficult to answer. Check your Drupal versions first, 7.xx, etc, i.e., if you use 7.18 at your home, the same version should be used at your work.

If the versions are same and you still encounter the problem, I would do personally this by copying everything from my home instance to my work instance.

* Copy the whole drupal site folder to my work PC.
* Dump the database via phpMyAdmin (including `DROP TABLE IF EXIST` statements) and import it to my work PC. As a side note, I normally export cache tables with structure only in a separate dump file for the sake of smaller dump file.

That should be fine. This is the usual way I do for site cloning.
> 1 votes

---
Tags: breadcrumbs
---


# Question
Title: What is the best way to calculate the price from selected line item field (a select line item field)
What is the best way to calculate the price from selected line item field (List field or maybe taxonomy) in final price ?

Example: we sell T-shirt. We define a color (list) as line item field, (red, blue, black) Then we want drupal to calculate the price with multiplying to the value specified for selected color. Red = 4 blue = 5 black = 6 The concept is that we don't want to make different product for each option, instead we want to use line item field (Select list) to calculate the price. Maybe for T-shirt doesn't make sense but it fits in our need.

How we can accomplish this and what is the best way of doing it ? Rules or own module ? How we can specify a value for each color option?

I am more interested in coding approach, because there are a lot of different options and we don't want to make many rules for those.

# Answer
The only reason I used following solution, was because we didn't need to make a product type for variety of options we had, and we had a lot of options which didn't make sense to make it as individual product.

I used rules, if any one find better solution let me know, hope it will help someone.

1) defined an action function to multiply the price to a coefficient

2) checked to see what option has been selected and proper coefficient has been applied

```
/**
 * Rules action: multiply the unit price by some amount.
 */
function modulename_unit_price_multiply($line_item, $amount, $component_name, $round_mode) {
  if (is_numeric($amount)) {
    // Coefficient variable
    $cf = '1';
    if(isset($line_item->field_color[LANGUAGE_NONE][0]['value'])){
        $selected_color = $line_item->field_color[LANGUAGE_NONE][0]['value'];
        switch ($selected_color){
            case 'red':
                $cf *= 2;
                break;
            case 'black':
                $cf *= 3;
                break;
           case 'blue':
                $cf *= 4;
                break;
            }
    } else {
        $cf *= '1';
    }
    $wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

    // Calculate the updated amount and create a price array representing the
    // difference between it and the current amount.
    $current_amount = $unit_price['amount'];
    $updated_amount = commerce_round($round_mode, $current_amount * $amount * $cf);

    $difference = array(
      'amount' => $updated_amount - $current_amount,
      'currency_code' => $unit_price['currency_code'],
      'data' => array(),
    );

    // Set the amount of the unit price and add the difference as a component.
    $wrapper->commerce_unit_price->amount = $updated_amount;

    $wrapper->commerce_unit_price->data = commerce_price_component_add(
      $wrapper->commerce_unit_price->value(),
      $component_name,
      $difference,
      TRUE
    );
  }
}

```
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Deleting nodes did not remove the node-related menus
Is there a "safe" way to delete all the existing content/pages/nodes from a Drupal 7 site, and delete corresponding menu entries? When I deleted the nodes using the admin UI, my menu entries didn't get deleted? What can cause this?

# Answer
These Q/A may be helpful for you:
Delete all nodes of a given content type
How to bulk delete content of a given type?
According to the first Q/A, the Delete all module is worth to try.

You could also try mass delete node. The function node\_delete() is safe to call. It has a call to node\_delete\_multiple() which deletes all related components of a node, such as entities, files, revisions, history, etc.

**\[UPDATE\]**
If you already deleted your nodes, but node-related menus are still there, you could also try out menu\_rebuild() to rebuild your navigation menus. Check this answer. You could also add `menu_rebuild()` at the end of the script of mass delete node I mentioned above.

OR

If you know menu IDs, you can remove each of them using menu\_link\_delete().
> 0 votes

---
Tags: nodes
---


# Question
Title: function uc_stock_adjust($sku, $newStock); not returning any value
Iam using uc\_stock module functions of ubercart module in my function but not getting result as i want. here is my code:

```
function my_module_node_presave($node) {
  if ($node->type == 'add_stock') {
    if (module_exists('uc_stock') && function_exists('uc_stock_adjust')) {
      $newStock = $node->field_stock_value['und'][0]['value'];
      drupal_set_message('new stock :' . $newStock);

      $sku = $node->field_sku['und'][0]['value'];
      drupal_set_message('sku :'. $sku);

      $key = $node->field_reference['und'][0]['nid'];
      drupal_set_message('key :'. $key);

      $items = field_get_items('node', $node, 'field_sku');
      drupal_set_message("<pre>" . print_r($items, true) . "</pre>");
      $sku = $items[0];
      drupal_set_message("<pre>" . print_r($sku, true) . "</pre>");

      $stock_adjust = uc_stock_adjust($sku, $newStock);
      drupal_set_message('stock_adjust :'.$stock_adjust);

      $stock_set = uc_stock_set($sku, $newStock);
      drupal_set_message('stock_set :'.$stock_set);
    }
  }
}

```

in my code

---

$stock\_adjust = uc\_stock\_adjust($sku, $newStock);

$stock\_set = uc\_stock\_set($sku, $newStock);

the above two functions were returning no value. now anyone can tell me whats the problem in my code

# Answer
Function uc\_stock\_adjust has no return value.

> Description: This function adjust a particular product SKU by a certain value (a positive integer will add to stock, a negative integer will remove from stock).
>
> Parameters:
> $sku - The product SKU that will have its stock level adjusted
> $qty - The quantity to add to the stock level
>
> Return value: **No return value.**
> 0 votes

---
Tags: nodes, hooks
---


# Question
Title: Multiple field, but each one as individule
I need an image field with only 2 field limit. I need to call first one front and second one back and be separated.(no problem I can do that with hook\_form\_alter)

My problem is that in drupal 7, in adding the content, it doesn't show the second field upload button until you upload the first one. You have to add the first file, than click on "add another" to be able to upload second file and after uploading both if you delete the first one, the second one goes to first one place, which I don't want that to happen!

I know I can make two separate fields call one front image and one back, but I want to know if there is an approach to do this with only one field. (save a database table)

Thank You

# Answer
Just use the single image field, add field description text for the user in regards to clicking to "add another" item when uploading the two images.

On updating, the user can adjust the weight of the images and drag/drop the front/back images into order.

Alternatively, you could look at using two fields, or a module like field\_collection
> 0 votes

---
Tags: entities
---


title: Show user ID in admin/people list?

text:
# Question
Title: Show user ID in admin/people list?
How difficult would it be to show a column in the user list (admin/people) that shows the user's ID number? Is this possible?

# Answer
> 8 votes
It's pretty easy if you're able to install the Administration Views module.

It replaces the default admin/people page with a view, which you can easily customise to add the user id as another column in the table.

If you're not able to use that module there are ways to do it in code, but it's a bit fiddly. I did roughly the same thing a couple of months ago (before I'd come across Admin Views) so let me know if you want me to dig the code out and post it here.

# Answer
> 5 votes
Implement `hook_form_BASE_FORM_ID_alter()` in a custom module to add the `uid` column to the list of people:

```
/**
 * Implementation of hook_form_BASE_FORM_ID_alter().
 */
function MODULE_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $uid_column = array('uid' => array(
    'data'  => 'ID',
    'field' => 'u.uid'
  ));
  $form['accounts']['#header'] = $uid_column + $form['accounts']['#header'];

  foreach ($form['accounts']['#options'] as $key => $row) {
    $form['accounts']['#options'][$key]['uid'] = $key;
  }
}

```

# Answer
> 0 votes
To fetch the profile2 fields you can just tweak the code like this:

```
/**
 * Implementation of hook_form_BASE_FORM_ID_alter().
 */
function MODULE_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $uid_column = array('uid' => array(
    'data'  => 'ID',
    'field' => 'u.uid'
  ));
  $form['accounts']['#header'] = $uid_column + $form['accounts']['#header'];

  foreach ($form['accounts']['#options'] as $key => $row) {
    $userProfile = user_load($key);  // this will have all user profile object which can be used below instead of $key.

    $form['accounts']['#options'][$key]['uid'] = $key;  // replace $key with the object value you need.
  }
}

```

---
Tags: users
---


title: What am I doing wrong in this code?

text:
# Question
Title: What am I doing wrong in this code?
I am trying to develop a module to insert a lot of node at one time and I would like to use Batch-API to display the progress of operations.

I read the example into 'Example' module and I wrote this code.

But don't made anything. I can see the progress bar go head but it don't save any node.

Can anyone help me on this?

```
function custom_content_archive_import_contents_submit($form, &$form_state) {
    $file=$form_state['values']['file'];
    unset($form_state['values']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    drupal_set_message(t('The file @filename was uploaded successfully.', array('@filename' => $file->filename)));

    ini_set('auto_detect_line_endings',TRUE);
    $path = drupal_realpath($file->uri);
    $importer = new CsvImporter($path, true, variable_get('custom_content_archive_file_delimiter'), variable_get('custom_content_archive_file_enclosure'));
    $data = $importer->get();
    ini_set('auto_detect_line_endings',FALSE);

    $_SESSION['http_request_count'] = 0; // reset counter for debug information.
    $all_data = array(
        'ctype' => $form_state['values']['list'],
        'data' => $data,
        'user' => $form_state['values']['user'],
        'lang' => $form_state['values']['languages'],
    );
    batch_set(start_batch_creation_nodes($all_data));
}

function start_batch_creation_nodes($all_data) {
    $num_operations = count($all_data['data']);

    $operations = array();
    $i = 0;
    // leggo il file uploadato e creo i nodi
    foreach ($all_data['data'] as $node) {
         $operations[] = array('create_node',
                          array($node,
                                $all_data['ctype'],
                                $all_data['user'],
                                $all_data['lang'],
                                t('(Operation @operation)', array('@operation' => $i))
                          )
         );
         $i++;
    }

    $batch = array(
        'operations' => $operations,
        'finished' => 'custom_content_archive_import_contents_finished',
    );
    return $batch;
}

function create_node($arrnode, $ctype, $user, $lang, $operation_details, &$context) {
    $node = new stdClass(); // Create a new node object
    $node->type = $ctype; // Or page, or whatever content type you like
    node_object_prepare($node); // Set some default values
    $node->uid = $user; // UID of the author of the node; or use $node->name
    $node->language = $lang; // Or e.g. 'en' if locale is enabled
    $node->promote = 0;

    foreach ($arrnode as $field => $value){
        switch ($field) {
            case 'title':
                $node->title = $arrnode['title'];
                break;
            case'body':
                $node->body[LANGUAGE_NONE][0]['value'] = nl2br($arrnode['body']);
                $node->body[LANGUAGE_NONE][0]['summary'] = text_summary($bodytext);
                $node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
                break;
            default:
                $arrfield = field_info_field($field);
                switch ($arrfield['type']) {
                    case 'datetime':
                         $my_date = new DateTime($value);
                         $node->{$field}[LANGUAGE_NONE][0][value] = date_format($my_date, 'Y-m-d H:i:s');
                         break;
                    case 'text':
                         $node->{$field}[LANGUAGE_NONE][0][value] = $value;
                         break;
                    case 'email':
                         $node->{$field}[LANGUAGE_NONE][0][email] = $value;
                         break;
                    case 'link_field':
                         $node->{$field}[LANGUAGE_NONE][0][url] = $value;
                         break;
                }
        }
    }

    if($node = node_submit($node)) { // Prepare node for saving
        node_save($node);
        workflow_execute_transition($node, 3, $comment = NULL, $force = TRUE);
        // Store some results for post-processing in the 'finished' callback.
        // The contents of 'results' will be available as $results in the
        // 'finished' function (in this example, batch_example_finished()).
        $context['results'][] = $node->nid . ' : ' . check_plain($node->title);

        // Optional message displayed under the progressbar.
        $context['message'] = t('Saving node "@title"', array('@title' => $node->title)) . ' ' . $operation_details;

        _custom_content_archive_import_contents_update_http_requests();
    }

}

function custom_content_archive_import_contents_finished($success, $results, $operations) {
    if ($success) {
        // Here we could do something meaningful with the results.
        // We just display the number of nodes we processed...
        drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _custom_content_archive_import_contents_get_http_requests())));
        drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
    } else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
    }
}

function _custom_content_archive_import_contents_update_http_requests() {
    $_SESSION['http_request_count']++;
}

function _custom_content_archive_import_contents_get_http_requests() {
    return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}

```

# Answer
> 1 votes
I'll refrain from trying to debug your code - that is probably a bit too localized, but will instead give you some advice/help on how to use the batch API in general.

What you are doing should work, but you are still using the batch API the wrong way.

The intended use is, that you create a function that receive all the data, which can handle it in chunks and add that as a single operation. I'll try to illustrate this in code. The code is fictional but should give you an idea of how to do batch jobs. The main thing is that the batch job operation function should keep track of how far it is in the process and do a repeat job a certain number of times. The function will then be recalled with the same args, but the context variable will be updated from each repeated call.

```
function form_submit_handler_submit($form, &$form_state) {
  // $form_state['values']['nids'] is an array of nids to opperate on.
  $nids = $form_state['values']['nids'];
  batch_set(array(
    'operations' => array('clone_nodes', array($nids)),
    'finihsed' => 'finised_callback',

  );
}

function clone_nodes($nids, &$context) {
  if (empty($context['sandbox']['count'])) {
    $context['sandbox']['count'] = 0;
  }

  $nids_to_handle = range($context['sandbox']['count'], $context['sandbox']['count'] + 49);

  foreach ($nids_to_handle as $key) {
    $node = node_load(nids[$key]);
    clone_the_node($node);
  }

  $context['sandbox']['count'] += 50;

  $context['finished'] = 1.0 * $context['sandbox']['count'] / count($nids);
  $context['message'] = t('Cloning node @current/@total', array('@current' => $context['sandbox']['count'], '@total' => count($nids));
}

```

---
Tags: 7, nodes, batch-operations
---


title: Migrating Multiple Files in a Node

text:
# Question
Title: Migrating Multiple Files in a Node
I am trying to migrate files to a content type called educational activity. My issue is that some instances of this content type have more than one file attachment. So what I am trying to do is use concatenation to get all the file names in one field and then append them to the node like it's done with multi-value fields. However the migration outputs: "ltrim() expects parameter 1 to be string, array given". It seems that after the concatenation I end up with an array of arrays instead of an array with file names, but I can't figure out why.

This is the code:

```
class EducationalActivityMigration extends EduMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

# Human-friendly description of your migration process. Be as detailed as you like.

$this->description = t('Migrate the Educational Activity content type along with its fields');

/**
 * We create the mapping in the database to be migrated instead of our default db.
 * Map Tables issue: http://drupal.org/node/1014558.
 */

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'nid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Node ID',
                       'alias' => 'n'
                      )
    ),
    MigrateDestinationNode::getKeySchema(), 'migrationDB');

$query = Database::getConnection('default', 'migrationDB')
           ->select('node', 'n');
$query->leftJoin('content_field_description', 'fd', 'n.nid = fd.nid');
$query->join('node_revisions', 'nrevi', 'nrevi.vid = n.vid');
//$query->leftJoin('node_revisions', 'nrev', 'n.nid = nrev.nid');
$query->leftJoin('content_field_age', 'fa', 'n.nid = fa.nid');
$query->leftJoin('content_field_target_group', 'tg', 'n.nid = tg.nid');
$query->leftJoin('content_field_rights_type', 'rt', 'n.nid = rt.nid');
$query->leftJoin('content_field_rights_holder', 'rh', 'n.nid = rh.nid');
$query->leftJoin('content_field_use_license', 'ul', 'n.nid = ul.nid');
$query->leftJoin('content_field_educational_stage', 'es', 'n.nid = es.nid');
$query->leftJoin('content_field_course', 'co', 'n.nid = co.nid');
$query->leftJoin('content_field_class', 'cl', 'n.nid = cl.nid');
$query->leftJoin('content_field_related_key_competence', 'rkc', 'n.nid = rkc.nid');
$query->leftJoin('content_field_filename', 'fi', 'n.nid = fi.nid');
$query->leftJoin('files', 'fil', 'fil.fid = fi.field_filename_fid');
$query->leftJoin('content_field_images', 'fim', 'n.nid = fim.nid');
$query->leftJoin('files', 'file', 'file.fid = fim.field_images_fid');
$query->addExpression('GROUP_CONCAT(DISTINCT fa.field_age_value)', 'age_list');
$query->addExpression('GROUP_CONCAT(DISTINCT tg.field_target_group_value)', 'target_list');
$query->addExpression('GROUP_CONCAT(rt.field_rights_type_value)', 'rights_list');
$query->addExpression('GROUP_CONCAT(DISTINCT rh.field_rights_holder_value)', 'holder_list');
$query->addExpression('GROUP_CONCAT(ul.field_use_license_value)', 'license_list');
$query->addExpression('GROUP_CONCAT(es.field_educational_stage_value)', 'edustage_list');
$query->addExpression('GROUP_CONCAT(DISTINCT co.field_course_value)', 'course_list');
$query->addExpression('GROUP_CONCAT(DISTINCT cl.field_class_value)', 'class_list');
$query->addExpression('GROUP_CONCAT(DISTINCT rkc.field_related_key_competence_value)', 'competence_list');
$query->addExpression('GROUP_CONCAT(fil.filename)', 'file_list');
//$query->addExpression('GROUP_CONCAT(file.filename)', 'image_list');
$query->fields('n')
        ->fields('fd', array('field_description_value'))
        ->fields('nrevi', array('body'))
        ->fields('fa', array('field_age_value'))
        ->fields('tg', array('field_target_group_value'))
        ->fields('rt', array('field_rights_type_value'))
        ->fields('rh', array('field_rights_holder_value'))
        ->fields('ul', array('field_use_license_value'))
        ->fields('es', array('field_educational_stage_value'))
        ->fields('co', array('field_course_value'))
        ->fields('cl', array('field_class_value'))
        ->fields('rkc', array('field_related_key_competence_value'))
        ->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
        ->fields('file', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
        ->condition('type', "educational_activity",'=')
        ->groupBy('n.nid');

# Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query);

# Set up our destination node as the Educational Activity node
$this->destination = new MigrateDestinationNode('educational_activity');

/**
 *  FIELDS WITH THE SAME NAME IN BOTH DBs
 *
 *  @nid: The primary identifier for a node.
 *  @title: General title of the node in plain text.
 *  @status: Boolean expression stating if the node is published.
 *  @created: Integer type timestamp of the node's creation.
 *  @changed: Integer type timestamp of the node's latest change.
 *  @promote: Boolean expression indicating if the node is present in the front page.
 *  @sticky: Boolean expression stating if the node should be at the top of the list wherever it appears.
 *  @comment:Shows whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write).
 *
 */

$this->addSimpleMappings(array ('title', 'status', 'created', 'changed', 'promote', 'sticky',
'comment'));

/**
 *  FIELDS WITH DEFAULT VALUES
 *
 *  @uid: value "36" corresponds to "grammateia" user.
 *  @language: default value set to "Ellinika".
 *  @translate: default value set to False.
 *  @tnid:The translation set id for this node, which equals the node id of the source post in each set.
 *  @revision_uid: The user id that shows which user did the revision.
 */

$this->addFieldMapping('uid')
  ->defaultValue($user);
  $this->addFieldMapping('language', 'language')
    ->defaultValue('el');
    $this->addFieldMapping('translate', 'translate')
    ->defaultValue('FALSE');
    $this->addFieldMapping('tnid', 'tnid')
    ->defaultValue('0');
    $this->addFieldMapping('revision_uid')
  ->defaultValue($user);

/**
 * FIELDS PENDING MIGRATION
 *
 * @vid: It means 'version id'. For every node in the node table, Drupal can save multiple versions in the node_revisions table.
 * The version id is the unique identifier in the node_revisions table.
 */

$this->addFieldMapping('vid', 'vid')
     ->description(t('Pending Migration Status'))
     ->issueGroup(t('What are gonna do with these?'));

/**
 * SOURCE FIELDS NOT TO BE MIGRATED
 *
 * @type: Shows the content type, not needed since we input the type in the MigrateDestinationNode constructor.
 * @moderate: Boolean expression showing if the node is under moderation. Moderation support has moved out of core.
 */

$this->addUnmigratedSources(array ('type', 'moderate', 'field_programma_ekpaid', 'field_syggrafiki_omada_ekp', 'field_schoolunit_ekp', 'fid','filepath', 'filemime', 'filesize', 'timestamp', 'file_fid', 'file_filepath', 'file_filemime', 'file_filesize', 'file_timestamp'), t('Source fields that we will not be migrating'));

/**
 * DESTINATION FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedDestinations (array('revision', 'log', 'is_new', 'field_rights_holder:language', 'field_keywords',
'field_keywords:source_type', 'field_keywords:create_term', 'field_keywords:ignore_case', 'field_knowledge_tree_category',
'field_knowledge_tree_category:source_type', 'field_knowledge_tree_category:create_term', 'field_knowledge_tree_category:ignore_case',
'field_tag', 'field_tag:source_type', 'field_tag:create_term', 'field_tag:ignore_case', 'field_related_item:language', 'field_body:summary',
'field_body:format', 'field_body:language', 'field_description:language', 'field_description:format', 'field_attachment:destination_file', 'field_attachment:description', 'field_attachment:display'),t('Destination fields that we will not be migrating'));

/**
 * FIELDS TO BE MIGRATED
 */

 $this->addFieldMapping('field_body', 'body')
      ->arguments(array('format' => 'full_html'));
 $this->addFieldMapping('field_description', 'field_description_value')
      ->arguments(array('format' => 'full_html'));
 $this->addFieldMapping('field_age', 'age_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_age_value'));
 $this->addFieldMapping('field_target_group', 'target_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_target_group_value'));
 $this->addFieldMapping('field_rights_type', 'rights_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_rights_type_value'));
 $this->addFieldMapping('field_rights_holder', 'holder_list')
      ->separator('--')
      ->arguments(array('source_type' => 'field_rights_holder_value'));
 $this->addFieldMapping('field_use_license', 'license_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_use_license_value'));
 $this->addFieldMapping('field_educational_stage', 'edustage_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_educational_stage_value'));
 $this->addFieldMapping('field_course', 'course_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_course_value'));
 $this->addFieldMapping('field_class', 'class_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_class_value'));
 $this->addFieldMapping('field_related_key_competence', 'competence_list')
      ->separator(',')
      ->arguments(array('source_type' => 'field_related_key_competence_value'));

 $this->addFieldMapping('field_attachment:file_class')
      ->defaultValue('MigrateFileUri');
 $this->addFieldMapping('field_attachment:language')
      ->defaultValue('el');
 $this->addFieldMapping('field_attachment:destination_dir')
      ->defaultValue('sites/default/files/educational_activity');
 $this->addFieldMapping('field_attachment:file_replace')
      ->defaultValue('FILE_EXISTS_REUSE');
 $this->addFieldMapping('field_attachment:preserve_files')
      ->defaultValue(TRUE);
 $this->addFieldMapping('field_attachment:source_dir')
      ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

 #Copy files (word etc)
 $this->addFieldMapping('field_attachment', 'file_list')
      ->separator(',')
      ->arguments(array('source_type' => 'filename'));

 #Copy Images
 //$this->addFieldMapping('field_attachment', 'image_list')
      //->separator(',')
      //->arguments(array('source_type' => 'filename'));

/**
 * We conditionally DNM these fields, so your field mappings will be clean,
 * whether or not you have path and or pathauto enabled.
 */

if(module_exists('path')) {

  $this->addFieldMapping('path')
       ->issueGroup(t('DNM'));
  if (module_exists('pathauto')) {
    $this->addFieldMapping('pathauto')
         ->issueGroup(t('DNM'));
  }

}//if ends

}//construct ends

}//class ends

```

Unfortunately, I didn't come to a working solution reading all the other questions.

# Answer
> 5 votes
So after managing to spend some time resolving this issue, I managed to migrate multiple files in a node like so:

To begin with this line:

```
$query->addExpression('GROUP_CONCAT(fil.filename)', 'file_list');

```

becomes:

```
$query->addExpression('GROUP_CONCAT(DISTINCT fil.filename)', 'file_list');

```

Cause we need to avoid migrating duplicates.

Secondly, this line:

```
->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))

```

became:

```
->fields('fil', array('filename'))

```

We don't really need to migrate this info cause the migration process can discover these values by itself. If however anyone believes that these should be migrated please advise.

And last and more importantly these lines:

```
 $this->addFieldMapping('field_attachment:file_class')
  ->defaultValue('MigrateFileUri');
$this->addFieldMapping('field_attachment:language')
  ->defaultValue('el');
$this->addFieldMapping('field_attachment:destination_dir')
  ->defaultValue('C:/xampp/htdocs/testpaideia/sites/default/files/educational_activity');
$this->addFieldMapping('field_attachment:file_replace')
  ->defaultValue('FILE_EXISTS_REUSE');
$this->addFieldMapping('field_attachment:preserve_files')
  ->defaultValue(TRUE);
$this->addFieldMapping('field_attachment:source_dir')
  ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

#Copy files (word etc)
$this->addFieldMapping('field_attachment', 'file_list')
  ->separator(',')
  ->arguments(array('source_type' => 'filename'));

```

become:

```
#Copy files (word etc)
$this->addFieldMapping('field_attachment', 'file_list')
      ->separator(',');

 $this->addFieldMapping('field_attachment:file_class')
      ->defaultValue('MigrateFileUri');
 $this->addFieldMapping('field_attachment:language')
      ->defaultValue('el');
 $this->addFieldMapping('field_attachment:destination_dir')
      ->defaultValue('sites/default/files/educational_activity');
 $this->addFieldMapping('field_attachment:file_replace')
      ->defaultValue('FILE_EXISTS_REPLACE');
 $this->addFieldMapping('field_attachment:preserve_files')
      ->defaultValue(FALSE);
 $this->addFieldMapping('field_attachment:source_dir')
      ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

```

We need to map the primary field (in my case field\_attachment) before its subfields (e.g. field\_attachment:preserve\_files, field\_attachment:file\_replace etc.), otherwise the migration fails. That's it hope it was helpful.

---
Tags: migrations
---


title: How to get this hierarchial view

text:
# Question
Title: How to get this hierarchial view
> **Possible Duplicate:**
> Clean way of building simple taxonomy browser of arbitrary depth

Here

Bachelor of programme -- Parent hierarchial term Year 1 -- Child term of Bachelor of programme Term 1 -- Child term of Year 1

NOTE: All 3 are TAXONOMY TERMS

Files listed below term 1 are Contents related to term1

kindly help in getting this through views.

# Answer
The easiest way (without views) to do that would be by enabling the core "book" module, which provides a "Book navigation" block which is very similar to the requirement.
> 0 votes

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


# Question
Title: How to create a single page with a jump select menu?
I need to create a page with a single jump select menu. Once the user makes a selection he/she will be redirected to a **view page** where the selection will be used as **contextual filter**

Can I do it with the webform module? What other option do I have?

I've found this one: http://drupal.org/project/jump but just a dev version for d7.

# Answer
> 1 votes
Views provides a "jump menu" display, you could just use that.

# Answer
> 0 votes
You can create a page with a page callback using hook\_menu(). Here is a workaround.

```
<?php
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['mypage'] = array(
        'title' => 'Available vouchers for you',
        'page callback' => 'mymodule_country_select_page',
        'access callback' => TRUE,
    );
    return $items;
}

function mymodule_country_select_page(){
    $country = array(
        '#type' => 'select',
        '#name' => 'country',
        '#title' => t('Select country to see your available Vouchers'),
        '#options' => array(
            '' => t(' - Select - ')
        ),
        '#attributes' => array(
            'onchange' => "window.location=this.value"
        ),
    );

    $options = array(
        '1' => 'Country 1',
        '2' => 'Country 2',
        '3' => 'Country 3',
    );
    foreach($options as $arg => $name){
        $url = url('path/to/view/', array('query'=> array('arg'=>$arg), 'absolute'=>TRUE));
        $country['#options'][$url] = t($name);
    }

    return render($country);
}

```

---
Tags: 7
---


# Question
Title: Make a field theme function work on empty fields
I am using a field theme function in my template.php file to override a field.

Everything works fine, but the function only seems to run if my field has content. If my field is empty, it does not run. How can I get the function to run all the time?

Here is the code I am using. The function checks a value in theme\_settings.php and then alters the output of the field accordingly.

```
function THEMENAME_field__field_call_to_action_button(&$variables) {
 // kpr($variables);

    //Load the value of CTA to determin which text to use
    $field_cta_option = field_get_items('node', $variables['element']['#object'], 'field_call_to_action_setting');
        $cta_option = $field_cta_option[0]['value'];

    //Assign theme/node settings to variables for easy access
    $cta_link_main      = theme_get_setting('cta_main_node');
    $cta_link_secondary = theme_get_setting('cta_secondary_node');
    $cta_link_custom    = theme_get_setting('cta_main_node');
    $cta_text_main      = theme_get_setting('cta_main_button_text');
    $cta_text_secondary = theme_get_setting('cta_secondary_button_text');
    $cta_text_custom    = $variables['#items'][0]['value'];
    switch ($cta_option) {
        case 'cta_main':
            return ctabutton($cta_link_main, $cta_text_main);
            break;
        case 'cta_secondary':
            return ctabutton($cta_link_secondary, $cta_text_secondary);
            break;
        case 'cta_custom':
            return ctabutton($cta_link_custom, $cta_text_custom);
            break;
        case 'cta_none':
            return "";
            break;
    }
}

```

# Answer
> 4 votes
You may want to change the way you are theming the information, for example by overriding node.tpl.php, but if you really want the field function to be run even when the field is empty, you can do it by modifying the node before it gets displayed:

```
function THEMENAME_preprocess_node(&$variables) {
  if($variables['type'] == 'mynodetype' && !isset($variables['content']['FIELD'])) {
      $variables['content']['body'] = array(
      '#theme' => 'field',
      '#field_type' => 'FIELDTYPE',
      '#field_name' => 'FIELDNAME',
      '#items' => array(),
      '#bundle' => 'mynodetype',
      '#label_display' => 'hidden',
      '#entity_type' => 'node');
  }
}

```

This will make sure the field is passed to your theme field function, even if it is empty.

To get the values to use for FIELDNAME and FIELDTYPE you can print out the contents of $variables\['content'\] on a page where the field is not empty.

Again, it might be better to override the theme of the entire node in this situation.

# Answer
> 2 votes
You appear to have no return if $cta\_option is NULL or empty, may this be the problem? If you have the devel module installed ( if not install it, it will help with debugging no end ), try adding this somewhere in the function:

```
dpm('THEMENAME_field__field_call_to_action_button has run');

```

If you get a notification on those pages then the function is running but just isn't doing what you think it is ( probably not returning when $cta\_option is NULL or empty ). If no notification appears then you may need to look at where that function is run.

if you do get the notification then change the line to

```
dpm($cta_option);

```

to see what the variable actually contains ( if anything ) on those pages and modify your switch accordingly.

---
Tags: theming
---


title: Adding data to node object

text:
# Question
Title: Adding data to node object
**Is there a hook responsible for generating the node object's data?**

I want to add some custom data to specific node objects to help with the functionality of a very complex website.

Can anyone help, please?

# Answer
`hook_node_load()` is exactly what you're looking for

> Act on arbitrary nodes being loaded from the database.
>
> This hook should be used to add information that is not in the node or node revisions table, not to replace information that is in these tables (which could interfere with the entity cache). For performance reasons, information for all available nodes should be loaded in a single query where possible.

The code example from the docs page is actually very good for your use case so I'll include it here too:

```
function hook_node_load($nodes, $types) {
  // Decide whether any of $types are relevant to our purposes.
  if (count(array_intersect($types_we_want_to_process, $types))) {
    // Gather our extra data for each of these nodes.
    $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
    // Add our extra data to the node objects.
    foreach ($result as $record) {
      $nodes[$record->nid]->foo = $record->foo;
    }
  }
}

```
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: How can I define a selection rule to use for Panels variants in code?
I have some custom PHP code that I would like to use as a selection rule for about 30 different variants. In the future, I may need to update this code, so rather than add the code 30 times, once for each variant, I would rather add it in code via a custom module so that I can more easily maintain it.

Is there a hook, etc. for adding Panels selection rules?

# Answer
What you want is internally called an "Access plugin".

Check my example on How does one create a new Ctools plugin?.

The advantage of this approach is that you can get rid of the evil eval.
> 3 votes

# Answer
You can add Panels selection rules.

However, in your case, have you tried just calling a module function instead in your PHP code for the selection rule?

e.g, call a function defined in a module:

```
return my_module_selection_rule('foo');

```

instead of all the raw code there.

That way, it can be updated once in the module codebase.

I use that technique a lot for views php contextual filter handling code.

If so inclined, see

* `panels/plugins/task_handlers/panel_context.inc`

for the default selection rules plugin definition. and

for the default form builder function for the selection rules.
> 4 votes

# Answer
You can make this by calling the function in your custom module. Lets say function is checkCondition() so you will have your code for selection rules return checkCondition(); and in the function you can set your condition to return true or false.

You can also do this for your content pane by adding visibility rule to it. Use php code for the same and call your checkCondition() function for it.
> 0 votes

---
Tags: panels
---


# Question
Title: Menu view does not render when editing profile2 profile
I am using profile2 and "Menu Views". Why would a view that I have in the menu not return any results at all when editing a user's profile (at the url /user/XXX/edit)? The menu view works on every other page of my site.

Maybe it's because I am theming the profile editing page? I can actually display the menu theme that i'm trying to display on my site's menu on the page itself by putting code within the theme, but no matter what I do it will not display in the menu on this page.

# Answer
The issue here ended up being that Drupal considers the page where a user edit's his profile in Profile2 an "admin" page. And, as of this writing, menu\_views.module (line 159) does not process menu views on admin pages. This has been reported to the module in the form of re-opening http://drupal.org/node/1790444.

Hopefully this helps somebody else as this was a very tough one to trace down.
> 0 votes

---
Tags: routes, users
---


# Question
Title: Image Migration from Drupal 6 to 7 fails
Happy New Year everyone,

I am fairly new to the Migrate Module and have come to a halt concerning image migration. To begin with, my problem currently is that when I run my migration, drush outputs: "New object was not saved, no error provided".

Now all I want is to get the images relating to a specific content type (educational\_activity) and copy them over to my destination folder.

CODE:

```
class EduActFile extends EduMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

// Describe the class for the Migrate UI

$this->description = t('Migrate files');

$query = Database::getConnection('default', 'migrationDB')
           ->select('node', 'n');
//$query->leftJoin('content_field_filename', 'fi', 'n.nid = fi.nid');
$query->leftJoin('content_field_images', 'fim', 'n.nid = fim.nid');
//$query->leftJoin('files', 'fil', 'fil.fid = fi.field_filename_fid');
$query->leftJoin('files', 'file', 'file.fid = fim.field_images_fid');
$query->fields('n')
      //->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
      ->fields('file', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
      ->condition('type', "educational_activity",'=')
      ->groupBy('n.nid');

$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

// Specify that we want to create files from the source data

$this->destination = new MigrateDestinationFile('');

// Remember what source record created each destination object and track migration status and allow rollback with MigrateSQLMap class

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'nid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Node ID',
                       'alias' => 'n'
                      )
    ),
  MigrateDestinationFile::getKeySchema()
);

$this->addUnmigratedSources(array ('fid','filepath', 'filemime', 'filesize', 'timestamp'), t('Source fields that we will not be migrating'));

$this->addUnmigratedDestinations (array('timestamp', 'destination_file'));

$this->addFieldMapping('uid')
  ->defaultValue($user);

// For each source row to be processed define data mappings to the destination field from source field

$this->addFieldMapping('value', 'filename');

// Specify the location of the source folder to find the files

$this->addFieldMapping('source_dir')
     ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

// Specify the location of the destination folder to place the files

$this->addFieldMapping('destination_dir')
     ->defaultValue('C:/xampp/htdocs/testpaideia/sites/default/files/educational_activity');

// Use existing files

$this->addFieldMapping('file_replace')->defaultValue('FILE_EXISTS_REUSE');

// Ensure files are not deleted during rollback

$this->addFieldMapping('preserve_files')->defaultValue(TRUE);

}//construct ends

```

}

Do I need to use a different class to migrate files? Is my query wrong? Thanks in advance, your help will be greatly appreciated.

# Answer
> 0 votes
This has been answered by me in another question I made. It can be found here: Migrating Multiple Files in a Node

---
Tags: migrations
---


title: Hosting modules internally

text:
# Question
Title: Hosting modules internally
Our company is looking to use Drupal as a platform going forward. We plan on making some modules for in house use only i.e. A module to talk to our holiday system. We wanted to know the best way to host these internally so people can browse the modules. Is it possible to get Drupal to report when a custom module is out of date?

# Answer
If you want somewhere to host modules you could use distributed version control such as Git or Mercurial to store them in a repository.

You can then use drush make to build the site with modules hosted on drupal.org and from your repository.
> 0 votes

---
Tags: 7
---


# Question
Title: Exposed Filter not shown in view which has a Custom Filter Handler
I have a view and I programmatically created a filter for this view. (I pasted the code below).

This filter works fine but I had **other Exposed Filter** created inside the view (created by clicking add filter in the view).

Now the filter added programmatically is working fine but the other one is not shown at all.

If I disable the filter added programmatically then the other one is shown correctly. So the problem is in the code I guess.

I need both filter working together.

here is the code which adds the filter:

```
/**
 * Implements hook_views_pre_view().
 */
function vouchers_views_pre_view(&$view, &$display_id, &$args) {

   if ($view->name == 'vouchers') {
    $info = array(
      'table' => 'field_data_field_labpoints',
      'field' => 'field_labpoints_value', // name of value field in that table.
      'value' => array('value' => userpoints_get_current_points()), // dynamic part.
      'operator' => '<',
      'id' => 'field_data_field_labpoints_vouchers', // unique id.
      'group' => 100, // new group.
    );
    $handler = views_get_handler($info['table'], $info['field'], 'filter');

    $handler->init($view, $info);
    $view->display_handler->handlers['filter'][$info['id']] = &$handler;

    unset($handler);
  }
}

```

# Answer
I would do this by adding a contextual filter, previously called an argument in D6 Views. You can set contextual filters / arguments in code when you embed a view. So, you could add a contextual filter for field\_labpoints (not sure what kind of field this is) and pass along the argument you want to filter for when you embed the View in a `.tpl` file or a panel or whatever:

```
print views_embed_view('my_view_name', 'block_1', $labpoints_value);

```

This allows you to make the View more dynamic without tinkering with the existing filters.
> 3 votes

# Answer
Why not simply add your custom filter in a `hook_views_query_alter`? This way you'd be sure there's no conflict...
> 1 votes

---
Tags: views
---


# Question
Title: Add CCK field to panel / page (from page manager)
Working in a D6 site, I was asked to add the CCK field that appears in all nodes, which is a taxonomy term reference, a tag, to a "Landing Page" created using page manager and panels. Is that even possible? If yes, how would I go about doing that?

# Answer
> 0 votes
In short, no. Pages are not entities (or nodes in D6) and so cannot have fields, CCK or D7 core, on them.

It's possible that FAPE does what you want, since it allows you to stick an `Entity` directly into a `Page`, but that's D7 only.

---
Tags: 6, taxonomy-terms, entities, panels, chaos-tool-suite
---


# Question
Title: How to manually use Drupal 7's admin Overlay?
I am thinking of using Drupal's built-in admin overlay jQuery script to overlay my own contents. Is it possible?

# Answer
> 7 votes
The Overlay module renders as overlay the pages for which an implementation of hook\_admin\_paths() returns `TRUE` for the associated path. For example, the implementation of that hook done from the Node module is the following one:

```
function node_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;
  }
}

```

This means that the node edit form is rendered as overlay, when the Overlay module is enabled. When the Overlay module is not enabled, then those pages are rendered using the administrative theme.

For paths implemented by other modules, a module can implement hook\_admin\_paths\_alter(). An example of implementation could be the following one, which would make the user profile pages rendered in an overlay.

```
function mymodule_admin_paths_alter(&$paths) {
  // Treat all user pages as administrative.
  $paths['user'] = TRUE;
  $paths['user/*'] = TRUE;
  // Treat the forum topic node form as a non-administrative page.
  $paths['node/add/forum'] = FALSE;
}

```

# Answer
> 9 votes
You can also use the Overlay Paths module. This is a simple module that enables administrators to use the built-in Overlay for non-admin pages. This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.

# Answer
> 3 votes
If you want to implement this function for a particular content type, so that all nodes of that content type opens in the administrative overlay, you can use the following code:

```
<?php
/*
 * Implements hook_admin_paths_alter().
 */
function YOUR_MODULE_admin_paths_alter(&$paths) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'YOUR_CONTENT_TYPE')
      ->propertyCondition('status', 1);
  $result = $query->execute();

  if (isset($result['node'])) {
    $nodes = array_keys($result['node']);
    foreach ($nodes as $node_id) {
      $node_path = 'node/' . $node_id;
      $paths[$node_path] = TRUE;
    }
  }
}
?>

```

# Answer
> 1 votes
The Overlay module is hardcoded for a single purpose, displaying admin pages. It would require a huge amount of effort to reliably re-use that code for your own content.

# Answer
> 1 votes
Maybe one of the numerous contrib module can help you out, like Dialog API.

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


# Question
Title: Drupal search - 2 search pages using their own settings
I would like to have 2 pages: \- http://domain.com/search-1 \- http://domain.com/search-2

Where search-1 is limited to results of contenttype blog and search-2 is limited to results of contenttype news.

I've been looking for contrib modules but cannot find anything. Please help me out, thanks.

Cheers, Wietse

# Answer
First, I would consider to use Views along with exposed filters to create your special "search" pages. E.g. create a view which only lists blog entries and then add a filter for body text to it.

My next approach would be the Search API module along with the Search API Page module.

Last but not least, you always can write a module for that. ;) I would take a look at different search modules which already implement additional search pages.
> 1 votes

---
Tags: search
---


# Question
Title: Exclude current node from entity reference view (for related news)
In Drupal 7 I have a news content type with a simple related news selection list. This works like a charm, I use an entity reference view to fill the list and new news-items are created just like they should be. But once the news-item is published it will of course be shown in the list. If you select it, the standard behaviour will be to render its full content view, resulting in a recursive content error.

How can I create an entity reference view that excludes the current node? I have found a lot of related issues, but nobody seems to answer the question of using parameters at all in this special kind of view. I tried to add an argument to the filter using the token syntax which says "AND Nid not equals \[node:id\]" but that turns out to be ignored. I also found that when you include the view it is possible to send parameters to it, but I was unable to find documentation for how to use them.

Does anybody have more information/documentation about this?

# Answer
there is a patch fixing that issue and helping you to use `[node:nid]` as an arg here.

---

Otherwise, did you try Entity Reference View Widget ?

> The module has a way of hiding selected items from the View. Simply add a base field contextual argument (Product ID for products, Node ID for nodes, etc) and in the "More" fieldset enable "Allow multiple values" and "Exclude". Then edit the Entity Reference field, and in the widget settings enable "Pass selected entity ids to View ".
> 1 votes

---
Tags: views, entities
---


# Question
Title: For someone who is not a programmer or is starting how can he/she contribute to Drupal.org?
I have been talking to people who are starting in the university about Drupal. But they are beginners in programming. so they told me how they can contribute to Drupal or being more involved.

What would be the best advice for them to contribute..or how they can start if they have limited program skills? Do you have any advice?

# Answer
> 38 votes
Both @David and @Patrick have put well on the ways to contribute to the Drupal community. I think a good place to evaluate yourself and start contributing would be at Drupal Ladder.
It was a result of the work from the folks from Boston, who came together and started something called Boston initiative where they come together and work on contributing.

You can look at the ladder screenshot below :

If one wishes to contribute, s/he is suggested to follow these steps starting from the bottom and climbing the ladder one step at a time.

You can also view the session about Drupal ladder at DrupalCon Denver.

P.S.: The Drupal Ladder was designed to encourage users to contribute to Drupal core and not focus on contributing towards the modules (contributed).

# Answer
> 16 votes
There are many ways to contribute to the open-source Drupal project.

For example:

> * Contributor task: Add keywords to a Community Documentation page
> * Contributor task: Add new content
> * Contributor task: Add screenshots for a Drupal issue
> * Contributor task: Answer a support forum question
> * Contributor task: Assess and clean up a Documentation issue
> * Contributor task: Document mobile CMS interfaces
> * Contributor task: Document steps to reproduce a reported issue
> * Contributor task: Handle or refer a support request in an issue
> * Contributor task: Manually do Accessibility testing of a patch for a Drupal issue
> * Contributor task: Manually test a patch for a Drupal issue
> * Contributor task: Verify a reported issue

Further information can be found here: http://drupal.org/contribute

# Answer
> 13 votes
I am not much of a programmer myself, but one way I contribute is to read through the issue queues of contributed modules that I have experience with. In the issue queues, there are many support requests from inexperienced Drupal users that I am able to answer, even without programming knowledge. I would imagine that the module maintainers appreciate this, because I bet that they would rather spend their time improving their modules than answering basic questions from new users.

Also, in the issue queues, one often finds multiple bug reports on the same issue. Closing duplicates and writing summaries for issue threads that have grown extremely long can help bugs get solved even if you yourself do not have the programming skills to fix them. Further, this gives one great insight into what a helpful bug report is (and how not to write a bug report!)

To get started, check out the guide for how to use the issue queues.

# Answer
> 11 votes
Lullabot has an article about why writing documentation makes a great deal of sense for beginners in Drupal and/or development.

# Answer
> 7 votes
Triaging large issue queues by identifying duplicate issues and issues that are filed against the wrong project, and following the guidelines for helping maintainers is always helpful and almost anyone can do it.

---
Tags: 7, community-official-site
---


# Question
Title: Displaying a field of an entitiy reference
In my *Page* content type there is an `image field` called gallery, and an `Entity reference` field refering to a **related** page.

I need to display the images contained in the gallery field of the **related** page.

I have created a Display Suite a code field. In the tokens I found `[node:field-related-page:field_gallery]` but it seems to be empty (it prints nothing).

I have used Devel's `dpm()` method to display `$entity`'s content but it does the related page fields do not contain any info about the gallery (which makes sense as recursion could be an issue):

# Answer
If you want to do it only in code, do a `node_load($node->field_related_page['und']['0']['target_id']`. If you want a view, use a relationship and show gallery field with the relationship.
> 1 votes

---
Tags: entities, display-suite
---


# Question
Title: Display of hierarchical Taxonomy in views along with the related content
I have a Hierarchical Taxonomy like:

> Bachelor of Degree
> -Year1(child term of Bachelor of Degree)
> --Term1(child term of Year1)
> -Year2
> --Term2
>
> etc etc...

The contents content1, content2... of a Content type will go under Terms Term1, Term2...

Can you kindly help me in getting the view as:

> Bachelor of Degree -Year1(child term of Bachelor of Degree)
> --Term1(child term of Year1)
> content1
> content3
> -Year2
> --Term2
> content2
> content4

# Answer
> 0 votes
1- Use Hierarchical Select module. it may help you.
2- by using the Taxonomy menu module
3- use Views Tree and Views Field View

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


# Question
Title: add first/last classes when using theme_menu_link
Im building my own menu tree for various reason, but one think i miss is the first / last classes. I dont find anything about it in the API and i do have `drupal_attributes($element['#localized_options']['attributes'])` set.

Where and how would the first/last classes be called?

my function in template.php goes something like this (taken direct from the API)

```
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

# Answer
Use Menu attributes module and give special ID or classes to your menu items. The module currently allows you to set the following attributes for each menu item:

```
Id
Name
Target
Rel
Class
Style
Accesskey

```
> 0 votes

---
Tags: routes
---


title: Add meta data to menu items

text:
# Question
Title: Add meta data to menu items
I have a Drupal website where many custom modules are implemented. These modules create custom rendered pages which are linked to menu items. This way a menu item represents a custom rendered page. Some other menu items are linked to node instances.

My goal is to provide meta data to each of these menu items. The meta data I want to add to each menu item are 'page description', 'user notes' and eventually term references (taxonomy).

Is there a way to add meta data to each of my menu items?

One possible solution I can come up with is creating a content type that wraps custom rendered pages with a 'description', 'user notes' and 'tags' field. Then I would create a node for each of my custom rendered pages and link the nodes to the menu items. But I'm wondering if there aren't more elegant solutions..

# Answer
> 0 votes
Use Menu attributes module. The module currently allows you to set the following attributes for each menu item:

```
Id
Name
Target
Rel
Class
Style
Accesskey

```

---
Tags: taxonomy-terms, routes, 7
---


# Question
Title: How to add fields from other modules in Drupal 6 Views?
I have a Drupal 6 website with Ubercart 2 and the "Delivery time slots for Ubercart" module installed, and I have created a View to pull a custom report of order info. I need for that report to also include the delivery time slot chosen by the shopper on each order, but that module apparently does not have Views integration. Is there a way for me to pull the time slot value (and/or any other arbitrary database field that related to the other data I am pulling in, I assume based on the order ID) for each order into the view?

I appreciate any feedback! Thanks!

# Answer
You can try out the below modules. They are meant for getting data directly from the database into views.

Table Wizard

Data Model

If both of them doesn't suit your requirement then you could use the Views Custom Field write php code directly into the view and collect the required fields using database queries.

You could also do the direct query with in the views template files.
> 1 votes

---
Tags: views, ubercart
---


# Question
Title: Embed block into a custom views template
I created a custom views template that I have called views-view--page.tpl.php. Now I would like to add a block into the template file.

In my page template file I was able to render a region and do this:

```
<?php print render($page['leftsidebar']); ?>

```

But it seems like this will not work for a views template. I am not the best with PHP so any help would be great!

I'm using Drupal 7.

# Answer
Using the answer given to me in the comments by @subhojit777 I was able to call it up using this code:

```
<?php
  $block = block_load('MODULE_NAME', 'DELTA');
  $output =      drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

```

I don't know if this is the best way, but it's working for now. :)
> 1 votes

---
Tags: 7, blocks, theming
---


# Question
Title: How to create User Account Registration form with Webform?
I am using Drupal 7. I have Webform with 6 fields:

* Your name
* User name
* password
* Email
* phone number
* Website

If we submit it will store in database, but here I need username & password should store in "User Account Registration" form also.

We can add fields from Configuration -\> People -\> Account settings for other fields, but it doesn't work in this situation. I need to store the User name & password values to "User Account Form" and then to login with that username and password.

# Answer
Storing the password as a regular Webform field is not nearly as secure as using Drupal's built-in user registration password. I would recommend instead of trying to create user registration via Webform, that you use something like Profile 2 to add additional information fields to the core registration form.
> 3 votes

---
Tags: webforms, users
---


title: Taxonomy view to display all terms

text:
# Question
Title: Taxonomy view to display all terms
I am using the default taxonomy view that comes with the views module and everything is working as expected. The one problem I have is that I cannot figure out how to display a page showing all nodes under my parent vocabulary term.

Vocabulary = videos

```
-Term 1
--Term A

-Term 2
--Term A

-Term 3
--Term A

```

So with the example above if I go to any of the terms I will get the terms and children associated with them. Ex: www.site.com/videos/term-1. That works.

But I would like to have a view listing ALL of the nodes when a user goes to www.site.com/videos.

It's gotta be pretty simple, but I am missing it. Thanks!

# Answer
You can create a view of taxonomy terms with a contextual filter of the type **Taxonomy vocabulary: Machine name**

Add relationship called **Taxonomy term: Content with term** and use that relationship to add the contents.
> 0 votes

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


# Question
Title: Image styles: Does not work with large images
The image styles, thumbnails and so on, are not created on my Drupal 7 site, when the original file is bigger than 5 MB. I did not find any error message in the log messages and the v-server, the site is hosted on, seems to have sufficient power to convert large files: I have 4 GHZ CPU and 4 GB RAM. The original file is uploaded correctly and I have double checked the file permissions.

Does anybody know, what to do?

# Answer
> 1 votes
I installed Imagemagick and now everything works as expected.

---
Tags: media
---


# Question
Title: Add float or align selector for CCK image fields
I'd like to add a float/align drop-down selector for each CCK image field in my content items. Then, that image would float/align itself on either side of the content (left or right), depending on whether "left" or "right" was selected from the drop-down. Ideally, this drop-down would be in the same general area as the ALT and Title fields are in the admin view of the content item.

Does anyone know if this is possible without custom programming?

# Answer
> 0 votes
Look into the Display Suite Module: http://drupal.org/project/ds

It is designed to give you more control of the display of your content from the Admin UI. There are links to detailed screencasts on the project page. You'll see versions for both D6 and D7.

I don't know if you get those options on the 'add new content' page, but it wouldn't surprise me if you did.

---
Tags: entities
---


# Question
Title: Redirect to mobile page (not theme switching)
I'm looking for a way to redirect mobile users to a mobile landing page (and I'm not looking for a theme switcher). I have a specific page that I'd like to redirect mobile users to: www.mysite.com/m/

Is there a way to utilize Mobile\_Detect.php and specify a single page as the redirect target?

# Answer
I suppose if you really wanted to, you could do something along the lines of this in a custom module:

```
function YOURMODULE_init() {

  if ($_SERVER['REQUEST_METHOD']=='GET' // most ajax/ahah etc use POST
      && arg(0)!='admin' // admin theme/backend
      && strpos($_GET['q'], 'sites/default/files')===FALSE // are we looking at anything under files that doesn't "really" exist, eg imagecaches that aren't created yet
      && $_GET['q']!='m') { // aren't already "here"

    include 'PATHTOSCRIPT/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if ($detect->isMobile()) {
      drupal_goto('m');
    }

  }

}

```

but they could never leave, or rather, be able to go to any other page on your site.

Addition: per @MPD's comments, some further protections.
> 3 votes

# Answer
My preference when doing mobile redirection is to use a javascript solution instead of PHP. It doesn't impact the load times significantly, and can easily be adjusted for more complex logic if required (user-agent, platform, etc).

```
<script type="text/javascript">
if ( (screen.width < 1024) && (screen.height < 768) ) {
  window.location = 'http://www.mysite.com/m/';
}
</script>

```
> 1 votes

---
Tags: redirection
---


title: Where are my breadcrumbs coming from?

text:
# Question
Title: Where are my breadcrumbs coming from?
I at one stage had the Menu breadcrumbs module, then the Custom breadcrumbs module enabled. I have now disabled both of them, but the breadcrumbs are still displaying. Only the Home breadcrumb is displayed on every page, and on the search results page "Home \> Search \> Content" is displayed.

Where are my breadcrumbs coming from since I disabled both modules?

* Search results page

```
<nav role="navigation" class="breadcrumb"><h2 class="element-invisible">You are here</h2><ol><li><a href="/">Home</a> › </li><li><a href="/search">Search</a> › </li><li><a href="/search/node">Content</a> › </li></ol></nav>

```
* Every other page

```
<nav role="navigation" class="breadcrumb"><h2 class="element-invisible">You are here</h2><ol><li><a class="active" href="/">Home</a> › </li></ol></nav>

```

# Answer
Typically the option to disable these are located under your theme settings (/admin/appearance/settings/THEMENAME). If your theme doesn't provide the option to disable these, you can always resort to http://drupal.org/project/disable\_breadcrumbs
> 1 votes

# Answer
Drupal will output breadcrumbs by default if you have the $breadcrumb variable in your page templates. It should be as easy as removing the `$breadcrumb` variable from those templates.
> 1 votes

---
Tags: breadcrumbs
---


# Question
Title: How do I create a menu item when a node is submitted?
I have created a new content type and want to add a menu item every time a user creates a new node for this content type. I can catch the submission using hook\_node\_submit, but I don't know how to add it to a menu from there.

# Answer
> 3 votes
Try using the menu\_link\_save function.

```
<?php
$item = array(
  'link_path' => 'node/' . $node->nid,
  'link_title' => $node->title,
);
menu_link_save($item);
?>

```

---
Tags: 7, routes, hooks, nodes
---


title: remove existing spam comments

text:
# Question
Title: remove existing spam comments
I have a Drupal 7 site. This is a live site with both legitimate comments and spam comments. From what I can tell, most of the spam modules work when a comment is submitted, but don't go back and look at existing comments, comments added prior to the module being installed. I'm looking for a way to do this programmatically.

# Answer
> 1 votes
Views Bulk Operations has an "Unpublish comments containing keyword" operation.

---
Tags: comments, advertising
---


title: Dynamically Theme Boolean Fields

text:
# Question
Title: Dynamically Theme Boolean Fields
I am trying to dynamically display boolean fields into columns based on their value. So for instance these 10 boolean fields on my node, if marked 1, I want it to theme it so that they show up in a column to the left titled Completed, and if marked 0, a column to the right titled Not Complete. I have tried using template.php and field.tpl.php but I am getting very lost.

I'd like to do this on the field node being viewed (not using Views) as a custom dynamic field formatter that applies a different css class to the field div. That or in the theme layer using some php magic.

# Answer
> 0 votes
Okay I think this might be what you're looking for: http://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook\_field\_display\_alter/7

I'd throw that function on your template.php, enable the Devel module, then use kpr() to print the variables to the screen and go from there.

# Answer
> 0 votes
The answer is easier than I thought. Here is some example code. Just change template in template\_preprocess\_field to the name of your theme and put it in template.php with an opening php tag.

```
    /*
 * Implements template_preprocess_field()
 */
function template_preprocess_field(&$vars) {
  //check to see if the field is a boolean
  if ($vars['element']['#field_type'] == 'list_boolean') {
    //check to see if the value is TRUE
    if ($vars['element']['#items'][0]['value'] == '1') {
      //add the class .is-true
      $vars['classes_array'][] = 'is-true';
    } else {
      //add the class .is-false
      $vars['classes_array'][] = 'is-false';
    }
  }
}

```

---
Tags: theming, entities
---


title: No Breadcrumb settings in Bartik theme?

text:
# Question
Title: No Breadcrumb settings in Bartik theme?
The breadcrumbs in my Bartik theme work perfectly. However, in my Zen subtheme are skipping a level!

I just noticed that there is no Breadcrumb settings section in the Settings for the Bartik theme.

I am using the Menu Breadcrumbs module for both sites...

# Answer
Try using Custom Breadcrumbs instead.

> Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home \> User Blog \> 2005 \> January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
> -2 votes

---
Tags: breadcrumbs
---


# Question
Title: GA Virtual pageview on Webform reload: is there an easier way?
I can't believe it was so difficult.

I have Webform and Google Analytics installed. I want to track submissions of my webform, but since it's set to reload current page on submission, I must make use of either Virtual Pageviews or Events. I went with the former.

At first I thought it'll be as easy as using `hook_webform_submission_insert()` and invoking GA code via `drupal_add_js()` from there, but somehow it didn't work: the hook itself was executed, but JS was never added to the page.

Now I reached the bottom of Google and haven't found any help on this specific case (everybody seems to be using separate "thank you" pages). Fast forward a couple hours, dozen approaches and hundreds of pages, I finally arrived at this working code:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //add custom submit callback
  if ($form_id == 'webform_client_form_[node id here]') {
    $form['#submit'][] = 'mymodule_submit_ga';
  }

  //add GA tracking upon successful submission
  if (isset($_SESSION['mymodule_submission_successful']) &&
      $_SESSION['mymodule_submission_successful'] == TRUE) {
    //reset temporary variable
    unset($_SESSION['mymodule_submission_successful']);
    //build JS
    $script = '(function() {';
    $script .= '_gaq.push(["_trackPageview","[virtual page path here]"]);';
    $script .= '})();';
    //add JS somewhere in the end
    drupal_add_js($script, array("type"=>"inline","group"=>JS_THEME,"weight"=>20));
  }
}

function mymodule_submit_ga($form,&$form_state) {
  //set temporary variable for the code above
  $_SESSION['mymodule_submission_successful'] = TRUE;
}

```

I'm sharing this in case it helps anybody, but as I'm not a PHP expert, I can't help the feeling that I missed something really simple.

Is there an easier way of doing this?

# Answer
> 0 votes
An easier method (that requires no coding) would be to set the webform's "Redirection location" setting to "Custom URL" and enter 'node/%nid?f=my\_webform\_success'.

This will post the form to itself and also allow you to add some unique key/value to the URL.

Then within Google Analytics you can set a Goal with the Goal URL set to 'f=my\_webform\_success' and the Match Type set to "Regular Expression Match".

---
Tags: 7, webforms, google-analytics
---


# Question
Title: How to include "Page Updated" in the footer of my drupal 7 site?
I would like to display a "Page Updated" snippet in the footer of my site. Is there a module which I can use, and then include as a block?

# Answer
> 0 votes
There is no module specifically to do that. Its very easy todo as you just put the message variable in the bottom of your footer. Just find the message variable in your page.tpl.php file. search for message and copy that $variable to the bottom of the page.

---
Tags: 7, updating
---


# Question
Title: Recommended tools/techniques for monitoring for spam attacks on multi-site and shared servers
I'm managing a number of servers with dozens of Drupal sites, some with a single multi-site Drupal installation and others with dozens of separate Drupal installations. We're constantly running into the issue of one site having a lax registration or comment policy and getting overrun with node spam to the detriment of the entire server.

Addressing the spam isn't a problem once we can detect the issue (CAPTCHAs and user registration approval usually knock out most of the attacks) but most of these sites have inexperienced administrators who aren't savvy enough to notice these attacks underway and we only detect them several months in when the damage to performance and SEO has already been done. Better security policies would also obviously help and we usually try and address any potential security issues during the site build but we don't usually try and prevent the client from enabling comments or adding new features, etc.

Any recommendations for how to monitor multiple Drupal sites to detect an attack like this before it gets too far? I've seen a number of 'drupal watch' modules and services like Drupalmonitor.com or NewRelic but they seem more focused on module updates, etc. Possible signatures for a spam attack would probably be an excessive amount of comments or nodes over a given period, coming from the same server, excessive load on a specific table, etc.

# Answer
> 1 votes
ether try the free mollom service or you can blacklist words before they get submitted. Another solution that does well is just use the disqus module to regulate your commenting. i have switched over to disqus completely. but its not seo friendly as its a js script call from what i remember. if you want seo capability best you blacklist words and links. say if someone posts a link it would throw an error. this would deter any link spammers as most bots posts links.

---
Tags: security, advertising
---


# Question
Title: Add extra information across cart/checkout/invoice in Ubercart
I would like to add extra information in cart, checkout and invoice in Ubercart. Idea is to show discount ammount that was implemented by hook\_uc\_cart\_alter - I want to add above the Total Price, Another value - Discount, and show that discount on all forms.

I can add extra values by appending in hook\_tapir\_table\_alter, but i am not sure if this right way, or is it only for viewing purpouse? Is there other more reliable method ?

Thanks.

# Answer
> 0 votes
there's no other module i know of that exposes this data. i too had to do hook alters to recalculate the total and discounts to have it show in the checkout forms.

---
Tags: ubercart
---