# Question
Title: Drupal 2 blocks same form function with different output not working
I have dynamically created some blocks depending on how many entries I have in the database:

```
    function my_module_block_info() {
        $result_set = db_select('my_products', 'products')
            ->fields('products', array('pid', 'name'))
            ->execute();

        $blocks = array();

        foreach($result_set as $product) {
            $blocks['my_product_' . $product->pid] = array(
              'info' => ('My Product ' . $product->name)
            );
        }

        return $blocks;
    }

    function my_module_block_view($delta = '') {
        $pieces = explode('_', $delta);
        $pid = $pieces[2];
        $product = db_select('my_products', 'products')
            ->fields('products')
            ->condition('products.pid', $pid, '=')
            ->execute()
            ->fetchObject();

        $block['subject'] = $product->name;
        $block['content'] = my_module_block_content($product);
        return $block;
    }

function my_module_block_content(&$product) {
    $form = drupal_get_form('my_module_block_form', $product);

    $output = '<p>' . $product->price . '</p>';

    $output .= drupal_render($form);

    return $output;
}

function my_module_block_form($form, &$formstate, $product) {
    $form['submit_product] = array(
      '#type' => 'image_button',
      '#button_type' => 'submit',
      '#src' => base_path() . path_to_theme() . '/images/buy.gif',
    );
    $form['product_name'] = array(
      '#type' => 'hidden',
      '#value' => $product->name,
);
    return $form;
}

```

My problem is that when I have 2 blocks with different products on one page, the submit function for the second block displayed has the value of $form\['product\_name'\]\['#value'\] equal to the first block, which is an entirely different product. What am I doing wrong?

# Answer
I found a solution here: Multiple forms on single page?. The problem is drupal assigns the same id to forms because they are using the same function. To overide the id, simply call to a function that ddosen't exist and have a simple hook\_form redirect it like so:

```
function my_module_forms($form_id, $args) {
    $forms = array();

    if(substr($form_id, 0, 10) == 'my_module_') {
        $forms[$form_id] = array(
          'callback' => 'my_module_block_form',
        );
    }

    return $forms;
}

```
> 0 votes

# Answer
I would suggest to prefix the form array with your product ID (I guess $product-\>pid or something like this) :

```
function my_module_block_form($form, &$formstate, $product) {
    $form[$product->pid]['submit_product] = array(
      '#type' => 'image_button',
      '#button_type' => 'submit',
      '#src' => base_path() . path_to_theme() . '/images/buy.gif',
    );
    $form[$product->pid]['product_name'] = array(
      '#type' => 'hidden',
      '#value' => $product->name,
    );
    return $form;
}

```

Then the fields shouldn't be overwritten.
> 0 votes

---
Tags: forms, blocks, database
---


# Question
Title: add new format to description fiield of taxonomy display modes
when you go to `structure -> taxonomy -> VOCABULARY_NAME -> manage display` you will find the description field with no label, and with two available format : hidden and visible.

I want to add new format to this field (exactly I want add the "trimmed" format) like existing in manage display of nodes...

I used the custom\_formatter module, but it didn't do the trick, because the description field is of type "Term description textarea", and custom\_formatter use text, text\_long... types. I used some hooks to change how this field is displayed but no luck

any help will be appreciated thanks in advance.

# Answer
This is because the description field isn't a 'field'.

It's a term property like 'title' in node content type.

You should add your own 'description' field and you should be able to use custom\_formatter module to add your format 'trimmed'.

===========================================================

Edit : **Update your taxonomy term**

This solution use the "View Bulk Operation" module for updating your terms.

**\[!\]First of all, make a backup of your database !!! and put your website in maintenance \[!\]**

After module installation, create a new View based on taxonomy term Your results need to correspond at all terms you need to update.

Create a VBO field like the following screen :

Save your View and display it on your web site. Go to the page where this View should appear and select all terms

In php script textarea enter this :

```
// Load a wrapper for the current term, access to value are easy now
$wTerm = entity_metadata_wrapper('taxonomy_term', $entity);
// Update your custom field (In example : field_mydescription) with description field
// use the format of description to keep same values (In example : filtred_html)
$wTerm->field_mydescription = array(
    'value'     => $wTerm->description->value(),
    'format'    => 'filtred_html'
);
// Save your modifications
$wTerm->save();

```

All your term should be updated. Careful, if you have too many terms to update, this operation should run in background via batch API.

Delete everything we have created for the update, put in offline minimum. That's done !

You can achieve that operation in many different ways, this is quick fix.
> 2 votes

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


# Question
Title: Displaying multiple node add forms using panels and contexts
I'm using panels to create a single page that will display multiple (different) node add forms. Within panels, I use contexts to activate the node add forms I'm using and then put the forms in as content. However, the resulting page shows only the first node add form and then displays "Form" and "Form goes here" in place of the Title and fields of the second node add form.

Is there a fix for this? Or another way to display multiple node add forms within a page?

# Answer
I doubt that panels can handle it.

I would try creating a custom page with hook\_menu and outputting all the forms on it via a page callback like $output = drupal\_get\_form('foo\_node\_form'); $output .= drupal\_get\_form('bar\_node\_form'); return $output;
> 1 votes

# Answer
`$created = true` in the `ctools_context_create_node_edit_form` function in the `node_edit_form.inc` context plugin seems to be the one thing keeping us from adding multiple content profile node forms to a user edit form.

we easily added the first node edit form by passing a context, but the second one wasn't available on the layout page. if we comment out `$created= TRUE` we can pass in multiple node edit form contexts.

it seems that this value is being set as part of a performance thing? we are going to copy the whole file, rename it, create a custom module, and drop it in.
> 1 votes

# Answer
Disclaimer: I haven't tested the following solutions myself.

Assuming you don't mind adding blocks to panels you can try the following solutions. Just make sure you allow blocks and regions in your panel.

I personally had problems with nested form tags using mini-panels (which should have worked in theory) so this (i.e. blocks) is the only solution I have outside of creating custom Ctools plug-ins.

(1) Try the Advanced Form Block module to create a custom block. It does nifty things like AJAX submits, multiple blocks and field selection.

(2) Write a module to create a custom blocks using `hook_block_info` and `hook_block_view`. In this example, a $form\_state is passed along to `drupal_build_form` so you'll make sure language etc is passed in and that your includes (node.pages) is refreshed each time with AJAX loads.

```
function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

}

function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
            //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}

```
> 1 votes

---
Tags: panels, 7
---


# Question
Title: Views relationship working back from a content type
This is a very specific issue with Views Relationships, I essentially want a table view incorporating 3 content types which are linked by an Entity Reference and field collection module. I'm having trouble setting up the relationships so I have drawn a mapped out picture of what it is - and how it should be:

The content types are "Curriculum", "Observation" and "Students". I can accomplish my table layout if I work from the Observation and include relationships, but I'm unsure how to connect the relationships to work backwards from Curriculum. The view should list all the Curriculum node titles (eg ELG 01 through to ELG 16) - this is why I need to work backwards from this content type and not just list ones that are set in the Observations.

An Observation will allow a user to tag a student (entity ref to Students content type) and it allows you to list a "Curriculum Area" and a "Curriculum Level" (these are grouped under the field collection field\_curriculum\_area\_level.

If I was performing the views from an "Observation" perspective it would look like this:

But I need to start by listing all the Node Titles from the "Curriculum Areas" and then list the associated "Observations"

This is how the view looks (though the filter should work from "Curriculum" and not "Observation"

So to recap, I can get a list of "Observations" showing "Students" and "Curriculum" strands that are related, but I can't setup the relationships by starting with a view that starts with "Filter: Content Type: Curriculum Area" - I need to essentially setup relationships to work my way back from these "Curriculum" areas and show the Observation titles and Student Names -- if anyone has any ideas that'll be brilliant.

Cheers, Garry.

# Answer
If I have understand your problem, you want display a list of "Curriculum" and inside each "Curriculum" show all observation of this item (like your second screen).

If you aren't blocked by add some module to your project, you can try "views\_field\_view".

In your View, you create a first display who list all your "Observations" filtred by "Curriculum" nid (like your second screen).

Then, you create a second display who list all your "Curriculum" with a View field who use the first display.
> 0 votes

---
Tags: views, 7, nodes
---


title: Checkbox-Field Tree Menu

text:
# Question
Title: Checkbox-Field Tree Menu
When creating content, I'd like to have something akin to a drop down menu. You could hover over an item and a list of checkboxes would appear. Essentially it'd be a Select List with sub-items. Is there any easy way to do this?

# Answer
> 0 votes
You can try Hierarchical Select module. Project page says

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

It will give you a way to select hierarchical items using select boxes.

---
Tags: routes, nodes, forms
---


# Question
Title: Is there a good way to set available countries in Drupal Commerce shipping and billing?
On `admin/commerce/customer-profiles/types/billing/fields/commerce_customer_address` and `admin/commerce/customer-profiles/types/shipping/fields/commerce_customer_address` one is supposed to select the available countries in a little box. This is not ideal. So I would like to do this programmatically (possibly with `drush`), is there already a quick solution for this or do I have to delve into this myself?

# Answer
> 2 votes
Depends what you mean by 'quick', really. Yes, you can do it programatically. With PHP:

```
$instance_config = field_info_instance('commerce_customer_profile', 'commerce_customer_address', 'shipping');

$instance_config['widget']['settings']['available_countries'] = array(
  'GB',
  'US',
  'FR',
  // etc...
);

field_update_instance($instance_config);

```

Or with JS (I'll let you work that one out, selecting a bunch of `<option>` tags based on a bunch of values is very easy).

IMO the time-consuming part is building up the array of default countries in the first place; no matter what automated method you use to put the values in, someone needs to spend the time choosing and preparing them. You can't get away from that.

# Answer
> 0 votes
When being confronted with large lists in a small field, I normally pull up the developer tools of the browser, find the appropriate `select`-element and manually assign a suitable attribute (e.g. `height=800px`). Like this it is much easier to choose ranges of entries without loosing oversight.

---
Tags: commerce
---


# Question
Title: Drupal 7 Module to Set image src to a URL
I am trying to do something pretty basic but I just cannot find the right module.

All I want to do is have a field type or widget that I can use in a content type that will set the image tag's src property to a URL without actually adding the file to Drupal. The images for our site are located in a database and are accessible via a URL.

I tried the Media module but that adds the file to the Drupal images folder.

There's got to be a module for this. Anyone know the right one?

Thanks.

# Answer
I think you're looking for Remote File Source.

> Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.
> 2 votes

# Answer
While media could definitely be extended to support the use-case, and there could already be such a module, there's a more specific option:

> Imagecache External is a utility module to allow you to use imagecache(D6) / Image Styles (D7) with external images.
> 2 votes

---
Tags: 7, media, uri, entities
---


# Question
Title: (How) can I implement a points system to track club member attendance/participation?
I run a Drupal 7 site for one of my clubs at school. My eventual goal is to create a system where club officers can manage all sorts of information about our members through this site (such as contact information, which I've already got working). I want to have a system where perhaps a content type like "Club Event" (*doesn't have to be an actual event like that found in the Date module*) or "Club Meeting" is created and there is some field where club officers can essentially get a checklist of members and check off who attended that event. This content type would then also have a field where a certain point value is assigned to that node and whoever is checked off on the list will get a certain number of points added to their account.

Finally there should be some sort of view where officers can view a list of all members and the number of points they've earned/events they attended.

Does this sound like something realistic to do within the Drupal framework? If so, any suggestions as to what modules might be necessary? Would this be something the User Points module can be used for?

I've never written any modules for Drupal before, but I'm not opposed to getting my hands a bit dirty if necessary.

# Answer
If it were me, I would first create a role for members. I would have each member register and then have an officer assign them the role `member`.

I would then use the views module to display a list of members by using a filter by role. That would allow a list of members to be shown.

Then, I would create an `attendance` table and a `meeting` table in the database. (You can do this through the next step if you want to learn how to create drupal db `schema`. I would probably have the fields:

```
meetingId
meetingDate
meetingDescription

```

The `attendance` table would have:

```
meetingId
userId

```

When a user attends, you create a reference to the `meetingId` from the `meeting` table and create an enter with the drupal user id. When you want to know who selected a given meeting, you select all userId's from the `attendance` table matching the `meetingId`.

I would then write a simple module that uses the `forms api` to create a meeting. Then, you would have another page that lists all of the users by selecting all the ones with the `member` role and again using the `forms api` you would add an entry for the `attendance` table for each person that was there.

So there would be one link and two coded pages now... one link to "view meetings" which would show all of the meetings. If you click on a meeting, you would be taken to the page which displays users. If the meeting was in the past (meaning some historical data exists), it should have historical attendance data. You can handle that in one of two ways... either show them the historical data and do not allow edits, or you show your original form but populate the check boxes of people that attended. Otherwise, it is a new meeting and should just display the form. If it were me, I would allow edits and it simplifies the page because it is the same form, just populated with check-boxes if there is any data.

This is an excellent opportunity to learn how to write a module. It is very simple yet complex enough to show you the ins an outs of creating a Drupal module. Also, it has a clear and definable end result which will either work or won't.

You can check out the schema module for help creating the database tables through the module. This is a good thing to learn.

If you want to go one step further, you can expose your tables to views and use the views module to create the display portions of your data. Although you will still need to create the forms on your own.

Update: Thought, you could also add a `notes` column to the meetings so people could enter and save notes. Also, your imagination is the limit here. All sorts of other things could be done. However, I would keep it as simple as you can stand for your first module.
> 1 votes

# Answer
You are on the right path, User Points is the module you should use. You might need to do some custom coding to assign points.

* Use User Points module
* Create a checkbox Update User Points
* Write a small custom module which will implement hook node update. Check for checkbox value Update User points and read Number of Points and Attendee list to add points to users. For more detail refer user points documentation.
> 0 votes

---
Tags: 7, users, userpoints
---


# Question
Title: How to create a theme that handle articles in different categories?
I am creating a theme that has many categories which have two types of handling articles. For example:

* Categories (A,B,C,D,E) will show articles in two column
* Categories (F,G) will show articles in only one column
* These articles will show in home page in a different manner

I had already created page.tpl.php as well as page--front.tpl.php, I also created a node--article.tpl.php. So am I able to do this with drupal theming? or it is not possible?

# Answer
I think you ought to use Drupal's taxonomy system for creating the categories. This is better than content types, because your articles aren't really different types of content... you just want them to display differently.

So first, you create a vocabulary called "Categories" with Terms "A, B, C, D, E, F, & G". Then, on your article content type, you add a taxonomy field, allowing you to choose which term to associate with a specific article.

Finally, you need a way to vary the display depending on the category chosen. I like this solution, which uses preprocessing to supply per-term template suggestions. You could tweak his example, to set template suggestions for one or two columns like so (note, this isn't running code... just an example):

```
function MYTHEME_preprocess_node(&$variables) {
  // Get the Term ID from the "Categories" vocab for the current node.
  $current_term_tid = ... // (figure out where that data is in the $variables)
  $one_column_tids = array(...) // (list the tids for terms you want to display in one column)

  if (in_array($current_term_tid, $one_column_tids)) {
    // Tell Drupal to use the 'one_column_template' template if it exists.
    $variables['theme_hook_suggestion'] = 'one_column_template';
  }
  else {
    $variables['theme_hook_suggestion'] = 'two_column_template';
  }
}

```
> 0 votes

# Answer
You will want to create different content types for each type article.

I would then use Views and Panels to create the page. Create a view for each subset of article types then place each view in your panels page.

You could also do it with a theme by creating what panels creates for you but you would still need a `view` with a `block` setting and then places the `views block` in the correct section of your site and set the block to only show on the home page.

The views+panels is a much cleaner implementation that is theme independent.
> 0 votes

---
Tags: theming
---


# Question
Title: How to modify template.php in bootstrap theme, to add a class tag to menu li tag?
I am using Drupal 7 with the Bootstrap theme and a customised subtheme.

I would like to modify `template.php` to add a class for each `<li>` in the menu. As per instructions provided in: https://drupal.org/comment/5830446#comment-5830446

Instructions say:

> "...use this snippet in `template.php` to put a unique id for `<a>` and `<li>` elements at the same time"

```
<?php
/**
* theme_menu_link()
*/
function MYSUBTHEME_menu_link(array $variables) {
//add class for li
   $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//add class for a
   $variables['element']['#localized_options']['attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//dvm($variables['element']);
  return theme_menu_link($variables);
}
?>

```

Which `template.php` file should I modify? and how? I have the following `template.php` available:

```
./bootstrapMYSUBTHEME/template.php
./bootstrapMYSUBTHEME/templates/template.php
./bootstrap/template.php
./bootstrap/bootstrap_subtheme/template.php

```

# Answer
Code for customized menus used with Drupal Bootstrap subtheme

```
<?php

/**
 * @file template.php
 */

 /**
 * Overrides theme_menu_link().
 */
function bootstrapf24_preprocess_menu_link(&$variables) {
    $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
    $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#title'])));
    // Another option $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#original_link']['link_title'])));
    $variables['element']['#attributes']['class'][] = 'menu-' . $menu_title_class;

    if ($variables['element']['#original_link']['menu_name'] == 'user-menu') {
        $variables['element']['#localized_options']['html']= true;
        $variables['element']['#title'] = '<span>'.$variables['element']['#title'].'</span>';
    }
}

```

without `<php` ending tag.
> 1 votes

# Answer
Whenever in a theming guide you see a reference to template.php without a context, it should (and in official documentation does) mean the template.php in the root directory of a theme / subtheme you are developing.

In your case it means *./bootstrapMYSUBTHEME/template.php*

Never hack your base theme. Your changes will be lost and gone if someone will decide to upgrade it. And if you will upgrade it, you will have to re-write them into new version after each upgrade. Waste of time, subthemes are there exactly to avoid that burden.
> 4 votes

---
Tags: theming, routes
---


title: custom module folder

text:
# Question
Title: custom module folder
In *Pro Drupal 7 Development: Third Edition*, the authors suggest moving custom modules inside subfolders of /sites/all/modules/custom/, i.e.

* /sites/all/modules/custom/mymodule1
* /sites/all/modules/custom/mymodule2
* /sites/all/modules/custom/mymodule3

Does this have any special meaning for Drupal core? For example, is this folder omitted when checking for new versions of modules? I haven't checked this so far so I'm just curious.

Before I read the book I put my custom modules like this:

* /sites/all/modules/mymodule1
* /sites/all/modules/mymodule2
* /sites/all/modules/mymodule3

# Answer
It shouldn't break anything, and it has no special meaning to core: as long as it's in a modules directory, it will be searched recursively (which is why larger projects often have submodules in a subdirectory).

However, it does allow site-builders to organize their modules more neatly than just lumping everything together. You'll often see `modules/` directories structured in a way similar to this:

* /path/to/modules/contrib: Modules downloaded from contrib
* /path/to/modules/custom: Custom modules that you write for this site
* /path/to/modules/devel: Modules not meant to be enabled on live
* /path/to/modules/features: Modules created by Features

This organizational setup is often used when building installation profiles and distributions as well, so if you download a few you'll probably see more examples of this sort of organization put into practice.
> 10 votes

# Answer
In regards to errors after moving modules around in folders: Configuration \> Development \> Performance \> Flush All Caches

If Errors persist: `http://example.com/update.php` then follow through steps.

Try the Administration Menu module.

1. Download Administration Menu.
2. from admin/modules enable *Administration Menu* along with *Administration Menu Toolbar* Style (at same time, disable core *Toolbar* module).
3. Move your modules and/or module folders as you like
4. Now, from Home (top left) dropdown, Flush All Caches \> Class (or Theme) Registry

Lookup "Drupal Registry" or see the Drupal API description.

Alternately, the PHP is: `<?php
 function registry_rebuild() {
 system_rebuild_module_data();
 registry_update();
 }
 ?>`
> 1 votes

# Answer
Remember that when you can always use drupal\_get\_path() in your custom code if you need to use the path to your module. It will continue to work when you have multiple subdirectories inside sites/all/modules.

```
drupal_get_path('module', 'my_module_name');

```

On large sites, I split up modules into three folders, but you can use more:

```
sites/all/modules/custom
sites/all/modules/contrib
sites/all/modules/features

```

If you are building your site with Profiler, you can also specify which folder the module code is placed in. For example, to add File Entity to your installation profile inside the contrib folder:

```
projects[file_entity][version] = "2.0-alpha3"
projects[file_entity][subdir] = "contrib"

```
> 1 votes

---
Tags: 7
---


# Question
Title: Panelizer settings page not found for OG group node
I have a site with several content types, all of which are OG content except one type, Group, which is a group.

I also have Panelizer and Panels Everywhere enabled. When I go to edit the default Panelizer settings for each content type, I have no problem doing so, *except* when the node type is Group. I can turn on Panelizer for Groups but then when I go to set the default settings for individual view modes, I get a "page not found" error.

I've cleared caches, rebuilt the registry, and even reinstalled Drupal, to no avail.

# Answer
It turns out that this is correct, though not very user-friendly, behavior. The user must enable a default panel, or trying to set settings for the default panel will not work.

on admin/types/manage/\[nodetype\]:
> 0 votes

---
Tags: organic-groups, entities, chaos-tool-suite, panels
---


# Question
Title: drupal course module adding payment object
Please Somebody help me. I have spent almost a week working on this functionality but haven't got any success yet. I have a Learning management system in drupal7 using the course 7.1 beta2 module, the LMS has courses in it. The requirement is to have the user buy the courses in-order to take the course but I am not able to configure it. Please can any body show me a way on how to configure the payment object so that the user will have to buy before even starting the course. I need a step-wise solution on this

Thanks in advance

# Answer
Here is the solution on the Course issue queue:

https://drupal.org/comment/7477856#comment-7477856
> -1 votes

---
Tags: ubercart
---


# Question
Title: Empty title on one View based on Taxonomy Terms
I'm struggling with a couple of pages that won't propagate a page title. Because the view is based on Taxonomy Terms I want it to change the page title to the taxonomy term it's using. I've spent hours going through different drupal blogs etc to try and trouble shoot the problem but nothing's working. The site is www.skyviewelectronics.com and the problem pages are all the pages that use the collection Taxonomy Terms:
/collection/cables-and-connectors
/collection/cell-phone-signal-boosters
/collection/clearance
/collection/computer-software
/collection/computers
/collection/data-storage-and-backup-drives
/collection/hd-tv-antenna-accessories
/collection/hd-tv-antennas
/collection/high-speed-internet
/collection/networking
/collection/notebook-bags
/collection/protection-and-cleaning
/collection/security

I've turned off the Metatag View module since some people report that is a problem.
Here is the options for my view:

Here is the options I have for the contextual Filter under content: has taxonomy term ID (with depth) - I've also tried without depth, and many many many other combos...
Can anyone help??

# Answer
Ok I found the answer (might not be the right answer but it's working). I changed the "title" section in the View to %1 %2 and it started pulling from the metatag title section in each taxonomy term.
> 0 votes

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


# Question
Title: drush archive-dump and archive-restore remotely
I know how to backup and restore a whole site using drush archive-dump and archive-restore which is explined in this link: Backup and restore Drupal sites with Drush

my question: is it possible to do the archive-dump and the archive-restore using aliases from a different server of the site.?

I have tried putting in the aliases file remote-host and root but it doesn't work.

# Answer
> 1 votes
After multiple tests using the command drush archive-dump and archive-restore, I came to the conclusion that it is necessary to install drush in the final servers. I wasn't able to run the command archive-dump from a server which has drush installed to make a backup of the other server which doesn't have drush installed because using the aliases file the drush cmd in the source server raises the following error:

```
bash: drush: command not found

```

That means that drush is needed in the destiny server. The way I concluded this was making a debug from the source server using the option --verbose and I realized that when you use the aliases file in drush command at the end this command makes a call with ssh like this: executing

`ssh -o PasswordAuthentication=no user@server 'drush --verbose --uri=urlserver.com --root=/var/www/html archive-dump --destination=/home/user/backup/example.com.tar.gz --overwrite 2>&1'`

If you notice the drush command is simply being passed to the destination server.

---
Tags: backups
---


# Question
Title: How to reset the id of the orders generated by Commerce module
I just finish a website which include a cart. I'm using the commerce module.

In the development stage I've been making some test. Now I just deleted all these testing order, but now the id of the next order is something like 189. I need to put this number to 1.

**Which database table do I need to truncate to get it done?**

# Answer
The commerce order module defines two tables, `commerce_order` and `commerce_order_revision`; you should truncate both of those to clear the data and reset the `AUTO_INCREMENT` counter.

In MySQL:

```
TRUNCATE TABLE commerce_order
TRUNCATE TABLE commerce_order_revision

```

Or using the API:

```
db_truncate('commerce_order');
db_truncate('commerce_order_revision');

```
> 6 votes

# Answer
Some additional thoughts regarding resetting the entire "order" environment back to the first order...

In addition to truncating the `commerce_order` and `commerce_order_revision` tables after manually deleting through the admin interface as indicated above you should should determine if the following tables exist and need to be deleted (if you are using the contributed modules).

`commerce_invoice` \- if using Invoice module

`commerce_paypal_ipn` \- if using PayPal modules

`commerce_payment_transaction` \- if using PayPal modules

`commerce_payment_transaction_revision` \- if using PayPal modules

I ran into issues when these tables where not reset/truncated.
> 1 votes

---
Tags: commerce
---


# Question
Title: Set the permission to view taxonomy term pages basing on the vocabulary
I'd like to completely disable taxonomy term pages based on the vocabulary. I want to use the taxonomy terms to organize nodes, and even let people use them, but users should not view the normal taxonomy pages.

Basically, I need to set the permission to view the taxonomy pages basing on the vocabulary.
Does a module like this exist?

Things like Taxonomy Access Control come to mind, but those are intended to hide content based on how it has been tagged; perhaps one of those modules does what I'm looking for.

# Answer
Several years later... wanted to list several easy options that now exist (quotes included are from their project pages):

* 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.
* Taxonomy Permissions

> Taxonomy terms are typically displayed as Taxonomy Term Fields and each term also has a corresponding taxonomy/term/% page, where % is the term's tid (if the term field is a link, you can click on it to get to the term's page). There are other contribs that allow you to control access to the fields, but those modules leave the term pages open for everyone to see, even for anonymous users.
>
> The Taxonomy Permissions module adds view terms in vocabulary permissions to the list of permissions of the Taxonomy core module and displays the resulting merged list on the Permissions page.
>
> To avoid surprises, vocabularies are visible by authenticated and anonymous users by default. You have to change the permissions to see any effect of this module. Roles without the 'view' permission for a given vocabulary will not see Taxonomy Term Reference fields for that vocabulary, and they will not be able to access the taxonomy/term/% pages for the terms in that vocabulary.
> 1 votes

# Answer
Use hook\_menu\_alter() to customize the access\_callback on `$callback['taxonomy/term/%']`.
> 2 votes

# Answer
There might be a way of doing this in a more general and broader sense, but I have used Custom Permissions in the past to achieve more granular permissions than what you normally get out of other access control modules. You could use this module to define the paths of the taxonomy pages you would like to block (I think you can also use wildcards).
> 1 votes

# Answer
This could be very easily achieved with some custom code - I'm thinking to implementing hook\_init() with code similar to the following one:

```
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) {
  drupal_access_denied();
}

```

I wrote that off the top of my head, so it might not be totally correct, but you get the idea.
> 0 votes

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


# Question
Title: Get the displayed node of a commerce_line_item in a component rule using 'commerce_display_path', doesnt work
I ve found something quite interesting in an other post Discount based on a field in product display node in Drupal Commerce?

It describe a way to get the 'node display' associated with a line\_item

1. Build a component rules action set with custom php code in it, providing a 'node\_fecthed' provider variable and then use it with other rules to do what you need.
2. The php code use the commerce\_display\_path backlink exploded url to find the displayed node, then return it.
3. The given code is the following :

```
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$url = $line_item_wrapper->commerce_display_path->value(); $url_parts = explode('/', $url);
$nid = $url_parts[1];
return array('node_fetched'=> $node);

```

Just before the return line, i added, regarding to a comment suggestion from the original post, 2 lines :

```
$node=node_load($nid);
dpm($node);

```

when rules is run, devel dpm() displays the right associated node as expected. But when in an other rules i try to display/debug/use the 'node\_fetched' it appears to do nothing as if it was set to null. What may be wrong with that ? Any suggestions will be appreciated as i'm going mad with that for 2 days. Thx

# Answer
In fact returning variables (providers) from a custom php code doesn't work ! If you do it in a module the same code works ! Rules bug ??
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Symbolic links and the file_scan_directory() warning
I wanted to use the following symbolic link in my root directory:

```
$ ln -s /data1/public/cases/ DownloadData

```

Such that when users go to www.example.com/~user/DownloadData/file they are rerouted to /data1/public/cases/file on the server.

When I did this I can verify that the symbolic link will work by using `ls -l` and clicking on the link.

After applying the symbolic link I get a page with MANY warnings from Drupal. The warnings show up in the Views UI, Modules UI, and i'm sure more places.

Below are all the warnings. Notice how it is trying to go into is a kind of combination of the symbolic link and the actual path. I'm very new to Drupal so please be patient with me :). Thank you ahead of time.

```
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/cases/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).
Warning: opendir(.//DownloadData/public/Indices/016): failed to open dir: Permission denied in file_scan_directory() (line 2070 of /data1/home/spaceweather/htdocs/sw_test/includes/file.inc).

```

# Answer
I've just resorted to suppressing the errors for now. My server admin showed me that it is possible with the .htaccess file to suppress php errors.

The line of code that was added to .htaccess looks like:

```
# Don't allow PHP warnings to be displayed in Drupal.
php_value error_reporting 6135

```

If anyone finds a real solution please assist. That darn file\_scan\_dir() is having a hell of a time with that symbolic link I placed in my root directory. The time to load several of the admin pages is much longer than it was before this warning appeared and i started using that symbolic link.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: Make feeds importer to replace instead rename file path
I am using commerce\_feeds module to import products. It works well except the image fields url gets renamed by adding \_0, \_0\_5, etc at the end of the image paths. How to turn this off? I would like to have path the same at all times no matter if the file is present with the particular path or not. Thank you for any help you can give in this regards.

# Answer
> 0 votes
The problem was on the server. It was not supporting image GD extension that prevented for generating images with a new path.

---
Tags: commerce, feeds
---


# Question
Title: drupal 7 + services 3 - inserting nodes with select fields
I'm using Drupal 7 + Services 3 to create nodes with POST and JSON. Everything works fine, except field types of select - entity reference select or plain text.

The entity reference uses the autocomplete widget, while the text select is a plain radio button.

This is the format I'm using:

```
"field_urgency": {
    "und": [  {  "value": 1    }   ]
}

```

# Answer
> 1 votes
Eventually I figured this out:

```
    {
    "title": "some more tests",
    "type": "weed",
    "field_sprouts": {
        "und": [ 8,9 ]
    },
    "field_urgency": {
        "en": [
            {
                "value": "2"
            }
        ]
    },
    "field_species": {
        "und": [ 4 ]
    }
 }

```

species and sprouts are entity references and only need the nid of the target (no value= or target\_id= or anything). For unknown reason (as of yet), the urgency field required a language to be defined (other then und\[efined\]). Its the only select field here with a normal select list, not entity refernce. Make sure your widgets are **select list** and not auto complete.

# Answer
> -1 votes
The PUT format for boolean or select list :

```
{
  "field_order_status":{
    "und":["1"]
  }
}

```

it would be ok.

---
Tags: nodes, services, ajax, 8
---


title: How feature works with panels?

text:
# Question
Title: How feature works with panels?
I have created cusotm layout with panels on my dev and staging site. I added a class to panels region and exported using feature. Then I enabled it on stage site. But there was no changes on stage site. Is there anything more needed for panels update using features? Or have anyone a documentation on features with panels, panelizer and panopoly module?

I exported Panels: mylayout (Default Config)

# Answer
> 0 votes
I noticed that, any update from feature module works only if that was created using feature module.

---
Tags: 7, panels, features
---


# Question
Title: Drupal #attached doesn't work with some themes
I've written a module which loads CSS and JS files using the #attached property. This works fine across most themes, but for some themes the files are not loading.

e.g.:

```
$page['header']['#attached']['css'][] = array(
  'data' => drupal_get_path('module', 'mymodule') . '/css/mymodule_default.css',
  'type' => 'file',
  'options' => array(
    'group' => CSS_THEME,
    'preprocess' => TRUE,
    'every_page' => TRUE,
  ),
);

```

As there is very little by way of explanation on #attached (most articles repeat the same stuff) I can't figure out where the problem may lie. Using `drupal_add_css()` and `drupal_add_js()` works, but is not recommended for caching reasons, and I prefer to pass settings using attached for this reason.

The #attached properties are showing in the `$page` array but are not being rendered.

In summary, are there situations when certain themes block the correct rendering of #attached elements that would normally be applied to a render structure by drupal\_process\_attached()

Any help is appreciated.

# Answer
The example code you are giving indicates, that you want to have this CSS included on every page. In this case do not bother using `#attached` at all and just call `drupal_add_css` from `hook_page_build`. An even better option is to include the CSS in the module-info file with the following line:

```
stylesheets[all][] = css/mymodule_default.css

```

In contrast if the asset is to be added to the page only when a given element is rendered (e.g. a form), then use `#attached` on that element. This way the path to the asset gets stored along with the render-array if the element is cacheable. On subsequent page requests, the element will be retrieved from the cache and the asset is attached to the page. If you would use `drupal_add_css` together with cacheable elements, the asset would be missing on subsequent page builds.

Note that even when using `#attached`, `drupal_add_css` is called internally from within drupal\_process\_attached. The responsible code, but actually boils down to this excerpt:

```
// Add both the JavaScript and the CSS.
// The parameters for drupal_add_js() and drupal_add_css() require special
// handling.
foreach (array('js', 'css') as $type) {
  foreach ($elements['#attached'][$type] as $data => $options) {
    // [...]
    call_user_func('drupal_add_' . $type, $data, $options);
  }
  unset($elements['#attached'][$type]);
}

```

The `call_user_func` will invoke either `drupal_add_js` and `drupal_add_css` respectively, depending the value of `$type`. It follows that there is no additional benefit from using `#attached` *unless* the asset is used by a render-array which is to be stored in the cache. Assets specified via `#attached` are guaranteed to be loaded if the associated render-array is rendered. They will not be added to the page when the associated render-array is not rendered.

In your specific situation you are attaching the CSS not to an element but to a page region. However the header-region apparently is not rendered by every theme, probably because it is not widely used. The header-region is rendered in page.tpl.php. If a theme chooses to ignore a region, like the Versatile and the Corporate Clean do, the CSS will not be attached.

To sum up:

* Use `#attached` when adding assets to cacheable render-arrays (especially forms and form elements)
* Add stylesheets / scripts to the module-info file or call `drupal_add_js` and `drupal_add_css` whenever adding assets globally.
> 3 votes

---
Tags: javascript
---


# Question
Title: Using Drupal Commons, how can I create a node of a specific content type on group creation?
I am looking for a way to create a node of a specific content type at the same time as a group is created.

So basically, when a group is created a node of type my-content-type is created at the same time with og\_group\_ref pre-populated to associate it with the group just created...

I don't think there is a module for this, so... any pointers on to how to code this?

# Answer
> 2 votes
Here's the solution:

Obviously you need to download and install Rules, then:

1. Add an event:

After saving new content of type *Group*

2 . Add conditions:

Any conditions you want here..

3.Add Actions:

a) **Create a new entity**

* Parameter: *Entity type*: Node, *Content type*: ContentTypeYouWantToCreate, *Title*: YourTitle, *Author*: TheAuthor
* Provides variables: Created entity (entity\_created)

b) **Save entity**

Parameter: *Entity*: \[entity-created\], *Force saving immediately*: true

c) **Add entity to group**

Parameter: *Entity*: \[entity-created\], *Group*: \[node\]

your content type should now be created when you create a new group - it will also be added to the newly created group.

Done!

---
Tags: organic-groups, entities, 7
---


# Question
Title: Programmatically alter taxonomy term tree options
I have a taxonomy term reference field in a form. This field has many options and I'm using the term\_reference\_tree module to display them. I'm trying to add a filter to this form so it only displays certain options depending on some factors (the value of a different field).

The problem is editing this field's options. I can't find a way to programmatically alter a taxonomy term reference field's options when using the term reference tree widget. I've tried using hook\_field\_widget\_properties\_ENTITY\_TYPE\_alter but this doesn't allow me to alter the actual **options**.

Any suggestions would be very welcome. Thanks in advance.

# Answer
> 2 votes
This can be accomplished by modifying the #after\_build item of your term\_reference\_tree field in hook\_form\_alter:

```
function MYMODULE_form_alter(&$form, &$form_state) {
  // You might want to do this only for certain forms,
  // or only for forms that have the field to be altered.
  $language = $form['my_taxonomy_field']['#language'];
  $form['my_taxonomy_field'][$language]['#after_build'][] = 'MYMODULE_branch_group_form_element_after_build';
}

function MYMODULE_branch_group_form_element_after_build($form_element, &$form_state) {
  MYMODULE_taxonomy_tree_form_element_alter($form_element[0]);
  return $form_element;
}

function MYMODULE_taxonomy_tree_form_element_alter(&$element) {
  foreach ($element as $tid => $data) {
    if (($tid[0] != '#') && is_numeric($tid)) {
      // MODIFY HERE:  If you do not want to show the term with
      // a specified tid, hide() it here.
      if ($tid == 60) {
        hide($element[$tid]);
      }
      else {
        // OPTIONAL: Alter the way each individual term is rendered.
        // See BONUS ANSWER, below.
        MYMODULE_taxonomy_tree_form_element_term_alter($element[$tid][$tid], $tid);
        // Recursively alter the children of the tree -- the item we
        // want to modify may be nested somewhere inside the tree.
        if (array_key_exists($tid . '-children', $element[$tid])) {
          MYMODULE_taxonomy_tree_form_element_alter($element[$tid][$tid . '-children']);
        }
      }
    }
  }
}

```

BONUS ANSWER: In addition to filtering out items, I also wished to add a rendered icon with each taxonomy term in the tree. In order to allow the specific fields of the taxonomy vocabulary to be selected and ordered, and the rendering mode (i.e. thumbnail size) of the image field to be selected through the admin user interface, I used the entity\_view\_mode module to define a new view mode for my taxonomies.

```
/**
 * Alter the data built by term_reference_tree.widget.inc.
 * @see: _term_reference_tree_build_item()
 */
function MYMODULE_taxonomy_tree_form_element_term_alter(&$element, $tid) {
  $term = taxonomy_term_load($tid);
  // In order for this to work, you will need to install the
  // entity_view_mode module, and make a 'term_with_icon'
  // view mode for your taxonomy vocabulary.
  $term_render_array = taxonomy_term_view($term, 'term_with_icon');
  $element['#title'] = drupal_render($term_render_array);
}

```

# Answer
> 1 votes
I haven't done this with any of the taxonomy widgets, but the approach I have used is:

* Clone the widget into my own custom module.
* Customize the cloned widget
* Add it as a new widget type via `hook_field_widget_info()`, setting the `'field types' = array(...)` to the type I cloned from.

This should then appear as a new widget. The same approach works for `hook_field_formatter_info()`.

---
Tags: entities, taxonomy-terms
---


# Question
Title: Whenever I edit/update a node all the page caches for anonymous user are lost
I have the following cache settings on the performance page

I have visited a few pages as anonymous user and made sure that they are being cached. Now I log in as admin in a different browser and edit a node. The moment I do this I see that Anonymous Page Cache for all the pages are cleared.

This seems counter intuitive and render caching useless for sites with high content editions.

# Answer
Whenever I edit a node all my page caches are cleared.

**As per the design :** This behavior is intended behavior and works as per the design. If you look at the `node_form_submit()` node submit handler function within the node module you will notice that there is a `cache_clear_all()` As the comment in the line above the function call reads it clears the *page and blocks cache* as expected.

**Reason for clearing all the caches:** When a node is created/updated there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

**Work Around :**

**Approach 1** : Since `node_form_submit` is form submit handler you could just implement a `hook_form_alter()` and change the submit handler to your own function which can omit `cache_clear_all()` function call.

**Approach 2 :** Set Minimum Cache Life Time to a high value. (By doing this you are asking Drupal not to clear caches if they are not older than the specified Minimum Cache Life time. So now if you edit a node, the changes will not be visible immediately. Your changes will only be visible when time elapsed is greater than Minimum Cache Life time and next general cache wipe has occured.)

Once you have set the Minimum Cache Life Time you can use Expire module to implement your custom logic for Invalidating a cache. You can have settings such that whenever a node is edited drupal can clear the cache for that particular page and all the listing pages.

***EDIT(After @MPDs comment)*** : If you are using a reverse proxy server then you might need to consider setting the Expiration of cached pages to an appropriate value and probably consider using purge module.

Futher Reading : Difference between Minimum Cache Lifetime and Expiration of Cached Pages value.
> 10 votes

---
Tags: caching, performance
---


title: Add product(s) to cart from DOM string

text:
# Question
Title: Add product(s) to cart from DOM string
*short version:*

how can I add multiple items to a cart from a served string that provides the product ids and their quantities? I suppose a rule could handle this somehow?

*long explanation:*

hey guys,

I'm trying to make some bigger changes to the add-to-cart form and the way it functions, for my client and I have specific needs here.
Usually the form only let's you add one type of product variation at a time, but I want visitors to be able to set multiple product variations of the same product node, and the 'Submit' button submits **all** of them, **instead of just the currently selected variation**.

To put this into perspective: Let's say I have a product (display node) called

* Brick

This Brick holds three variations:

* Brick (Front) , Brick (Side) , Brick (Top)

Using a Custom Line Item, it gets these options added automatically (taxonomy term list reference):

* Red , Green , Blue

Here, we want users to be able to (for example) click *Side* and select *Green*, then hit *Front* and choose *Red*, and when they hit *Submit*, both of these get added to their cart. By default however, of course only one - the last selection - is added.

Now, using a `hook_form_commerce_cart_add_to_cart_form_alter()` and custom JavaScript, I've gotten to a point where my JS automatically stores the entire selection inside a *JS Object*. But from hereon, I'll need your help guys.

I can easily print the JS Object into the DOM as a string with a format such as `VariationID:LineItemOption:Quantity[_repeat]`.
For example the string could read `31:2:1_32:3:1` (which for humans would read *Side:Green:1, Front:Red:1*).

From hereon, though, I dont really know how to progress. My idea would be to perhaps create a custom rule that (replacing the action of the default Submit button) receives that string, filters it and adds matching items to the cart.

Really hope someone here has an idea on how I could progress. Any suggestion and recommendation would be highly appreciated!

# Answer
If I understood you right. I had some similar task in the past. I had form of all product variations in the table with textbox inputs for quantity. And they must be added multiple to cart.

The main function is commerce\_cart\_product\_add\_by\_id($product\_id, $quantity);

**What I did**: I created custom field formatter for "Product reference" field and rendered it as table of variations with text inputs for quantity. And on form submit I loop all products in foreach and add them to cart.

But if you don't want to create additional formatters there is another solution.

1. You can use your hook `hook_form_commerce_cart_add_to_cart_form_alter()`
2. Render form elements for all your product variations there by custom code.
3. Replace form submit with your custom submit
4. Add products to cart in custom submit (call `commerce_cart_product_add_by_id()` in foreach).

Also you can write your text `VariationID:LineItemOption:Quantity[_repeat]` into some hidden textfield element. After submit you'll read this text in `$form_state`
> 1 votes

---
Tags: rules, forms, commerce
---


title: Customizing node reference widget

text:
# Question
Title: Customizing node reference widget
As you now, when we use node reference field in a data type, during inserting a content, a list is very simple and it shows only node title.

I want to know is there any way to customize the list. for example I want to add css classes to list or add additional field such as thumbnail image and other field in this widget.

Please guide me. How can I do that ?

# Answer
> 0 votes
You can create own field formatter in code. Or use field preprocess function.

But I would suggest you to render this references as view. Than you can do with field anything you want

---
Tags: nodes
---


# Question
Title: After setting $base_url, I can only access the front page
I have Drupal installed in a subdirectory of `public_html` on BlueHost.

It looks like this: `/www/drupal7/mywebsite`.

I want to run the site out of the `mywebsite` subdirectory instead of `www`. However, I want the URL to appear to be http://mywebsite.com.

Here is the suggested `.htaccess` configuration from BlueHost. This is the `.htaccess` for the `www/` directory; I am using the default Drupal 7 `.htaccess` in Drupal's subdirectory.

```
# BlueHost.com
# .htaccess main domain to subdirectory redirect
# Do not change this line.
RewriteEngine on
# Change example.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subdirectory/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /subdirectory/$1
# Change example.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ subdirectory/index.html [L]

```

This successfully allows me to use Drupal from the subdirectory, but the URLs look like this:

http://www.mywebsite.com/drupal7/mywebsite/PAGE

But I want it to look like this:

http://www.mywebsite.com/PAGE

This post on Drupal.org suggests that the $base\_url must be set in `default/settings.php`. I set the `$base_url` to "http://mywebsite.com"; however, when I do this, whatever link I click, I am redirected to the front page.

Is there an additional step? What am I missing?

# Answer
It sounds like the answer from Oleg Ivanov would work. However, if you want to tackle this with a .htaccess approach, the following works for me. Find and replace `SUBDIRECTORY` with your subdirectory.

Amend your Drupal's .htaccess with the following:

```
RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]

```
> 2 votes

# Answer
Use the default `.htaccess` shipped with drupal and

1. Make sure line 110 is commented like this

`# RewriteBase /`
2. Uncomment and edit line 106 to read like this

`RewriteBase /drupal7/mywebsite`
> 1 votes

# Answer
I host several of my Drupal websites on BlueHost, and I've achieved basically what you're asking without changing any of `.htaccess` files:

here's what I do - (I have a separate Drupal installation for each site for a number of reasons, although I believe the same can be done with a multi-site install)

I have a Drupal installation in `/public_html/mywebsite`;

I add http://mywebsite.com to my account via "Assign Domain", as an Addon Domain -

in Step 4 - "Choose Addon Directory and Sub-domain" - I choose "Use an existing directory" (from a list of sub-directories under `public_html`) - `mywebsite`; (it also appears as `mywebsite.mymainaccountdomain.com` \- so be it, I just don't use it)

after all the changes propagate through BlueHost servers' "insides" (sometimes takes up to 15 minutes, especually for 'www' redirect to catch on) -

my site is accessible as both http://mywebsite.com and http://www.mywebsite.com and all its pages load as expected - http://www.mywebsite.com/page and so on

hope this helps
> 1 votes

---
Tags: redirection
---


title: Bulk update lat/long taxonomy terms

text:
# Question
Title: Bulk update lat/long taxonomy terms
I have Province/City taxonomy with 5000+ terms.

I would like to add lat/long field or something and bulk update whole taxonomy so i can use it later for maps and proximity search.

# Answer
> 0 votes
Have you looked at Geofield and Geocoder modules?

I believe you can configure the geofield as a field on your taxonomy to hold the Lat/Lng. Then, you can configure your geofield widget as `Geocode from another field`.

For batch back-filling, Geocoder provides the drush command:

```
geocoder-backfill     Geocodes all nodes that have a geocoder widget but no geodata.

```

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


title: Redirect to login on form submit

text:
# Question
Title: Redirect to login on form submit
I want to allow users to fill and submit a form even if they are not logged in, however if they are not authenticated yet, they should be redirected to login first, and after a successful login the submitted for will be really processed.

I will try to explain the solution that I did with a simple example:

```
function mymodule_menu() {
  $menu_items['custom/path/xyz'] = array(
    'page callback'   => 'mymodule_page_callback',
    [...]
  );
  [...]
}

function mymodule_page_callback() {
  // If there is a form_id_state saved in session, then
  // this is a redirect after login. Call the submit function again.
  if (isset($_SESSION['mymodule']['form_id_state'])) {
    $form_state = $_SESSION['mymodule']['form_id_state'];
    unset($_SESSION['mymodule']['form_id_state']);
    //drupal_form_submit('mymodule_form_id', $form_state);
    mymodule_form_id_submit(NULL, $form_state);
  }

  // Do normal things here.
  [...]

  return drupal_get_form('mymodule_form_id');
}

function mymodule_form_id_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  if ($op == t('Save') and !user_is_logged_in()) {
    // Save $form_state to session and redirect to login.
    $_SESSION['mymodule']['form_id_state'] = $form_state;
    drupal_goto('user', array('query' => drupal_get_destination()));
  }

  // Do normal form processing here.
  [...]
}

```

So, if user clicked *Submit* but he is not logged in, he is redirected to login with `drupal_goto()` and with come-back instructions, but first the state of the form is saved in the session.

Then, on page display, we check first whether there is a form state saved in session. If yes, then call again the form submit function, so that the processing of the form is finished (this time the user will be logged in).

All this seems a bit hackish to me. I wonder:

* Are there any drawbacks to this approach?
* Which is the best way to submit the form again,
    + calling the `drupal_form_submit('mymodule_form_id', $form_state)` (commented),
    + or calling the form submit function directly `mymodule_form_id_submit(NULL, $form_state);`?
* Is there any better way to do it?
* *Is there any Drupal way to do it?*

I have seen that this is a frequently asked question among the Drupal developers. So, maybe there is any standard answer for it.

# Answer
> 1 votes
This might help in terms of understanding Rules: https://drupal.org/node/878718

And in terms of flow, I think you could use a rule via the Rules module to direct them to a login page specific to them (people who have just filled out the form), and then the Login Redirect module to redirect them back to the form/submit action after they login. That's assuming the information they entered would remain in the form. You'll probably have to do some experimenting with that.

Jennifer

# Answer
> 0 votes
You could set up Rules for this.

Use the Rules module for getting this thing done.

---
Tags: forms, redirection
---


title: Retriving field value

text:
# Question
Title: Retriving field value
I have field called field\_3d\_model\_xml\_path which is a text type. I am currently retriving the value like this.

```
//get current node
$node = menu_get_object();
//build xml path
$xmlPath = DRUPAL_ROOT . "/" . $node->field_3d_model_xml_path['und'][0]['value'];

```

Is this right way to do it or there is some better way?

# Answer
The safest way is to use field\_get\_items() like this (which will handle any languages):

```
$xmlPath = '';
if ($items = field_get_items('node', $node, 'field_3d_model_xml_path')) {
  $xmlPath = $items[0]['value'];
}

```

If you want to access it like you currently are (sometimes it is useful to do so but in your case I don't think so, this is just to be more complete), use the LANGUAGE\_NONE constant for the 'und' language instead of hard coding it, like this:

```
$xmlPath = DRUPAL_ROOT . "/" . $node->field_3d_model_xml_path[LANGUAGE_NONE][0]['value'];

```
> 2 votes

---
Tags: entities
---


# Question
Title: List all bundle types for entity field query?
Trying to use entity field query to simplify some times; e.g. a slide show of images.

How does one get the field values for entity field query. Specifically, get a list of all the possible bundle types there are?

E.g.

```
<?php

function foo_load() {
   $query = new EntityFieldQuery;
   $query
     // What conditions or properties are there?
     ->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'banner')
     ->propertyOrderBy('created', 'DESC');
     ->propertyCondition('status', 1);

}

```

# Answer
If as per your example code you are just concerned with nodes then the bundles are just your node types.

If you want to get a list of node types you can use:

node\_type\_get\_types()
or
node\_type\_get\_names()

You can get the bundles from the array keys of the arrays returned from those functions.
> 1 votes

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


# Question
Title: Override the region.tpl.php template for an internal path
I have a view which I want to output as plain raw data (no html tag, no div, nothing, just the view content as text). I managed to override html.tpl.php, and page.tpl.php templates, but i still have some default markup... I get this:

```
<div class="region region-content">

```

And don't know how to get rid of it. I guess the region.tpl.php template is responsible for this, but how could I override it just for that given view (which has an internal path: user-export).

I tried region--user-export.tpl.php but my template is not seen by drupal. Do I need to use a template suggestion ?

Thanks in advance!

**EDIT: I found a solution.** Probably not the cleanest way but it works. I created a "blank" theme, where I overrode region.tpl.php by creating a file named region.tpl.php and stripping all divs and classes from it. I then downloaded the "Page Theme" module and set the template to "blank" for the view url. And that was it. my view got displayed with no wrappers, no divs, just plain text.

# Answer
> 1 votes
I would personally not use the method you currently have as it would seem to be overkill.

You can use your template.php file of your theme to set a different template file to use under your given conditions.

Like this, in your theme's template.php file (Note: this is adapted from the Zen theme):

```
/**
 * Preprocess variables for region.tpl.php
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */
function THEMENAME_preprocess_region(&$variables, $hook) {
  // Use a template with no wrapper for the content region on the path VIEWPATH.
  if ($_GET['q'] == 'VIEWPATH' && $variables['region'] == 'content') {
    // Allow a specific template to override the content region.
    // The template file will be region--no-wrapper.tpl.php
    array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
  }
}

```

Then to your theme add the region--no-wrapper.tpl.php file with the wrapper markup stripped out.

Then clear the drupal cache.

# Answer
> 0 votes
If you are using views you can find out what the name of the template should be looking under the following in views ui:

Advanced \> Theme : information

---
Tags: views, theming
---


# Question
Title: Send report of all changed or updated content in past day?
Trying to use Rules to do this but I think it's a bit too complicated.

I want to specify a time interval - say 24 hours - and generate an email report that lists all of the content that has been changed or created.

I can do this for individual items quite easily, but I'm looking for an aggregate report that someone could look at in the morning or evening to get a general overview of all the content changes.

I did stumble across the Views Rules module, which is interesting. It would allow me to create a view containing all the new content or updated content in the past xx hours and present that data to Rules. But it seems that would still just allow me to loop over the data and send out individual emails.

I could of course just write a small module to do this as well, but I'm wondering if there's an existing solution?

# Answer
Have you loooked at message notify? Have a look at the blog post by gizra or watch the video, message notify allows you to use view as the body of the email.
> 0 votes

# Answer
@Brian There is the Report module for D6 that does this. If you are doing something custom, might as well port it to D7.

Some details from the module's project page:

> The Report module provides an overview of user and content activity on your site.
>
> Historical data is collected through a daily cron job, and can be viewed in Daily/Weekly/Monthly/Annual tabular summaries. The Chart module will be also used for presentation, if available.
>
> Collected user data includes daily counts for registration, logins, and access for selected roles. Content data includes daily counts of nodes and comments created for selected node types.

I have not have not used this module so I cannot say how close it comes to what you exactly need.
> 0 votes

---
Tags: 7, notifications, rules
---


# Question
Title: Why do so many classes define a ::t() method?
I've encountered MANY methods substituting the translation function — forms, entities, plugins... What is the point when there is the global t() function that has exactly the same code

```
return \Drupal::translation()->translate($string, $args, $options);

```

as the methods do?

# Answer
The point is unit testing. You can extend the class and override `t()` or just create a mock out of it. Global functions are not available during PHPUnit runs and in general just a pain.

Since this became so popular let me link the relevant handbook page on global functions and unit tests.
> 7 votes

# Answer
On the longrun we want to create a trait which contains exactly the t() method and getTranslationManager() to make it as easy as possible to use that.

This sadly requires php 5.4, before it is usable.

Just in case someone wonders why we not just call the translate method: Using t() allows tools like potx to extract the strings.
> 2 votes

---
Tags: i18n-l10n, 8
---


# Question
Title: Create a list of figures, equations and other items
I run a website that is like an electronic book http://www.pveducation.org Presently there are equations, images, mini-calculators that are included in the body of each page. How do I get Drupal to automatically create a list of links to,for example, the equations? I also thought of making the equations a Content Type and use Views to make a page of all the equations but then I can't figure out how to use the new type in the body of each page. Should I use entities instead?

# Answer
> 0 votes
This is a typical use case for views.

If I understand your requirements correctly, you need to do the following:

1. create a block in views (see http://www.inmotionhosting.com/support/edu/drupal-7/views-module-tutorial/create-block-display)
2. assign that block to the region you want it to appear in your default theme (Structure -\> Blocks), see https://drupal.org/documentation/modules/block

You can also restrict the pages on which the block should appear.

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


title: drupal 7 users blog address selection

text:
# Question
Title: drupal 7 users blog address selection
I installed the blog module. Now I want that each user before posting first blog, choose their blog address. I want that they can choose their own blog address. For example user A can select that his blog be on `http://mydomain.com/myblogaddress`. How to achieve this ?

# Answer
You should be able to do that adding a field to user, say **Blog address** `field_blog_address`. Then you can use tokens in pathauto pattern configuration page to set the blog path as `[user:field_blog_address]`.
> 0 votes

---
Tags: nodes
---


# Question
Title: Do I need to delete uploaded files if I only want to parse them
I'm building an upload form for uploading files which are only parsed, and don't need to stay on the server.

I have this code:

```
$validators = array('file_validate_extensions' => array('xml'));
$file = file_save_upload('file', $validators);

```

After which I parse the file.

As I understand it, it saves in tmp by default. Now if I don't do anything else but parse that file, will Drupal or the OS discard the temporary file automatically or do I need to do something else in my code to achieve that?

# Answer
> 1 votes
According to the docs for file\_save\_upload() the file will be registered as a temporary file, so that it will be deleted anyway, assuming you have cron running on a regular basis.

> "The file will be added to the {file\_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file\_save() to save the changes."

# Answer
> 0 votes
You need to delete the file stored in you temp folder, i think its a standard specially if your uploading big files. you may use the ff:

```
drupal_unlink($uri);

```

---
Tags: forms
---


# Question
Title: Return to calling page after save button
I am putting together a simple restaurant menu function for a site. I have a menu content type imaginatively called 'restaurant menu item' I use for each dish. I have created a restauranter's "dashboard" for them to update their site including the menu. With views, I have created a table containing the full menu, a row for each dish and on each row there's an 'edit' and 'delete' button. Their function is pretty obvious I'm sure.

When the edit button is clicked, it goes to the (themed) edit content page. I've used the more buttons module to provide a cancel button. If the cancel button is pressed, then the user is returned to the table page and can continue editing. However, if she clicks on save it simply displays the updated content (and not particularly nicely) and it's not easy for the user to get back to the table and continue their updates.

I was wondering if there's a simple way of returning the user to the table page after the save button? Note if the edit is performed from the more standard drupal content listing admin pages, then it should return to the content listings pages there.

# Answer
You can use a rewritten "Content: Nid" field to create the Edit link field with a `destination` parameter that points back to the URL of the page with the table.

The "Link path" field should look something like this:
`node/[nid]/edit?destination=path/to/table`
> 0 votes

---
Tags: redirection
---


# Question
Title: Creating Pay and Configure Products on Drupal Commerce
I am using Commerce Product Option (https://drupal.org/project/commerce\_option) module to create a customisable product.

I want a way in which the user can checkout and make payment for the product and then be allowed to customise it. What would be the ideal set of Rules for this scenario?

# Answer
This module set only supports customizing the product prior to checkout. Achieving customization after checkout will require custom module development.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Prevent Drupal from rewriting # as %23 in URLs
I have a field where I am rewriting the output, trimming it and providing a read more link. The read more link contains a # because it's a page anchor that triggers a views accordion on the destination page.

Views is converting the # character into %23 in the actual displayed link, which is breaking the link.

How can I convert it back to a # character in the url?

# Answer
```
function drupal_urlencode($text) {
  if (variable_get('clean_url', '0')) {
    return str_replace(array('%2F', '%3F', '%3D', '%26', '%2523'),
                       array('/', '?', '=', '&', '#'),
                       urlencode($text));
  }
  else {
    return str_replace('%2F', '/', urlencode($text));
  }
}

```
> 3 votes

# Answer
So this was what we actually ended up doing, no preprocess or overrides required. Thanks to Peter Bull at Acquia for the help on this:

We handled this with some additional Views fields to rewrite the HTML.

1. Added an additional field for the term description, identical to how you I currently had it, except select "Exclude from display" and remove the "more link".
2. Changed the order of fields so the new term description field is loaded before the existing one.
3. Edited the original term description field. Check "Rewrite the output of this field" and put the token for the new field in the textarea, and then append the HTML for your link. So you are rewriting the HTML output as:

`[token-for-new-term-description-field] <a href="/mypagewiththeview#training-block-[counter]" class="foo">more</a>`

Then I removed the more link as it was included in the rewrite above.

This workaround will preserve the trimmed output of the description field, and allow you to render the link with the appropriate counter ID in the anchor, without running that path through l() and check\_plain().

Also needed to prepend the link with a / so it's root-relative. Since it's not being passed though l() it won't do that automatically and if this view page has a path that's not relative to the docroot you could get broken links.

Wheeeee!
> 3 votes

# Answer
```
$url = l(t("title of your page"),"$link_url",array('fragment' => 'hash url without #'));

```

first argument is title of your page

second argument is $link\_url means ex. www.google.com/link\_url.

and last is array of fragment in this array you can pass link you want to pass after #

ex.http://domain.com/india#rajkot so you haven,t need to use encode or decode any any other conversion

full syntax is

```
l(t('My Anchor Link'), '', array(
 'fragment' => ' ',
 'external' => TRUE,
 'attributes' => array(
 'title' => 'Title here.'
 ),
 ));
?>

```
> 2 votes

---
Tags: views
---


# Question
Title: Show a form element only to certain roles
Drupal's form API has a visibility state property that allows you to hide certain Form fields depending on the options selected in earlier forms.

Is there something similar for User role (e.g. a particular form field will only display if the logged in user has a certain role).

I know I can hide unwanted form fields according to role via CSS, but I would rather not print out the fields in the first place. I am creating my form inside theme-settings.php

**Edit Update:**

Here is my code following Rooby's answer:

```
function legendarysettings_form_alter(&$form, &$form_state, $form_id) {
  // To get the currently logged in user.
  global $user;
  // To target the required form.
  if  ($form_id == 'system_theme_settings') {
    // Set the role ID of the role that can edit.
    $rid = 3;
    // If user doesn't have the role in question.
    if (isset($user->roles[$rid])) {
      // Deny access to the field.
      $form['theme_settings']['admin']['#access'] = FALSE;
    }
  }

```

This works, except it hides the 'admin' field for role 3 (which is the admin role) but shows it to all other roles. I want the admin field to be only visible to the admin role.

# Answer
> 6 votes
Generally when you are hiding fields from user roles there are security implications.

The visibility state functionality you mention just hides things on the front end, which is not secure in terms of stopping users editing fields they are not actualy allowed to use.

If you want to use custom code, you can do this:

```
/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // To get the currently logged in user.
  global $user;
  // To target the required form.
  if ($form_id == 'FORM_ID') {
    // Set the role ID of the role that can edit.
    $rid = ROLE_ID_FOR ROLE USER NEEDS TO EDIT;
    // If user doesn't have the role in question.
    if (isset($user->roles[$rid])) {
      // Deny access to the field.
      $form['FIELD_NAME']['#access'] = FALSE;
    }
  }
}

```

This is a basic example and you might have to change it to deal with multiple roles having access or something.

This is ok for custom forms or if you only need to control access to a couple of fields but if you want more control or don't want custom code, etc, the best option is the field permissions module.

With that module you can go to the field edit form and select to use custom permissions, after which you can select which roles can access the field.

**EDIT**
To answer the edit in the question, your code

```
// If user doesn't have the role in question.
if (isset($user->roles[$rid])) {

```

Is doing the opposite of what the comment says it is doing. To do what the comment says you would want to do this:

```
// If user doesn't have the role in question.
if (!isset($user->roles[$rid])) {

```

# Answer
> 0 votes
Else you can just list out all the roles who can access the field as an array in the same form beginning and just check if the logged in user has any one of the roles you declared in that array.

For example.

$roles\_accepted = array(2,3,4,5);

now get the roles of the user from $user variable. so you have two variables. 1.$roles\_accepted 2.$user\_roles

And now, using in\_array() you can compare the roles and display the field to those who have the role you specified.

---
Tags: forms
---