# Question
Title: Print out custom field and footer in newsletter
**1.** I have two fields in my newsletter content, the normal 'Body' and another called 'The List' (.field-field-thelist). I am trying to print this out in the newsletter but I cannot seem to get it working.

**htmlmail-simplenews.tpl.php:**

```
// this doesn't work
<?php print $node->field_field_list[0]['view'] ?>

```

I don't think I am doing this correctly, but I am basing it from this walkthrough.

---

**2.** For some reason when I call the newsletter to print **$body** (simplenews-newsletter-body.tpl.php), it also prints the **$footer** (simplenews-newsletter-footer.tpl.php) content ($footer doesn't actually print anything alone).

**htmlmail-simplenews.tpl.php:**

```
//Prints body AND footer for some reason, I want to separate these as two variables
<?php echo $body; ?>

```

The reason #2 confuses me is because there is very clearly 2 variables for each a body and footer in the simplnews.module file. Is there another way I can call these separately?

Note: I am not using Views for this newsletter

# Answer
> 1 votes
$node is available within the simplenews templates. htmlmail-simplenews.tpl.php is a generic template that is not simplenews specific.

$body in this context is the mail body, which has been created by combining the simplenews body and footer. Again, within Simplenews, those are separated, but are then simply concatenated together before passed to the htmlmail template.

To get to the node object in there, look at the example templated provided by HTML Mail, which uses `$params['context']['node']` and `$params['simplenews_source']->getNode()` in Drupal 7.

---
Tags: entities, 6
---


title: Programatically create a menu?

text:
# Question
Title: Programatically create a menu?
I can login to /admin/structure/menu and create a new menu. How can my module create a custom menu like that?

# Answer
There is a function called menu\_save that looks like it will help you out (I assume drupal 7)
> 2 votes

---
Tags: routes
---


title: Adding Divs in Blocks

text:
# Question
Title: Adding Divs in Blocks
I've created a custom block with Div and P tags in which some have id and class attributes. I've tried use FULL & Filtered html formats for the block body however the id and classes don't show up once I've added the block.

# Answer
> -2 votes
Please try change to PHP code which this option appear when you enable php filter in Modules page.

# Answer
> 1 votes
In admin/structure/types/manage/your\_content\_type/display (drupal 7 path) make sure field Body has format "Default" selected. If you have any other format those will remove the div ids and classes from the body.

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


title: fbconnect module invite issue

text:
# Question
Title: fbconnect module invite issue
This is a test site where i have installed fbconnect module I am facing issues while Inviting Friends:

What i am doing: 1. Connect to site through Fbconnect (by clicking on Login with Fb button) 2. Click on Invite Friends link which goes to fbconnect/invite/friends 3. Select Friends i want to invite. 4. Click "Send FB APP NAME Invitation"

Now, the Invited person gets a notification

```
Naushad Shaikh
Invited you to FB APP NAME. Try Now

```

URL Points to : http://www.facebook.com/games#

However nothing happens and the invitation does not succeed as it should.

Please let me know what should i do / what am i doing wrong.

# Answer
> 0 votes
This issue has been resolved.

After a lot of research, i came to know that the Facebook Application for FbConnect did not have a Canvas URL and Secure Canvas URL

So i did below:

1. Added Canvas URL to the Application as domain.com
2. Added Secure Canvas URL as Fb's changed policy required so added https://www.domain.com
3. Now, i could click the Application and it opened In Fb IFRAME,
4. I wanted it to redirect on the website, (NOT ALLOWED AS PER FB TERMS & COS)
5. Solution an Image Pointing to External link (www.domain.com)

Thanks for the viewers of this question. I got a Tumbleweed badge for this question.

---
Tags: social-network
---


# Question
Title: Field API - defining a field, attaching it to privatemsg, and populating it "behind the scenes"
This is actually related to a previous question ( Appending markup to privatemsg message body ) but as it's a slightly different issue I figured I'd start a new question.

In my original question, tenken's suggestion is to create a new module implementing `hook_field_info()`, then use `field_create_field()` and `field_create_instance()` on `hook_enable()` to attach the custom field to the privatemsg bundle.

I have sort of figured out the gist of defining a custom field and attaching it to a bundle, but I'm stuck with a few things despite extensive googling, searching drupal.org and documentation as well as searching for video tutorials on YouTube. Specifically:

* when populating arrays to use with `field_create_field()` and `field_create_instance()`, I'm not sure what I should specify for the `entity_type` value. I know typical examples for these functions usually refer to 'user' and 'node', but what should it be for privatemsg?
* I don't want the field to be visible on any forms as it's only intended to be populated "behind the scenes". I understand that I need to define a custom field formatter for that. How do I do that?

I think those are my only obstacles at the moment. Sorry if I appear lazy at all, but I only have very limited experience with Drupal module development, much less the field API, and this is my first D7 module. Needless to say I have searched for specific answers to the above but they continue to elude me!

Thanks

# Answer
> 1 votes
There is no need to define your own field type, just use a simple text field. You are storing a string after all, no need to re-invent the wheel.

The entity\_type of privatemsg is privatemg\_message. Note that you are not required to specify this property as the purpose of it is to limit the field for certain entity types. Leaving it empty means that instances of it can be attached to any entity.

To hide the field, you could use a module like Field permissions which gives you fine-tuned permission-based control over all fields. What that module actually does is provide a user interface for hook\_field\_access(), so you can alternatively implement that hook yourself and simply return FALSE for the field you created based on the field name.

---
Tags: 7, entities, privatemsg
---


# Question
Title: Get form element's label/value pairs from &$form or &$form_state
I need to pass an array with all the fields (with their values) from a form from the submit function to a rules\_invoke\_event.

to do this I'm calling a get\_fields() function, in this function I have acces to the form and form\_state objects. Just wondering how I could loop through one of these with a foreach to get an array with the pairs?

```
function get_fields($form, $form_state)
  $fields = array()
  foreach(element in form)
  {
    $fields[$element[key]] = element[value];
  }
  return$ fields
}

```

something like this but with correct syntax?

Help would be greatly appreciated :)

# Answer
This might work.

```
function get_fields_this_step($form_state) {
    $fields = array();
    foreach($form_state['values'] as $key=>$value){
        $fields[$key] = $value;
    }
    unset($value);
    return $fields;
}

```
> 1 votes

# Answer
You are very close, simply dpm($form\_state) (if you have Devel Module installed) or print\_r it. You'll find there all the form values you're needing. Loop over the array that contains form values inside the $form\_state array.
> 0 votes

# Answer
Or you can just use

`$form_state['values']['submitted_tree']`

which is already formatted in the way you want. I'm not sure if this only applies to forms created with the webform module, but worth a shot!
> -1 votes

---
Tags: 7, forms
---


title: Creating Content List

text:
# Question
Title: Creating Content List
I have an custom content type movie.By which users can create "movie" content. The movie content type is simple containing a title, director's name and a poster.

Now,what i need is, Each user should be able to create lists of movies.As example , one may create "10 most scariest movies" , "10 most comedy movies" etc.

I want the creation of list in the following way ,

1) User will give it a title to his list.

2) Then he will add movies to his list , which are already crated .(like the way one user can tag other user in facebook - user should be able to tag movies.)

3) After the list is created when a movie on a list is clicked, it should lead to the page of the corresponding movie.

How should i solve this problem??

I am using Drupal 7

Thanks in advance

# Answer
I solved the problem using Entity Reference Module.

I made a custom content type - "Movie List" , and add a field of "Entity Reference" type , then made a reference to "Movie" content.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to filter URLs for embedded IMG tags?
This is a great presentation about Drupal security. They were talking about ways to only allow tags from certain trusted domains.

Any ideas how to do that? I couldn't find a D7 module for that.

# Answer
What I've done in this circumstance is to create my own BBCode style filter so as to take out that huge regex issue and have total control over the creation of the img tag, eg, I never allow casual users to enter it in any html filter. Also, it's a lot easier to input for some less than stellar users :)

For example, `[img:www.host.com/foo/bar/baz.jpg]` can be easily checked for the host, and if you don't want potentially animated gifs, you can disallow them (although yes I do know browsers are looking at the contents of the file now, not the extension, but that's another story), and also, important at least for me, you can set up the css so you don't have a huge image ruining your site formatting, and pretty easily the above turns into

`<img src="http://www.host.com/foo/bar/baz.jpg" class="user-submitted-image">`

if all is good in the world, or

`<img src=".../badhost.png" title="Sorry: images aren't allowed from www.badhost.com" class="user-denied-image">`

or even `<img src=".../blink-was-bad-enough.png" title="Sorry: gifs aren't allowed here" class="user-denied-image">`

if it's not.

Obviously, this doesn't help with any pre-imported content, but moving forward, it might help out.

ADDITION:

I pulled this out of some code and I hope I got all of it:

```
function YOURMODULE_bbc_inject($text) {

  $types=array('img', 'youtube');

  foreach ($types as $type) {
    $match=array();
    if (preg_match_all('/\[(' . $type . '):([^=\\]]+)\]/i', $text, $match)) {
      $s = $r = array();
      foreach ($match[2] as $before => $after) {
        $s[] = $match[0][$before];
        $r[] = YOURMODULE_bbc($type, $after);
      }
      $text=str_replace($s, $r, $text);
    }
  }

  return $text;
}

```

and then helpers:

```
function YOURMODULE_bbc($type, $after) {

  switch ($type) {

    case 'img':
      $foo=explode('/',$after);
      $host=$foo[0];

      if (YOURMODULE_valid_img_host($host)) {
        return '<img src="http://' . check_plain($after) . '" class="user-submitted-image">';
      } else {
        return '[INVALID IMAGE]';
      }

    case 'youtube':
      return '<iframe class="user-submitted-youtube-video" src="http://www.youtube-nocookie.com/embed/' . check_plain($after) . '?wmode=transparent" frameborder="0" allowfullscreen></iframe>';

    default:
      return '[HUH?]';
  }

}

function YOURMODULE_valid_img_host($host) {

  $foo=explode(',', variable_get('YOURMODULE_img_host_blacklist','www.foo.com,foo.com,www.bar.com,bar.com'));

  if (in_array($host, $foo)) {
    return FALSE;
  } else {
    // you can check for valid image type here if desired, otherwise...
    return TRUE;
  }
}

```

You would use the first function in a filter process, I'd show you how to do it in D6 in a second or two, but I know you are using D7, but it should be straightforward enough to figure that out from some of the other questions and answers on here. Just make sure it runs as late as possible so it doesn't inject some HTML that another filter would disable.

But, if all is installed correctly, you "should" now be able to have a `[img:www.foo.com/evil.jpg]` denied on your website, plus I threw in the `[youtube:35I6Iue_XDE]` to show how to extend it to other injectable things.

(It's up to you to add the black list variable into an admin/settings form, but that's also pretty straightforward)

END OF ADDITION :)

Of course, another avenue for this is to not allow images at all in your text and instead have a multiple value image field that can populated and then displayed alongside the text or in a lightbox, etc. And there you could use all sorts of node() and validate() operations to check those fields for sanity/safety before displaying them.
> 1 votes

# Answer
If you mean disallowing `<img>` elements where the `src` isn't on a whitelist, then you can make a custom input filter.

The first step is to make a `hook_filter_info` to declare your input filter. You would then make a callback function that does the work.

The callback would do some regex matching, looking for `<img>` elements and pulling out the `src` attributes. Then regex match the src against your whitelisted domains. If everything is OK, let the image pass, else replace it with whitespace.

Finally, make a `hook_menu` which sets up a settings page so you can enter your whitelist via the UI.

Once you have done all of this, you add your filter to the appropriate input formats. When the page gets rendered out, the filter will be applied.

All of this is rather easy. The heavy listing is the `<img>` regex, but I suspect 15 min of googling will find some good ones.
> 4 votes

---
Tags: 7, input-formats
---


# Question
Title: hook_menu() item is not showing in primary-links even it exist in menu_links and menu_router tables
I'm using `hook_menu()` in my module which defines a menu item in the primary-links.

I flushed the cache and refreshed the modules page but the item didn't show in the primary-links.
I checked the menu\_links and menu\_router tables and the item was defined it them.

```
function mymodule_menu() {
  $items['newuser'] = array(
    'title' => 'Register',
    'menu_name' => 'primary-links',
    'page callback' => 'register_browse_page',
    'access callback' => 'newuser_access_callback',
  );

  return $items;
}

function newuser_access_callback() {
  global $user;

  if ($user->uid == 0 && user_access('access content')) {
    return TRUE;
  }

  return FALSE;
}

function register_browse_page() {
  $form = drupal_get_form("newuser_form");
  return theme("newuser_form_page", $form);
}

```

What is the problem? How do I fix it?

# Answer
This condition in your `newuser_access_callback` tells to your link to shows only to anonymous.

```
if ($user->uid == 0 && user_access('access content')) {

```

If you want see it as admin also, you should add yourself like that

```
if ($user->uid == 1 || ($user->uid == 0 && user_access('access content'))) {

```
> 1 votes

# Answer
If you want the menu to be visible to anonymous users, you should use the following code.

```
function mymodule_menu() {
  $items['newuser'] = array(
    'title' => 'Register',
    'menu_name' => 'primary-links',
    'page callback' => 'register_browse_page',
    'access callback' => 'user_is_anonymous',
  );

  return $items;
}

```

This is similar to the code used in openid\_menu().

```
function openid_menu() {
  $items['openid/authenticate'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'openid_authentication_page',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
    'file' => 'openid.pages.inc',
  );

  //...
}

```

user\_is\_anonymous() also allows administrators to see items for anonymous when administering, as long as the global $menu\_admin is set to `TRUE`. This is done before checking which users have access to a menu handler.

```
function user_is_anonymous() {
  // Menu administrators can see items for anonymous when administering.
  return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
}

```

Normally, user\_is\_logged\_in() should instead be used as access callback.

Checking if the user anonymous user has the permission to access to the content is not necessary; plus, the code would work if you assign that permission to anonymous users.
> 0 votes

---
Tags: routes, hooks
---


title: How do I find the primary links config?

text:
# Question
Title: How do I find the primary links config?
I'm running Drupal 7, and I am using the Acquia Marina theme. I am having issues with the drop-down menu (using superfish). The menu items with children simply remain expanded.

Every tutorial and user post I've looked at, the Primary Link Configuration table always comes up.

I cannot find this screen, anywhere. Can anybody help me?

# Answer
> 2 votes
You can get to that screen via the 'Administration' page, which you'll find at yourdrupalroot/admin . You'll need to drill down through the subpages there differently depending on your Drupal version; in Drupal 7 it will be under Structure \> Menus \> Main menu (the renamed version of 'Primary links').

---
Tags: navigation
---


# Question
Title: How to create on mouse over dropdown menu in drupal 7?
Am working on drupal 7.x and using pixture reloaded sub theme 2.x. Under the Main Menu, am creating a menu with the menu name "Development". On mover over the menu "Development", in drop drop, list of sub-menus should list out. I installed a nice-menu module, but i don't know how to use. Please give a step by step tutorial to create a sub menu on mover over. Thanks

# Answer
> 1 votes
You can use nice menu or super fish menu nice menu will create two blocks called nice menu 1 and nice menu 2 you have to choose on of them as a block and in configuration you will choose a menu to display

also superfish module will create 4 blocks (it is a dynamic number form config menu) and give you more options to style your menu also option to choose which menu you want to display

---
Tags: 7
---


# Question
Title: Update imported feeds to only get one taxonomy term per node
I have used feeds to import some nodes with taxonomy term reference.

The source XML is the following one.

```
<items>
  <item>
    <title>Test 1</title>
    <body>Test body 1</body>
    <term>My_term_foo</term>
    </item>
</items>

```

First import is OK. I edited `<term>My_term_bar</term>`, and started importing a second feed. After the second time, the node has both "My\_term\_foo" and "My\_term\_bar," but I need only "My\_term\_bar" from the second import.

Is there any `hook_feeds_node_item_presave()` I can use to alter the values being imported?

EDIT:

My final code of hook\_nodeapi inpired by sel\_space:

```
switch ($op) {
      case 'presave':
        if ($old_node = node_load($node->nid)) {
          $taxonomy = array_diff_assoc((array) $node->taxonomy, (array) $old_node->taxonomy);
          if (!empty($taxonomy)) {
            $node->taxonomy = $taxonomy;
          }
        }
        break;
    }

```

# Answer
If data needs to be modified before it is saved use this module : Feeds tamper

For advanced modification use hook\_nodeapi in drupal 6 with the insert parameter , with hook\_nodeapi load the old node like this :

```
$old_node = node_load(node->nid);
$node->taxonomy = array_diff($old_node->taxonomy,$node->taxonomy)

```

So now you are sure that the $node contain only the new value , Hope this will help
> 1 votes

---
Tags: 6, taxonomy-terms, nodes, hooks, feeds
---


# Question
Title: How to show a menu item for anonymous users only?
I want to show a "Join Now" tab on the main menu for anonymous users only.

In the past I used Menu per Role module which does exactly that.

Since it's only one tab I would rather use 5 or 10 lines of code. Which hook should I use and what are the functions to check the current user role and add a menu item (or hide it for logged in users)?

# Answer
I think the simplest way would be to override the `access callback` for the path that your menu link will be pointing to. You can do this in a custom module with `hook_menu_alter()`, and use `user_is_anonymous()` as the callback function:

```
function MYMODULE_menu_alter(&$items) {
  $items['path/to/page']['access callback'] = 'user_is_anonymous';
}

```

If you add a menu link for this path, Drupal's menu system will respect the access callback, and the link won't be shown to anyone who's logged in.

Using this method will also make sure that logged in users can't access the page directly, which is probably a good thing.
> 10 votes

# Answer
1. Create a view and allow anonymous only to view it
2. Use the node access module to set permissions
3. Create a new content type for content only viewable by anonymous users. set anonymous as the only ones with permission to view that content.
4. Create a custom module for just that page.

3 is my chosen approach. I like the idea of have the type in place should I need additional non member content in the future.
> 7 votes

---
Tags: routes, hooks, users
---


# Question
Title: Drupal Commons on D6 - Visibility of 'Group members' and 'Latest group activity' blocks
Out of the box the 'Group members' and 'Latest group activity' blocks on the main page of a group are visible to all users regardless of whether one is a member of that group or not.

How can both blocks be displayed only when a user is a member of that group?

Thank you,

Alex

# Answer
> 0 votes
I had an urgent need to fix this issue quickly so I added a few lines of code to one of the Drupal Commons files directly. Once I have more time I plan to extract the functionality into a custom module. Until then this was my fix:

1. Open file /profiles/drupal\_commons/modules/features/common\_core/commons\_core.blocks.inc
2. Locate functions '\_commons\_core\_group\_activity\_block\_view()' and '\_commons\_core\_group\_members\_block\_view()'.
3. Add the following lines before the if statements:

//Determine group nid $url\_parameter = explode("/", $\_GET\['q'\]); $group\_nid = $url\_parameter\[1\];

//Determine group membership, exclude Admins $is\_group\_member = og\_is\_group\_member($group\_nid,$include\_admins = FALSE);
4. Add `&& ($is_group_member != '')` as second condition to each if statement

If you know a better way please share.

Alex

---
Tags: 7
---


# Question
Title: Wrong value when using PHP with the Views module
I have a float field, and I just want to print this field in a PHP field. I am using this code.

```
print $row->title; // It prints the same value.
print $row->field_pa_total; // It prints the wrong value; the field value is 5000, but the printed value is 40.

```

How do I print the field value?

# Answer
> 2 votes
`print_r($row);` should give you the structure of the row and tell you the names of the various fields and values etc.

---
Tags: views
---


# Question
Title: Customizing the comment form with custom user profile fields
I've just started using Drupal 7 and cannot find an answer to this question so I'm hoping for some help here. I've added custom fields to the user profile on the /admin/config/people/accounts/fields page. For example, I've defined a School field which is text type and a Specialty field which is a list text type.

I'd like logged in users to be able to update their user profile information when submitting a comment to an article. How do I customize the comment form to allow a user to update the custom user profile fields. I've looked in the form and there is an author field, however this only contains the basics like name and email, not the custom fields.

Edit: I want this to be one form submission, both adding a comment and updating user profile information. It seems the way to customize the comment form is through the method function THEMENAME\_form\_comment\_form\_alter(&$form, &$form\_state), however the $form object doesn't contain the custom user account fields that I've defined.

# Answer
The module Profiles2 will allow you to add fields through an associated profile structure and provides the familiar Drupal form format for managing fields.
> 0 votes

---
Tags: users, entities
---


title: How to Print and style Profile2 fields?

text:
# Question
Title: How to Print and style Profile2 fields?
I created a profiles type called: Game Player Profile (Machine name: game\_player\_profile). This contains : field\_firstname, field\_lastname, field\_profilephoto, field\_zipcode.....

How do I print and style these fields to create a page with a list of the 'Game Players' First Names + Last Names + Photo.....

Thanks

J.

# Answer
> 3 votes
Take a look at the Views Module. It is the primary module used to select fields and display them. You can find out just about everything you need to know about using the module in this Video series

---
Tags: users
---


title: Sub menu not displaying in Bartik Theme

text:
# Question
Title: Sub menu not displaying in Bartik Theme
I am using Drupal 7.9. I need to display main menu with sub-menu.

```
print theme('links__system_main_menu', array(
'links' => $main_menu,
'attributes' => array(
'id' => '',
'class' => array('menu'),),
'heading' => array(
'text' => t('Main menu'),
'level' => 'h2',
'class' => array('element-invisible'),
),)
);

```

That is the code I have used, but it does not show sub-menu items.

Then i have also tried following code :

```
if ($main_menu){
  $pid = variable_get('menu_main_links_source', 'main-menu');
  $tree = menu_tree($pid);
  $tree = str_replace(' class="menu"', '', $tree);
  $main_menu = drupal_render($tree);
  }
else {
  $main_menu = FALSE;
}
if ($main_menu): print $main_menu;
endif;

```

Even it does not display sub-menu.

Does anybody know a solution?

# Answer
The main menu in Bartik only displays the first level. Since it's hardcoded in page.tpl.php there's nothing you can do about it.

Here's how to get the menu to work properly:

1. In your theme settings (admin/appearance/settings/barti) disable "Main menu"
2. Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it)

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.
> 2 votes

---
Tags: routes
---


title: Additional Uncaught Exception?

text:
# Question
Title: Additional Uncaught Exception?
I updated some modules, and the site was working fine afterward; then, I made some changes to my .info file, uploaded, and suddenly I'm getting this error.

> Additional uncaught exception thrown while handling exception.
>
> Original
>
> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column "base.access\_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access\_exposed AS access\_exposed, base.data AS data FROM {rules\_config} base WHERE (base.plugin = :db\_condition\_placeholder\_0) AND (base.active = :db\_condition\_placeholder\_1) ; Array ( \[:db\_condition\_placeholder\_0\] =\> reaction rule \[:db\_condition\_placeholder\_1\] =\> 1 ) in EntityAPIController-\>query() (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).
>
> Additional
>
> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column "base.access\_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access\_exposed AS access\_exposed, base.data AS data FROM {rules\_config} base WHERE (base.plugin = :db\_condition\_placeholder\_0) AND (base.active = :db\_condition\_placeholder\_1) ; Array ( \[:db\_condition\_placeholder\_0\] =\> reaction rule \[:db\_condition\_placeholder\_1\] =\> 1 ) in `EntityAPIController->query()` (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).

I do have a database backup that was made before updating the modules.

The error cites entity, but nothing has changed there since Drupal was installed.

# Answer
> 5 votes
If you updated the modules manually, rather than using the Drupal UI system then you must run example.com/update.php on the URL. It is likely that one of the modules you updated made changes to the database table system. If you do not run update.php, then the modules may not have made the necessary table structure changes that match the code.

# Answer
> 0 votes
Entity API is constantly evolving and still has backwards-incompatible changes with new releases. Furthermore, the latest stable release is pretty old (5 months ago).

There's a good chance some of the modules you updated rely on an updated version of Entity API.

Try updating Entity API to the dev version and running update.php.

---
Tags: database, entities
---


# Question
Title: hook_form_alter isn't being called when node fails validation
I'm noticing that hook\_form\_alter isn't being called when a page has errors that display a message from form\_set\_error. Changes to my form aren't taking effect, and the error page is effectively broken.

I've tried to output a dpm statement in hook\_form\_alter, but it isn't appearing on the error page.

Is there a way to get drupal to call the hook and alter the form?

# Answer
> 3 votes
Forms are cached in Drupal so the form is loaded once (where your form\_alter runs) and then it's loaded from cache to be reloaded when there are validation errors.

You should use an #after\_build callback, which always gets run.

Just remember to return $element in your #after\_build callback or you'll be getting WSODs.

---
Tags: 7, forms, hooks
---


# Question
Title: Problem changing colors in the mayo theme
I have installed the mayo theme on my new site. When I try to go to "appearance" menu, and change the color combination from mayo (default) to anything else, the system saves the settings. but the website is not using the colors I chose.

What could be the cause?

I'm trying to change colors, but nothing I do works; the colors are correct only with the default color combination.

# Answer
Have you installed the theme in the right location (sites/all/themes)? If so, verify that each template has a CSS file for it. If so, then the next place to check is within the template's .info file to ensure that the CSS file is indeed being used.

Perhaps this thread would help assist you: http://drupal.org/node/1118068
> 1 votes

# Answer
This is almost guaranteed to be a permissions problem.

The color module relies on rewriting CSS files so you have to have your "files" folder correctly configured and with 777 permissions and also you should have your temporary directory working properly.

Have you tried checking out your Status Report (admin/reports/status) to see if there are any warnings about directory permissions?
> 0 votes

---
Tags: 7
---


# Question
Title: How can I translate "Read More" on Drupal 7
I have installed the internationalization module, but can't find where to specify a translation for "Read more" and other system strings. Thanks for any hints

# Answer
> 5 votes
Assuming you have added and enabled another language in `admin/config/regional/language`

Just head over to `admin/config/regional/translate` and search for the string you want translated.

**IMPORTANT** The strings are both case and whitespace sensitive. Searching for "Read More" returns no results but "read more" has a hit (see screenshot).

Also, since a lot of strings have placeholders that are substituted with variables you might have better luck with other strings if you search for a small subset of it as opposed to the entire thing!

Additionally, I **strongly** recommend installing the Localization Update module, it will automatically download and update translations for all contributed modules.

---
Tags: i18n-l10n
---


title: Integrating Impress.js

text:
# Question
Title: Integrating Impress.js
I'm trying to integrate Impress.js into a Drupal 7 instance, so that I can define a new content type (ie. keynote) for which I use a specific page.tpl.php template.

I build a small module to load impress.js files (both .css and .js) only when I have a node of that content type displaying in full view mode. I'm using preprocess\_node\_view.

But for some reason, though impress.js is being loaded, the browser returns the fallback message as it wasn't loading correctly.

May it be a problem with jQuery? May it be that the file is not properly loaded?

To test if it is a collision problem between jquery and impress I'd like to unset jquery for that page load, but I'm being unable to do it. (during preprocess\_node\_view it is too late, but I'm not finding how to do it in preprocess\_page).

Do you have any idea?

Also, If anyone has already tried this integration (I dont like the Impress 3D module approximation) and may offer a pointer on where the real problem resides, it would be very appreciated, as I'm starting to get mad.

PS. I didn't find a solution yet. Here is the code i'm using:

* Module that loads JavaScript and CSS through `hook_node_view()`:

```
<?php
/**
 * Implements hook_node_view()
 */
function impressintegrator_node_view($node, $view_mode, $langcode) {
  // if node is a presentation, and we're looking at a full node view
  if ($node->type == 'presentacion' && $view_mode == 'full') {
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/impress.js');
    // and add this css file
    drupal_add_css(drupal_get_path('module', 'impressintegrator') .'/css/impress.css');
  }
}

```
* Node body (with PHP Code filter):

```
<div id="impress" class="impress-not-supported">
  <div class="fallback-message">
    <p>Tu navegador <b>no soporta las funciones requeridas</b> por impress.js. Por eso, lo que ves es una versión simplificada de la presentación.</p>
    <p>Para una mejor experiencia, recomendamos usar la última versión de <b>Firefox</b>, <b>Chrome</b> o <b>Safari</b>. La incipiente versión 10 de Internet Explorer también <i>debería</i> ser compatible con impress.js.</p>
  </div>
  <div id="titulo" class="step slide" data-x="-1000" data-y="-1500">
    <div class="caja1"><p>Slides para la web</p>
    </div>
  </div>
  <div id="documental" class="step slide" data-x="0" data-y="-1500">
    <div class="cajadocumental"><p>Hacer presentaciones se parece más a crear cómics que a redactar informes. Necesita una dosis extra de creatividad.</p>
    </div>
  </div>
</div>

<script>
  impress();
</script>

```

With Firebug I can see 2 errors: "body is null" (in impress.js) and "impress() is not defined" (in page body), though impress.js is loaded (and even giving errors, he he).

This is the hook I had implemented before posting here:

```
function impressintegrator_node_view($node, $view_mode, $langcode) {
  // if node is a presentation, and we're looking at a full page view
  if ($node->type == 'presentacion' && $view_mode == 'full') {
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/jmpress.js');
    drupal_add_js(drupal_get_path('module', 'impressintegrator') .'/js/ejecutarjmpress.js');
    // and add this css file
    drupal_add_css(drupal_get_path('module', 'impressintegrator') .'/css/jmpress.css');
  }
}

```

Thanks for your feedback. The existing module for impress doesn't fit my needs, as I need to create many presentations and managed them as content, no as a view.

Right now i'm trying to use jmpress (as even the creator of that module says the demo is built using jmpress)

For some reason, my function is loading every file (from js to css), but it isn't working. The code to run jmpress is as simple as follows:

```
jQuery(function() {
    jQuery('#simple').jmpress();
});

```

But, even with all scritps being loaded, it is not working. As you see, I was using the function you recommend (drupal\_add\_js) but I don't know how to specify weight of each script, and I don't know how to implement Drupal.behavior (I did a couple of attempts but I think I'm not getting it...

I tried the following code, but have no experience with behaviors and i don't know if I'm missing some dependencies or anything else :)

```
(function ($) {
  Drupal.behaviors.impressintegrator = {
    attach: function (context, settings) {
      $('#simple').jmpress();
    }
  };
}(jQuery));

```

From what I understood, I can just call "diapos" even though I'm not declared it previously, and it will even run, but I didn't get anything running so I've probably missed something.

# Answer
> 1 votes
First off, you should add the javascript and css includes in a preprocess function: `yourmodule_preprocess_node()`

Also, you never mentioned where/how you are calling `impress().init();`?

Ideally, you should either add it inline using drupal\_add\_js() and make sure it has a weight that is higher than the impress.js include or you could wrap it in a Drupal.behaviors in your own custom js (make sure its loaded after).

In case you are thinking about it, you should really avoid putting any css and js in node bodies, its just terrible practice and will likely get shredded by filters.

Also, this is unlikely to collide in any way with jQuery, try adding jQuery in your static demo page to find out.

**EDIT**

Your behavior code is almost there, it should look like this:

```
(function ($) {
  Drupal.behaviors.impressintegrator = {
    attach: function (context, settings) {
      $('#simple', context).jmpress(); // notice passing context variable to optimize selector
    }
  };
}(jQuery));

```

One thing though, you specify $('#simple") in your example, but I don't see it anywhere in your markup. Also the code example from the library link suggests an entirely different approach than you are taking.

**However, the main problem is that the "impress-not-supported" class should be added to the body element!**

In your behavior, before anything else, do this:

```
$('body', context).addClass('impress-not-supported');

```

Also, I've never heard of jmpress, I've been working with impress.js, so you should try including it and using the impress.init() function call as in the project's example.

Finally, to add weights to your javascript includes:

```
drupal_add_js('path/to/impress', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => 0'));

```

You should add the JS\_LIBRARY group to the impress.js file and JS\_THEME to your custom script. Weight = 0 should be fine for both as libraries get added before theme scripts. Do read up on the drupal\_add\_js() documentation it explains all of this stuff in detail! :)

# Answer
> 0 votes
Plan B: Try and use the existing Impress.js module!

---
Tags: 7, nodes, javascript
---


# Question
Title: Cannot display a custom user field in php in Drupal 7
I added an array field with three possible values to the user. It is called field\_user\_school\_category. I am using Drupal 7.

I want to extract the field value for the current user and use it in a page in an if statement (in php text format). I just can't get the extract code to work. I can't even get the value to print - see code below. What am I doing wrong?!

The field is currently set up to accept multiple values. (I know I need to probably loop through to extract any other values later on). I have also tried using $school\['und'\]\[0\]\['safe\_value'\] instead of $school\[0\] amongst a myriad other things.

Any ideas or help would be very gratefully received.

Thanks Sheila

```
<?php
global $user;
$account = user_load($user>uid);
$school = field_get_items('user', $account, 'field_user_school_category');
$schoolcat = field_view_value('user', $account, 'field_user_school_category', $school[0]);
print $schoolcat;

```

# Answer
Some problems, and their solutions:

1. Never use the PHP input filter.
2. When you are developing code, ensure that you have proper error reporting on. This would show you that you have a problem on the `$account =` line.

1. PHP 5.3: `E_ALL | E_STRICT`
    2. PHP 5.4: `E_ALL`.
3. Your general problem is not in code per se, but in not understanding how to debug code. If you have devel installed, you can `dpm()` values on a line per line basis, in an attempt to nail down the problem. If you were to do that, you would quickly notice that $account does not contain the values you expect. `$user>uid` is actually a mathematical operation, and will **not** return the users uid. What you want is `$user->uid`.
4. `field_view_value()` will, as the documentation suggests, return "a renderable array", it's not going to actually give you meaningful output, and since it's an array, you can't `print` it.

I'm guessing what you actually want is:

```
<?php
global $user;
$account = user_load($user->uid);
$school_cats = field_get_items('user', $account, 'field_user_school_category');
foreach ($school_cats as $school_cat) {
  print $school_cat['safe_value'];
}

```
> 1 votes

---
Tags: entities, users
---


# Question
Title: How can I filter content with a date that is somewhere this week by using Views?
I am developing a project in Drupal 7, in this every content have date field by using the Date module.

I am trying to create a block by using the Views module in which I want to display content with its date field containing a date that is 'this week'.

How can I do this?

# Answer
> 3 votes
You simply add the filter criteria to view.

* **operator type**: is greater than
* **value type**: -7 days

# Answer
> 1 votes
Views and the various date modules are pretty slick in that you can "free form" a lot of the values: `last week`, `this week`, `last tuesday` etc all work in the filters. So you would select Date in the filters and then greater than, less than, etc and input what you needed in the to and or from fields.

---
Tags: 7, views
---


# Question
Title: Drupal 7 submit function not called for themed form
I am developing a form. 2 functions are:

```
function reserve_multi_step_form($form, &$form_state)
{
       $module_path = drupal_get_path('module', 'reserve');

       $form['#theme'] = 'reserve_form_2';
       $form["agreed"] = array(
                            '#type' => 'checkbox',
                            '#title' => t("I accept the deposit policy"),
                            '#attributes' => array("onChange" => "policy_accepted();"),
                            );

       $form['submit'] = array(
                       '#type' => 'submit',
                       '#value' => t('Submit'),
                       '#attributes' => array('style' => "padding: 0 10px;"),
                       "#disabled" => true,
                       );

       return $form;
    }

function reserve_multi_step_form_submit($form, &$form_state) {
       print 1111;exit;
}

```

The theme function:

```
function reserve_theme($existing, $type, $theme, $path){
   return array(
                'reserve_form_2' => array(
                                          'render element' => 'form',
                                          'template' => 'reserve_form_2',
                                          'path' => drupal_get_path('module', 'reserve'),
                                          ),
}

```

In the template file I print some text and render the form:

```
    <?php
    print "text";
    print drupal_render_children($variables["form"]);

```

The form is displayed correctly. But after I click submit button, the reserve\_multi\_step\_form\_submit is not called. Without theming it works. What can be an issue?

# Answer
You have the `#disabled` property set on your submit element. Drupal's form API does not process the input for any element, including submit buttons, if the `#disabled` property is set on the server side.

If you're interested in the code behind this, the decisions are made in the `_form_builder_handle_input_element()` function in the `includes/form.inc` file of your Drupal installation.

If you want the submit button to be disabled by default for client-side purposes (i.e. you'll be enabling it through JS based on some action taken by the user) you would be better off setting the `disabled` attribute directly on the element, as Drupal pays no attention to this when processing the form:

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array(
    'style' => "padding: 0 10px;",
    'disabled' => 'disabled'
  )
);

```
> 1 votes

---
Tags: theming, forms
---


title: Reloading JavaScript only

text:
# Question
Title: Reloading JavaScript only
I am developing/testing some JavaScript functionality. Every change in the JavaScript code I make means I have to reload the page, and wait for Drupal to build the page from scratch, which I don't need at the moment.

Is there a way for telling the browser to reload that one file only?

# Answer
> 1 votes
A possible solution is entering the following code into the console, where "xxx" is a part of the name of the script you want refreshed, and "yyy" its exact adress; the string after the question mark has to be changed each time to force Chrome not to cache it.

```
jQuery("[src*=xxx]").replaceWith('<script type="text/javascript" src="http://yyy?m2fua6ijsufsds"></script>')

```

It could probably make for a nice useful mini module, which would provide a button/shortcut that would automate the call.

---
Tags: javascript
---


# Question
Title: How to hide a field from anonymous users?
I've been searching for this for quite some time, but so far I haven't been able to find a good way to hide a field on my custom content type from anonymous users. I want some fields to be visible only to logged-in users. Any idea how I can do this?

# Answer
Use the Field Permissions module.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> ### Features
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> 6 votes

---
Tags: users
---


# Question
Title: Is there a way to get a default e-mail recipient by default when adding a new webform node?
When I add a new **Webform** node type, this have no e-mail recipien by default. You can read this message:

> Currently not sending e-mails, add an e-mail recipient below.

Is there a way to get a e-mail recipient value by default when creating a webform node?

# Answer
> 5 votes
You can do this with a custom module and hook\_node\_presave(). After you have a custom module created, you can use code like this to create a default e-mail configuration for any created Webforms.

Assuming your module were called myexample.module, the hook would look like this:

```
<?php
/**
 * Implements hook_node_presave().
 */
function myexample_node_presave($node) {
  // Add a default e-mail configuration for new nodes.
  if (empty($node->nid) && $node->type == 'webform') {
    $node->webform['emails'][] = array(
      'email' => 'example@example.com',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
      'html' => 0,
      'attachments' => 0,
    );
  }
}
?>

```

# Answer
> -1 votes
Yes, you can.

You go to your webform node, click on "webform" then "email's", you should set up one if you don't have one, and on "E-mail to address" you can write your default email. You can even set up the subject and the body. You can print the whole email through %email\_values token value, or field by field with label using %email\[yourfield\] or without label using %value\[yourfield\].

I'm editing my answer:

You can set a defaul email recipient you have three choices:

1. You create an email field with a defaul value (your email) and the user can change that value;
2. create an email field with your email such as default value and click on "disable" if you don't want the user changes the email but he can still see it;
3. create a email field with your email such as default and click on "hidden", the user won't be able to see and change that email;

I hope this time will be useful :D

---
Tags: webforms
---


# Question
Title: Google shows node links instead of Custom URL
I have got a serious problem. My drupal website was going well. All Links crawled and indexed by Google were custom(natural), But some days ago my website went down because of bandwidth problem. After then, all my links in Google started appearing in /node/number form. e.g I had a link like http://www.myexamplee.com/all-good and now its appearing as http://www.myexamplee.com/node/234 . Can any body help? (I have done autopath tricks, robot.txt node exclusion and clean url like stuff but did not get any results in one week of time). Any expert any paid service any idea will be welcomed. Many thanks to all readers and experts.

# Answer
> 5 votes
Not sure how google got to index the node/123 URLs. Do you use a sitemap? I would install the Global Redirect module to make sure those URLs get redirected to the SEO optimized URLs. Select the "canonical" tag option in the config for that module.

I wouldn't worry to much about the SEO impact, especially if it's a new site.

---
Tags: taxonomy-terms
---


# Question
Title: Ubercart file downloads - group user's file downloads by product
Setting up a site using Drupal 6 and Ubercart (UC) to sell video downloads. I've configured UC as required to sell the file downloads and that all works. However, when a user visits their profile and views their file downloads, I need that page to display files on a per product grouping.

For example, a customer purchases product A, which includes three files. They then purchase product B, which includes two files. I need the user file downloads page to display the five files in two groups, Product A files and Product B files.

# Answer
> 1 votes
I solved this issue with a combination of:

* Advanced profile
* Views
* Node access

I used the Node Access module to create products that were nodes. Only users that had purchased a particular node could see it.

I used Views to create a view that displayed all nodes of the relevant type, including the files attached to them, in a table. The view will only display items that the user viewing it has permissions to see (i.e. those that they have purchased).

I used Advanced Profile to create a new profile page that displayed the view outlined above.

---
Tags: ubercart, files
---


title: Create link to node on view

text:
# Question
Title: Create link to node on view
I want to add a 'like' button to a table. I get as far as the like button appearing on the page, but I can't figure out how to build the link into that spot.

The problem is, the only way to do that (that i've found so far) is to make a full html field on the content item and place the code for the iframe in there. I can't figure out how to make that a link to the node itself.

I tried using the view to add a field Global text, but I can't get an iframe to load from there. If I could do it there then I could use replacement patterns to build the proper link.

If it helps unmuddle it to remove some context: I want to create a table of nodes that pass a filter. I want that to be a table of iframes loading the node the table row represents.

# Answer
In views you can simply do it with the help of Views PHP module

This module allows administrators to add fields, filters and sorts to views which use PHP code.
> 0 votes

# Answer
Is this table generated from Views?

If so, you should be able to just add a node link, rewrite it to output ONLY the URL, hide it, then use that field as a rewrite pattern in your facebook button's output, so the like button is applying to the URL of the node itself.
> 0 votes

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


# Question
Title: Easiest way to add x-webkit-speech to the search block's input element
I am creating a zen sub theme and I was wondering what't the quickest way to add the x-webkit-speech attribute to the search box so user's can search with their voice? I know there is a Drupal project that can modify the search for me but I would prefer to do it in my templates somewhere so the rendered output is something like...

```
<input title="Enter the terms you wish to search for." type="text" x-webkit-speech id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

```

# Answer
as described in hook\_form\_FORM\_ID\_alter and @tenken said, write a simple module:

```
function mymodule_form_search_block_form_alter(&$form, $form_state, $form_id) {
  $form['search_block_form']['#attributes']['x-webkit-speech'] = 'x-webkit-speech';
  $form['search_block_form']['#attributes']['speech'] = 'speech';
}

```

also to have valid xhtml avoid valueless attribute.
> 1 votes

# Answer
use hook\_form\_alter on the search\_form and add an HTML attribute via the `#attributes` for x-webkit-speech.
> 2 votes

---
Tags: search, theming
---


# Question
Title: Migrate part of a Drupal 6 installation to a new Drupal 7 installation
I'm trying to migrate the users and the Forum nodes (including comments) from Drupal 6 Installation (current productive system) to a new Drupal 7 installation (staging system). I wanted to start from scratch with Drupal 7 so I did not go the upgrade way, but now I'm facing the problem that some data has to be migrated anyway.

I tried several Import/Export modules, but none really does what I want. Any ideas?

# Answer
> 1 votes
I might try the Migrate module. It takes some coding but but the documentation and example modules for it are very detailed and helpful. Basically you would create a migration class for the users (see BeerUserMigration) and a class for the forum nodes (see BeerNodeMigration).

One of the great things about this module is it creates a mapping between both data stores which allows you to rollback and re-run the migration until you get it right.

---
Tags: migrations
---


# Question
Title: How can I stop a Rule action from being executed, programmatically?
How can I stop sending an email, for example? Assume the event is `before_sending_an_email`.

# Answer
> 1 votes
Once happened, you can't stop an action.

The only thing you can prevent from happening is executing the action at all. In case of e-mails, you can only stop an e-mail with rules if it has been sent by a rule. Then you need to add a condition to that rule to prevent it from executing the action that sends the mail.

To prevent a mail that is sent directly in the code, you need a custom module, implement hook\_mail\_alter() and redirect it to a dummy address, you can't really stop it there either.

---
Tags: 7, rules
---


title: "set" version of field_get_items?

text:
# Question
Title: "set" version of field_get_items?
One can retrieve field items from an entity with

```
// Find all terms on $node in field 'field_tags'.
$terms = field_get_items('node', $node, 'field_tags');

```

But is there a convenient way to do the reverse, Core, or otherwise?

```
// Attach new term $term to $node in field 'field_tags'.
$term = taxonomy_term_load($tid);
$node = field_set_items('node', $node, 'field_tags', 'taxonomy_term', $term);
node_save($node);

```

I would like to avoid the hassle of manually assigning a $term, go look in devel what the array structure looks like and then build the array by hand, as it is sometimes non-trivial.

The only issue in the core queue I could find that looked vaguely similar was about the field language api DX.

# Answer
> 6 votes
No, there is no such function.

See my comment at Language support for entity fields.

# Answer
> 2 votes
For such a function to exist, `field_set_items()` would need to be able to identify the `stdClass` object as that of a taxonomy term, and also map it to a function that can decode the object and create a field array out of it.

Since there's no core function to do that, I don't think this will be easy.

# Answer
> 2 votes
Although this doesn't help building the some times complicated array structure, I see that what I'm looking for has to some extent been introduced in Drupal 8. Perhaps it will be extended further in the future. :)

New simpler API available for accessing fields, properties and language information.

Example usage from the linked page:

```
<?php
// Change a field value.
$body = $comment->get('comment_body');
$body[0]['value'] = 'This is actually a perverted tango';
$comment->set('comment_body', $body);

```

---
Tags: entities
---


title: Multiple submit/save buttons in form

text:
# Question
Title: Multiple submit/save buttons in form
I wanted to add another submit/save button above a node form (for only one content type) and added the code below. The thing is that it messes up the submission, so I had to remove it.

Whats wrong with it and is ther a better way of doing this?

```
if ( $form_id == 'news_node_form' ) {
        $form['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Save'
                );
        }

```

# Answer
Thank you JimJamma, that worked!

Here's how my code looks now:

```
    $form['submit'] = array(
        '#type' => 'submit',
        '#access' => variable_get('node_preview_branschguiden', DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
        '#value' => t('Save'),
        '#weight' => 5,
        '#submit' => array('node_form_submit'),
    );

```
> 4 votes

---
Tags: 7, forms
---


# Question
Title: how to give parameters in url for getting json parse for both taxonomy terms AND nodes
i created 2 nodes in Company CCK under taxonomy A, 2 nodes in Company CCk under taxonomy B. now i want to get a json parse for all the nodes in a taxonomy A.

I tried like this www.mywebsite/api/taxonomy\_term?selectNodes&parameters\[tid\]=1 it gives the value of that taxonomy term but, i wont get nodes under that category . In what way the url should be framed for attaining values of nodes of a particular category(taxonomy) i.e i would like to filter the nodes of my choice.

so any one help me, Thanks in advance

# Answer
you can use `taxonomy_select_nodes` to find all nodes associated with a term.

Return nodes attached to a term across all field instances.

**Parameters**

**$tid:** The term ID.

**$pager:** Boolean to indicate whether a pager should be used.

**$limit:** Integer. The maximum number of nodes to find. Set to FALSE for no limit.

**$order:** An array of fields and directions.

API
> 1 votes

---
Tags: 7, services
---


# Question
Title: Entity Reference - show link on referenced node
I have a "Entity Reference" field in a custom content type. I want to show on any referenced node the link to the node. How can I do it?

# Answer
I found the solution! I just went to "Manage display" of the content type and I checked "Link label to the referenced entity" in the "Entity Reference" field.
> 2 votes

# Answer
you can create a view page. while selecting the entity reference field you have to select the "Formatter:" as Title(link)
> 1 votes

---
Tags: entities
---


# Question
Title: Isn't it possible to have multiple buttons  along with a submit button?
I have a simple Drupal 7 form, with 3 dropdown select lists and a submission button. I want to add another button to the form which does some function (but not submitting the form). I want to bypass the validation part for the form and directly run the submission handler of that button.

The button I am using is the following one.

```
$form['my_fieldset']['click'] = array(
  '#type' => 'button',
  '#value' => 'click me',
  '#limit_validation_errors' => array(),
  '#executes_submit_callback' => FALSE,
  '#submit' => array('my_module_click_submit'),
);

```

FYI, all the select lists have `#required=>TRUE`, and `#type=>'submit'` for the button also doesn't work.

When I click it, it shows the error about the fields being required. How can I avoid that error, avoid validation handlers are run, and just run the code in `my_module_click_submit()`?

Also, I dont know why, but even if I fill the entire form and then click this button, the page just gets refreshed and `my_module_click_submit()` does NOT run. What's wrong?

I haven't put anything fancy inside `my_module_click_submit()`; I just wanted to see if it works. The submission handler I am trying is the following one.

```
function my_module_click_submit($form,&$form_state) {
  drupal_set_message('Click me button is clicked');
}

```

# Answer
Jaypan gave me the answer.

> 1. Required checks happen irregardless of validation - they happen before any other validation even occurs.
> 2. You cannot skip the default \_validation() function, it is always executed
> 3. When you choose limit\_validation\_errors(), anything that is not part of that array is not submitted.
>
> As such, you will want to explicitly declare your submit and validate functions for the original submit button, and leave the second button as-is, using the default submit and validate functions:
>
> ```
> function some_form($form, &$form_state) {
>   // Form definition not shown.
>   $form['submit1'] = array(
>     '#type' => 'submit',
>     '#value' => t('Submit 1'),
>     '#validate' => array('my_explicit_validate'),
>     '#submit' => array('my_explicit_submit'),
>   );
>
>   $form['submit2'] = array(
>     '#type' => 'submit',
>     '#value' => t('Submit 2'),
>   );
>
>   return $form;
> }
>
> // my_form_validate is not created, since we don't want to validate the second submit button, but we do want the submit function.
> function my_form_submit($form, &$form_state) {
>   // You need to check which submit button was pushed, as this function
>   // will be run for both buttons, but you only want do something if it was the
>   // secondbutton.
>   if($form_state['values']['op'] == $form_state['values']['submit2']) {
>     // Second submit button's submit function.
>   }
> }
>
> function my_explicit_validate($form, &$form_state) {
>   // Validation for the first submit button.
> }
>
> function my_explicit_submit($form, &$form_state) {
>   // First submit button's submit function.
> }
>
> ```
>
> To deal with your required issue, you will need to not set `#required => TRUE` for the elements, and check them manually in your validation function (the function explicitly declared for the first button). If you want to have the required marks, I think you can manually add them to the element title, or you can override the theme function for those elements and manually add them there.
> 3 votes

# Answer
You are correctly using the `#limit_validation_errors` property; the documentation clearly states that setting it to an empty array avoids any validation being done. Even reading what reported for form\_set\_error(), I cannot find anything that would explain the behavior you are observing.

> The standard `form_set_error()` behavior can be changed if a button provides the `#limit_validation_errors` property. Multistep forms not wanting to validate the whole form can set `#limit_validation_errors` on buttons to limit validation errors to only certain elements. For example, pressing the "Previous" button in a multistep form should not fire validation errors just because the current step has invalid values. If `#limit_validation_errors` is set on a clicked button, the button must also define a `#submit` property (may be set to an empty array). Any `#submit` handlers will be executed even if there is invalid input, so extreme care should be taken with respect to any actions taken by them. This is typically not a problem with buttons like "Previous" or "Add more" that do not invoke persistent storage of the submitted form values. Do not use the `#limit_validation_errors` property on buttons that trigger saving of form values to the database.
>
> The `#limit_validation_errors` property is a list of "sections" within `$form_state['values']` that must contain valid values. Each "section" is an array with the ordered set of keys needed to reach that part of `$form_state['values']` (i.e., the `#parents` property of the element).

I can only think of a collateral effect of setting the `#limit_validation_errors`, and the `#executes_submit_callback` properties. The latter is causing the submission handler not to be called for your button; when you set it to `FALSE`, the button doesn't submit the form, which means the submission handler for that button is not being called.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Can I have a webform in sidebar block reload current page
I have a webform in my sidebar as a block. If I set `Redirection location` to `No redirect (reload current page)`, it loads the form url in the main content. I can understand why it's doing this, but I would like it to reload the current page instead (or submit the form with AJAX but that's not necessary). Is there any simple way of achieving this?

# Answer
> 11 votes
This is an old question, but it comes up high in search results, so I thought I'd provide an answer.

The behavior you've described is the intended behavior. The module maintainer states that the original implementation of the `No Redirect` option was designed "under the assumption that if you were starting a form you'd enter minimal information (such as an e-mail address) to start the form, then you'd want the rest of the form on a larger page."

To achieve *your* desired behavior (i.e., reload whatever page the block form is submitted from), you need to take one extra step: From the block configuration page, check the box for `Show all webform pages in block` and save the configuration.

# Answer
> 1 votes
What version of Drupal and webforms are you using? I don't remember what D6 allowed, but in D7 you can set a custom redirection and use a token to control what the redirect is.

You would want to get the URL of the current page (i.e. with a token like %request) and redirect to that.

---
Tags: 7, blocks, webforms, redirection
---


title: drupal_mail() in HTML

text:
# Question
Title: drupal_mail() in HTML
I want the outgoing mail that is sent by my custom module to be in HTML, but I dont know how.

This is my submit function:

```
//create an array from the companies in the db in a comma separated list
$companies = db_query("SELECT companies FROM {offer} WHERE id = $id")->fetchField();
$companies = explode(',', $companies);

// Set some variables
$from = 'noreply@danielholm.se';
$subject = 'Sent mail';
$module = 'mymodule';
$key = 'mykey';
$language = language_default();
$params = array();
$send = TRUE;

// the data
$question = db_query("SELECT message FROM {offer} WHERE id = $id")->fetchField();
$name = db_query("SELECT name FROM {offer} WHERE id = $id")->fetchField();
$mail = db_query("SELECT mail FROM {offer} WHERE id = $id")->fetchField();
$phone = db_query("SELECT phone FROM {offer} WHERE id = $id")->fetchField();
$compname = db_query("SELECT compname FROM {offer} WHERE id = $id")->fetchField();
$comptype = db_query("SELECT comptype FROM {offer} WHERE id = $id")->fetchField();

// Sort the companies
foreach($companies as $company) {
        $message = drupal_mail($module, $key, $company, $language, $params, $from, $send);
        // Create the mail content
        $message['subject'] = $subject;
        $message['body'] = array();
$message['body'][] = 'THe HTML MAIL HERE';

        // Retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // Format the message body.
        $message = $system->format($message);

        // Send e-mail.
        $message['result'] = $system->mail($message);

        // Update table where sent to 1
        $update = db_update('offer')
            ->fields(array(
            'sent' => '1',
            ))
            ->condition('id', $id, '=')
            ->execute();

        // Set message of performed action
        drupal_set_message('Done');
        $form_state['redirect'] = 'admin/content/offer';
        cache_clear_all();
}

```

# Answer
drupal\_mail() by default adds text/plain headers. You have 3 options here:

1. use Hook\_mail\_alter and add your custom text/html headers;
2. use custom pre-build modules mentioned already here;
3. Implement MailSystemInterface and send you own mail as follows:

```
class YourMailSystem implements MailSystemInterface {

/**
 * Concatenate and wrap the e-mail body for plain-text mails.
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 *
 * @return
 *   The formatted $message.
 */
public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);

    if ($message['module'] == 'your_module') {
        $body =  $message['body'];
        $message['body'] = array();

        // Convert any HTML to plain-text.
        $message['body']['plain'] = drupal_html_to_text($body);
        $message['body']['plain'] = drupal_wrap_mail($message['body']['plain']);

        // Wrap the mail body for sending.
        $message['body']['html'] = drupal_wrap_mail($body);
    } else {
        $message['body'] = drupal_wrap_mail($message['body']);
    }

    return $message;
}

/**
 * Send an e-mail message, using Drupal variables and default settings.
 *
 * @see <a href="http://php.net/manual/en/function.mail.php
  " title="http://php.net/manual/en/function.mail.php
  " rel="nofollow">http://php.net/manual/en/function.mail.php
  </a>   * @see drupal_mail()
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 * @return
 *   TRUE if the mail was successfully accepted, otherwise FALSE.
 */
public function mail(array $message) {
    $mimeheaders = array();

    if ($message['module'] == 'your_module') {
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // main header
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = $message['from'];
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = $message['from'];
        $message['headers']['Content-Type'] = "multipart/alternative; boundary=\"".$separator."\"";

        // message
        $body = "--".$separator.$eol;
        $body .= "Content-Type: text/plain; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['plain'].$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['html'].$eol;
        $body .= "--".$separator."--";

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);

        $sendM = mail(
                $message['to'], mime_header_encode($message['subject']),
                preg_replace('@\r?\n@', $line_endings, $body),
                join("\n", $mimeheaders)
        );

        return $sendM;
    } else {
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = $message['from'];
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = $message['from'];
        $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

        if(isset($message['customMode']) && $message['customMode'] == 1) {
            $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed; delsp=yes';
        }

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $heads = join("\n", $mimeheaders);

        $sendM = mail(
                $message['to'], mime_header_encode($message['subject']),
                // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
        // on Unix and CRLF on Windows. Drupal automatically guesses the
        // line-ending format appropriate for your system. If you need to
        // override this, adjust $conf['mail_line_endings'] in settings.php.
                preg_replace('@\r?\n@', $line_endings, $message['body']),
                // For headers, PHP's API suggests that we use CRLF normally,
        // but some MTAs incorrectly replace LF with CRLF. See #234403.
                $heads
        );

       return $sendM;
    }
  }
}

```

Then in your module you need to implement a mailSystem usage like so:

```
  function hook_install() {
      variable_set('mail_system', array_merge(
                      variable_get('mail_system', array('default-system' => 'DefaultMailSystem')), // Previously set mail_system variable
                      array('your_module' => 'YourMailSystem')   // My new key(s) which ADD to the previous keys
              )
      );
  }

  function hook_uninstall() {
      // Unset module keys in variable mail_system
      $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
      unset($mail_system['your_module']);
      variable_set('mail_system', $mail_system);
  }

    function hook_mail($key, &$message, $params) {
      global $language;
        // We can define more then one email template, naming is by key
        //global $language;
        switch ($key) {
          case 'registration':
              // note: data can be passed to this function in the $params array
              $body = ''; // GET YOUR BODY CONTENT
              $subject = ''; // YOUR SUBJECT HERE

              break;
          case 'remind_pass':
              // note: data can be passed to this function in the $params array
              $body = ''; // GET YOUR BODY CONTENT
              $subject = ''; // YOUR SUBJECT HERE

              break;
        }

        $message['subject'] = $subject;
        $message['body'] = array();
        $message['body'][] = '<html><body>';
        $message['body'][] = $body;
        $message['body'][] = '</body></html>';
        return $message;
    }

```

And to use this mailSystem, call drupal\_mail from your module like this:

```
drupal_mail('your_module', 'remind_pass', 'someone@somewhere.com', language_default(), $params, 'from@mail.com', true);

```

**Things to note:** This implementation will send multiple email types, that is: plain and html at once. We could also further improve this to support attachments.

This implementation looks for my custom module content to process as plain/html, if it does not get one, then it sends all stuff as default: text/plain.
> 9 votes

# Answer
You can try Mime Mail module.

> This is a Mime Mail component module (for use by other modules).
>
> 1. It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
> 2. If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
> 3. Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
> 4. If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
> 5. Allows you to theme messages with a specific mailkey.
> 6. Converts CSS styles into inline style attributes.
> 7. Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
> 11 votes

# Answer
I've written a module (which bridges Drupal with the Swift Mailer PHP library) which handles HTML, attachments, inline images, theming and the like. It let's you define wether e-mails by default should be sent as HTML or plain text.

It's currently awaiting approval, but I'm using it myself on production sites and it works well. Have a look at it on http://drupal.org/sandbox/sbrattla/1163884.
> 5 votes

---
Tags: 7, emails
---


# Question
Title: How do I get the fivestar module's vote on a review node to count towards a product node?
Should be simple. I have a content type called Product. I have another content type called Review.

I want people to vote when they create the Review content type and have the vote count towards the Product. When I display the Product, I want the average of the votes to appear with the product. Problem: When I add the fivestar field to the Review content type I DO NOT see an option to set a target node.

Note: I am not using comments as reviews, I am using another content type.

I have tried to find a solution in other postings and I have no problem with a programmatic solution but I have not found anything clear.

# Answer
> 2 votes
The problem was that I had just switched the links between my Reviews -\> Products to use entity relationships (instead of node links) and Fivestar does not support that.

A patch that seems to work was posted two days ago. As soon as I applied the patch, the "target node" field appeared. http://drupal.org/node/1488914

In addition, the product's Fivestar field had to be set to "rate while viewing" and the Review's Fivestar field had to be set to edit while eediting.

# Answer
> 0 votes
Since Fivestar uses Voting API to do the heavy lifting, you can use some of Voting API's hooks to intercept votes and do your magic there.

Alternatively, when you display the Product you can implement a preproces\_node to fetch all reviews for that product and manually count the votes and calculate the average.

That said, I'd create some hidden fields in the product (#access false ftw) and manually update them with every vote using the aforementioned hooks.

---
Tags: rating
---


# Question
Title: content_extra_field_weight() function in Drupal 7
I am porting a module to Drupal 6. I came across this function content\_extra\_field\_weight(), what is the similar function in Drupal 7 for content\_extra\_field\_weight()?

# Answer
> 1 votes
Invoke hook\_field\_extra\_fields(), pass the result to hook\_field\_extra\_fields\_alter() and look for *weight* keys in the result.

---
Tags: 7, entities
---


# Question
Title: Can I programmatically create a new node revision, without the new revision becoming the "current" one?
Whenever my feeds import finds a new version of an existing piece of content, it creates a new revision of this node instead of overwriting data.

Normally the new revision becomes the "current" one right away. I would like the currently displayed revision however to remain the same, and let a moderator decide later if the new one should be published.

# Answer
A standard Drupal install does not allow you to create a "Pending" revision. You have two options:

1. Programatically create a new revision but programatically revert back to the original revision (which creates an even newer revision, but it has the original content)
2. (Recommended) Use Workbench Moderation, Revisioning or Workflow which are well thought-out solutions for version control and/or access control.

For option 1: You can add this code as a new Rule or use it in a new module

```
<?php
  // Programatically load the existing revision and save it
  // Taken from http://api.drupal.org/api/drupal/modules!node!node.module/function/node_save/7
  // Load the revision
  $original_revision = node_load($nid);
  $original_revision->revision = 1;
  $original_revision->log = t('Copy of the revision from %date.', array('%date' => format_date($original_revision->revision_timestamp)));

  $new_revision = node_load($nid);
  // Make any changes to the new revision here...
  $new_revision->revision = 1;
  $new_revision->log = t('Summarize your changes here');

  // Save the new revision first
  node_save($new_revision);

  // Save the original one again so that it is still the current revision
  node_save($original_revision);

  watchdog('content', '@type: reverted %title revision %revision.', array('@type' => $node_revision->type, '%title' => $node_revision->title, '%revision' => $node_revision->vid));
  drupal_set_message(t('@type %title was saved with a new revision, but reverting to original revision from %revision-date.', array('@type' => node_type_get_name($node_revision), '%title' => $node_revision->title, '%revision-date' => format_date($node_revision->revision_timestamp))));
  drupal_goto('node/' . $node_revision->nid . '/revisions');
?>

```

For option 2: I would recommend Workbench over Revisioning or Workflow, but each is different depending on your needs. Workbench is kind of the successor to Revisioning, and Workflow is a lot more than just version control, so it may or may not be a good fit for your needs.

Here's a quick breakdown on the differences between Workbench and Workflow.
> 15 votes

# Answer
This is a guess, but I would give the Workbench Moderation sub-module in the Workbench module a shot. I have found this much easier to set up than Workflow.

The fact that you are creating nodes in code shouldn't matter, as long as the `node_save()` runs as a user with the proper settings for the content type (the moderation states are handled with the node API). This may mean, though, that you need to do some session shenanigans to get things done as the proper user when Feeds runs.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Same file_temporary_path for localhost and production server?
Each time I move one of my Drupal website from localhost to production server or vice-versa, I have to edit my `settings.php` to update the path of the temporary file directory:

```
# $conf['file_temporary_path'] = '/home5/dawnings/public_html/fw2/tempdir';
$conf['file_temporary_path'] = 'c:/Temp/Drupal/tempdir';

```

Is there a way to specify a unique relative path to this temporary file directory once for all and which would work both for localhost and production server? The objective is to avoid having to update my `settings.php` anymore.

# Answer
> 4 votes
There is more than 1 way to accomplish something like this. I am not aware of a simple "1 line universal fix" unless you try a relative path, but that assumes *some consistancy* between your servers which clearly by your directory paths you dont have.

Option 1:

At the bottom of you settings.php put something like:

```
$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

```

I do this programmatically in BASH with like:

```
#!/bin/bash

# I actually install drupal via the command line with a custom install
# profile and append on the tidbit to settings.php programmatically like
# so ...

cd $drupal_www_dir
drush site-install MY_INSTALL_PROFILE \
  --locale=en \
  --db-url="mysql://dev_user:dev@localhost:3306/demo_drupal" \
  --account-name=admin \
  --account-pass='admin' \
  --acount-mail=foo@test.com \
  --site-name=demo --verbose -y

#
# Now that drupal is built we modify the settings.php file with additional db
# and other custom configuration values by appending a child seetings file.
#
# This is in concept similar to an Apache vhost directive file.
#
echo "altering settings.php to be aware of our 3rd party remote databases."
sudo chmod -Rv a+rw "${drupal_www_dir}/sites/default"
read -r -d '' PHPCODE <<'EOF'
/*
 * For our project we provide our own localized configuration schemes.
 */
$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

EOF
echo "${PHPCODE}" >> "${WWW}/sites/default/settings.php"

```

Then for each server you keep a version of this file. Or in this file make an If-Else PHP block that stores the correct `$conf` value based on whether this configuration file is `$local` vs `$dev` or `$prod`. So basically you can move all your custom settings.php stuff that arent 100% stock drupal into a special appended configuration file ... this way the stock drupal settings.php stays as it is and all your custom stuff can go into its own file as-needed.

Option 2:

Use something like the Environment module and in PHP set the value for the `file_temporay_path` with variable\_set as that is what is being called by file\_directory\_temp().

Those are the two options I know of that aren't brain surgery ...

**EDIT 09/26/2014 by author**

* You can also use Drush on each server to run: `drush vset file_temporary_path "to/some/path"`
* If you're comfortable with virtualhost settings you can also always create a aliased directory in your webserver configuration (pushing the problem up 1 level in the production stack (out of PHP))

---
Tags: 7, configuration
---


title: Expiring roles for users?

text:
# Question
Title: Expiring roles for users?
I have created few user roles and one of them should be an expiring role, which would be active only for a period of time (something like paid subscription - if user pay for new period of time, the account becomes fully active again). I know of Role Expire, but I'm not sure it's the right think - it wasn't updated in long time and first activating the module instantly created few error messages. Similiar thing (probably) with Notifications.

Any hints how to achieve it? Use one of these modules? Or is there something more I couldn't find so far?

# Answer
> 2 votes
One way to do this would be using rules.

Rules allow you to execute some rules/action sometime in the future.

See http://dev.nodeone.se/node/1032 shows a great similar example.

---
Tags: users
---


title: Add role on custom register form

text:
# Question
Title: Add role on custom register form
I'm using the default register form on a custom page, which I want to use to set a specific role for the user who registers using that custom page.

Now I need to know how I add this specific role when the user registers.

Can I use like, the submit funcion for the custom form function, and then use user\_multiple\_role\_edit()?

But how di I get the $uid?

What's best?

# Answer
Here is my solution based on my favorite Rules module ;)

These 2 rules below automatically assign a predefined role to a user who registers to your website using a promotional link and code.

Important: Before importing these 2 rules:

1. backup your site :P
2. replace `example.com` with your domain name
3. replace `11` with your role id number
4. replace `code=promo1` with your secret promotional code

You can import rules via this page on your website: `/admin/config/workflow/rules/reaction/import`

**Rule 1:**

```
{ "rules_auto_assign_role_1" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "11" : "11" } } } },
      { "data_is" : {
          "data" : [ "site:current-page:url" ],
          "value" : "http:\/\/example.com\/user\/register?code=promo1"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user?code=promo1" } } ]
  }
}

```

**Rule 2:**

```
{ "rules_auto_assign_role_2" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
      { "AND" : [
          { "NOT user_has_role" : {
              "account" : [ "site:current-user" ],
              "roles" : { "value" : { "11" : "11" } }
            }
          },
          { "data_is" : {
              "data" : [ "site:current-page:url" ],
              "value" : "http:\/\/example.com\/user?code=promo1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "11" : "11" } }
        }
      }
    ]
  }
}

```
> 4 votes

# Answer
So I did it like this: 1. I skipped the usage of role 1 and just used the altred register form to redirect the new user to the user page with a secret query in the url. 2. Then I used rule 2 and changed the query to the one I was using, changed the static URL to a relative one, and finished the rule of by redirecting the user to another page so he/she wouldn't see the secret query in the URL.
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: Is it possible to load different versions of the same module?
I am running Drupal 6, in a multisite installation. While I fully understand the problems with having varying versions of the same modules running concurrently, I guess I want to know if there's a way to match a specified version of one module to only process requests, or handle calls made by another module?

I currently have Views 2.x in sites/all/modules. It doesn't work w/ Views Slideshow: Cycle 3.x. I want a way to also have Views 3.x in sites/www.mysite.com/modules, and force it to only process requests that would normally be made by Views Slideshow: Cycle 3.x - but nothing else, as Views 2.x would pick up the rest.

I sort of envision it in the same way Blocks work - where you may have regular expression matching for specified URLS. Thanks for any help in advance.

# Answer
I'm afraid this simply isn't possible without hacking at Drupal core and the Views module(s) in ways I can't even imagine.

As you know Drupal will only ever let you have one version of a module installed at any one time, and there's no mechanism to 'swap' a module based on a condition (such as the current URL).

Conceptually this would be almost impossible for quite a lot of reasons; the most obvious that jumps to mind is the fact that one version would have to be uninstalled before the other could be enabled, thus destroying all of the data that exists for the first version. By the time you 'swap' back to the other version, you've lost all of your original Views data.
> 2 votes

# Answer
In short, there's no reasonable way you could do this, so don't even try.

That said, I found the question interesting so I gave it some thought. In theory, you could abuse Drupal's table prefix, to create a completely separate system table and views table setup.

On this particular URL, you swap the system table, rebuild the modules list, execute your Views, and swap the data back.

Could possibly work, even witout actually hacking Core, but I imagine it's going to require *a lot* of research on how Core works.

A more long term approach that I've actually considered investigaing myself, is implementing module "slots". One could allow each module to declare a "version slot", much like Views internally separates API 2 from 3, allowing Drupal to keep two versions installed at once. This however would probably require some serious refactoring of both Core, and any modules that want to support this.
> 2 votes

# Answer
No.

It really would not work. With some simpler modules you might be able to make it work by renaming one version's folder, file, function and database schema names from " mymodule\_" to " mymodule\_v2\_" before enabling it, and then changing code in the modules that may integrate with it from using the module\_invoke hook functions to explicitly calling the mymodule\_v2\_ function...

but hopefully you see that it's probably not going to work with any module, especially not with Views.
> 1 votes

---
Tags: 7
---


title: Internal mail system

text:
# Question
Title: Internal mail system
How do I allow users send emails to the other users?
What module can I use to allow users to email each other?

# Answer
> 4 votes
I don't know about 'best' (although @Berdir might have something to say on the matter ;) ), but Privatemsg would probably be perfect for this:

> Privatemsg allows your site's visitors to send private messages to each other.

It also provides e-mail notifications of new messages.

---
Tags: 7, emails
---


title: PowerPoint reader (.ppt)

text:
# Question
Title: PowerPoint reader (.ppt)
I searched for a PowerPoint player (ppt from Microsoft Office) but I couldn't find what i needed.
Is there a module that can display PowerPoint files on Drupal sites?

# Answer
> 5 votes
You can use the Embedded Google Docs Viewer module:

> The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.

There's a tutorial that details how to use it on the module page.

---
Tags: 7
---


# Question
Title: Showing child taxonomy terms if the parent is selected
I want to show one drop-down with a list of parent vocabulary terms and then when one of those select corresponding child terms displays in page.

I am using Drupal 7 with views 7.x-3.0-rc1.Any one guide me do this.

# Answer
> 1 votes
Views doesn't have any built in way of creating an exposed filter like you explain, which means that you either need to create this functionality yourself for Views - which is very hard unless you have messed with Views APIs. The other option is to create this functionality in a custom module which a lot easier but also quite time consuming, so you will have to code it all in a custom module.

As a side note you should update your views install, currently up to date version is 3.3, This is quite important as 3.1 or 3.2 had a security fix, meaning you site has a known security vulnerability.

---
Tags: views
---


# Question
Title: Add Custom Line item API or Method Drupal Commerce
I have some products in a Drupal Website using Drupal Commerce. Those products are listed via a custom modules to the front end. If the user clicks on any of the products then it goes to the product display page. There I have 2 checkbox and the Add to Cart Button. Such as

* Gift Packaging ($10.99)
* Custom Messages ($4.99) These are 2 checkboxes coming from a drupal form created on my custom module. I want to add these as line items to the Selected Product. Such as,

If user choses Product A and Gift Packaging then, Product A ($10.00) Gift Packaging ($10.99) Total : $20.99

1. So how can I add the chosen line item to that product once the user clicks on the Add to Cart Button. I have a function that is fired once the button is clicked. The function is "my\_module\_add\_to\_cart()".
2. How can I show the updated Price as $20.99 to the /cart page table?

# Answer
> 2 votes
Why not use Commerce Product Options which provides this functionality out of the box, directly in the default Add to Cart form?

To adjust the price based on the chosen options, you can use the Commerce Pricing module, which comes as part of the Commerce project. It basically provides a number of rules conditions and actions which allow you to adjust the price of a line item and e.g. add a fixed amount or multiply it by a certain value.

---
Tags: commerce
---


# Question
Title: Exist any way to integrate Google Rich Snippets in D6?
I have a dilemma with the topic of Google Rich Snippets in drupal 6. Looking, no module to do so (Yes in Drupal 7, but work with drupal 6) and looking not find any solution. (I use Fivestar on my site)

So my dilemma is whether or, if it can implement this in Drupal 6 ... And that way you can do.

Someone to do? Someone could find a solution? I'm not as expert in Drupal but I want to know whether and in what way. It is urgent.

Thanks :D

# Answer
> 1 votes
Given the comments, I am thinking all you'd need to do is theme the fivestar summary with google's snippets. To do that, I pulled the `theme_fivestar_summary()` out of the module and plopped it into my theme's template.php file like so:

```
function YOURTHEME_fivestar_summary($user_rating, $average_rating, $votes, $stars = 5, $feedback = TRUE) {
  $output = '<span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">'; // ADDITION #1
  $div_class = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= '<span class="user-rating">'. t('Your rating: <span>!stars</span>', array('!stars' => $user_rating ? $user_stars : t('None'))) .'</span>';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    $div_class = isset($votes) ? 'average-count' : 'average';
    $average_stars = round(($average_rating * $stars) / 100, 1);
    $output .= '<span class="average-rating">'. t('Average: <span itemprop="ratingValue">!stars</span>', array('!stars' => $average_stars)) .'</span>'; // ADDITION #2
  }
  if (isset($user_rating) && isset($average_rating)) {
    $div_class = 'combo';
  }

  if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
    $output .= ' <span class="total-votes">'. format_plural($votes, '<span itemprop="reviewCount">@count</span> vote', '<span itemprop="reviewCount">@count</span> votes') .'</span>'; // ADDITION #3
    $div_class = 'count';
  }
  elseif (isset($votes)) {
    $output .= ' <span class="total-votes">('. format_plural($votes, '<span itemprop="reviewCount">@count</span> vote', '<span itemprop="reviewCount" >@count</span> votes') .')</span>'; // ADDITION #4
  }

  if ($votes === 0) {
    $output = '<span class="empty">'. t('No votes yet') .'</span>';
  }

  $output = '<div class="fivestar-summary fivestar-summary-'. $div_class . ($feedback ? ' fivestar-feedback-enabled' : '') .'">'. $output .'</div>';
  $output .= '</span>'; // ADDITION #5
  return $output;
}

```

and commented where I added the snippet additions.

---
Tags: nodes, 6, rating
---