# Question
Title: How to prevent node creation if blacklisted words detected in the body?
I have a forum and when user creates new thread (which is some custom content type) and if the thread lets say has word 'loan' in it somewhere, in a title field, or a body field and etc. then the thread doesn't get saved and gives some warning or something like that.

Is there a module for that? Recently my forum got spammed with loans and there's about 1000 of those threads and all about loans. And those spams bypass all anti spam protections. So I came up with this 'brilliant' idea.

Please don't suggest Captchas and etc. I need something like I described with a blacklist.

# Answer
I can't give you working code, but the basic approach I have used is:

* Make a new Vocabulary. Call it Naughty Words. Populate it with all of your naughty words.
* `hook_form_alter()` your submission form, and push on a new `$form['#validate']` functions.
* In your validation function, read in all of the naughty word terms into an array. Then check the submitted element(s) against the naughty words. `form_set_error()` if there is a match.

There are several ways to do the matching. One is a simple loop with a strpos against each term; another is to explode the submission and then do an array intersection. Play around with it in something standalone.
> 2 votes

# Answer
I use Recaptcha with captcha. I did not get a single spam submission since the time I've installed this module :-)

> Uses the reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.

It uses Google's web service for authenticating, which is pretty much secure.
> 1 votes

# Answer
There are many modules available in drupal for such spam prevention.

I suggest Mollom module

> Mollom is an "intelligent" content moderation web service. By monitoring content activity on all sites in the Mollom network, Mollom is in a unique position to determine if a post is potentially spam; not only based on the posted content, but also on the past activity and reputation of the poster. In short, Mollom handles incoming posts intelligently, in much the same way a human moderator decides what posts are acceptable.
> 0 votes

# Answer
Alter that node\_add\_form and add additional validation function
> 0 votes

---
Tags: 7
---


# Question
Title: How to let users change their own profiles?
I have a site running Drupal 7.9 and users can register for their own account. Some of the fields they have to input can change over time (email adress and phone number(s)). Is there any way for me to make it so the user can change his/her own email address and phone numbers?

The only thing I could find in the documentation (and controlpanel) was how to enable users to change their own username, which gets me sort-of there but not quite.

Also, I tried googling this for the longest time but I couldn't find anything. Maybe my search terms were wrong?

Any help would be greatly appreciated!

# Answer
By default, users can change their own profile information, including their email address, and excluding the username. To change the username, the user must have special permissions. To change the profile informations, go to example.com/user in your website, then click the "Edit" button.
> 6 votes

# Answer
Actually you CAN give users the permission to change their own usernames. Go to admin/people/permissions and then under "user" \> "change own user name." But I realize this was not your original question.

Like Marius said, by default users can change their profile information, including their email address, so I don't understand the question. Can you rephrase it maybe?
> 3 votes

# Answer
if the edit button isn't present at your website, maybe you're using a custom template like me hehe, try to change your site to a default stock template go to the user account and see what is the URL address, or read the users module and figure out how do the users to edit their own data, actually i haven't tried yet, but i'm with the same problem so i'll do it....

but, it's true, users can change their own account data, change username requires the permission that you already know...

I wish us luck jejeje
> 0 votes

---
Tags: 7, users
---


# Question
Title: ImageCache throwing 500 internal server error
I'm trying to use imagecache for the first time. (already installed by someone else. currently not serving any images)

So whenever I try to see an image modified by imagecache I have a 500 internal error. In the drupal's watchdog report log there is just an error without much description:

```
Failed generating an image from imagecache_sample.png using imagecache preset small_analysis.

```

I have no idea why, but in the apache error logs, I can't find anything...

This happens even when I try to display the imagecache sample:

http://www.radicalislam.org/sites/default/files/imagecache/small\_analysis/imagecache\_sample.png?1344778168=

# Answer
> 2 votes
I've just ran into this issue and i solved it by enabling the `ImageAPI GD2` module and disabling the `ImageAPI ImageMagick` module.

There's also a number of things to check: presence of the GD library in system and in PHP config, enough PHP memory to parse the images, valid file system configuration and permissions, etc.

---
Tags: 6, media
---


# Question
Title: Drupal / Ubercart says it's not saving CC data... then what's "_save_cc_data_to_order"?
I'm using Drupal 6, Ubercart 6.x-2.4, and the Stripe payment module.

I wanted to double-check my PCI compliance and make sure I'm not storing credit card data in my database, but I looked at my database and found encrypted CC data in the `uc_orders` table.

In `modules/ubercart/payment/uc_credit/uc_credit.module` there is a method called `_save_cc_data_to_order`. If I comment out this method's contents, the orders still go through my test gateway but the database is no longer populated with cc data.

Hacking up ubercart module code is an effective way to stop from saving cc data in my database, but I didn't think this should be necessary.

What is going on? I have debug mode off in admin/store/settings/payment. I don't understand why it would save ANY cc data--I don't need persisted users and turned anonymous checkout on intentionally.

# Answer
`_save_cc_data_to_order()` is called from 3 places:

* `uc_credit_order()`'s Save operation. When Debug mode (`uc_credit_debug`) is on, it saves the full payment details. When Debug mode is off, it saves the last 4 digits of the credit card number (and all other payment details except the CVV).
* `uc_credit_order()`'s Submit operation. When Debug mode is on, it saves the full payment details. When Debug mode is off, it's never called.
* `uc_credit_terminal_form_submit()`. When Debug mode is on, it saves the full payment details. When Debug mode is off, it's never called.

So, under normal circumstances (when Debug mode is off), Ubercart is storing some sanitized information. I can't speak to whether this meets your level of PCI compliance requirements, but this answer might be helpful.
> 1 votes

---
Tags: ubercart
---


# Question
Title: Detect page redirection and execute code
I have two modules which I am trying to make work in synch.

The first module creates a dynamic page and redirects users if certain conditions are met. The redirect URL takes to following form: `testsite/event/registration/success/277/466`.

When the redirect happens, I want my second module to detect the redirection and pickup from when the first module left off. I am trying to make it check and determine if the user is on: `testsite/event/registration/success/*/*`

Is this possible and can anyone give me some direction, please?

# Answer
> 0 votes
You may be able to use hook\_drupal\_goto\_alter to achieve this. It'll get called during the processing of the redirection.

---
Tags: 7, uri, redirection
---


# Question
Title: enable dd() for drush - temporary://debug_drupal.txt call fails
If I included calls to `dd()` from code I run with drush, I see messages like this:

```
WD php: Warning: file_put_contents(temporary://drupal_debug.txt):      [warning]
failed to open stream: "DrupalTemporaryStreamWrapper::stream_open"
call failed in drupal_debug() (line 1624 of
/home/planetary/April/sites/all/modules/devel/devel.module).

```

How to make it so that `dd('...')` actually prints stuff to the drupal\_debug.txt file?

# Answer
As of a recent change to Drush (March 30, 2013), Drush is aware the environment variables `TMP` and `TEMP`. So the solution (on Ubuntu) is:

```
export TMP="/tmp/"

```

and

```
sudo chmod g+w /tmp/drupal_debug.txt
sudo usermod -a -G www-data DrushUser

```
> 3 votes

---
Tags: drush, debugging
---


# Question
Title: How do I copy the values of one field collection field to another content type with the same field collection?
I have one content type with a multi-value field collection entity on it.

On the event that this content type is flagged I would like to fire a rule that will create a new piece of content and copy all of the field collection lines to the same field collection type on the new content type.

The rule I have included bellow fires and creates the new content however the field collection is not copied.

```
{ "rules_generate_pal" : {
"LABEL" : "Generate PAL",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "flag" ],
"ON" : [ "flag_flagged_generate_pal" ],
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "flagged-node" ],
      "field" : "field_project_personnel_needed"
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "project_activity_log",
        "param_title" : "[site:current-date]",
        "param_author" : [ "flagging-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created_pal" : "Created PAL" } }
    }
  },
  { "drupal_message" : { "message" : "BOOM!" } },
  { "LOOP" : {
      "USING" : { "list" : [ "flagged-node:field-project-personnel-needed" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "list_add" : {
            "list" : [ "entity-created-pal:field-project-personnel-needed" ],
            "item" : [ "flagged-node:field-project-personnel-needed:0" ]
          }
        }
      ]
    }
  }
]

```

} }

# Answer
Okay so I figured it out. On the new field collection item you need to first add the action to create a new entity of the type of field collection and then the specific field collection. Then you can add to the fields on that newly created field collection.
> 0 votes

# Answer
I have used the "set data value" action in Rules to make one field collection equal another field collection. It just dumps the whole field collection in at once, so you don't have to loop through each item one at a time.
> 0 votes

---
Tags: 7, rules, flags, entities
---


# Question
Title: How to fix the variable names in a simplenews subscription confirmation mail?
I have a Simplenews subscription block for the anonymous users of my site. When they enter their name and email address and hit subscribe, a mail is sent to their email ID for confirmation. It is a single confirmation email.

When i see the mail it displays the variable names that i am using. For eg :

> 1) The subject of the mail is Confirmation for !newsletter\_name.
> 2) please use the link below, then click "Subscribe" on the web page that will open: !confirm\_subscribe\_url

How can it be fixed?

# Answer
I am guessing you upgraded from D6. The tokens you are using are D6 tokens.

Go to **/admin/config/services/simplenews/settings/subscription** and change the tokens. For instance, the default subject for D7 is :

```
Confirmation for [simplenews-category:name] from [site:name]

```

Note the new (D7) token format. You can find he new tokens by expanding 'Replacement patterns'.
> 4 votes

---
Tags: 7, emails
---


title: Permission to see hidden fields

text:
# Question
Title: Permission to see hidden fields
There is a node type with hidden fields. Anyone can find nodes of that content type from the search form, and see open information. To see all the fields, users must make a request to the node owner, who decides the users who can see, or not those fields.

Is there any module with this purpose? Is there any other way?

# Answer
> 0 votes
I think you can accomplish this with the field permissions module. You can then specify that users without permission cannot view the field.

Secondly, create a new user role for the people who can see the field. When a user makes a request to see the field, you can set the field permission to view the field by assigning the new role to that user.

---
Tags: users
---


# Question
Title: Modifying Field Values for a Custom Content Type?
I have a custom content type that has a field whose values need to be modified. The field in question is a select list and I need to add a new value to the list and re-order the list to satisfy the requirements of the project. The existing list looks like this:

```
1_Value A|Value A
2_Value B|Value B
3_Value C|Value C

```

The new list needs to look like this:

```
1_Value A|Value A
2_Value D|Value D
3_Value B|Value B
4_Value C|Value C

```

I realize because this field/content type already contains data, that this field cannot be edited. That being said, I suppose my question is two-fold:

1. How can I easily edit this field? What is the best way to export the data, make my modification and re-import?
2. Will re-ordering the values have any impact on the existing data associated with this content type?

# Answer
> 0 votes
I just checked a select list I have on a site with text key|value pairs under 'Allowed Values'. Although I had the message at the top that 'There is data for this field in the database. The field settings can no longer be changed.' I went ahead and altered the list, and it took the changes fine.

There should be no impact on the existing data if you change the order. Just be careful you never delete a value.

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


# Question
Title: What is the best practice for having a global collection or set number?
I am setting up a content type for a collection of samples. There is already a lot of samples that have a collection number that can't be changed, so I will have to import that data. But My question is how to apply this number; I know its a broad question, but would using taxonomy, or a field in the content type be better?

# Answer
A field would be better if the collection number must be unique. If so you can activate the Unique Field module to enforce it, then go ahead and import your existing data.

If it does not have to be unique, either will work, but I would still recommend using a text field rather than a taxonomy.
> 1 votes

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


# Question
Title: Generate image styles with a rule on "node save"?
This QA has some discussion about the lazy image loading. Imageinfo\_cache is D6 only at the moment, and rules\_image\_styles apparently runs on every node view which isn't great for performance.

Wouldn't it be possible to just create a rule that fires "on node save" and for all types that include images you'll execute PHP code to generate all image styles?

# Answer
> 1 votes
There seems to be a third module that has this ability already, however it doesn't seem to be compatible with Rules just yet. It is compatible with Trigger however (I don't know if this allows it to be automatically compatible with Rules...let me know if you find out how). Here is the module: http://drupal.org/project/ispreg

---
Tags: 7, rules, media
---


title: Insert image or link links

text:
# Question
Title: Insert image or link links
When in edit, and presented with a wysiwyg editor for example, I've got a "Switch to plain text editor" link under. However, in one of the sites, in addition to this link I also have "Insert image or link" links. But not in the other sites. Where is this setting coming from? Is it generally good practice to have these links?

# Answer
> 1 votes
There are few standard "Text formats" for a text field. Which one you actually can use depends on your permission settings (for example permission `Use the Full HTML text format`).

Then you have the settings for each of the text format (admin/config/content/formats), there you can set up what options a specific format has (you can add/remove image/link buttons).

The last thing to know is that order in which text formats are listed in the administrator page is important. It decides which text format is used as a default. A typical problem with ordering of text formats are automatic messages with broken links (result of "Plain text" format having too high priority).

# Answer
> 0 votes
At the very bottom of the IMCE configuration page (/admin/settings/imce) you'll find a section labeled: "Enable inline image/file insertion into plain textareas:"

You should be able to edit the value in this configuration field (or remove it altogether) to remove these links from your add/edit pages.

---
Tags: wysiwyg, files
---


# Question
Title: in views row-template, how to obtain rendered output of each item in multi-valued field?
I have a custom row template, and I know I can obtain the rendered field output with:

```
$field_output = $view->render_field($fieldname, $view->row_index);

```

For a certain multi-valued field, I would now like to create an array of the rendered output of each item in the field.

```
$field_output[3] = rendered field output for 3rd item in my multi-valued field

```

Anyone know how I can do this?

**UPDATE:**

There are two approaches I am aware of, but neither is a good, robust solution.

### Approach #1: get\_values()

One approach is to call get\_values, and then grab the safe\_value:

```
$vals = $view->field[$fieldname]->get_value($row);
$field_values = array();
foreach ($vals as $i=>$v){
  $field_values[$i] = $v['safe_value'];
}

```

The problem with this approach, as described here, is that (a) it breaks localization and (b) some fields do not have a safe\_value.

### Approach #2: render\_field()

The second approach (see below) uses render\_field() and then explodes the result:

```
$field_values = array();
$field_output_str = $view->render_field($fieldname, $view->row_index);
if (!empty($field_output_str)){
  $separator = ',';
  $field_values = explode($separator, $field_output_str);
}

```

The problem with this approach is that, in addition to exploding multi-valued fields, it also explodes individual fields that contain commas, such as text fields.

Does anyone have a better, more robust solution?

# Answer
If the field is multi-valued, then $view-\>render\_field($fieldname, $view-\>row\_index) returns a comma-separated string of the individual rendered items:

```
rendered_item0,rendered_item1,rendered_item2,...

```

To generate the array `$field_output_array` where `$field_output_array[2] = rendered_item2`, explode the string:

```
$field_output_string = $view->render_field($fieldname, $view->row_index);
$separator = ',';
$field_output_array = explode($separator, $field_output_string);

```
> 1 votes

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


# Question
Title: What's wrong in my code for setting up entity title in a Computed Field?
I have written inside a Computed Field's Computed Code section the following code:

```
<?php
//work if the node is new and there is no value for the field yet
if (empty($entity_field[0]['value'])) {

  do {
    //calculate a promotion code
    $new_promotion_code = strtoupper(substr(md5(rand(999, time())), 0, 5));

    //check db for conflicts
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle','gift')
      ->fieldCondition('field_gift_code', 'value', $new_promotion_code)
      ->addMetaData('account', user_load(1));
    $result = $query->count()->execute();
  } while($result > 0);

  //assign the field value
  $entity_field[0]['value'] = $new_promotion_code;

  //option#1
  //$entity->title[0]['value'] = $new_promotion_code;
  //option#2
  //$entity->title[LANGUAGE_NONE][0]['value'] = $new_promotion_code;

  //presave the node with attached fields (not sure if this is working)
  field_attach_presave($entity_type, $entity);
}
?>

```

This code works except the commented out section which includes two options for setting up same node's title. I am also not sure if `field_attach_presave()` works but I have no means to debug it and it just doesn't fail like `field_attach_update()`.

Using Auto Entity Label is also a solution but the token (`[node:field-gift-code:rawvalue]` or `[node:field-gift-code]`) for this field just prints `Array`.

Any suggestions?

# Answer
You can't do it all in the first box.

Use the Computed Code box to create a value for the field in $entity\_field\[0\]\['value'\].

Then use the Display code box to do something with this value.
> 0 votes

---
Tags: 7, entities
---


title: How to remove Powered by Drupal?

text:
# Question
Title: How to remove Powered by Drupal?
I just installed Drupal 7.2 on my localhost using xampp, made some pages, and installed a theme, I'm also modifying the CSS of the theme to my own convenience.

My front page has (at the end of the content, not the footer) a "Powered by Drupal" written over there. In WordPress I would just edit the content PHP file, and delete that; with Drupal, I can't find where the line is located.

I thought the index.php would give me some ideas, but I think Drupal works differently.

How exactly do I find my front page in the directories? I have a c:\xampp\htdocs\drupal7 main directory.

# Answer
> 3 votes
Drupal constructs the pages you see using blocks and nodes through a template file. To find that text, look in menu option "website information", next if not found look in the block list for a block placed in copyright or footer area.

Drupal will depend on block/regions; learn that too. Finally, when that doesn't work, in /sites/all/themes/ you'll find the PHP and HTML files delivering the themed page.

---
Tags: 7
---


# Question
Title: simple numeric token string 2 max 3 digits
I need to generate numeric string and append it at the end of node url. Tried using some token random number options but the result is 10 digit number which is not neccessary for my purpose. Is there any other option? Node NID is not possible to use. Thank you

# Answer
> 0 votes
```
$length = 3; // character length
$token = substr(drupal_hmac_base64($node->nid, drupal_get_private_key() . drupal_get_hash_salt()), 0, $length);

```

---
Tags: 7, tokens
---


# Question
Title: How do I put form field sets in jQuery UI tabs?
I have created a custom form in a module via Form API. The form sits in a page created by hook\_menu, which calls a function that renders the form from a form builder function. Also included in my module is a form submit function.

Currently, my form is divided into field sets that can be collapsed and expanded. It would be a lot nicer if the field sets were in tabs. To acheive this I intend to use jQuery UI tabs with the following code snippet:

```
drupal_add_library('system', 'ui.tabs');
drupal_add_js('
(function($) {
    $(function() {
        $( "#tabs" ).tabs();
    });
})(jQuery);
', 'inline');

```

I know I can put the other required markup in #prefix and #suffix properties in the $form array to wrap the field sets in tabs - but where does the above code go in the module? Should I be using hook\_node\_view or hook\_view or something to ensure that jQuery UI tabs are initialised on my form page?

Thanks

# Answer
If you're adding javascript for a specific form, use

$form\['#attached'\]

e.g:

```
$form['#attached']['library'][] = array('system', 'ui.tabs');
$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/my_module_init.js',
);

```

You might also be interested in field\_group, which provides jquery tabs etc.. for entity forms
> 0 votes

---
Tags: forms
---


# Question
Title: How to delete/remove Views display programmatically?
Any idea how can I remove or delete Views display programmatically?

I have a Views that has 5 displays and I want to delete one of them. For the sake of avoiding manual intervention I want to do it automatically via code. Is there a way to do that?

# Answer
Here is an example you would put in mymodule.install

```
/**
* Disable workbench views
*/
function mymodule_update_7001() {
    // an array of views (their view name) I want to disable
    $viewnames = array(
      'workbench_current_user',
      'workbench_edited',
      'workbench_moderation',
      'workbench_recent_content',
    );

    // grab the array of views that are already disabled
    $views_status = variable_get('views_defaults', array());

    // add our views to be disabled to the list
    foreach ($viewnames as $key => $viewname) {
      $views_status[$viewname] = TRUE;
    }

    // reset the variable with the new list
    variable_set('views_defaults', $views_status);

    // empty cache now
    if (function_exists('views_invalidate_cache')) {
      views_invalidate_cache();
    }
}

```
> 2 votes

---
Tags: views, 6
---


# Question
Title: Restricting Field List Entries Based on User Role in Drupal 7
I'm using the Field permissions module in Drupal 7 to restrict access to a list field I created based on the user's role and that works great. But is there a way to restrict the content of that list based on the user role?

For example:

for user role 1, I want the custom field list to show:

Apple Banana Grape Orange

for user role 2, I want the custom field list to show:

Apple Grape

# Answer
> 2 votes
There is a contributed module available in drupal.org 'Field Permissions' .

http://drupal.org/project/field\_permissions We can set the field permission based on user role.

Hope this will help you.

# Answer
> 0 votes
You have to hook on hook\_form\_alter and modify options depending on the role. I see no non-programming way.

---
Tags: entities, users
---


# Question
Title: How to translate only the interface back to English?
My site default language is Hebrew (RTL), the problem is that it's all the site, and I want my sites admin-interface to be in English (American). how could I re-translate it to English?

# Answer
> 4 votes
There is a module for that: Administration Language.

> This module lets the administrator see all administration pages in his/her preferred language.
>
> You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).
>
> You can use the standard Languages page to choose the language of the admin pages.

---
Tags: i18n-l10n
---


# Question
Title: Display count of nodes from the parent terms of a taxonomy where dummy nodes are based on the child terms of the parent terms of taxonomy
'State' is the vocabulary of my taxonomy where North, South, East & West are parent terms with child terms like Montana, Texas, New York, Washington respectively which are states of USA.

I've created some dummy nodes on based of the child terms from taxonomy, is there any way to display the count of nodes from the parent terms of that taxonomy, so that the result would be something like North 10, South 5 and so on

# Answer
Although this is an old question, I just had to do something similar and decided to share the steps (I'm using views 3):

1. Create a **content view** listing your nodes.
2. **Add** a relationship **"Content: Taxonomy terms on node"**, limit this to the "States" vocabulary and give it an Identifier like **"term\_on\_node"**.
3. Now add another **relationship "Taxonomy term: Parent term"** using the "**term\_on\_node**" relationship defined in the previous step. Name this one **"parent\_term"**.
4. Enable **"Use aggregation"**.
5. In "Format" select to **show** fields.
6. Add the following fields:
    * "**Taxonomy term**: Name" using "parent\_term" relationship
    * **"Content: Nid"**
7. For "Content: Nid" click **"Aggregation settings"** and select **"Count DISTINCT"**

Now this view should display your parent terms with the number of nodes assigned to each parent's children.
> 0 votes

# Answer
Try creating a Taxonomy View with the following settings.

* field: taxonomy term/id
* filter: taxonomy vocabulary; states vocabulary
* contextual filter: taxonomy term parent; display summary, show link w/ count, set a base url for link

I have done something similar with a contextual filter of Taxonomy Term/ID and it works fine. Should work with Term Parent. you might have to add a relationship to content as well, not too sure but that should get you started. Good luck!
> 0 votes

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


# Question
Title: Search engines tries to access node editing links
In my dblog occassionally I am seeing query coming probably from search engines for links as

http://mydomain.com/node/13130/delete?destination=node

I wonder how possibly search engine got idea to query that kind of links (of course those links are not exposed to anonymous users)

I have xml sitemap installed but no such links exists in the index

When I query google for that link, I see that link is present in index (of course clicking on that link leads to access denied page), and also shows

*A description for this result is not available because of this site's robots.txt*

# Answer
> 2 votes
One possibility is that one or more logged-in users have Google Toolbar or something similar installed. I don't have it installed any more because I noticed when developing locally that every time I fetched a page in my browser the request was repeated by the toolbar, presumably sending it to Google.

In my experience there is no such thing as a non-public URL as far as Google is concerned. Any URL can be listed for indexing and so crawlers may attempt to fetch it from time to time. I suspect other tools may record URLs in a similar manner.

---
Tags: security
---


# Question
Title: How to add inline Javascript code properly with drupal_add_js for a Drupal Commerce checkout pane?
I have a custom checkout pane with a basic validation callback. That pane function `commerce_checkout_xyz_pane_checkout_form` adds some inline Javascript code with `drupal_add_js()`.

**The problem**, that Javascript only appears on the initial form and is not added when the form is shown again after failed validation.

I thought about moving the `drupal_add_js()` to a `$form['#after_build']` callback but I don't know if that's the right thing to do and how to do it.

# Answer
> 1 votes
Presumably you're using hook\_commerce\_checkout\_pane\_info

Try using $form\['#attached'\] to add your js to the checkout pane form instead. That may work better there.

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . '/checkout_pane.js',
);

```

# Answer
> 0 votes
I ended up using this inside the validation callback function:

```
if( empty($foo) ) {
    $form_state['#rebuild'] = TRUE;
    form_set_error('foo', t('Foo error'));
}

```

---
Tags: hooks, commerce
---


# Question
Title: How to create multi select list programmatically
How to create a multi select list in a custom module, populate values from taxonomy term and access the selected values when the form is submitted.

I have to code below for multi select list. I want to know how to access the multiple selected values from multi select list when the form is submitted.

```
function rice_graph_form($form, &$form_state) {
  $form['country'] = array(
  '#title' => t('Country'),
  '#type' => 'select',
  '#multiple' => true,
  //'#description' => 'Select a Country.',
  '#options' => rice_graph_get_terms('country')
  );
  if(isset($form_state['values'])) {
    $multivalues = $form_state['values']['country'];
  }
}

```

# Answer
> 1 votes
In your submit handler add something like this:

```
$selected_countries = array_filter($form_state['values']['country']);

```

`$selected_countries` will contain the array keys of all the selected items in your Country select list. You need the `array_filter` to get rid of unselected items, which also come through to the submit handler but with a value of `0`.

---
Tags: forms
---


title: When is hook_file_download triggered

text:
# Question
Title: When is hook_file_download triggered
I wonder which files are being considered to go through hook\_file\_download. When this function is triggered, what are conditions ?

(Generally, how I can track myself hooks conditions ?)

I am trying to put some custom created download links (files are not uploaded via drupal, but link to them are defined manually, as described in this issue.)

**EDIT:** For those searching for hook\_file\_download related issue, it seems that it is triggered (also) whenever you try to access a valid link to a file in private filesystem.

# Answer
> 4 votes
The easiest way to track where core hooks are called, from core code, is to look on the docs page.

For `hook_file_download()`, you'll see this:

A nice list of all implementations/invocations of the hook with links to the relevant functions.

For the cases that don't get covered there, I usually just grep the codebase for, e.g.

```
module_implements('file_download'

```

That takes me straight to file.inc, and the `file_download()` function, which I guess answers your main question.

If that's not quite enough, I thoroughly recommend using Eclipse/Netbeans with XDebug which will let you set breakpoints to see what's happening in more depth.

---
Tags: hooks
---


# Question
Title: How to prevent accidental clicks in the Save button when saving a node?
I need to prevent accidental clicks in the Save button when a node is being saved.

I found this module which does exactly this. But the problem is that it uses javascript (jquery). Then if the user disable javascript this module is useless.

My problem is that in my website the user get points when creating nodes, so I have to prevent this in a more secure way.

How can I do this?

What do you think of these ideas?:

1) Maybe I would forbid the node being saved more than one time programmatically instead of disabling the Save button.

2) Or better: I would allow the user to just save a new node every 5 minutes.

# Answer
Finaly I got this using these 2 modules:

http://drupal.org/project/hide\_submit (to prevent clicking the bottom using jquery)

and

http://drupal.org/project/node\_limit (just for browsers with javascript disabled) This allowed me to set a time interval limit to post new nodes.
> 1 votes

# Answer
You can use confirm\_form() to confirm the users submit instead of hiding save button so that user will get chance to think whether he really wants to submit and not accidental click on save button. You need to alter the form on which you need to confirm.
> 0 votes

# Answer
Use the 'form\_build\_id' to prevent duplicate submissions. This is located at

```
$form_state['input']['form_build_id']

```

(drupal-7) and is generated with each form load.

See created module: http://drupal.org/sandbox/interlated/1963144.

A database table or widget field would be required to store it with each submission. Ideally the table holding the field would be locked. In a validation callback or node\_save hook. A specific field per content type to prevent too much locking. The validation messages drupal\_set\_message() saying that multiple submissions were detected would still display. In practice the locking may become too cumbersome, so a cron job is required to clean it up.

There is a fair bit of code required. Create a module, then register field, widget, formatter. Create a widget form with a validator, write the validator. Finally write a cron job to delete duplicate nodes, or at least delete duplicate tallied points. Add the created field to your node.

Firstly, set up a constant.

ognotify.info

```
files[] = includes/OgNotifyManage.inc

```

In the declared file:

```
class OgNotifyManage {
  const field_id = 'duplicate_token';
}

```

In the .module file:

```
/**
 * Define the field definition for the node editing form.
 */
function ognotify_field_info() {
  return array(
    OgNotifyManage::field_id => array(
      'label' => t('Token'),
      'description' => t('Record tokens to reduce duplicates.'),
      'default_widget' => OgNotifyManage::field_id,
      'default_formatter' => OgNotifyManage::field_id,
    ),
  );
}

/**
 * Define the field for sending invitations.
 */
function ognotify_field_widget_info() {
  return array(
    OgNotifyManage::field_id => array(
      'label' => t('Detect Duplicates'),
      'field types' => array(OgNotifyManage::field_id),
    ),
  );
}

/**
 * Implements hook_field_formatter_info().
 */
function ognotify_field_formatter_info() {
  return array(
    OgNotifyManage::field_id => array(
      'label' => t('Default'),
      'field types' => array('duplicate_token'),
    ),
  );
}

/**
 * Define whether the field is empty. This is required by field API and
 * determines whether the field is to be saved.
 */
function ognotify_field_is_empty($item, $field) {
   // items. No applicable concept of empty.
   if (empty($item[OgNotifyManage::field_id])) {
      return TRUE;
   }
  return FALSE;
}

function ognotify_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element[OgNotifyManage::field_id] = array(
    '#tree' => TRUE,
    '#type' => 'fieldset',
    '#theme' => 'ognotify_form',
    '#weight' => 10,
    '#element_validate' => array('ognotify_duplicates_validate'),
  );

  return $element;
}

function ognotify_duplicates_validate($element, &$form_state) {
  // Finally do some entity queries for our form token
  // We can do a rough first check for duplicates here, but cannot guarantee
  // that another node has been saved while we are checking without locking the
  // field table.

  // Save the form token in the form.
  form_set_value($element, $form_state['input']['form_token'] , $form_state);
}

function ognotify_cron() {
  // Do queries for nodes with duplicate form tokens.
}

```

It looks like a standard module. Let me know if you agree and I could help create it.

I was surprised that drupal doesn't just do this. The token answer is a good one.
> 0 votes

---
Tags: nodes
---


# Question
Title: how to add html/ccs element s inside drupal mail function
I am developing function that send a email to user..,and i want to add some html.css styleing to the email how can i achive that folllwing is my code i tried

```
function zgcrons_mail ($key, &$message, $params) {
  switch ($key) {
  case 'mymail':
    // Set headers etc
    $message['to'] = $usermail;
    $message['subject'] = t('Your Donation Statues ');
    $message['body'][] = '<table width="100%" cellspacing="0" cellpadding="10" border="0">
    <tbody>
    <tr>
        <td valign="middle" style="border-collapse:collapse;border:0" colspan="2">
            <div style="color:#585858;font-family:Georgia;font-size:12px;line-height:125%;text-align:center">
                <a target="_blank" style="color:#ee3524;font-weight:bold;text-decoration:underline" href="http://www.twitter.com/ZealousGood/">follow on Twitter</a> |
                <a target="_blank" style="color:#ee3524;font-weight:bold;text-decoration:underline" ref="http://www.facebook.com/ZealousGood2011">friend on Facebook</a>
            </div>
        </td>
    </tr>
    <tr>
        <td width="372" valign="top" style="border-collapse:collapse">
            <div style="color:#585858;font-family:Georgia;font-size:12px;line-height:125%;text-align:center">
                <em>Copyright © 2012 Zealous Good, All rights reserved.</em>
                <br>
            </div>
        </td>
    </tr>
    </tbody></table>';
  break;
  }
}
drupal_mail('zgcrons', 'mymail',$usermail, $language, $params = array('username' =>'John Potato'), $from = NULL, $send = TRUE);

```

# Answer
> 2 votes
Your way will work if you enable the html format for email in your website. By using http://drupal.org/project/htmlmail or http://drupal.org/project/mimemail that will help you format the email in html and choose which method that will use for sending email.

---
Tags: 7, forms, emails
---


# Question
Title: How Can I add a Hierarchical taxonomy Select in views filters and when editing content in Drupal 7
I have created a taxonomy vocabulary called Cars makes and models with a structure similar to this:

```
    -Car Make
    ----Car model
    -----------Year

```

I want to give the customer, options to sort them in a View , like many cars sites do: a customer choose first the Car make, and automatically models from this make shows in a second level list. But I want also to use this functionality in the (add content )page, so when customer try to sell a car, he will not need to scroll a very large list with makes and models in the same field. I cannot use Hierarchical Select. As many topics in this site suggest, because it doesn’t work for exposed filters in Views, with Drupal 7: http://drupal.org/node/1170192

I have spent hours and days, trying to fix this issue without any success, my options are very limited:

1. Turn back to Drupal 6, Just to use HS with Views exposed filters. (not a brilliant idea)
2. Use other CMS like Joomla, in fact there is many Joomla plugins offering this functionality: http://extensions.joomla.org/extensions/vertical-markets/vehicles , but then I will lose all the power of Drupal taxonomy.
3. Add autocomplete functionality to the views filter and Use Autocomplete term widget , in the (create content page) , but this is not very user-friendly method for no experimented users. More, Autocomplete term widget will allow the creation of new terms, and I do not want users to accidentally create new terms when they enter an incorrect model or make in the field. Maybe I can correct this using Content Taxonomy module(http://drupal.org/project/content\_taxonomy), which can deny the creation of new terms. But this is not a global solution to my problem.

Is there a module or any JavaScript or PHP snippet to fix this ?

# Answer
Response is late but I think(/hope) accurate. You can use the "Simple hierarchical select" http://drupal.org/project/shs. With the help of this module you can make use of the hierarchical select functionality both through views-\>exposed filters and of course when adding content.

> The widget is available in node forms and as Views exposed filter.
> 3 votes

# Answer
I've got a similar situation. What I currently do isn't perfect (it'd be better if it was the same on the admin side as the public-facing side) but it works:

I'm not a big fan of the javascript tree library they suggest in that Better Exposed Filters issue, it takes a bit of modifying to get satisfying results, but it does work.

If you've got the time, I'd try a few different tree libraries to use with Better Exposed Filters, or, trying to make the one bundled with Term Reference Tree work with it. If you get something working really satisfyingly well on the front end, I'm sure a comment here would be appreciated :)
> 2 votes

# Answer
Use Hierarchical Select module.
> -2 votes

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


title: clickable links in revolving banners

text:
# Question
Title: clickable links in revolving banners
I am a newbie to Drupal 7.21. I have got as far as creating a rotating banner for my front page. Now I want to have a clickable link from each banner to a new page that gives more information about each banner topic. The banners automatically pause nicely when the mouse hovers over them, but I can't find a way to get the link attached to the image. Can anyone help? Thanks Andy

# Answer
> 1 votes
There is a combination of modules listed on the site HOW TO INSTALL & SETUP VIEWS SLIDESHOW MODULE ON DRUPAL7? that will allow you to do that.

Effectively the modules work together to give you:

* A content type where you can store your banner and the URL
* A view that has some nice JQuery slideshow options for displaying rotating banners that will link to their included URL

# Answer
> 0 votes
There should be a few ways to do this but it really depends on what you want to do.

You can link directly to the node. so if your content node has an image field, simply create a new view and add a new filter to the `fields` section. in the configuration screen, select the `link image to: content` drop down. this should make the image link directly to the node.

the other option is to not have the image link back to the node but another url (can be an internal and external link). for this one, you'll add a content fields filter again. select your image field and in the configure screen, go to the `rewrite results` collapsed section. from there you'll see a check box for `Output this field as a link`. check that and then adjust your link path. you can use a classic url (http:/blah.com/blah) or you can use a replacement pattern.

---
Tags: 7, views, blocks
---


# Question
Title: Showing unpublished content to the anonymous creator
I am working on a Drupal 7 module called Anonymous Publishing. In brief: It lets the anonymous user create posts.

The anonymous user create contents using the standard content creation `node_form`. When the user press save, Drupal automatically creates and loads the node. However, since the node is unpublished at this point, the user just gets an access denied message. I want to avoid this, and instead show the user the node just created. I've so far only managed to do this with this rather nasty kludge in a hook\_node\_grants():

```
$result = db_query("SELECT created FROM {node}
   WHERE nid = :nid", array(':nid' => $nid))->fetchField();
$delta = time() - $result;
if ((0 == $account->uid) && ($delta < 20)) {
  $grants['anonymous_publishing'] = array(1);
}
return $grants;

```

What the above code does is this: It checks the age of the node, and if it was created less than 20 seconds ago, it grants the anonymous user the right to view it.

While this *works* (sort of) it is ugly and it may even expose the content to someone else if there is *another* anonymous user around that requests the content within the same 20 second window.

Any suggestions for a *better* solution?

# Answer
You can (relatively) safely store per-user data for anonymous users in $\_SESSION. So if you intercept the node page view callback and add some extra code in there for the case in question (falling back to the core function), you should be able to achieve what you are after.

To elaborate: when you save the node in question, save its ID and an expiry timestamp in an array in the session, via a hook\_node\_insert. In the new callback check if that entry exists and has not expired. If present, fetch the node and display it. Otherwise call the regular node view callback.
> 2 votes

# Answer
In Drupal 7, users are not allowed to view any unpublished content by default, not even content created by themselves. By enabling 'View own unpublished content', you grant users access to their own unpublished content.

The only way to allow users access to all unpublished content in Drupal 7 (without using a contributed module), is to enable the permission 'Bypass content access control'. Use this permission with extreme caution as it has far more consequences than just allowing access to unpublished content. In combination with Organic Groups for example, this permission allows access to private group content regardless of whether the user is a group member.

The module View unpublished allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard. Additionally, using this module does not require any modifications to your existing URL structure.

\[source\]
> 0 votes

---
Tags: users
---


# Question
Title: Is it safe to purge the /files/styles directory?
I use Image Styles to automatically generate thumbnails (for teasers and views). I have a lot of images, so I end up with a lot of cached thumbnails in the `/files/styles` directory.

Is it safe to delete the contents of `/files/styles` without doing anything like clearing the cache in Drupal? My hope is that the thumbnails would be regenerated as needed without issue.

# Answer
It's perfectly safe to delete the *files/styles* directory. Drupal will regenerate the images the next time someone accesses them.

The Image module defines a menu router item which maps `$directory_path . '/styles/%image_style'` to `image_style_deliver()`. `image_style_deliver()` verifies the generated derivative image exists. If it does, it serves it; otherwise, it calls `image_style_create_derivative()`.
> 9 votes

# Answer
If you have lots of images, deleting everything inside files/styles is not recommended because regenerating this can have a large performance impact.

I usually run a cron to keep it clean:

```
0 1 * * * find /var/www/<project>/sites/default/files/styles -type f -atime +30 -delete

```

This only deletes files that were not accessed in the last 30 days.
> 5 votes

# Answer
It is safe to delete them. When you clear the image cache all it is doing it deleting the files in the cache directory. If a request for an image cache file is made and the said image cache file does not exist it will be generated as long as the source file still exists. Do not the delete the source files as this will cause errors.

If you can I would suggest installing Drush. It's a command line tool for a large number of Drupal management features. You can clear cache, download modules, backup your database etc...
> 1 votes

---
Tags: 7, caching, media
---


# Question
Title: Mobile Tools detects mobile and iPad, not Android tablet
I have used the Mobile Tools module for Drupal 6 to distinguish between mobiles,tablets and browsers. I am not using themes, just provided the redirection urls from the drupal admin settings.

The aim is to redirect to mobile site while accessing from mobile(mysite.com/mobile). Must redirect to the existing site while taken from tablet and web browsers(mysite.com). It works fine for iphone,andorid mobile,blackberry and iPad.

But it redirects to mobile site when taken from Android tablet while I need to redirect to the desktop url.

Can anybody suggest how can I handle the android tablet using mobile tool so that it does not get redirected to mobile site?

# Answer
Have you looked at ThemeKey? It has OS based redirection rules. Here is a quote about it (from the module's project page):

> ... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server
> 1 votes

# Answer
Finally, I made some modification in the mobile tool file to work for android tablet and it seems to be okay now.
> 0 votes

---
Tags: 6, mobile-tools
---


# Question
Title: How do I list my profile in the profile list after downloading the Drupal distribution with drush make?
I am creating a profile for my site.

So I basically have the following files:

```
myproject.info
myproject.make
myproject.profile

```

Evertime I run

```
drush make myproject.make

```

the drupal files + modules are copied but during install I only see the profiles: standard and minimal.

**How to make my profile myproject visible in the list?**

UPDATE:

I copied my profile inside the profile folder of a Drupal installation. Now my profile is being listed. But I prefer this should be done from a script.

I asume I should edit the make file to copy the new profile inside the profile folder. I am not sure this can be done from within the make file therefore I assume should run a .sh file instead.

I am waiting for some suggestions.

# Answer
> 1 votes
You need a custom sh file that does the drush make, and moves the profile files for you.

---
Tags: users, distributions
---


title: Redirection to home page

text:
# Question
Title: Redirection to home page
I am working on a Drupal site. I have put a "Create an account" block on one of my content pages. After the form is submitted the user is redirected to the home page. I want to reload the same page on submit. Can anyone help me out with this.

# Answer
Download and install this module http://drupal.org/project/login\_destination

It is also possible to keep users on the currently visited page after logging in or out.

Hope it will match your requirement!!!
> 0 votes

---
Tags: forms
---


# Question
Title: How do I not cache dynamic content but cache everything else (or similar workaround)?
I have a production site with page caching enabled (this is not negotiable). One very popular feature requires dynamic content to be queried from an external socket and displayed; this content is required to be fresh at all times and cannot be cached. Current implementation has a vanilla, non-Drupal .php script polling the socket, whose output is either pulled into the page via javascript, or put in an iframe if no js. The vanilla .php is not cached by Drupal, but the rest of the page (menus etc.) is cached. It's fast.

Due to new requirements, the hard-coded config in the vanilla .php must instead be configurable through the Drupal UI. I have a working admin implementation, and have brought the socket-polling code inside the Drupal module. It's slow.

Putting the dynamic content in a block with DRUPAL\_NO\_CACHE doesn't help, because the whole page is being cached, ignoring block-level settings. Excluding the whole page (including menus etc.) from the cache will not meet performance requirements. I don't think I can use the javascript/iframe trick again, unless there's a way to get Drupal to render a minimal uncached page without building any of the rest of the site. Using 'print $my\_html;' in the hook\_block\_view rather than 'return $my\_html;' renders a page with just the dynamic content, but it performs slowly enough that I think Drupal is doing a lot of unnecessary work. Is there a better way of rendering a very-minimal page while still having access to e.g. variable\_get()?

Is there a better way to approach this? Being able to set block caching independently of its parent page caching would be nice...

(Using local dev servers, a fully uncached page takes about 1000ms to render. The 'minimal print-don't-return' page takes about 400ms. The actual module code for getting the dynamic content takes 6ms of this. A fully cached page renders in 20ms.)

# Answer
> 0 votes
"unless there's a way to get Drupal to render a minimal uncached page without building any of the rest of the site"

There's the clue - yes, there is. This is what AJAX callbacks do, after all. In your menu callback you print the desired output instead of returning it, and return NULL. IIRC, the result won't be subject to page caching either, but if it is, you can use the cache exclude module to ensure it is not cached.

---
Tags: caching
---


title: New action for Views Bulk Operations

text:
# Question
Title: New action for Views Bulk Operations
I'm trying to add some custom actions to my `Views Bulk Operations`, but for some reason, they don't appear in the list.

This is my code (got it from Drupal.org, so I guess this is a working code...)

```
function publication_action_info() {
  return array(
    'node_unpublish_action' => array(
      'description' => t('Unpublisedh node--'),
      'type' => 'node',
      'configurable' => FALSE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
    'node_unpublish_by_keyword_action' => array(
      'description' => t('Unqsdfqsdfpublish node containing keyword(s)--'),
      'type' => 'node',
      'configurable' => TRUE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
  );
}

```

So what's wrong with my code or logic to make this thing to work?

# Answer
Try to use configuration\>\>Actions and create new actions
> 5 votes

# Answer
Here is the way, I found for D7...

```
/**
 * Implementation of hook_action_info().
 */
function MODULE_action_info() {
   $action = array(
    'MY_ACTION_NAME' => array(
      'label' => t('MY ACTION LABEL.'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
 );
 return $action;
}

/**
 * Action function for MY_ACTION_NAME.
 */
function MY_ACTION_NAME(&$entity, $context = array()) {
  // Your code here.
}

```

Now just add the action MY ACTION LABEL in VBO list.
> 12 votes

# Answer
Just a note -- For Drupal 7, IMO @tanmayk's answer is best -- define the action in your custom module using hook\_action\_info() and the action will then appear in the Configuration \> System \> Actions window as well as in the VBO list.

But remember that you have to permit the user to use the action (People \> Permissions)! Thanks to @autopoietic for triggering that memory.
> 2 votes

# Answer
Try using triggers

```
'triggers' => array('node_presave', 'node_insert', 'node_update'),

```

instead of

```
'hooks' => array(
    'node' => array('insert', 'update'),
 ),

```

Here is worrking exaple of action.

```
'action_example_node_sticky_action' => array(
      'type' => 'node',
      'label' => t('Action Example'),
      'configurable' => TRUE,
      'triggers' => array('node_presave', 'node_insert', 'node_update'),
),

```

See action\_example in Examples for Developers for more details

Also this article can be usefull: Views Bulk Operations (VBO) development guide.

But notice:

> This guide applies to Drupal 6 only, last updated for release 6.x-1.13
> 0 votes

# Answer
Try permitting all hooks, rather than just node actions.

```
'hooks' => array('any' => TRUE),

```
> -1 votes

---
Tags: 7, actions, views
---


# Question
Title: Why doesn't "Allow multiple values" in Views' Contextual Filter work?
I'll try to explain this as simply as possible...

I'm using the Views Datasource plugin to create a JSON view to output a restaurant list.

We need to be able to filter the list via several fields - We'll just use "Cuisine" as an example.

I setup a contextual filter and when I browse to the view with "/sushi" at the end of the URL, I get only the results with Sushi in the Cuisine field. This is working correctly.

However, the Cuisine field can hold several types, such as "asian," or "carryout," or whatever.

Now, when I select "Allow multiple values," I SHOULD be able to browse to the view with "/sushi+asian" and get anything with either Sushi or Asian in the cuisine.

Instead, I get NO results.

I'm running out of hair to pull out - Anyone got any ideas? I'm at a total loss.

-- UPDATE --

Here's some SQL Query stuff - I've stripped everything but the WHERE clause as this is the only place where anything changes.

```
### WITHOUT MULTIPLE VALUES CHECKED ###

// Ran "/restaurants/all/$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

// Ran "restaurants/all/$+$$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$+$$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

### WITH MULTIPLE VALUES CHECKED ###

// Ran "restaurants/all/$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

// Ran "restaurants/all/$+$$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$+$$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

```

Obviously the query isn't changing regardless of whether I tell it to allow multiple values - How do I get this to take values separated by a + and make them ('$', '$$')?

# Answer
Try using commas instead of plus signs, i.e. sushi,asian,italian since some apache configs do not support plus signs. Slashes should only be used between different contextual filters like cuisine and street, etc.

Also, make sure to check that the operator between filters is set to and not or. hth.
> 1 votes

# Answer
Instead of `/sushi+asian` use a `/` to separate your arguments `/sushi/asian`
> 0 votes

---
Tags: views
---


# Question
Title: Dynamic Taxonomy Filter dropdown with childs in Drupal 7
For a while I'm trying to sort this but no luck

I need exact same filter like here http://www.pets4homes.co.uk/

I have pet types as taxonomy terms and breeds as child\`s. I want to accomplish same thing like on that website, when I select dogs I want just dogs breed to be on second dropdown. Location is not needed but if you know the way to add it even better, but now I'm focusing on dropdowns.

Already I tried with Simple Hierarchical Select module and Hierarchical Select but I just can't set it up to work like I want, or I don't know how to set up it properly.

With SHS module I have one dropdown with pet type and when I select it than other dropdown shows up, but I need it to be all the time there, and that is not possible with this module as I read it in issues of that module.

# Answer
You need to use Ajax and the drupal form api to build this type of search form.

I recommend looking at the Taxonomy Edge module to make "finding the children terms of some parent" really easy, because the SQL can be annoying. Then you can just focus on the Ajax needed. Drupal has great support for Ajax!

I recommend looking here on drupal.stackexchange to find ajax examples of which there are plenty. I'm nearly positive there is an example of this type of ajax "update the form with some new options or div" in the Drupal 7 Developer Examples module.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I add a menu subtitle to field sets displayed as vertical tabs?
I have formatted my field sets in a form builder function to display as vertical tabs. Here's a snippet of my code. It works fine:

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

// * Form elements: fieldset tree.
$form['episode'] = array(
    '#title' => t('Episode details'),
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'vertical_tabs',
);

```

I see a lot of vertical tabs with, let's call it, a menu subtitle just below the menu title. It's the grey text under the blue anchor text in this pic from the vertical\_tabs module page - the top one reads 'Create new revision':

I guessed, wrongly, that adding a #description attribute with my menu subtitle would add it in, but is just appears at the top the field sets' tab contents. Does anyone know how this is done?

Thanks

**SOLUTION**

Some may consider this not to be the 'correct' Drupal way, but this is simple, requires hardly any code, resides in the Sites folder (so it won't be over written on update), and does not require editing any core files. Just a bit of CSS. This is what I did:

```
.vertical-tabs ul.vertical-tabs-list li:nth-child(1) .summary:after {
  content: 'Menu subtitle 1';
}
.vertical-tabs ul.vertical-tabs-list li:nth-child(2) .summary:after {
  content: 'Menu subtitle 2';
}

```

Clive's answer (see below) may be a better option if you're handy with JavaScipt.

**ANOTHER SOLUTION**

Here, is a jQuery solution I've developed:

Add this jQuery file to your module directory, call it jquery.YOURFILE.js:

```
/**
 * Vertical tabs summary setters.
 */
(function( $ ) {
  $(function() {
    $( ".summary:gt(0)" ).html( "Foo" );
    $( ".summary:gt(2)" ).html( "Bar" );
  });
})( jQuery );

```

Here I used the `.gt` method, but you could target tabs individually with the `.eq` method. In your form element definition, where you define your fieldsets, add:

```
'#attached' => array(
  'js' => array(drupal_get_path('module', 'YOURMODULE') . '/jquery.YOURFILE.js'),
),

```

**MORE SOURCES OF INFORMATION**

See the vertical\_tabs examples module for another way to do this.

Look in content\_types.inc and content\_types.js in the node module too.

This is an update of the jQuery file above. It uses Drupal.behaviors and the eq method. Probably more 'correct' than the one above.

```
(function ($) {

Drupal.behaviors.yourModule = {
  attach: function (context) {
    $( ".summary:eq(0)" ).html( "Foo" );
    $( ".summary:eq(1)" ).html( "Bar" );
    $( ".summary:eq(2)" ).html( "Baz" );
  }
};

})(jQuery);

```

# Answer
The tab summary is set by JavaScript (I don't think you can do it in PHP), per the comments in misc/vertical-tabs.js:

> Each tab may have a summary which can be updated by another script. For that to work, each fieldset has an associated 'verticalTabCallback' (with jQuery.data() attached to the fieldset), which is called every time the user performs an update to a form element inside the tab pane.

The node module has a good example of how to do this, the code in node.js should be pretty easy to adapt for your own module:

```
Drupal.behaviors.nodeFieldsetSummaries = {
  attach: function (context) {
    $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) {
      var revisionCheckbox = $('.form-item-revision input', context);

      // Return 'New revision' if the 'Create new revision' checkbox is checked,
      // or if the checkbox doesn't exist, but the revision log does. For users
      // without the "Administer content" permission the checkbox won't appear,
      // but the revision log will if the content type is set to auto-revision.
      if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) {
        return Drupal.t('New revision');
      }

      return Drupal.t('No revision');
    });

    ...

```

I think the only PHP change you'll need to make is to add a specific class to the fieldset so the JS can target it:

```
$form['episode'] = array(
  '#title' => t('Episode details'),
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#collapsible' => TRUE,
  '#group' => 'vertical_tabs',
  '#attributes' => array('class' => array('mymodule-node-options')),
);

```
> 2 votes

---
Tags: forms
---


# Question
Title: Unable to send e-mail via sendmail, because User is unknown
```
*hostname.domain.com is substituted throughout for my actual subdomain*

```

## My Setup

I have **Drupal 7.14** on an **OpenVZ VPS** running **Ubuntu 11.10** (also tested with 10.04). Ubuntu has installed the repository versions of Apache2/php5/mysql, (**not the LAMP metapackage**) with php5.ini configured to dump all error messages to `syslog`.

## My Problem

Consistently, when the site is to send an email to any address, it returns:

> Unable to send e-mail. Contact the site administrator if the problem persists.

And the Drupal Error in 'Recent log messages' readds:

> Error sending e-mail (from noreply@hostname.domain.com to noreply@hostname.domain.com).

This Error shows in the Drupal logs no matter what address the email is being sent to.

*The email does actually end up sending after a short delay.* Usually 1 second, but also 6 or more seconds.

## Contents of Syslog

```
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: Authentication-Warning: hostname.domain.com: www-data set sender to noreply@hostname.domain.com using -f
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: from=noreply@hostname.domain.com, size=649, class=0, nrcpts=1, msgid=<201209211322.q8LDMYe9001648@hostname.domain.com>, relay=www-data@localhost
Sep 21 13:22:34 hostname sm-mta[1649]: q8LDMYxB001649: from=<noreply@hostname.domain.com>, size=1023, class=0, nrcpts=1, msgid=<201209211322.q8LDMYe9001648@hostname.domain.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: to=newuser@fakedomain.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30649, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LDMYxB001649 Message accepted for delivery)
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: Authentication-Warning: hostname.domain.com: www-data set sender to noreply@hostname.domain.com using -f
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: from=noreply@hostname.domain.com, size=465, class=0, nrcpts=1, msgid=<201209211322.q8LDMYgo001653@hostname.domain.com>, relay=www-data@localhost
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0G001654: <noreply@hostname.domain.com>... User unknown
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: to=noreply@hostname.domain.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30465, relay=[127.0.0.1] [127.0.0.1], dsn=5.1.1, stat=User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0G001654: from=<noreply@hostname.domain.com>, size=465, class=0, nrcpts=0, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: q8LDMYgp001653: DSN: User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: <noreply@hostname.domain.com>... User unknown
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgp001653: to=noreply@hostname.domain.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31489, relay=[127.0.0.1] [127.0.0.1], dsn=5.1.1, stat=User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: from=<>, size=1489, class=0, nrcpts=0, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgp001653: q8LDMYgq001653: return to sender: User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0K001654: from=<>, size=4700, class=0, nrcpts=1, msgid=<201209211322.q8LDMYgq001653@hostname.domain.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgq001653: to=postmaster, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=32513, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LDMY0K001654 Message accepted for delivery)
Sep 21 13:22:34 hostname sm-mta[1655]: q8LDMY0K001654: to=root, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=34947, dsn=2.0.0, stat=Sent
Sep 21 13:22:40 hostname sm-mta[1651]: q8LDMYxB001649: to=<newuser@fakedomain.com>, delay=00:00:06, xdelay=00:00:06, mailer=esmtp, pri=121023, relay=fakedomain.com. [86.48.74.19], dsn=2.0.0, stat=Sent (Ok)

```

## Not Understood By Me

There are several seeming anomalies I do not understand, such as:

* `stat=User unknown`
* `DSN: User unknown`
* `Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: <noreply@hostname.domain.com>... User unknown`
* I can't understand why Drupal's error says `from
noreply@hostname.domain.com to noreply@hostname.domain.com`
* I can send mail from the command line using `sendmail`, and it goes through just fine:

## Contents of mail.log after sending with the command line on root

```
Sep 21 16:00:07 hostname sendmail[3283]: q8LFwxIS003283: from=root, size=167, class=0, nrcpts=1, msgid=<201209211558.q8LFwxIS003283@hostname.domain.com>, relay=root@localhost
Sep 21 16:00:07 hostname sm-mta[3305]: q8LG07FE003305: from=<root@hostname.domain.com>, size=487, class=0, nrcpts=1, msgid=<201209211558.q8LFwxIS003283@hostname.domain.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 16:00:07 hostname sendmail[3283]: q8LFwxIS003283: to=gmail.account@gmail.com, ctladdr=root (0/0), delay=00:01:08, xdelay=00:00:00, mailer=relay, pri=30167, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LG07FE003305 Message accepted for delivery)
Sep 21 16:00:08 hostname sm-mta[3307]: STARTTLS=client, relay=gmail-smtp-in.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-RC4-SHA, bits=128/128
Sep 21 16:00:08 hostname sm-mta[3307]: q8LG07FE003305: to=<gmail.account@gmail.com>, ctladdr=<root@hostname.domain.com> (0/0), delay=00:00:01, xdelay=00:00:01, mailer=esmtp, pri=120487, relay=gmail-smtp-in.l.google.com. [74.125.142.26], dsn=2.0.0, stat=Sent (OK 1348243208 ut4si13805795igb.1)

```

# Answer
This error appeared after I've changed my host name from webserver to webserver.com, thus anything sent to `*@webserver.com` confused sendmail, as it's been searching local user with such name.

Adding a local user won't solve the problem completely, because if you try adding user like `firstname.lastname`, Linux system will complain.

What I've done though to fix my system, is **configuring sendmail properly**:

1. Modify `/etc/mail/sendmail.mc` by adding following lines to the very end:

```
define('MAIL_HUB', 'webserver.com.');
define('LOCAL_RELAY', 'webserver.com.');

```
2. Run:

```
sudo sendmailconfig

```

Optionally reloaded the sendmail by:

```
service sendmail restart

```

On some Linux distributions (such as Ubuntu) it may be reloaded automatically.
> 5 votes

# Answer
I still do not understand why, but creating a linux user on my Ubuntu VPS named "noreply" fixed this issue. I am happy it works, but would appreciate an answer from anyone who might have insight or an alternative solution other than creating new linux users for every email id I want to send from.

Special thanks to junedkazi for discussing this with me in comments.
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Is drush required on the remote server to do sql-sync or rsync operations?
I am working my way through the Drush chapter in Definitive Guide to Drupal 7 by Apress. I want to sync the mysql database and files to/from my local MAMP developer stack and the remote live server (shared hosting).

Given that the drush rync commands deal with the files and the database, then surely it is not necessary to have to have drush on the remote server? If it has to be on the remote server the I accept that but please explain why. I do appreciate that other drush operations would require it e.g. core-status though but the aforementioned operations I am doing involve just the drupal code and database not anything to do with drush.

Please advise, guides don't state everything and make assumptions sometimes.

# Answer
Drush is needed on the remote server only to fetch the database credentials for the remote system. If you declare your databases array in the site alias for your remote systems, then Drush will not need to have Drush installed on the remote machine to work.

I don't remember if I explained this in detail in the book, but there is an example on how to define database records in aliases in the example alias configuration file, example.aliases.drushrc.php. Also, try running `drush @site sa --with-db` to see the whole site alias record for the given site with the databases array included. This won't help you if Drush is not installed on the system where the site is installed, but you can run it on a local site, and edit the result to match the necessary settings for the remote end.
> 7 votes

---
Tags: 7, drush
---


# Question
Title: Is there a Rules Action to set an entity reference field to null / empty?
Is there any rules action you can use to set an entity reference field to null or empty?

Thanks very much and have a great day.

# Answer
> 3 votes
Ahh, got it. If anyone else runs into a problem doing this. The issue I had was that I was leaving the data selector blank and it was giving me an error message. BUT If you switch to the direct input mode and leave it blank it will work. Have a great one.

# Answer
> 2 votes
You can use the **Set a data value** action. To be able to select the correct field, you may need to add a condition **Node is of type**. (Rules does not always know about which fields should be available if you do not set a condition.)

---
Tags: rules, entities
---


# Question
Title: Computed field - count number of taxonomy terms in term reference field
So I simply want to count the number of tags on a term reference field.. I've tried a count (below) and it simply returns "1" (there are a lot more terms tagged than 1):

```
$entity_field[0]['value'] = count($entity->field_termref);

```

Also something like below does not work either and also returns "1" - I'm thinking I have to loop through the multiple tags somehow but I'm not sure how to do it. Thanks a lot for any help.

```
$myterms = array();
foreach($entity->field_guests as $tmp) {
  $myterms[] = $tmp_field_term;
}
$entity_field[0]['value'] = count($myterms);

```

# Answer
> 0 votes
Your first code was correct as far as it went: `count($entity->field_termref)` will return a count of one because the array has only one item, the list of terms.

To count the members of the list your will need to drop down into the array to actually count the list:

```
$entity_field[0]['value'] = count($entity->field_termref[LANGUAGE_NONE]);

```

The members of the list can then be counted:

```
$entity->field_termref[LANGUAGE_NONE][0]
$entity->field_termref[LANGUAGE_NONE][1]
$entity->field_termref[LANGUAGE_NONE][2]
...etc

```

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


# Question
Title: Creating a dynamic contextual filter list
I would like to make a grouping of articles based on the year and month. In other words something like

* April, 2013
* March, 2013
* February, 2013
* January, 2013

Each would be a link to the articles section and provide a contextual filter (/articles/2013/1 for January 2013).

I've tried playing with the views module to create this view. I selected only the posted date and then formatted it to show only the Month and Year. Then I turned on aggregation to group the results together, but it appears aggregation is using the entire date (including the day). I also tried grouping by the posted date in the table settings but there doesn't appear to be a way to rewrite the results of the group header.

Is there a way to do this with views or some other module?

# Answer
> 0 votes
I have personally done the contextual filter part of it and can confirm it works very well and is easy to setup.

Simply add a contextual filter for "Content: Created year" and "Content: Created month" and then set the Path of the view to "/articles". I use basic validation for the contextual filters and have also setup something for no results so the users aren't presented with a blank page.

I'm not quite sure what you're asking for with the other part of the question.

I think the easiest way of going about this is to create a separate Views block and add a field that contains the post date. You can then use a custom Date format to display the post dates the way you want them. "F, Y" should do it.

Turn on Aggregation and make sure it's grouping the results together and you should be good to go. You can now use the rewrite as link to accomplish what you need. You may need to add a couple of other hidden fields to get all the parameters you need.

UPDATE: I realized there is a problem here. Views aggregation works on the raw SQL data only which is what I think your original problem was. This means that group by date doesn't actually work as you mentioned earlier. There are a couple solutions I came across http://drupal.org/node/388140, http://drupal.org/project/views\_date\_format\_sql, and http://groups.drupal.org/node/40356.

---
Tags: views
---


title: hook_uninstall not working

text:
# Question
Title: hook_uninstall not working
I have created a custom content-type in my custom module with custom fields.. It works fine.. But when I try to uninstall it, it doesnt call hook\_unistall().. Can any one suggest what can be the problem ?

Here is my code :

```
function homepage_blocks_uninstall() {
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => 'homepage_blocks'));

    //echo "hello";
    //exit;

    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }

    node_delete_multiple($nids);
    foreach (array_keys(_homepage_blocks_installed_fields()) as $field) {
        field_delete_field($field);
        //db_drop_table($field);
    }

    $instances = field_info_instances('node', 'homepage_blocks');
    foreach (_homepage_blocks_installed_instances() as $instance_name => $instance) {
        field_delete_instance($instance);
    }

    node_type_delete('homepage_blocks');
    field_purge_batch(1000);
    //variable_del('comment_homepage_blocks');
    //variable_del('node_submitted_homepage_blocks');
    drupal_flush_all_caches();
    //module_disable('homepage_blocks');
}

```

And I want to delete all tables, cache, variables node entries related to that module while uninstalling module so that I can re-install it.. What extra code I need ?

\_homepage\_blocks\_installed\_fields() and \_homepage\_blocks\_installed\_instances() are functions reside in homepage\_blocks.functions.inc file and I have included this file to my homepage\_blocks.module and homepage\_blocks.install

# Answer
> 3 votes
Are the functions you are calling from your implementation of `hook_uninstall()` defined in your .module file? If that is the case, those functions will not be found, as the module file is not anymore loaded in memory.

> **When hook\_uninstall() is called, your module will already be disabled, so its .module file will not be automatically included**. If you need to call API functions from your .module file in this hook, use drupal\_load() to make them available. (Keep this usage to a minimum, though, especially when calling API functions that invoke hooks, or API functions from modules listed as dependencies, since these may not be available or work as expected when the module is disabled.)

# Answer
> 0 votes
```
function homepage_blocks_uninstall() {
    $query = db_select('node','n');
    $query->fields('n', array('nid'))
            ->condition('type', 'homepage_blocks')
    $data=$query->execute();
    while($result=$data->fetchObject()){
        node_delete($result->nid);

    }
    drupal_flush_all_caches();

}

```

I think it will work or u can implement this by batch process also... :)

---
Tags: hooks, nodes
---


# Question
Title: Extracting a specific data part of a Field Collection Item
I've been playing around with this for the better part of a few days now with no luck. Here is my Collection data:

Collection name: `field_video_collection`

Within the collection there is a field called: `field_video_file_col`

My fields print fine in my custom `field-collection-item--field_video_collection.tpl.php` template, I followed the documentation according to this issue to get my template name and I simply print the fields as `<?php print render($content['field_video_file_col']); ?>` etc... within that template.

Now for the fun part, I'd like to extract the `fid` for each `field_video_file_col` item in the collection in any given node and render it as a printed variable. I followed the answer in this question here on Stack but it does not seem to work for me. if I do:

```
print '<pre>';
var_dump(get_defined_vars());
print '</pre>';

```

I see I have this as part of the data available to me for `field_video_file_col`

```
["field_video_file_col"]=>
          array(1) {
            ["und"]=>
            array(1) {
              [0]=>
              array(12) {
                ["fid"]=>
                string(3) "888"

```

So it looks to me that the FID is 888 in this case and I want to render that in my template. My node preprocess function is as such:

```
function MYTHEME_preprocess_node(&$vars, $hook) {

    $entity_type = 'field_collection_item';
    $bundle_name = 'field_field_video_collection'; // Field name the collection is attached to
    $field_name = 'field_video_file_col'; // Field name within the field collection
    $video_file_fid = field_info_instance($entity_type, $field_name, $bundle_name);
    if ($video_file_fid) {
      $my_fid = $video_file_fid['fid'];
    }
}

```

***The end result needed*** is that I need to render the variable in my *field-collection-item--field\_video\_collection.tpl.php* template as:

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

```

... but this does not seem to work. I've searched all over and tried many different incarnations of this code and combinations but still no joy.

# Answer
I use Entity API when work with Field Collection Items. See: Programmatically create and update field collection with Entity API

To work with field collections can do smth like this:

```
// Wrap node with Entity API
$node_wrapper = entity_metadata_wrapper('node', $node);
// Get the first item from the muli-value field collection
$raw_collection = $node_wrapper->field_video_collection[0]->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
debug($collection->field_video_file_col->value());

```

If you already know your field\_collection id you can just do:

```
$collection = entity_metadata_wrapper('field_collection_item', $fid);
//dsm the old value
debug($collection->field_video_file_col->value());

```

**UPDATE:**

use the code above in `MYTHEME_preprocess_node`

**UPDATE 2:**

So in your case it will be:

```
function MYTHEME_preprocess_node(&$vars, $hook) {
  if (empty($vars['nid'])) {
    return;
  }
  // Wrap node with Entity API
  $node_wrapper = entity_metadata_wrapper('node', $vars['nid']);
  // Get the first item from the muli-value field collection
  $raw_collection = $node_wrapper->field_video_collection[0]->value();
  // Wrap field collection with Entity API
  $collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
  // print value
  $fid = $collection->field_video_file_col->value();
  debug($fid);
}

```

Also you can find answer at Understanding Field Collection Values
> 8 votes

# Answer
The code from dropbucket might be helpful to get and prepare all the field collection's data into an array:

```
$fieldname = 'field_lorem_slides';

// Get the items
$slides = array();
foreach($vars[$fieldname] as $delta => $item_id){
    $data = field_collection_item_load($item_id['value']);
    if ($data)){
                $l = isset($data->language) ? $data->language : LANGUAGE_NONE;
        $slides[$delta] = array();

                // Get the field collection's data prepared in an array
                // Alternatively, you could do $slides[$delta] = $data; in order to get the full objects in the array
        $slides[$delta]['lorem_image'] = '<img src="'.file_create_url($data->field_image[$l][0]['uri']).'">';
        $slides[$delta]['lorem_data'] = isset($data->field_heading[$l]) ? $data->field_heading[$l][0]['safe_value'] : null;
    }
}

// Send the information to the template file
// $vars['slides'] = $slides;

```
> -1 votes

# Answer
You may try this one. The first line gets the object, the second line the fid from it.

```
$field_video_col=current(current($vars["field_video_file_col"]));
$video_file_fid=$field_video_col['fid'];

```
> -1 votes

---
Tags: 7, entities
---


title: Drupal Views Export

text:
# Question
Title: Drupal Views Export
I added a data export to the view and also with glossary mode enabled..

When I filter the view by alphabet and then click on export then it not generating excel file.

# Answer
This you can do by just installing the Views data export module and could play around the data that you want to export.
This would provide a module to do your desired work.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS
> * Microsoft DOC
> * Basic TXT
> * XML.
> 1 votes

# Answer
are u getting any data in the view . If yes then you could export it to csv or excel and get the desired file. If no data is being viewed the n you need to check the view once again.
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: clone of drupal project failing: operation timed out
I am trying to clone the drupal project locally but getting this error

```
k10593:htdocs welcha$ git clone git://drupalcode.org/project/drupal.git fooproject
Cloning into 'fooproject'...
fatal: unable to connect to drupalcode.org:
drupalcode.org[0: 140.211.10.6]: errno=Operation timed out

```

I am following this tutorial: http://drupal.org/node/803746

Any idea what the problem might be?

# Answer
Try disconnecting your wifi and then connecting again. Used to resolve the issue before, when i got "some broken pipe error". This generally happen iF your wifi network keep switching to different connection to balance the load. Just a suggestion.
> 1 votes

# Answer
There is some connection issues. Try it once again after disconnecting your wifi.

Now go to you github account http://www.github.com Now search for the project that you want to clone.

then go for forking.

https://help.github.com/articles/fork-a-repo (what is forking and it works.)

there is a fork button on the top right side of your github account.Click that button. It would copy the project in your github account.

Now go for **git clone (ssh url of the project)**
> 0 votes

---
Tags: version-control
---


# Question
Title: Page body content updated only after second load
I want to programmatically update the HTML contents of a page (a node of bundle type 'page') on my Drupal 7 site, by doing the following:

```
function my_page_generate() {
   // Find and load the page I want to update (can't do it by nid since
   // it might differ)
   $query = new EntityFieldQuery();
   $entities = $query->entityCondition('entity_type', 'node')
   ->propertyCondition('type', 'page')
   ->propertyCondition('title', 'Last News')
   ->propertyCondition('status', 1)
   ->execute();
   $node_key = array_keys($entities['node']);
   $node = node_load($node_key[0]);

   //Update its HTML contents
   $node->body[LANGUAGE_NONE][0]['format'] = 'full_html';
   $node->body[LANGUAGE_NONE][0]['value'] = '<h1> BREAKING NEWS </h1>';

   node_save($node);

   return node_view($node, 'full');
}

```

This method is called when requesting a URL by using the hook\_menu hook, like this:

```
function my_module_menu() {
   $items = array();
   $items['last-news'] = array(
    'title' => 'Last News',
    'page callback' => 'my_page_generate',
    'menu_name' => 'main-menu',
   );

   return $items;
}

```

However, when I navigate to /last-news on my site, the old contents of the page are displayed. If then I reload the same page again (using the same path), the new contents I created show up. I have tried to disable the page cache for this page by calling $GLOBALS\['conf'\]\['cache'\] = FALSE, but it keeps showing the same behavior.

Any ideas how to solve this?

# Answer
Check http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_view/7

You should clear cache programmatically if you want to use current solution or just load node again (http://api.drupal.org/api/drupal/modules!node!node.module/function/node\_load/7) after save.

Third argument of node\_load must be true
> 0 votes

---
Tags: 7
---


# Question
Title: How to establish a condition to show another view if the first view has no results?
I have some blocks with views that show upcoming events of different categories. Now, if one category has no results, how can i trigger another views-block with another category (that is normally not displayed)? I was trying to get this done with the context-module, but i have only the possibilty to create a context IF a view is shown...

# Answer
> 2 votes
Try to write a php code, in your view UI, in the textarea for behavior when no result :

```
print views_embed_view( 'your_other_view_name', 'default');

```

NB : enable PHP filter module

---
Tags: views, 7
---


# Question
Title: drupal 7 workbench: Can I limit different users/roles within a particular section via taxonomy?
drupal 7 workbench: Can I limit different users/roles within a particular section via taxonomy? If I setup 2 roles Author and Editor and I assign different users with the same role (i.e. Author) but assign them to a different section via taxonomy (i.e. Northeast region or Southwest region). Once this is done will users with Northeast region taxonomy and Editor role only see "Needs Review" documents within the Workbench section created by Author user that have the matching Northeast region taxonomy?

# Answer
> 2 votes
You use the submodule of Workbench, called Workbench Access to limit users to a "sub section" of the content based on Taxonomy or Menu path.

> Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.
>
> When creating and editing content, users will be asked to place the content in an editorial section. Other users within that section or its parents will be able to edit the content. A user may be granted editorial rights to a section specific to his account or by his assigned role on the site.

There is a great documentation page and associated web video for Workbench Access on configuration within the project page.

---
Tags: workflows, workbench
---


# Question
Title: How to get a field value of multiple nodes?
I have some node ids from entityfieldquery. I would like to get the values of a field from all of these nodes. Should I use db\_query, or should do a node\_load\_multiple, and get the field value with a foreach? db\_query seems more efficient.

# Answer
> 1 votes
You can use field\_attach\_load() which will load the fields for a group of entities. You can also pass in the field\_id value so it doesn't load unnecessary fields. I benchmarked `field_attach_load()` against `entity_load()` (which is what node\_load\_multiple will call) and the former was approximately ten times faster.

Here is an example:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'post')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (isset($result['node'])) {
  // field_attach_load() requires entities to be passed on it with the bundle
  // and the ID instead of just IDs. We need to add these values to the result
  // of EntityFieldQuery()
  foreach ($result['node'] as &$node) {
    $node->bundle = $node->type;
    $node->id = $node->nid;
  }
  field_attach_load('node', $result['node'], FIELD_LOAD_CURRENT, array('field_id' => 'body'));
}

```

# Answer
> -1 votes
ya u r right. node\_load\_multiple fires huge pressure on db and it can effect on ur site's performance. So, always use db\_select or db\_query for ur use, if there is no option available then only use loads....

---
Tags: nodes, entities
---


# Question
Title: Custom Field Not Being Saved programattically through node_save()
So there is a custom field I added called 'qid'. I can see that it is being created with each node. My issue is that I cannot programmatically save a value to my custom field. In the code below I will display and instance where I add two values, one to my custom field `qid` and another to the Ubercart uc\_product field `height`. `Height` will be saved successfully and `qid` will not.

```
function my_module_test_page() {
  $output = t('foo');

  $node = node_load('151');
  dpm($node);
  $node->height = '555';
  $node->qid = '222';
  dpm($node);
  node_save($node);
  $test = node_load('151');
  dpm($test);

  return $output;

}

```

While I understand that this is probably not enough code to get to the root of the problem I have no idea where to look. I have scoured the `node_save()` function and I dont understand why my field is having a problem. If it helps I have checked `field_data_qid` in my MYSQL db; however, the table is empty.

EDIT: So the next interesting fold is that when I enter the QID field through the GUI it saves fine.

# Answer
> 3 votes
My suggestion would be to inspect an existing node that already has a value for field\_data\_qid. Is qid a field created through the Fields GUI? $node-\>qid is not where I'd expect to see a custom field like this.. $node-\>field\_qid\['und'\]\[0\]\['value'\] is a more likely candidate. You'd end up with:

```
function my_module_test_page() {
  $node = node_load(151);
  dpm($node, 'Pre-modified node');
  $node->field_qid['und'][0]['value'] = 222;
  dpm($node, 'Pre-saved modified node');
  node_save($node);
  // Passing TRUE for $reset to bump the cache
  $test = node_load(151, NULL, TRUE);
  dpm($test, 'Reloaded node');
  return 'Test page';
}

```

Also: node\_load takes a nid integer as a parameter, not a string: http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_load/7

See also: https://stackoverflow.com/questions/7876458/drupal-6-drupal-7-migration-field-unds and Best practice for language key for "und" in hook\_form\_alter

---
Tags: entities, nodes
---


# Question
Title: drupal_add_js() won't work with footer scope
i 'm trying to add a file to end of body via template.php in mytheme\_preprocess\_page. this is the line i have:

```
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/file.js',array('type' => 'file','scope' => 'footer'));

```

why i can't see file.js in view source? -if i change footer scope to header file.js add to head tag -

doc says:

> Possible values are 'header' or 'footer'. If your theme implements different regions, you can also use these

i tried to add footer region to page.tpl.php but it doesn't work.

what do means footer scope?

# Answer
Make sure you're printing `$page_bottom` in `html.tpl.php`.

In Drupal 6, it looked like this:

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

```

In Drupal 7, you now want all 3 of the `$page_top`, `$page`, and `$page_bottom` variables which correlate to the `header`, `content`, and `footer` scopes. Here's a sample (and simple) `html.tpl.php`:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<body>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```
> 4 votes

---
Tags: 7, javascript
---