# Question
Title: Hierarchy between terms from different vocabularies in Drupal 7?
Is there a way to have a hierarchy of terms by reusing the same terms that reside in different vocabularies? There seem to be so many different options for dealing with taxonomies in Drupal 7 that it feels very daunting to figure out...

For example, let's say I want to make a directory of athletes for different sports. I've created 3 vocabularies, each with several terms:

Vocabulary: Sports
* Soccer
* Basketball
* Baseball

Vocabulary: Divisions
* Division 1
* Division 2

Vocabulary: Teams
* Team 1
* Team 2

Each type of sport will be divided into Divisions and then into different teams per Division.

The hierarchy looks like:

Soccer
* Division 1
--Team 1
--Team 2
\*Division 2
--Team 1
--Team 2

Basketball
\*Division 1
--Team 1
--Team 2
\*Division 2
--Team 1
... and so on for each sport.

Since the terms for vocabularies Divisions and Teams are always the same, I'm thinking it would make more sense to be able to reuse the same terms under those two vocabularies instead of creating the same terms over and over again for each sport, each division...etc.?

Is that even possible and if so, what would be the best way to go about implementing it?

# Answer
> 2 votes
You can make a term reference field on a vocabulary. So on a the team vocab one of the fields would be "division". So when you create a new team you would enter the team name and "tag" the division it is in using auto complete or a dropdown.

# Answer
> 1 votes
The only problem with free-tagging it (by that I don't mean allowing all users to tag the content), which is really the only solution except to create everything in one vocabulary, is that when users search or click on tags for the generic labels like "Division 1", it will not be focused enough in the outcome to be useful.

Since these items have a hierarchy, I think the only solution is to fully duplicate that hierarchy to make results relevant. Someone clicking a linked tag "Division 1" is going to get results for all sports, even when the page in question that is displaying the tags is only about 1 sport. And it won't sort your results based on the previous page unless you set some variable.

I see how the shortcut saves some time but in the long run it completely separates things and in search results only the first result with all terms will be relelvant, the rest will be listings of everything else. Just a thought.

Unless you're going to have separate term reference fields, I'd think it would be a better user experience to simply have the hierarchy in one vocab where pulling the dropdown down would make clear and concise sense.

I guess a good question would be: will you ever have a reason to pull a listing of all Division 1 teams across different sports?

Another question would be: are there so many teams and divisions that one dropdown is simply too long to be user friendly?

# Answer
> -1 votes
It is also possible to assign multiple parents to a term. The easiest way to do this that I have found is with the Taxonomy Manager module.

---
Tags: taxonomy-terms
---


# Question
Title: control the view access permissions by field.tpl.php in D7
I would like to be able to control who can view a field by a custom field.tpl.php for a given field. Basically I would like to set a coditional at the beginning so that is displays nothing if the user does not have a given role (say, "registered-user").
I would think that this amounts to adding an "if" at the very beginning of the the field template, but I do not have much experience. Is it possible to do it that way?

# Answer
Never put any business logic into tpl files. They can be cached. So unless it's the *"if odd, add class `odd`"* type of logic, it may fail you miserably.

If you need more elaborate rules than Field Permissions give you, you need to implement `hook_field_access($op, $field, $entity_type, $entity, $account)` in your custom module.

> Return value
>
> TRUE if the operation is allowed, and FALSE if the operation is denied.

Field Permissions module is open source. You can see it's source to learn how this hook is supposed to be used. Same with User role field module. Both are pretty well commented in code, and can serve as good examples how to write your own custom logic. Just make sure you are not forking one, this may lead to more complications than it's worth - if they are not sufficient, inspire and even copy parts of code, but use your own name and info file.
> 4 votes

# Answer
If you don't have much experience in writing a custom code then take a look at Field Permissions module.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 2 votes

---
Tags: entities, users
---


# Question
Title: Conditionally display a field based on another field's content by field.tpl.php
What i would like to achieve is to be able to show the field's content only if another field of the node being displayed has a certain value. So I'd like to put an **if condition** at the beginning of the custom field.tpl.php that controls whether the content is public or restricted based on another field's value (whether the node is tagged as free or not).

Actually, what I am trying to achieve is to make a double control: if the node is tagged FREE, display it right away, if not, see the user's permissions and display it of he has "paid user" role (just to explain things).

# Answer
> 1 votes
I don't think that you need a custom field.tpl.php or custom module. You can just copy the field.tpl.php from a field module and modify it. Look at comments above the field.tpl.php:

1. $items: An array of field values. Use render() to output them.
2. ...
3. $element\['#object'\]
4. $element\['#field\_name'\]
5. you can get user info from global $user object;

i think these are key variables which you can use. E.g. (poorly modified version of field.tpl.php. But logic is like this):

```
<?php
  global $user;
?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>

      <?php
        if($element['#field_name'] == 'field_NAME') {
          if($item == 'MY_VALUE (e.g. free)') {
            $output = render($item);
          }
          elseif($item != 'MY_VALUE (e.g. free)' && isset($user->roles[MY_ROLE_KEY]) {
            $output = render($item);
          }
          else {
            $output = ''; // or whatever you want
          }
        }
      else {
        $output = render($item);
      }
      ?>

      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print $output; ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

//P.S. Putting your logic into .tpl is not good..

---
Tags: entities
---


# Question
Title: How to apply an image style based on a condition (a date for ex.)?
I'm looking for a way to apply a grayscale image style to a content type image field when certain conditions are met. A date is reached (date field) for example

Can the rules modules do this ?

Thanks for the suggestions & ideas

# Answer
Yes you can do it with rules module with the help of **Field formatter conditions** module

> Adds conditions to field formatters. Configuration happens on the "Manage Display" screens of every entity type on a per field basis when clicking on the cogwheel on the right.

Supports

* Rules
* Field API fields
* Display Suite fields (only branch 2)

Simple conditions and actions

* Hide source field when target field is empty.
* Hide source field when target field is not empty.
* Hide source field when current user has specific roles.
* Hide source field on specific pages.
* Hide source field when target field contains a specific string.
* Hide source field when target field doesn't contain a specific string.
* Hide link field if title is empty.
* Hide date field if from/to has expired.

Rules actions

* Hide a field.
* Change image style.

Rules should always be a 'A field is rendered' event before they can be selected in the conditions dropdown on the "Manage Display" screens per field.
> 1 votes

# Answer
Hope this will help you,

In Drupal 7 you can achieve it by creating a template file. Based on the your certain condition you can change the image style with **Desaturate Effect**.

Steps

* If you don't have the template file for a particular content type then, just create new template file inside your **active theme** `sites/all/themes/ACTIVE_THEME_NAME/templates/`. Just copy and paste **node.tpl.php** and rename it to **node--your\_CONTENT\_TYPE\_MACHINE\_NAME.tpl.php**.

+ For example to create an template file for an **ARTICLE CONTENT TYPE** rename to **node--article.tpl.php**.
* Now get the image field by printing the $node object. User **drupal\_set\_message()** to print the object with in PHP tags. You can print it after the **variables listing**

```
<?php
 drupal_set_message("<pre>" . print_r($node, 1) . "</pre>");
?>

```
* Add the grayscale image style using `admin/config/media/image-styles/add` with **Desaturate Effect**.
* After printing get the image field name

+ For this example Im using the field **field\_image**.
* Based on your certain conditions change the image style and render the image using **theme()**
* Now its time to render the image.

Note

* In the custom template file you can go through the **available variables** at the top of the file. And you can use the variable as per your requirement.
* Variable **$content** will have an array of node items.
* `print render($content);` will print all the node items. You can use `hide($content['field_name'])` to hide the specific field.
* You can also use `$node` object to add fields as per your requirement.
> 0 votes

# Answer
If a date is reached, then you want to change the image in to graycale, there is no need to use rules. Create two image presets using ImageCache Actions. Then print your image field in your node tpl according to your conditions:

```
<?php
  print theme('image_style', array('path' => $node->field_image['und'][0]['uri'], 'style_name' => [STYLE NAME]));
?>

```
> 0 votes

---
Tags: rules, database
---


# Question
Title: Create relation between two select list for Hierarchical select option
In a content type, I want to have two select fields eg:

**Select list 1** contains the Mobile phone brands names

```
Nokia
Samsung
HTC
Apple

```

**Select list 2** contains the phone type like:

```
Lumia 520
Lumia 620
Galaxy S3
Galaxy S4
Hero
One
iPhone 4
iPhone 5

```

While adding new content, I want to make a Hierarchical select in this case, When a user selects **Nokia** from ***Select 1***, then only Nokia phones are available for selection in ***Select 2*** like:

```
Lumia 520
Lumia 620

```

But if nothing is selected in Select 1, then Select 2 doesn't show any options but still visible.

So far I tried Hierarchical select Module, but works only when I put the taxonomy term in hierarchical form instead of lists like:

```
Nokia
    Lumia 520
    Lumia 620

Samsung
    Galaxy S3
    Galaxy S4

HTC
    Hero
    One

Apple
    iPhone 4
    iPhone 5

```

and it only stores one value in the database (the phone Name). I want to be able to store both Brand and Phone name in Database as fields, so, I could display both fields using Views and also have exposed filter to filter through this.

Any suggestions how should I approach ?

# Answer
Is the Conditional Fields module of any help to you? Here is a quote about it (from the module's project page):

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
> 1 votes

# Answer
Hope this will help you

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

//put your form id
if ($form_id == 'two_state_node_form')  {

    $options_first = dynamic_add_options();

   $value_dropdown_first = isset($form_state['triggering_element']['#value']) ? $form_state['triggering_element']['#value'] : key($options_first);

    $form['#validated'] = TRUE;
    //put your first field name
    $form['field_select_list_1']['und']['#options'] = $options_first;
    $form['field_select_list_1']['und']['#default_value'] = $value_dropdown_first;
    $form['field_select_list_1']['und']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'dynamic_ajax_callback',
    'wrapper' => 'dropdown_second_replace',
 );
    //put your secon field name
  $form['field_select_list_2']['und']['#prefix'] = '<div id="dropdown_second_replace">';
  $form['field_select_list_2']['und']['#suffix'] = '</div>';
  $form['field_select_list_2']['und']['#options'] = dynamic_second_dropdown_options($value_dropdown_first);
  $form['field_select_list_2']['und']['#default_value'] = isset($form_state['values']['field_select_list_2']) ? $form_state['values']['field_select_list_2'] : '';
 }
}

function dynamic_ajax_callback($form, $form_state) {

    return $form['field_select_list_2'];
}

function dynamic_add_options() {
  return array(
        'None' => 'None',
        'Nokia' => 'Nokia',
        'Samsung' => 'Samsung',
        'HTC' => 'HTC',
        'Apple' => 'Apple'
    );
   return $options;
}

function dynamic_second_dropdown_options($key = '') {
    $options = array(
        'None' => array(
            'None' => 'none',
             ),
        'Nokia' => array(
            'Lumia 520' => 'Lumia 520',
            'Lumia 620' => 'Lumia 620'
        ),
        'Samsung' => array(
            'Galaxy S3' => 'Galaxy S3',
            'Galaxy S4' => 'Galaxy S4'
        ),
        'HTC' => array(
            'Hero' => 'Hero',//trancate the code
            'One' => 'One'
        ),
        'Apple' => array(
            'iPhone 4' => 'iPhone 4',
            'iPhone 5' => 'iPhone 5'
        ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

```

this is demo for you demo
> 2 votes

# Answer
I would use a hierarchical taxonomy and use hierarchical\_select. It only stores one value in the database, but you can still create a view that filters on brand by using a parent term filter.
> 0 votes

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


title: Commerce get product id's from order

text:
# Question
Title: Commerce get product id's from order
My question is simple: How do I get the product id's from a commerce order with Drupal code? I have something like this at the moment:

```
  $orders = commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE);
  foreach($orders as $order) {
    foreach ($order->commerce_line_items['und'] as $line) {
        $line_id = $line['line_item_id'];
        // ... product id, where are you?
    }

```

Hopefully somebody is able to answer this question :)

# Answer
> 9 votes
I can't remember the exact structure of the commerce product reference field, but you need to do something like this.

Warning this code style won't work on many orders as the internal cache for the line item entities will use too much memory. This will be a problem if you have thousands of orders.

```
$orders = commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE);
foreach($orders as $order) {
  foreach ($order->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    $product_id = $line_item->commerce_product['und']...
  }
}

```

# Answer
> 22 votes
Using the entity metadata wrapper, you could also do:

```
foreach (commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE) as $order) {
  $product_ids = array();
  foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      $product_ids[] = $line_item_wrapper->commerce_product->raw();
    }
  }
}

```

The important part here is checking the type of the line item, so you don't end up including shipping line items or other types of line items in your list of product IDs. Additionally, with the wrapper notice that I used the "raw" value of the commerce\_product field on the line item. This is because the "value" would be the fully loaded referenced product, while the "raw" value is simply the product ID.

# Answer
> 3 votes
If you don't need to load whole objects (line items, order and commerce products) You could run query like this:

```
 $args = array(
    ':order_id' => $order_id,

);
$product_ids = db_query("SELECT p.commerce_product_product_id
   FROM {commerce_line_item} li
   JOIN {field_data_commerce_product} p ON (p.entity_id = li.line_item_id)
   WHERE li.order_id = :order_id AND li.type = 'product'", $args)->fetchCol();
return $product_ids;

```

---
Tags: commerce
---


title: "Keep me informed" module

text:
# Question
Title: "Keep me informed" module
It is good practice when starting a new web project to begin with an alpha version. I like to add a "Keep me informed" e-mail field for the visitors. I may use the contact module and vary, but maybe there is such a module ?

I will need only field e-mail, a checkbox to accept conditions and a first confirmation mail.

# Answer
> 1 votes
The way I would do this is with a *Notification* module. There is a page at Drupal.org that lists the notification modules that exist. You may want to look at that page to find a module that suits you.

One particular module I would like to suggest (since I maintain it :-) is the one named Notify.

> The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily news letters sent by some websites.

You can set it up so that users become automatically subscribed to notifications when they register at the site. You may notify about all new content or only specific content types. I.e. you can create a special content type named "Site updates" and use that to post site updates about your alpha site. Then, all your subscribed users will receive an e-mail update update whenever you post new content of the type "Site updates".

---
Tags: 7, emails
---


# Question
Title: How to create sticky Social Media Tabs to the right of the website?
How to create sticky Social Media Tabs to the right of the website?

See the below screenshot for how it stick at the right:

>

Is there any Drupal module or plugin available?

# Answer
> 1 votes
Try Social media module, it will display as block and then assign it to the proper region and AFAIK no module exist as such, you need to customize through CSS.

> The social media module helps integrate your website with social media sites such as Twitter, Facebook and Google+. It provides an centralized way of managing social media profile information and plug-in widgets such as follow and share buttons.

if you are looking to share the posts then Share Bar is the right choice for you.

> The Drupal Sharebar module lets you easily add a "floating" social media submission bar on your website (like that found on Mashable) that includes share buttons for the most popular social media websites online such as Facebook, Twitter, and Google +1 Buttons.

---
Tags: 7, javascript, theming
---


# Question
Title: How to access Vertical Tabs from Contrib Modules in Panels?
Drupal node forms have a vertical tabs area, which provides options such as "Revision Information", "Authoring Information", "Publishing Options" etc. Contrib modules such as Node Hierarchy and XML sitemap can add custom tabs to this area.

How do you access these tabs from contrib modules in Panels.

In the past, with Drupal 7 & Panels, you could access them via the "Form" section of "Panels \> Add Content". However, I am creating a new Drupal 7 site and I can no longer access Vertical Tabs from Contrib modules. Only the tabs from Code Drupal modules are shown.

Steps I have tried to overcome the problem:

1) I have made a fresh install with just Panels and Node Hierarchy. I have made a second fresh install with just Panels and Xml Sitemap. In both cases, Vertical Tabs from Contrib modules are not accessible.

2) I have tried installing Node Vertical Tab Elements. It too only gives access to core tabs (and not tabs added by Contrib modules).

3) I have tried upgrading my older Drupal 7 sites to the latest versions of Drupal 7. In these older sites, the Vertical Tabs from Contrib modules are still accessible, so I am not sure if this means a special setting is required to access the tabs. I have disabled all custom themes and modules on the site, so I know the tabs are not coming from custom code.

Any help would be most appreciated.

# Answer
I have figured this out. It is Ctools 7.13 that breaks it (Ctools 7.12 works fine). I have raised an issue here: https://drupal.org/node/2147191
> 0 votes

# Answer
Sounds like this should work.

In your 1) scenario, where you restricted your installation to the minimum amount of modules -- you might have run into a change/bug with a module version which you intentionaly have upgraded. Try not to test with "most recent versions".

Because you phrased your experience as "in the past you could ...".
> 0 votes

---
Tags: panels, forms
---


# Question
Title: I would like to display only the teaser view of nodes
I hope someone can help me. Here's my issue:

I'd like to create a content type - let's call it News Story.

Amongst its other attributes, this content type will have a taxonomy field.

I would like to be able to create a number of views around my site to display a subset of the News Story content, based on its taxonomy value.

However, I do not want the News Story to generate a standalone node/page - I only want the news stories to appear in views of news stories.

Have you done this before? How did you do it?

I'd be really grateful for your help.

Thanks

# Answer
> 0 votes
One solution would be to use the Rules module. Add a new rule and set this:

Condition:

* Node is of type: News Story
* Custom PHP: check display\_id == full
* User rôle: not admin/editor (so you can still view/edit if you're not anonymous)

Action:

* Redirect to the page you want (404 or your news list for example)

# Answer
> 0 votes
In fact in the end I used the Rabbit Hole module:

https://drupal.org/project/rabbit\_hole

...as suggested by Alex. It pretty much exactly met my use case.

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

@todo description of how I used it.

---
Tags: views, nodes, entities
---


title: Use Views for Search

text:
# Question
Title: Use Views for Search
You can use Views for search results by using "Search Keywords" as a Contextual Filter.

This works fine when you search using a single word. But when entering multiple words with spaces, you don't get the correct results (usually no results).

Any idea how to solve this huge problem?

# Answer
I was looking for an answer for hours... I thought I made a mistake, but it seems there is a bug in the Views module! I guess I'm not the only one with this problem, so I'd like to share the sollution I finally found.

Make a custom module and add these lines of code:

```
function mymodulename_views_query_alter(&$view, &$query) {
  // Fix bug where multiple terms in search index filter returns no results
  if (isset($query->relationships['search_total'])
      && !empty($query->fields['score'])
      && empty($query->fields['score']['table'])) {
    $query->fields['score']['table'] = 'search_total';
  }
}

```

The sollution was found here: https://drupal.org/node/1948510
> 2 votes

---
Tags: 7, views, search
---


# Question
Title: Generate Install Scripts from current Nodes, Views, Fields in Drupal
I have theme with custom content types, views, etc. and i would like to package into a custom module so it can be easy installed in another Drupal instance via MODULE\_install().

Currently, Module\_install() looks something like this:

```
function MODULE_install(){
    $t = get_t();
    foreach (_jobs_installed_fields() as $field) {
        field_create_field($field);
        drupal_set_message($t('Field type: '.$field['field_name'] . ' created'));
    }

    foreach (_jobs_installed_field_instances() as $field) {
        field_create_instance($field);
        drupal_set_message($t('Field instance: '.$field['label'].' initiated and added to User Profile'));
    }

    drupal_set_message($t('Finished adding fields to User profile'));
}

function _jobs_installed_fields() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}

function _jobs_installed_field_instances() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}

```

The content of \_jobs\_installed\_field\_instances and \_jobs\_installed\_fields functions is generated via PHP Execute Script Dev module block from the current instance content and then copy/paste in the install script.

```
$entity_type = 'user';
$field_name = 'field_name';
$bundle_name = 'user';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">" . $output . '</textarea>')

```

This can be lot of work for larger Themes and i cannot rerun it later once the change is introduced. I was thinking creating some Php scripts that would generate me the install script from the current nodes, views, etc so i can rerun as like in future. Is there anything like this already available? What would be your approach to this problem? Thank you

# Answer
Looks like Features module is what you really want:

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

With addition of UUID Features Integration:

> The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. *What's that you say? You thought features was only for configuration?* This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.

Of course you will probably only use a subset of it's capabilities, but it should cover all your needs with content types, nodes, and views definitions.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How can I programatically select the node template to render a node in Drupal 7
I have a node--mynodetype.tpl.php, the problem that I have is that I have a module to show public contents.

In this module I need to render something completely different to what is in node--mynodetype.tpl.php.

So I was thinking to create a file named, for example, node--mynodetype-public.tpl.php but I was googling and I can't find a function to select one node template or other node tpl.

Is this any function to select wich node template to render?

Thanks in advance.

# Answer
Unless I am missing something here, this is a classic job for `hook_preprocess_node()`, eg...

```
function YOURMODULEORTHEME_preprocess_node(&variables) {

  if ( /* whatever logic */ ) {
    $variables['theme_hook_suggestions'][] = 'node__YOURNODETYPE_public';
  }

  // other preprocessing here

}

```

...which would cause Drupal to look for a `node--YOURNODETYPE-public.tpl.php` template when whatever logic was true.

Read Working with Template Suggestions and Theme Suggestions for a lot more info on all of this.
> 2 votes

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


# Question
Title: How to create a automatic Field value number to display in the lable for an custom content type: Itinerary e.g Day 1, Day 2
I have a content type which I've called Itineraries which lists activities users will do on certain days of the package. I've created a 'day' field which the admin will populate with each day's activities, the value is set to unlimited as some packages have 7 days and others 21 days - how do I get the label of each field to automatically set to the number of values sumbitted by the admin ?

So if the admin enters 3 values it should display the label for each submission as - Day 1 : fishing, running ... Day 2: camping Day 3: drive home

I've looked at the Computed field but lack the php knowledge to implement.

Is there another way of implementing the above ? Thanks for the help in advance.

# Answer
Using computed field you could do this.

1. Install computed\_field module
2. add a field into the content type you want to count the field for, and then in the display code box add this (field\_slect is the field you want to count)

$display\_output = sizeof(field\_get\_items($entity\_type, $entity, 'field\_select'));
> 0 votes

---
Tags: entities
---


title: How to show basic page without summary?

text:
# Question
Title: How to show basic page without summary?
So I've got a basic page 'home' I want to use as my homepage. But when I make one and publish it to front page, I only see a summary, like it's an article. And if I don't publish it to front page, it's just not there, even with homepage link setup.

So basically I want text on my front page without the "read more" button, just the full text.

# Answer
> 0 votes
Go to Configuration \> Site Information. Under the Front Page section, change FRONT PAGE to include your node information - meaning set the path you want to show as front page and then click save. see the below screenshot.

If you made the above settings then it will show the new front page **without summary**.

---
Tags: nodes
---


# Question
Title: Glossary view: Show all results separated by letter
I have a glossary view set up. When I go to example.com/glossary/all, all of my results are shown, but I'd like them to be separated by letter. The layout I'm looking for is exactly like this...

https://drupal.org/glossary

For example..

**A**

* Amy
* Angie
* Annie
* Amanda

**B**

* Billy
* Bob
* Ben

**C**

* Catwoman
* Cathy
* Crystal
* Caitlyn

Is there a way I accomplish that with Views?

# Answer
> 0 votes
Check out the Glossary module.

> The glossary module scans posts for glossary terms (including synonyms). The glossary indicator is inserted after every found term, or the term itself is turned into an indicator depending on the site settings. By hovering over the indicator, users may learn the definition of that term. Clicking the indicator leads the user to that term presented within the whole glossary or directly to the detailed description of the term, if available.

or

Lexicon

> A lexicon is a stock of terms used in a particular profession, subject or style; a vocabulary. The Lexicon module generates one or more Lexicon pages based on terms in taxonomies and optionally marks terms in the content and links them to the appropriate Lexicon page.

or

take a look at G2 Glossary module.

---
Tags: views
---


# Question
Title: Features/Themes and Drush Make Files: How to manage updates?
I am trying to automate my development by using Drush Make Files and Features.

I am using Drush Make.me to create the make file.

I have created a Features module on my local machine. What's the best way of telling DrushMake.me about this module.

I guess I could upload it to my webspace and then put the URL into Drush Make. However, I am not sure if this is the best way of doing it. For example, what happens if I update the feature in the future. How will existing website that contain the old feature know that it has been updated.

Also I have my own custom Theme which I want to include in the makefile. If I just Zip and upload it, I would have to do this everytime I update the theme which doesn't seem very efficient (plus how will existing sites know that the theme has been updated).

At this stage, I would like to keep my theme and features private as I want to work out all the kinks.

Any advice on how to managed everything would be most appreciated.

# Answer
You should build an installation profile to go with your make file. Then, you could store your theme inside the installation profile. There's a Drush command to make an installation profile; see this issue on drupal.org. If you use this technique, you can just run `drush pm-update` to update modules, and then re-build your makefile and installation profile using the Drush generate-profile command.

Another option would be to just store your custom theme in a git repository. You can load a module or theme from a Git repository. See this answer for details on how to do that.
> 2 votes

---
Tags: features, drush
---


title: assign permissions to a created role?

text:
# Question
Title: assign permissions to a created role?
i want to assign permissions to a role in my `hook_install()` , but the permissions that i'm adding are part of my modules `hook_permission`() don't exist yet? so how to grant permissions role created in `hook_install` after `hook_permission` ?

NB :

* i have D7.23 \-
* my module create the role and his permissions .

Thanks.

# Answer
> 0 votes
the solution found in http://www.dibe.gr/blog/drupal-7-create-users-and-roles-programmatically in the author comment , so i'm set only the permissions array of my custom module in `hook_install()` `user_role_grant_permissions($role_rid,array_keys(module_invoke('my_module', 'permission')));`

---
Tags: 7, users
---


# Question
Title: Exposed Filters View is not functional with Anonymous Users
I created a Filtering Search with Multiple Exposed Filters. It all has been working fine except one thing; when I logout as an admin and use the site as an anonymous user, exposed filters don't work.

The screenshot of my exposed filters form is below:-

In a functional scenario, When I click on any value, let's say EMEA, the form auto-sumbits and show hierarchical values in all the below filters and show the data on the right side.

As an example, When I click `EMEA`, the form auto-submits, and all the `offices` from `EMEA` appear in the lower filter of `Filter by Office` and results are shown.

The problem is that all the filters, data and values are shown for anonymous users but not auto-submitting takes place. It seems it just refreshes the page when I click on any filter.

Any idea?

Best.

## P.S

I used two modules within it:-

1. Better Exposed Filters (for making filters more readable)
2. Views Hacks (to use Views Selective Exposed Filters for showing hierarchy within Filters)

# Answer
> 0 votes
I got it.

I had LDAP module enabled and that was de-authorizing the access. Had to deactivate it.

Thanks a lot guys.

---
Tags: views
---


# Question
Title: Allow user to choose role immediately after registration
I have 2 roles (driver, owner) with very different permissions on my site. I want to allow Facebook Connect during registration, so I am resigned to a 2-step registration process:

1. Register as a basic user via Facebook Connect or standard Drupal registration.
2. Basic user selects the appropriate role.

I will auto-assign the role "basic" upon registration and present a block to all users of the basic role which asks them to select Driver or Owner as their account type. Upon clicking the appropriate link, their user account will be updated with the new role. I can use Rules to remove the "basic" role whenever an account has been saved with one of the other roles.

**How can I assign a role using a link displayed in a block?**

Thank you.

# Answer
I solved this by using the Rules module and 2 basic pages. Not a very scalable solution, but works in this limited application.

1. User registers using Facebook Connect or the core Drupal registration process.
2. The new user with the "basic" role is redirected (via Rules) to a "select your role" page with links to a "Welcome new driver" page and a "Welcome new owner" page.
3. Upon viewing the node, "Welcome new driver/owner", with the role "basic" a rule is triggered which sets the desired new role, removes the "basic" role and triggers role-specific welcome email.
> 2 votes

# Answer
I don't know this will help you or not:

1. Create two pages.
2. 1-page callback will be a registration form. This can be a facebook reg: Link to discussion or Drupal reg. form. Then redirect the registered user to second page.
3. 2-page, simple form which requires user to choose a role. You can get an info here: user\_roles()
4. On second form submission, you can update user account information with user\_save() an redirect him anywhere you want...

Notice, that I did not mention how will be handled the user role control. Because a user can simply skip the second page. You can store some kind of flag in $\_SESSION or even better in database table which verifies that user actually chose a role or not. If not then redirect him back to second page.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Cloning content types and corresponding Display Suite settings
I need to clone a content type, so I choose to do that with module: Bundle copy.

I need to clone Display Suite settings of my bundle as well. How would I clone that? (Found a patch that enables that with Bundle copy: https://drupal.org/node/2055157). Wondering is there any better solution?

# Answer
Nevermind, found a solution:

1. Bundle copy version 7.x-2.x-dev allows cloning directly (without exporting/importing and changing bundle's machine name).
2. There is a patch that gives support for display suite cloning, exporting and importing. (I had to fix the patch first to be able to apply it with patch manager.)

All worked like a charm!
> 2 votes

---
Tags: nodes, display-suite
---


# Question
Title: Write the value of a field as a css class to another field
Could someone point me in the right direction to write the value of a field A to the css classes array of field B?

In my case I'm using a field collection (with text and file/image field, to make a sort of paragraph) and want to make a select field (with 4 preset options) so the node creator can choose if they want the file/image field displayed top, left, or right.

I don't really want to mess around with dynamic views or special formatters, just write the value of my select list to the class of the file/image field wrapper.

# Answer
Here is some sample code to help you further which adds a class on a field (`field_image`) based on the value of another field (List field of type `text`) (`field_alignment`).

You will need to implement 2 preprocess hooks:

1. On node `preprocess` to retrieve the objects / values of the fields and add extra datamember which contains the class value
2. On field `preprocess` to retrieve the previously added extra datamember and merge it with the default `classes_array` part of a field

```
function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_image']) || !isset($variables['field_alignment'])) {
        return false; // if 1 of both fields is not available, don't do anything
    }

    $alignment = reset($variables['field_alignment']); // retrieve first item of array
    $variables['content']['field_image']['#extra_classes'] = array($alignment['value']); // add an extra datamember containing an array with the value of the other field
}

function YOURTHEME_preprocess_field(&$variables)
{
    $field = $variables['element'];
    if ($field['#field_name'] !== 'field_image') {
        return false; // only manipulate the image field
    }

    if (!isset($field['#extra_classes'])) {
        return false; // don't do anything if the array with extra classes is not available
    }

    $variables['classes_array'] = array_merge(
        $variables['classes_array'], $field['#extra_classes']); // merge the default field classes with the new added class
}

```

**Update - When assigning class to field\_image which sits within a field collection (named field\_collection)**

```
function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_collection']) || !isset($variables['field_classes'])) {
        return false;
    }

    if (!isset($variables['content']['field_collection'])) {
        return false;
    }

    $alignment = reset($variables['field_classes']);
    foreach (element_children($variables['content']['field_collection']) as $index) {
         foreach ($variables['content']['field_collection'][$index]['entity']['field_collection_item'] as &$field_collection_item) {
              if (!isset($field_collection_item['field_image'])) {
                  continue;
              }

              $field_collection_item['field_image']['#extra_classes'] = array($alignment['value']);
         }
    }
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: Deleted nodes appears in Views VBO list with their pathauto links
Deleted nodes appears in Views VBO lists with their pathauto links.

I have custom VBO view which I use to delete filtered nodes. After processing I get this message i.e. 'Skipped Delete node on node id 251'. It's probably because the node doesn't exist, but in the views list it's still listed and has its original title and path to it and when clicked it gives page not found.

# Answer
> 0 votes
Deleted directly from database.

---
Tags: 6, nodes, views
---


# Question
Title: Adding Information to Maintenance mode message
I'm trying to setup my maintenance mode message so that it will display a twitter feed and a facebook like box to my sites facebook page. I want to do this so I have a place to send information to the people who need it or want to keep up to date while I do something that could have the site in maintenance for an extended period of time. I'm just wondering how I would set that up and if it's possible in the default maintenance mode settings of if I have to do something else, like a separate page or module.

# Answer
> 0 votes
If you just wanted to add some text I'd say go into the admin settings of /admin/config/development/maintenance and update the text but if you want to add dynamic code like a facebook Iframe like button you're probably better off adding the code to a custom maintenance-page.tpl.php in your theme. Grab the code from Facebook and twitter and paste.

Just add it below the line that reads

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

```

Drupal api reference - https://api.drupal.org/api/drupal/modules!system!maintenance-page.tpl.php/7

---
Tags: maintenance-mode
---


# Question
Title: why does internationalization menu i18n_menu translate but never localizes?
I have a menu set to :

Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.

And I have include menu items that are "language neutral" and provided translations for said items.

Nothing but the original 'language neutral' language ever shows regardless of what the users profile language is set to (user's profile language is the primary way I have translation determining what language to use)

What do I have to do to get the Menu items to localize to the current users current profile language ?

# Answer
> 1 votes
As said in the 2nd choice Translate and Localize, there are two different ways for translating menus.

If you want to use the **Menu items with language will allow translations** option, set a link in each of your defined languages, but none in language neutral, and check in *admin/structure/menu/manage/main-menu* then in \*admin/structure/menu/item/\[ITEM\_ID\]/edit\* for each set of translation, that it is correctly translated.

Now if you wish to work with the **Menu items without language will be localized** option, make sure you create the menu item in the site default language (because localization always happens from the site's default language to other languages). And choose *language neutral* for the menu item when created.

Now in the opened up Translate tab, you'll translate the menu item title and description instead of creating another menu item. And you're done !

For a complete explanation read this nice tutorial about Drupal multilingual navigation.

---
Tags: routes, i18n-l10n
---


# Question
Title: How to add_js per content type in my module?
I'm looking for a way for my module to evaluate the content type in a preprocess hook and conditionally add some javascript.

*Theme*\_preprocess\_page() makes the content type accessible plus some other useful things (I could differentiate between nodes & views & such), but I can't use it because it is likely to have already been declared by the theme.

\*My\_module\*\_preprocess\_page() doesn't appear to provide the content type anywhere.

What is a good option here?

# Answer
> 4 votes
Here's how to add content type specific javascript to a node using `hook_node_view` and `#attached`

```
/**
 * Implements hook_node_view().
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {

  // Add content type specific JS on full page node view
  if($view_mode == 'full'){
    switch($node->type){
      case 'article':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/article.js');
      break;
      case 'page':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/page.js');
      break;
    }
  }

}

```

---
Tags: 7, javascript
---


# Question
Title: Panels variant selection rules using query string in the URL
I need a variant in Panels' selection rule of "String: URL path" to be related to the the query string of the URL:

```
Variant 1 - String: URL path = mypath/page?querystring=1

Variant 2 - String: URL path = mypath/page?querystring=2

```

Surprisingly I can't find a solution for this!

# Answer
> 1 votes
You can accomplish using query strings in panels if you use php code for your selection criteria.

Something along the lines of

```
$url_comp = explode('/', request_uri());
$desired = $url_comp[2];
check_plain($desired);
if ($desired == "page?querystring=1") {
return true;
}

```

will provide you with the access check on whether or not to show the panel variant. Check\_plain may be called incorrectly in the code above but including some sort of check to make sure your querystring is clean would be very advantageous to prevent any sort of security issue.

You may need to adjust the position of your desired path above. url\_comp\[0\] will return empty, url\_comp\[1\] from your example above would return mypath and url\_comp\[2\] would be page?querystring=1

I came up with the idea for this approach from the comments on https://api.drupal.org/comment/18449#comment-18449

---
Tags: panels
---


# Question
Title: Where and how are escape quotes stripped when saving a taxonomy terms which include comas or quotes?
in taxonomy\_autocomplete: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.pages.inc/function/taxonomy\_autocomplete/6 we have the following code:

```
   // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $tag->name) . '"';
      }

```

Imagine we have the taxonomy term which is exactly the following string:

```
George "madcow" Stewart

```

THe above code would cause the taxonomy autocomplete to display:

```
"George ""madcow"" Stewart"

```

I have re-implemented the taxonomy\_autocomplete in order to work with a single term (no comma separated list of terms allowed). The problem now is that when we want to enter `George "madcow" Stewart`, a new term `"George ""madcow"" Stewart"` is created, including all the extra quotes!

I cannot find where and how in core the escape quotes are stripped before insertion to the database…

# Answer
Oh! I just found it:

The function taxonomy\_node\_save(&$node, $terms) calls drupal\_explode\_tags()

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_explode\_tags/6

which has:

```
// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));

```
> 1 votes

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


# Question
Title: How to alter image captcha title in drupal 7
I am working on drupal 7 image captcha module.I want to alter or hide image captcha title like 'What is in your code'.How can I do it by without hacking the module?

# Answer
use hook\_form\_FORM\_ID\_alter() and Form API pre\_render function. E.g:

```
// Explains pre_render. This is when you create a form;
function feedbackForm($form, &$form_state) {

  $form['#pre_render'][] = 'feedbackForm_pre_render';

  $form['name'] = array(
    '#title' => t('Ваше имя'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

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

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Отправить'),
  );

  return $form;
}

function feedbackForm_pre_render($element) {
  $element['captcha']['captcha_widgets']['captcha_response']['#title'] = t('Защитный код');
  return $element;
}

```

You can also use hook\_form\_alter() function:

```
function MY_MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);

  if($form_id == 'FORM_ID') {
    $form['#pre_render'][] = 'feedbackForm_pre_render';
  }
}

```
> 4 votes

---
Tags: 7
---


# Question
Title: How to embed "Exposed form in block" into top bar? Using foundation theme
I have a product search view. I use the "exposed form in block" in order to have only the filters show on all pages and the results show on a separate page. I want to put my filters in the top bar. How would I embed the "exposed form in block"? I know how to embed a view but I cant figure how to embed the "exposed form in block." in the top bar (the nav). The biggest reason is because its not a region. So I cannot place the block in it from the structure\>blocks. Ive tried moving my header region to be on top of the nav but this create issues also. I was thinking that maybe there is a way to print the "exposed form in block" in the page.tpl.php... is this possible? Or will I have to use a hook in the template.php? Or Can I redefine the nav bar as a region possibly?

# Answer
1. Views UI -\> create a page view
2. Set 'Exposed form in block' -\> Yes
3. Go to Structure -\> Blocks
4. Find the exposed filter block which you recently created and configure the Region and Visibility settings

EDIT: to specify a new region modify .info file and page.tpl.php file of you page: e.g. MY\_THEME.info:

```
....
regions[top_bar] = TOP BAR
...

```

page.tpl.php:

```
...
    <?php if($page['top_bar']): ?>
    <div class="header_top_bar">
      <?php print render($page['top_bar']); ?>
    </div>
    <?php endif; ?>
  ...

```

Documentation

or if you want to insert a block into template file here is an issue.
> 0 votes

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


# Question
Title: Add a field to multiple content types at once?
I want to add a field to multiple content types at once, and configure it for all of them at once as well.

Reason being is that I have many content types, all of which need to be updated by adding this new field to each. This field will be configured the same for all of the content types as well. I have to repeat this process of adding and then configuring the field every content type I want to add it to, and it gets arduous after a while.

Is there any way to do a mass add/configure of a new field to many content types?

# Answer
> 9 votes
Broad lines using the Features module could be:

1. Add the field to two (to see the pattern) content types by hand
2. Create a Feature including field bases and field instances for the newly created fields
3. Edit the created module multiplying the field bases and instances to all content types needed
4. Enable the edited module

# Answer
> 5 votes
Use the Field Tools module:

A collection of useful UI tools for working with fields:

```
Overview of fields with links to edit single instances, and all instances at once
Clone any field instance to multiple entities and bundles
Clone all field instance of a bundle to multiple entities and bundles
Import and export fields
Delete multiple instances of a field
Apply a vocabulary to multiple entities and bundles at once (the same way vocabularies were applied to content types on Drupal 6)
... your idea here. Patches welcome!

```

# Answer
> 3 votes
If you don't mind writing a custom module for this, it's relatively easy to add a field to a content type via code:
`$instance = array(
'field_name' => 'field_firstname',
'label' => 'First name',
'entity_type' => 'node',
'bundle' => 'person',
);
field_create_instance($instance);`

The above code will add the field "field\_firstname" to the content type with machine name "person". So you could create a module that a form that allows you to select a field and a number of content type and upon submission the field is added to all selected content types.

# Answer
> 1 votes
The few times that I've had to do this I've used Field Collection.

> Provides a field-collection field, to which any number of fields can be attached.

It's still pretty arduous though, as you have to add the field collection field to every content type. That said, if you're adding 5 or 6 fields to multiple content types, you only have to configure the initial 5 or 6 fields once in the field collection.

Following that, you create the field collection field (for arguments sake let's call it `field_collection_field`) on one of your content types, and then re-use the same field on all the others.

As I said, you still have to configure one field on x amount of content types..but it's better than creating 10 fields on 10 content types (for example).

# Answer
> 1 votes
If you're comfortable manipulating the database directly, field instances are stored in the {field\_config\_instance} table. You can add/configure your field for one content type, then find the record in the database table and duplicate it.

You'll have to change two column values on the duplicated row:

* id: Should be a new integer unique to the table
* bundle: Should be the machine name of the new content type

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


# Question
Title: How Do I Replicate Computed Field Functionality In Drupal 8?
I have a question regarding Computed Values in Drupal 8. I currently use Computed Fields in Drupal 7 to perform mathematical operations on certain fields and save that calculation in another field. I am attempting to recreate this functionality in a Drupal 8 install.

I recently saw an article that said Computed Fields would be depreciated by the functionality of Drupal 8 core. However, it is not clear to me how to recreate this in Drupal 8. Could someone explain how I take one integer field and multiply it by a percentage to get a decimal number?

I would appreciate any help provided.

Thanks,

Chris

# Answer
There you are:

https://drupal.org/node/2112677

Basically you have to write a plugin and store your calculations in the getValue() function.
> 3 votes

---
Tags: entities
---


title: Facet Api and acive filters

text:
# Question
Title: Facet Api and acive filters
In my website, I'm using ApcheSolr with facet api and with some configuration I listed facets blocks and it works fine!

But now I want to create a block that list to me the active filter chosen by user

I read some facet api documentation but I'm lost !!

Can anyone help me!

Tanks in advance.

# Answer
> 1 votes
Enable Current Search submodule, you can also install Current Search Links

> Extension to the Facet API current search blocks module. Instead of just showing the current search it turns the current search keywords into links that you can drop from the search.

---
Tags: blocks, search
---


# Question
Title: Taxonomy Terms node count of different content type
Hi I have a issue for which I searched everywhere but not getting any solution,

I have two content types Store and Deals with the following fields Store is having the fields 1.Store-title 2.Logo 3.Categories--\> Added as a taxonomy term field. 4.Outlets When I am adding a node of type store I am selecting the corresponding category terms with it and saving.

Other content type Deal having the fields 1.Title 2.Store-title---\> This field is of content type Store and is added here as a node reference. 3.Outlets

When I am adding a node of type deal I am selecting a store here( In deals content type, store-title is added as a node-reference), and selecting its outlets.

Issue: I need a counter on the category terms, the counter should be based on number of deals added to that particular store node on respective categories.

Hope you understand the issue, I have seen the issue of same type where node counter is displayed but they show the count of nodes of the same content type where that taxonomy term is added like here http://www.brightwebsitedesign.com/how-to-use-views-aggregator-to-create-taxonomy-term-count-block, But I have a bit different, taxonomy is added to stores, but I need the count of deals( another content type) on the taxonomy term. If you still need more clarification please let me know.

This is very urgent Any help would be much appreciated!

# Answer
> 3 votes
You can achieve this with help of an additional relation. If you are following view creation from the post mentioned by you

After selecting ' Taxonomy term: Content with term ' add another relation and choose the node referenced field - reverse and choose Require this relationship. (in your case 2.Store-title---\> This field is of content type Store and is added here as a node reference)

Now you will get your count of deals

---
Tags: taxonomy-terms
---


title: Drush isn't bootstrapping drush script

text:
# Question
Title: Drush isn't bootstrapping drush script
I can't get drush to bootstrap my script. I'm using version 5.9.

Below is my test script (test.drush):

```
#!/usr/bin/env drush

$site = drush_sitealias_get_record('@site1');
_drush_sitealias_print_record($site);

$result=drush_invoke('core-status');
drush_print($result['output']);

while ($arg = drush_shift()) {
  drush_print($arg);
}

```

And I have the aliases defined in ~/.drush/aliases.drushrc.php (see end of post).

When I run `test.drush @site1` it doesn't bootstrap the script with site1. It has access to the alias because it can output the site record. Also it outputs @site1 as an argument. It should remove @site1 from the argument list and bootstrap it but it doesn't.

Below is the output:

```
$aliases['site1.local'] = array (
  'root' => '/Users/mark/Documents/drupal6',
  'uri' => 'http://site1.local',
  '#file' => '/Users/mark/.drush/aliases.drushrc.php',
);

 PHP configuration     :  /private/etc/php.ini
 Drush version         :  5.9
 Drush configuration   :
 Drush alias files     :  /Users/mark/.drush/aliases.drushrc.php

@site1

```

BTW running `drush @site1 status` on the command line works fine

Also, is there any way to change the current site in a script. When I use:

```
drush_invoke('use', '@site2')
$result=drush_invoke('core-status');
drush_print($result['output']);

```

it doesn't apply to the subsequent drush commands but it does the next time you run the script.

aliases.drushrc.php:

```
$aliases['site1'] = array(
  'root' => '/Users/mark/Documents/drupal6',
  'uri' => 'http://site1.local',
  'db-url' => 'mysql://user:password@127.0.0.1/site1'
);

$aliases['site2']=array(
  'root'=>'/Users/mark/Documents/drupal7',
  'uri'=>'http://site2.local',
  'db-url'=>'mysql://user:password@127.0.0.1/site2'
);

```

# Answer
> 1 votes
Drush shell scripts such as the one you show above do not automatically bootstrap to any argument passed to them. (**EDIT:** This is due to a bug.) You have a few options.

1: Force the bootstrap: `$site = drush_shift();
drush_bootstrap_max_to_sitealias($site);
drush_invoke('core-status');`

2: Do all of your work in a subshell: `$values = drush_invoke_process($site, 'core-status');`

Those two should get you started. Note that option number two will re-bootstrap Drupal in an isolated subshell every time you call drush\_invoke\_process. drush\_invoke always works on the currently-bootstrapped site, and you can only bootstrap once. Therefore, that `drush_invoke('use', ...)` trick won't work. 'use' is only for use in the shell, not in scripts.

There's another error above. This code isn't working as you expect it is:

```
$result=drush_invoke('core-status');
drush_print($result['output']);

```

What's really happening here is that drush\_invoke is printing the output of drush status to stdout, and drush\_print is printing nothing. You'll get $result\['output'\] if you use drush\_invoke\_process.

In my somewhat biased opinion, the Drush chapter of the Definitive Guide To Drupal 7 covers these topics pretty well. It is available for download as a free sample chapter at http://definitivedrupal.org/book/26-drush

# Answer
> 0 votes
The approach to force the bootstrap sounds great but doesn't work as proposed in the previous answer. But a little tweak makes it working pretty nicely:

```
$site = drush_sitealias_get_record(drush_shift());
drush_bootstrap_max_to_sitealias($site);

```

---
Tags: drush
---


title: The meaning of form_build_id

text:
# Question
Title: The meaning of form_build_id
Can you tell the meaning of form\_build\_id

I am trying to solve problem "add to cart form breaks after using Exposed filter with Ajax"

As I investigated, only form\_build\_id value changes when we are trying to search product catalog for certain products with Exposed Filters.

If I take initial form\_build\_id value for product's add to cart form, search catalog with Exposed Filter, than substitute via Firebug new form\_build\_id value with initial, and the form works

# Answer
> 6 votes
The form\_build\_id is used as key to cache a particular build of the form. For multi-step forms, this allows the user to go back to an earlier build, make changes, and re-submit.

See also : drupal\_build\_form, drupal\_rebuild\_form

---
Tags: views, commerce, ajax
---


title: Store Drupal files outside of the root

text:
# Question
Title: Store Drupal files outside of the root
My website is running on Windows and it sits on drive `C:/`, however I'd like to keep all my files on drive `D:/`. How can I do it? I know that I can move the whole site to drive `D:/` but I was wondering if it's achievable at all.

# Answer
> 7 votes
On linux, you could create a symlink to the other folder, or mount it over NFS etc..

On Windows you can actually create a symlink as well.

Something like this should work:

```
# Open a windows terminal and
mklink /J "C:\Webroot\Drupal\Mysite\sites\default\files" "D:\Data\Drupal\Mysite\"

```

That should create a hard link connecting the files folder across the two drives, with the data being stored on D:

More info:

---
Tags: files
---


# Question
Title: convert a cck field from integer to string (text)
How do I convert an existing integer field to text without having to copy paste manualy each value on each node and then delete the old integer field I´m using Drupal 7.9

I tried altering the database.. on the definition of the field and the value type I'm still getting errors

```
Notice: Undefined property: stdClass::$field_ubi_gps_x_format en field_sql_storage_field_storage_load() (línea 360 de /modules/field/modules/field_sql_storage/field_sql_storage.module).

Notice: Undefined variable: regexp en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module).
Warning: preg_replace() [function.preg-replace]: Empty regular expression en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module)

```

that is because the validation and presentation of the field has remained as integer.. I can't find in the DB where it stores that to copy if from another text field

I've so far altered field\_data\_field\_FIELDNAME\_THAT\_WAS\_INT changing field\_FIELDNAME\_value from int to varchar and paradores\_field\_config . copying the blob data field from a text to ID of the FIELDNAME and using text on type and module fields

# Answer
You would have to change the type in field data and field revision tables and add the FIELD\_NAME\_format column in both the tables. Change the type and module columns in field\_config to 'text'. And change the data column in field\_config and field\_config\_instance tables.

For more info on this you can visit this link.
> -1 votes

---
Tags: 7, entities, database
---


# Question
Title: How can I skip field validation if the field is hidden?
I get a node form with node\_form and then I render it with some modifications.

One of the modifications is that I duplicate the fields so I have the same fields twice. One field is disabled and the other same field is enabled, I also have a checkbox to show or hide the disabled/enabled field with `#states`. So I have only one field visible at time, for example, I have a disabled field visible, if I check the checkbox then disabled field is hidden and enabled field is shown.

The problem comes with the `#requried = TRUE` fields. When I submit the form it validates the two fields (enabled and disabled) but I only want to validate the visibile field. So, if it's visible the disabled field, I don't want to validate the enabled field.

What is a good way to achieve this?

# Answer
I've tacked a variation on this before and this was the only solution I found that didn't have problems of some sort.

The key is not to skip all validation as you may add security holes so you have to specifically skip required validation. - Specifically what I'm getting at here is don't use #limit\_validation\_errors.

You cannot stop drupal core from validating that required fields are not empty, so you have to make the fields not required when they get validated.

Note that this example will make all fields not required, so you'll have to add some logic to only do that for the fields you are interested in. I couldn't add this because I don't have enough info about your setup.

In your form add this:

```
  // Add an after build callback so we can modify the form before validation.
  $form['#after_build'][] = 'MYMODULE_form_after_build';

```

Then add that after build function and a helper function:

```
/**
 * Form after build callback.
 *
 * We are using this to modify the form after it has been submitted,
 * but before it has been validated.
 * This means we can remove required flags for certain fields.
 *
 * @param array $element
 *   An associative array containing the structure of a form element.
 *   In this case the form.
 * @param array $form_state
 *   The form state array.
 *
 * @return array
 *   An associative array containing the structure of a form element.
 */
function MYMODULE_form_after_build($element, &$form_state) {
  // Check that the form has been submitted.
  if ($form_state['process_input']) {
    // Deal with required fields.
    _MYMODULE_remove_required($element);
  }
  return $element;
}

/**
 * Make elements of a form not required.
 *
 * This example function will make all required fields not
 * required.
 * In your case you want to only do certain fields so you will have
 * to add logic in here to only affect some fields.
 * You could do this based on field name or some other flag you have
 * set, or whatever.
 *
 * @param array $elements
 *   An associative array containing the structure of a form.
 */
function _MYMODULE_remove_required(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      _MYMODULE_remove_required($elements[$key]);
    }
  }
  if (!empty($elements['#required'])) {
    $elements['#required'] = FALSE;
  }
}

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: Authcache: Getting user_link to work in template.php
**Problem**

I'm trying to set-up an Authcache customised menu.

The first way of doing it would be to create 3 menus, one for each of my roles and one for anon then create a custom tpl.php for each using the `user_link` and `user_name` variables.

(These variables are provided by the user example module in authcache to all templates.)

Block logic would then give the correct user the correct menu.

It seems a little clumsy.

Is it possible to grab the links inside template.php and use `user_link` and `user_name` variables there because I can't find a function which has the links available.

Or how has anyone else solved this problem?

# Answer
> 0 votes
In the context of a preprocess hook, yes:

```
function MYTHEME_preprocess_foo(&$vars) {
  $user_link = $vars['user_link'];
}

```

Outside of that context I guess you could invoke `authcache_usercookie_preprocess()` manually:

```
$vars = array('user' => $GLOBALS['user']);
authcache_usercookie_preprocess($vars, NULL);
$user_link = $vars['user_link'];

```

# Answer
> 1 votes
Ok so here is my solution.

Menu's are themed in `MYTHEME_preprocess_page`, the menu data is also still structured here unlike in `MYTHEME_preprocess_menu_tree`.

I enabled the memcached example module, this enables the variables `user_link` and `user_name` in the preprocess. Then I created a third variable `user_account` just copying from the other two and altered the cookie so it stores `uid` not `name`.

This is because I wanted the "My Account" link to link to "user/x/edit" and I didn't need the name.

I then added the following chunk to my page preprocess.

```
function MYTHEME_preprocess_page (&$vars) {
  $user_account = $vars['user_account'];
    if (array_key_exists('menu-xxxx', $vars['secondary_menu'])) {
      $vars['secondary_menu']['menu-xxxx']['href'] = $user_account;
    }

```

The secondary menu in this case is my user menu and My Account is always labelled menu-xxxx in the array. (xxxx will be numbers).

---
Tags: 7, routes
---


title: Flag a content with Scheduler

text:
# Question
Title: Flag a content with Scheduler
Flag a node using scheduler & Rule. But not getting the way how to achieve that.

Scenario:

* I have a Content type "xxx" and I have set a flag with this content type.
* So, whenever a user creates a content,I want to use scheduler so that user can specify at which particular date & time it should be flagged.

(Scheduler provides when to publish and unpublish content,I want to Flag the content)

Let me know if anyone having any idea about this.

Thanks in advance.

# Answer
I know it was not that difficult but I was not getting the actual thing how to achieve it but now it is working for me.

Things to do:

1. Go to your /admin/config/workflow/rules/components and click on "Add new Component"
2. Select "**Action set**" under **Component plugin** & Press **Continue**.
3. Give appropriate Name.E.g: Flag Node.

**Data type** : Content, **Label**: Node, **Machine name**:node & Press **Continue**.
4. Click on "**Add action**" & select "**Flag a node**" ,once it returns the result data,Select which flag should be clicked.

For =\> node :**Data selector** use **node** &

For =\>User on whose behalf to flag : **Data selector** use **node:author**

& Press **Save**.

Done with the component.

Now **Add a New Rule**
5. Go to your /admin/config/workflow/rules and click on "Add new Rule"
6. Give appropriate Name.E.g: Flag Node Rule.

**React on event** : **After updating existing content**. (as you need)

& Press **Save**
7. You can add conditions if you want whether it should be published or should belong to any content type or what so ever you need. I have used **Content is of type**.
8. This is the thing which works like a magic to schedule your event(Here Flag). Click on "**Add action**" & Select "**Schedule component evaluation**" under **Rule Scheduler**

& Select the **Component Value \** as (\**Flag Node**) which we created just before configuring this rule & Press **Continue**.
9. Enter **Scheduled evaluation date** which will schedule your event when to get triggered.

**Data selector** :(Enter Your values as +2 minutes, +2days, +2 weeks etc as your need)
10. **Identifier** =\> **Value** : \[node:title\] has been Flagged.(You can use any message you want to see on /admin/config/workflow/rules/schedule along with list of scheduled events.)
11. **Node** =\> **Data selector** : **node**

& Press **Save**.

Done with the Rule.

Configuration is done. You can test it now.

**But** please have a look into this. I was not checking such thing so was not able to see the result. Your event will respond you only after the cron run because it is executed by the cron. The cron triggers a query to check whether something should be published or flagged.If your cron runs every hour and you want something published on 22:35 and it is past that time it will be actually published the next time your cron runs. So if your cron runs at 22:30 and 23:30 the publish will be at 23:30.

Hope this will be helpful for someone.
> 3 votes

---
Tags: flags, rules
---


# Question
Title: how to display the last mailchimp campaign?
I need to display the last campaign (preview, description, name) in my website but currently mailchimp module doesn't have a block or view to do this, is there another alternative?

# Answer
> 0 votes
I think you use mcc module for create mailchimp for node. when you disable this module its show list of all campaign which you created.

you can also use mailchimp function for getting list of campaign:

$campaigns = mailchimp\_campaign\_load\_multiple();

---
Tags: views, blocks, emails
---


title: Views Field View issue

text:
# Question
Title: Views Field View issue
I am new to drupal, so this issue may be something extremely basic that I am missing.

Basically, I have 2 views. A parent and a child. There are 3 content types. Industries, Applications and Minerals.

I need the parent view to show all industries, then the child view should show the applications within each industry, which are linked using an Entity Reference field.

Can someone please point me in the right direction on how to pass a contextual filter from the parent view to the child view. Basically i need to filter the child view on the title field of the parent view.

---

FIXED

Used NID instead of Title!

# Answer
> 3 votes
1. Create two views or one view with two displays
2. Configure Parent view or display
3. Configure Child view or display and add context. filter by parent node title (this can be provided by Relationships). You can test it by passing one of Parent node title to Preview textfield.
4. Open parent view or display, add Global:View field, choose your child view and display in settings.. Important part: you need to provide parent node's title as an argument to Contextual Filters input of Global:View settings, for that expand Replacement Patterns, find Title pattern, it should be somthing like \[!title\], copy it and past it into Contextual Filters input of settings form.

I didn't test it but you can correct it by your needs.

---
Tags: views
---


# Question
Title: Need to export multiple fields collections via views data export in XML
I have my site set up to import CSVs and manual entry and exporting the key information into an XML feed/File using views data export. I have a problem when I need to add a group of fields. The user can add as many of these groups of fields as they need and they should appear in the output in a single row as nested items.

When I use field collections the output produces invalid XML or is stripped of all wrappers so that it is just plain text. I have tried custom template files in my theme but views data export strips out the tags.

**Desired output**

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<file_information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<asset_data>
    <upn>GBHIS3473610HD30P001</upn>
    <title>My Title</title>
    <version>Sunday 26th January</version>
    <duration>00:00:30:00</duration>
    <tc_in>10:00:00:00</tc_in>
    <tc_out>10:00:30:00</tc_out>
    <aspect_ratio>16:9</aspect_ratio>
    <segment>
        <sequence>1</sequence>
        <tc_in>10.00.00.00</tc_in>
        <tc_out>10.00.30.00</tc_out>
    </segment>
    <segment>
        <sequence>2</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
    <segment>
        <sequence>3</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
    <segment>
        <sequence>4</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
</asset_data>
</file_information>

```

**Actual output** (rest of XML is fine)

```
<segment>
  <sequence>
    <section class="field field-name-field-sequence field-type-number-integer field-label-above view-mode-full">
     <h2 class="field-label">sequence:&nbsp;</h2>
     <div class="field-items">
     <div class="field-item even">1</div>
     </div>
    </section>
  </sequence>
  <tc_in>
  <section class="field field-name-field-tc-in field-type-hms-field field-label-above view-mode-full">
     <h2 class="field-label">tc_in:&nbsp;</h2>
     <div class="field-items">
       <div class="field-item even">
         <span class="hms hms-format-h-mm-ss">0:00:00</span>
       </div>
     </div>
   </section>
  </tc_in>
  <tc_out>
    <section class="field field-name-field-tc-out field-type-hms-field field-label-above view-mode-full">
    <h2 class="field-label">tc_out:&nbsp;</h2>
    <div class="field-items">
     <div class="field-item even">
       <span class="hms hms-format-h-mm-ss">0:00:30</span>
     </div>
    </div>
   </section>
  </tc_out>
  <sequence>
    <section class="field field-name-field-sequence field-type-number-integer field-label-above view-mode-full">
     <h2 class="field-label">sequence:&nbsp;</h2>
     <div class="field-items">
       <div class="field-item even">2</div>
     </div>
    </section>
   </sequence>
   <tc_in>
     <section class="field field-name-field-tc-in field-type-hms-field field-label-above view-mode-full">
     <h2 class="field-label">tc_in:&nbsp;</h2>
     <div class="field-items">
      <div class="field-item even">
        <span class="hms hms-format-h-mm-ss">0:00:00</span>
      </div>
     </div>
    </section>
   </tc_in>
   <tc_out>
     <section class="field field-name-field-tc-out field-type-hms-field field-label-above view-mode-full">
     <h2 class="field-label">tc_out:&nbsp;</h2>
     <div class="field-items">
      <div class="field-item even">
        <span class="hms hms-format-h-mm-ss">0:00:20</span>
      </div>
     </div>
    </section>
  </tc_out>
 </segment>

```

So how can I customise the output or should I use something other than field collections?

contents of my **field-collection-item.tpl.php**

```
<sequence><?php print render($content['field_sequence']); ?></sequence>
<tc_in><?php print render($content['field_tc_in']); ?></tc_in>
<tc_out><?php print render($content['field_tc_out']); ?></tc_out>

```

contents of my **views-data-export-xml-body.tpl.php**

```
<?php
   $item_item = 'asset_data';
?>
<?php foreach ($themed_rows as $count => $row): ?>
  <<?php print $item_item; ?>>
<?php foreach ($row as $field => $content): ?>
  <?php if($content != NULL){ ?>
    <?php $content = str_replace("<","<",$content);
     $content = str_replace(">",">",$content); ?>
     <<?php print $xml_tag[$field]; ?>><?php print_r $content; ?></<?php print $xml_tag[$field]; ?>>
    <?php } ?>
 <?php endforeach; ?>
   </<?php print $item_item; ?>>
 <?php endforeach; ?>

```

# Answer
> 1 votes
As suggested by @Molot I needed to clean fields.tpl.php which I had done but had a typo in the name which is why I was puzzled.

In addition to this I needed to add some logic into views-data-export-xml-body.tpl.php to wrap each set of field items seperately.

(used str\_replace to find the closing tag of the last element and insert the closing and opening wrapper tag)

```
$content = str_replace("/tc_out> <sequence>","/tc_out> </segment>
    <segment> <sequence>",$content);

```

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


# Question
Title: Taxonomy Terms node count of different content type along with zero count in a hierarchy
After much headache I was able to maintain a kind of hierarchy for the taxonomy terms, of the already continuing issue here, please click the below link

Taxonomy Terms node count of different content type

I did It like this, but still needs to do more.

In second step select the parent relation and check the exclude display.

Under format option select the parent taxonomy under group 1

I am getting the parent category under tag and the child terms as list-terms. using jquery I can display it in an accordion style somehow.

Now the problem i am facing is that empty taxonomy terms with counter zero are not getting displayed, please help if anyone knows the solution.

# Answer
Check what you have set for the "no results" behaviour on that field. You will not want it set to "hide".

Also check if it displays in the views preview. If it displays there but not on your page then it may be that your template is checking if a field is blank and before deciding whether to show it - you could solve this by setting a default/no results value of "0"
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I remove js from a specified page?
How do I remove js from a specified page?

templates.php

# Answer
> 12 votes
You can use `hook_js_alter()`

```
function MYTHEME_js_alter(&$javascript) {
  if ($some_condition) {
    unset($javascript['path/to/script.js']);
  }
}

```

---
Tags: javascript
---


# Question
Title: how do I add a table and where clause to query object using hook_views_query_alter()?
I currently have a unique situation whereby I need a to use a different term reference field in a view's contextual filters based on a node's content type value. I don't want to have to manually add a display for each possible combination of content types so I have been tying to use hook\_views\_query\_alter() to accomplish what is now seeming impossible to me.

In my .module file I have:

```
/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() { // your module name into hook_views_api
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule').'/includes',
  );
}

```

Then in the file mymodule/includes/mymodule.views.inc:

```
/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(&$view, &$query) {
   //this is the name of our View and Display
   if ($view->name == 'shop' && $view->current_display == 'listings') {

       $query->add_table('field_data_field_my_category');
       //then add where clause afterwards etc etc
   }
}

```

This throws the error:

> Fatal error: Call to undefined method SelectQuery::add\_table()

Which leads me to believe that the Views API is not loading properly, unless I'm completely on the wrong track here.

I've been trying to find the best practices for altering views queries but have just ended up being generally confused and frustrated. Could anyone lead me towards the light please?

# Answer
I don't know enough about your problem to say whether using `hook_views_query_alter` is the best approach.

In regards to the error you're getting, the answer is in the error message: the query object you have is an instance of `SelectQuery`. If you look at the documentation for SelectQuery you will see that it doesn't have an `add_table` method.

Instead you should use SelectQuery::addJoin (or one of the more specific methods, such as SelectQuery::innerJoin, SelectQuery::leftJoin, etc.)
> 2 votes

# Answer
Try adding $view to the line:

{$view-\>$query-\>add\_table('field\_data\_field\_my\_category');}
> 0 votes

---
Tags: views
---


# Question
Title: PDOException Error upon saving node with computed field
I have a node with three fields that I need to concatenate into a single computed field: title, icon, and track. Track is a term reference to a taxonomy term, and icon is a field attached to the taxonomy.

In my computed code, I'm using this:

```
$tmp = field_get_items('node', $entity, 'field_track_term');
$track_tax = taxonomy_term_load($tmp[0]['tid']);
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');
// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);
// Get the URI
$uri = $first_item['uri'];

$icon_vars = array(
   'path' => file_create_url($uri),
   'attributes' => array(
      'class' => array('session_list_track_logo')
   )
);
$icon_img = theme_image($icon_vars);

$sess_num_tmp = field_get_items('node', $entity, 'field_session_number');
$sess_num = $sess_num_tmp[0]['safe_value'];
$sess_title =  $entity->title;

$entity_field[0]['value'] =  $icon_img . " " . $sess_num . " | " . $sess_title;

```

I've set it to save to the database, field type text, no size limit. What I'm trying to save to the database is a string that looks like this:

```
<img class="session_list_track_logo" src="http://example.com/sites/default/files/track_icon/shopper_marketing_best_practices.png"
 /> A22 | In-Home Insights that Drive In-Store Purchase Decisions

```

When I try to save a node, I get the following error:

> Notice: Undefined index: safe\_value in eval() (line 18 of /home/www/expo/sites/all/modules/contrib/computed\_field/computed\_field.module(466) : eval()'d code).
>
> PDOException: SQLSTATE\[22001\]: String data, right truncated: 1406 Data too long for column 'field\_computed\_label\_value' at row 1: INSERT INTO {field\_revision\_field\_computed\_label} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_computed\_label\_value) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 163 \[:db\_insert\_placeholder\_2\] =\> 163 \[:db\_insert\_placeholder\_3\] =\> session \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> | The Path to Purchase Begins At-Home: In-Home Insights that Drive In-Store Purchase Decisions ) in field\_sql\_storage\_field\_storage\_write() (line 449 of /home/www/expo/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module). The website encountered an unexpected error. Please try again later.

(Note that the image string is included in the query shown after the db\_insert\_placeholder\_6 line; I just can't get SO to format it correctly inside a blockquote.)

I'm not too worried about the first part of the error; I'm obviously just not getting at the session number correctly. What I'm unsure of is what's causing the PDOException error. It says the data is too long for the column. I've double-checked in the database, and the column is definitely set to text with no size limit.

So why would the simple string that shows up later in the error be too long to save?

Just out of curiosity, I set the computed code to do nothing but this:

```
$entity_field[0]['value'] = $entity->title;

```

I got the same error.

# Answer
> 0 votes
I encountered a similar error on my current project and fixed it by adjusting the size of the related field.

Try using PhpMyAdmin to view the '`field_computed_label_value`' table and then select the structure tab. It will list the type as varchar(###) where ### = the character limit for the string.

Try increasing the size of the type for the field value by selecting the 'change' icon for the value row and then adjusting its length.

Remember to back-up before trying this in case it does not solve our problem.

# Answer
> 0 votes
I encountered a "PDOException: SQLSTATE\[22001\]" error which kept giving a blank white screen of death error. After some 2 hours or so, I sussed out that the error stemmed from my creating of a Mini Panel and giving the machine name what I thought was reasonable but the SQL DB didn't like it the length. The length I gave was just 5 words with underscores, some 35 characters but it would stop me viewing any of the Admin/blocks. Once I disabled the Mini Panel in question, everything then worked fine.

I hope this helps others not to lose such valuable time in projects.

---
Tags: 7, entities
---


# Question
Title: How to create a product class programmatically in D7 / Ubercart 3
I'm looking to create a new module that when enabled will create a new content type and create an ubercart product class for it automatically.

I've tried googling and searching stackexchange for a few days but couldn't find much that is current or applicable to D7/U3 (or so I think).

There's plenty of info on creating a node programmatically.

My question is: Once I have created the node, how do I programmatically "productize it"?

# Answer
> 3 votes
Thanks to Clive for pointing me in the right direction. As requested here is a code snippet I used in my module. I was able to take the code found in uc\_product\_class\_form\_submit() and make minor changes to make it work for my situation.

Essentially, in my module, I'm using hook\_enable to call a helper function which checks for an existing product class. If it doesn't exist, then it creates it (as well as the node type). My module will go on to do more, but this is the relevant piece. (more specifically the function uc\_suggested\_donation\_levels\_add\_product\_class).

```
<?php

/**
 * @file uc_suggested_donation_levels.module
 * Adds up to 4 donation levels including a "you choose" amount.
 */
// Constants
define('DONATION_PRODUCT_TYPE_MACHINE_NAME', 'giving_project');
define('DONATION_PRODUCT_TYPE_READABLE_NAME', 'Giving Project');
define('DONATION_PRODUCT_TYPE_DESCRIPTION', 'Adds up to 4 donation levels including a [you choose] amount.');
define('DONATION_PRODUCT_TYPE_ERROR', 'Content type already exists in database. No need to re-create.');

/**
 * Implements hook_enable.
 * When this module is enabled it will check if the product type exists,
 * if not, then it will create it and productize it.
 */
function uc_suggested_donation_levels_enable() {
  uc_suggested_donation_levels_add_product_class();
}

function uc_suggested_donation_levels_add_product_class() {
  // first check to see if this product already exists.
  if (in_array(DONATION_PRODUCT_TYPE_MACHINE_NAME, uc_product_types())) {
    // The product type already exists, abort.
    watchdog('uc_suggested_donation_levels', DONATION_PRODUCT_TYPE_ERROR, array(), WATCHDOG_INFO);
    drupal_set_message(DONATION_PRODUCT_TYPE_ERROR, 'status');
    return;
  }

  $pcid = DONATION_PRODUCT_TYPE_MACHINE_NAME;

  $result = db_merge('uc_product_classes')
    ->key(array('pcid' => $pcid))
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->execute();

  db_update('node_type')
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->condition('type', $pcid)
    ->execute();

  uc_product_node_info(TRUE);

  if ($result == MergeQuery::STATUS_INSERT) {
    variable_set('node_options_' . $pcid, variable_get('node_options_product', array('status', 'promote')));

    if (module_exists('comment')) {
      variable_set('comment_' . $pcid, variable_get('comment_product', COMMENT_NODE_OPEN));
    }

    module_invoke_all('uc_product_class', $pcid, 'insert');
  }
  else {
    module_invoke_all('uc_product_class', $pcid, 'update');
  }

  node_types_rebuild();

  $type = node_type_get_type($pcid);
  node_add_body_field($type, t('Description'));
  uc_product_add_default_image_field($pcid);

  menu_rebuild();

  drupal_set_message(t('New donation content type and product class has been created.'));
}

```

---
Tags: ubercart
---


# Question
Title: How to prevent data loss from custom field when using Views Bulk Operations?
I have developed a custom field type, widget etc all in its own module.

We also use Administration Views module with Views Bulk Operations.

Our content guys used the VBO action Publish from the Content Overview (Views) screen to mass publish few nodes which have this custom field. This caused data loss from all the nodes, but only the data from my custom field.

What causes this and how to prevent it?

# Answer
The action does this:

```
  $node->status = NODE_PUBLISHED;
  entity_save('node', $node);

```

So the fail is not coming from VBO, you have a bug in your field code. Hard to tell where without looking at it.
> 1 votes

---
Tags: 7, entities, views
---


# Question
Title: How to track mailchimp signup form location
Mailchimp has an article that explains how to track signup form locations by adding hidden fields to the mailchimp form.

All well and good, but if you put the form in a Drupal block, the location of the form suddenly becomes a variable.

I'm wondering if the token module, and a token in place of a hard-coded hidden field value that tracks location, would be a good approach? The form code for the hidden field currently looks like this:

```
 <input id="SIGNUP" name="SIGNUP" type="hidden" value="global" />

```

So, the value "global" is the one that needs to change based the the page that the block is displayed with.

I'm not sure about which token to use, but thinking I'd use something like the page title or page url. In the case of a simple block, do I just need to get and enable the token filter module?

Any thoughts on token as a good option, or other ideas I should consider?

Note - this has nothing to do with the mailchimp module (http://drupal.org/project/mailchimp), which I don't have installed on this site since this site doesn't yet have any notion of user logins.

Links: token and token\_filter.

# Answer
> 1 votes
I'm sure there's a simple answer to the above question, but in the end I took a different approach described here: Create custom signup block with mailchimp module?

Because I'm using hook\_form\_submit to control processing once the form is submitted, I can add the form location (using request\_path()) to the merge variables that are passed back to mailchimp. That way, the form is the same on ever page that it appears, but the location is passed back to mailchimp as part of the sign-up process.

---
Tags: forms, tokens, emails
---