# Question
Title: How to implement revisioning in my own module?
In my module I store some node related data in a specific table of the database. Now I want to implement the revisioning system, so I create `my_table_revision` with the same information and a new column called `revision_id`.

But, How can I know when a new `revsion` of the node is created? and how can I know when a node `revision` is reverted?

It exists something like `hook_revert()` or `hook_revision`?

# Answer
As Free Radical and Clive says the best way to implement a revisioning system is creating a custom entity. But if you can't create a custom entity and you have to use your own table, I answer here what I have done.

So, you have your `table` and you have to create a `table_revision` with the same fields and one mor field called `revision`.

With the `hook_node_update` you can control when a node is updated, even when a node is revisioned.

So in the `$node` argument of the `hook_node_update` you have three `vid` (revision ID): `$node->vid`, `$node->old_vid` and `$node->original->vid`. The `$node->vid` is the new `vid`, the `$node->original->vid` is the previous `vid` that the node had, and the `$node->old_vid` is the `vid` of the node where you revert.

If the `$node->old_vid` is the same value than `$node->original->vid` means that the node is edited and not reverted, and if it is not the same value, it means that the node is reverted to a previous revision.

If the node is edited, you have to insert the new values in the `table_revision` with the '$node-\>vid`revision ID. But if the node is reverted, you have to get the old values from the`table\_revision`with`revision\_id = $node-\>old\_vid`and then copy this values in the`table`and`table\_revision`with the`$node-\>vid`as new`revision\_id\`.
> -1 votes

# Answer
As Clive says, you need to create a custom entity (with the API) to hold the data. Then Drupal will create the necessary tables and take care of the versioning for you.

If you need to do special things (that is not already done by Drupal's built-in versioning), you can intercept both saving of new revisions and reversals with `hook_entity_update`.

AFAIK, there is no simple way to tell a new revision apart from a reversal. Technically, a reversal results in a new revision with a new version ID (`vid`) being created, where the *content* of the new revision just happens to be identical to some old revision.

If it is really important for you to tell them apart, I guess you could keep a table with SHA2 (or MD5) hash signature for each revision, and look up the signature in that table to identify a reversal.

For the sake of completeness, I'll also mention that I've observed than when someone do a reversal, a log message is generated and placed in {node\_revision.log} (E.g. "`Copy of the revision from <em class="placeholder">Thu, 2014-06-19 13:53</em>.`". Otherwise, this field is filled in with a user-written change notice (or left blank). You may be able to use this to detect reversals, but IMHO this method is not reliable as the string can easily be spoofed by a user who knows about this.
> 2 votes

---
Tags: 7, nodes
---


title: How can I do math on fields?

text:
# Question
Title: How can I do math on fields?
I am trying to learn the principals required to make a Drupal 7 math/calculator module that simply takes user's inputs and does some math on them and then displays the results on the same page without a page refresh.

# Answer
Drupal modules are basically PHP code, and because PHP is on the server side, you cannot do mathematical actions upon user's input without submitting your data to the server(Which will refresh your page).

The only solution to do what you want is to add some Javasciprt to do it for you.

Here is a tutorial explaining how to add JS to Drupal

https://www.drupal.org/node/756722
> 0 votes

# Answer
The options suggested above are prefect, but there is no use of creating a calculator widget that does a full round trip to get the answer.

So i would recommend to use only javascript to get this done. The following code will help you to parse Integer(parseInt) and Decimal(parseFloat) values.

```
<html>
<body>
<script>
    var result = parseFloat("10.3333") + parseFloat("10.3333");
    document.getElementById("demo").innerHTML = result;
</script>
<p id="demo"></p>
</body>
</html>

```

Thanks
> 0 votes

---
Tags: forms
---


# Question
Title: How to remove deleted nodes from Google search?
When I search my site on goolge, it shows some nodes that are deleted.

How can I remove these results from Google?

If I'm not wrong, with the `Re-Index` button in the search config form It cleans the index and then, with CRON, it fills the index again.

But is there any way to do that automagically when a node is deleted? It's better if not reindex all the index, and only removes the node deleted.

# Answer
Another good practice is to use XML sitemap module and keep everything updated.You can submit this sitemap to Google webmaster tools and it will automagically get your updated sitemap.

Re-indexing by Google can take two weeks or more...
> 5 votes

# Answer
Re-indexing definitely needs to be done. I believe when the next crawling happens it will automatically pick valid nodes only.
> 2 votes

# Answer
You can use Auto Indexer module.

> This module should be used when an up-to-date index is desired/required after any addition or update of indexable node content. Not just after the successful execution of cron.php.
>
> **This module is ideal for projects where, other than search indexing, there is no need to run cron often.** Use this module to ensure your search index is up-to-date while keeping the frequency of cron executions to a minimum.
> 0 votes

# Answer
Why would you do something that would stop the Incoming Traffic to your site. I would use Global Redirect Module and redirect(after adding an alias from old url to the new one) the deleted links to relevant links on my site.

> GlobalRedirect is a simple module which…
>
> Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> 0 votes

---
Tags: 7
---


# Question
Title: rewriting results in view: trim from the back
I am working on Drupal 7 Omega Subtheme, Panels Views. In one of my views I have a path field which displays the whole url and I need only the last 6 characters (6 digits, to be precise. Also, if it helps - part of the URL I want to get rid of is fixed.) Under REWRITE options there is 'Trim this field to a maximum length' but I need to trim it from the end (i.e. from the right). Do I have to use php? Do I require views\_php module? Thanks.

# Answer
Yes. You will have to use something like

```
$newstring = substr($dynamicstring, -6);

```

in the php code for the field.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Debugging what has been submitted in a form
I would like to like to be able to print out what has been submitted in my form in the submission form. How can I achieve this?

# Answer
You can display the submitted values in your `hook_form_submit()` and set it like this (example):

```
function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth', array(
   '@first' => $form_state['values']['first'],
   '@last' => $form_state['values']['last'],
   '@year_of_birth' => $form_state['values']['year_of_birth'],
  )));
}

```
> 4 votes

# Answer
Its better to install devel module and use the dpm function.

```
function MYMODULE_FORMID_submit($form, &$form_state) {
  dpm(hook_form_id_submit);
}

```
> 2 votes

# Answer
Instead of printing stuff in the page output, I would recommend to use an IDE such as PhpStorm, Eclipse or Netbeans. Combined with Xdebug, you can set a breakpoint in the form submit function and inspect all variables available at that point. You'll find the submitted values in `$form_State['values']`.
> 0 votes

---
Tags: 7, blocks, forms
---


# Question
Title: HTML after label radio button (depending on radio button)
I need to add some html to specific radio buttons. This is a picture to clarify what I'm looking for:

As you can see I want to add some text to the options. These are radio buttons where you can select one option. This is what I have now:

I've tried adding html with the theme\_radio function with suffix like this:

```
function ppprogram_radio($variables) {
    $element = $variables['element'];
    $element['#attributes']['type'] = 'radio';
    $element['#suffx'] = "<p>just testing</p>";

    element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

    if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
        $element['#attributes']['checked'] = 'checked';
    }
    _form_set_class($element, array('form-radio'));

    return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

But that didn't do anything ... . I've also tried adding html to the return but then it's added before my label and I want it after my label.

# Answer
Hope this will help. please follow the comments.

```
 function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id){
        if($form_id=='YOUR FORM ID'){
           /* uncomment the following code after updating the key variables<field machine name> and check out the option keys.
           */
           // echo '<pre>';
           // print_r($form['<field machine name>']['und']['#options']);
           //exit;
            $form['<field machine name>']['und']['#options']['<key>'] .= '<h3>Hello World </h3>';
            // the above code will add <h3>Hello World </h3> alone with the existing radio button label
//Remove the comments if it helps.
        }

    }

```

Let me know if you need any additional clarity.

Thanks
> 2 votes

# Answer
'suffx' is misspelled on line 4. Does it work if you correct the spelling?

```
 $element['#suffix'] = "<p>just testing</p>";

```
> 0 votes

# Answer
Implement `theme_form_element_label($variables)` in your `template.php` and append your value to the returning label.
> 0 votes

---
Tags: 7, theming, forms
---


# Question
Title: Allow/restrict access based on privacy setting flags in profile
I have privacy profile type and flags with checkbox like "Keep all my friends private" and "Keep all my videos and channels private".These are in my privacy settings profile.Now i want to allow or restrict the access based on my flagging (on/off checkbox) for the users.Here i have two content types videos & channels.By default other users can watch my videos & channels and i want to make it private when i click my checkbox on for "Keep all my videos and channels private" and once i uncheck this,it should become public.The same need to be done for "Keep all my friends private".I have used user relationship module for friends.How can i do this? Is it possible using php coding or is there any other solution.Please help. Thank you.

# Answer
Implement `hook_node_access($node, $op, $account)` and check whether the user has flagged his content to be private, if so then deny access.

```
function MYMODULE_node_access($node, $op, $account){
  global $user;

  if($node->uid != $user->uid && $node->type=='video' && $op=='view'){
     $entity_type = 'profile2';
     $profile = profile2_load_by_user($node->uid,'main');

     $flagging_data = flag_get_user_flags($entity_type, $profile->pid ,$node->uid);

     /************ UPDATED ****************/
     if(isset($flagging_data['channels'])){
          return NODE_ACCESS_DENY;
     }
  }
}

```
> 1 votes

---
Tags: users, flags
---


# Question
Title: How to redirect toward a specific node from front-page in Drupal 7?
I have a multi language site made in Drupal 7. And I want to check if I am on the front page then if true to redirect the user to a to some specific node.

I have tried different methods:

1. to create a page `front--page.tpl.php` and then to check language and then redirect
2. I have put this code in `page.tpl.php`:

```
 global $language;

 if ($node->nid == 1) {
     if ($language->language == "en") {
         header('Location: en/home');
     } elseif ($language->language == "fr") {
         header('Location: fr/accueil');
     }
 }

```
3. I am using i18n module for Drupal 7 so I have tried also to use `$conf['i18n_variables']` in `settings.php` like that:

```
  $conf['i18n_variables'] = array(
     'site_frontpage',
     'site_name',
  );

```

But I have not succeed to do it. Have you any suggestions ?

# Answer
> 7 votes
page--front.tpl.php simply allows you to create a different page template than the default page.tpl.php template. When drupal loads the homepage and there is a page--front.tpl.php it will laod that template instead.

If you want to check if you are on the homepage you can use the is\_front variable. It would be best to use hook\_boot in a custom module.

```
hook_boot(&$vars) {
  if($vars['is_front']) {
    // do your redirect
  }
}

```

You can use drupal\_goto() to handle the redirect.

# Answer
> 4 votes
Using a custom module that implements a menu handler for "frontpage", for example, it is possible to set the *Default front page* to "frontpage".

The module should then implement `hook_menu()` and a page handler, similarly to the following code:

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu callback; shows the frontpage node.
 */
function mymodule_view() {
  $langcode = $GLOBALS['language']->language;

  if ($langcode == "en") {
    drupal_goto('en/home');
  }
  elseif ($langcode == "fr") {
    drupal_goto('fr/accueil');
  }
}

```

# Answer
> 1 votes
Why not set the value of *Default front page* (the `site_frontpage` variable) in *Administration » Configuration » System » Site information* to node/\[NID\]? If you want different node for the different languages, keep `site_frontpage`in `i18n_variables` in settings.php and visit the *Site Information* page in each language.

# Answer
> 1 votes
googletorp's solution will not work as is.

If you try to use `drupal_is_front_page()` in a hook\_boot you will get errors because the function libraries haven't even been loaded until after the boot.

This is why EK Kosmos is getting a blank screen (why is anybody developing with error messaging turned off?).

A solution is to use `hook_boot()`, as suggested, but to evaluate directly from the url if it is the front page or not.

# Answer
> 1 votes
I created a (sandbox) module to do exactly this, Front page redirect:

> Drupal allows you to define what content to serve on the home page. However, Drupal does not redirect visitors to that page but instead just serves the content of that page on the front page.
> ...
> To alleviate these problems, this module really redirects visitors that arrive at the front page to the page that is defined as front page. It does so using a 301 (Moved Permanently) status code.

# Answer
> 0 votes
I would go for hook\_boot:

```
module_boot() {
  global $language;
  if (drupal_is_front_page() && $language->language == 'XX') {
    drupal_goto('node/[NID]');
  }
}

```

It's early in the process, so should be quicker and use less resources, than doing it in a theme function.

# Answer
> 0 votes
For a redirection you don't need to render the page therefor you should use hook\_boot instead of hook\_menu. In hook\_boot you don't have access to all the Drupal function so I tried as much of possible stay with native PHP function.

```
/**
 * hook_boot
 */
function modulename_boot() {
  // Check if it's the front page
  // using hook_boot we avoid wasting resources
  // It's to early to use drupal_is_front_page and we should avoid loading unnecessary extra resource
  if ($_GET['q'] == '') {
    // http_negotiate_language() is a better option but require  pecl_http >= 0.1.0
    // Locale::acceptFromHttp() require intl extension
    $langBrowser = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);

    // Get the activated languages on your drupal site
    $langAvailable = language_list();

    // set a default in case the language is not avaible
    $lang = 'en';

    if(isset($langAvailable[$langBrowser]) ){
      $lang = $langAvailable[$langBrowser]->prefix;
    }

    $http_response_code = 302;
    header('Location: ' . $lang, TRUE, $http_response_code);

    drupal_exit();
  }
}

```

---
Tags: 7, nodes, redirection, i18n-l10n
---


# Question
Title: Create Drupal User when creating commerce customer
I am using drupal commerce. What I've found out so far is, that when you create a commerce customer, no drupal user is generated. But without a drupal user attached to the customer, you can't use that data in an order. Am I just missing something, or is this the most useless user-management I've ever seen? What do I have from customers if I can't use them.

Do I have to generate a drupal user first, then change to commerce and generate a customer there and attach the drupal user? Any chance for a one-step-solution?

# Answer
It is not a usual workflow to create customer profiles "by hand" even if the UI allows for this, the normal workflow would be when the user performs an action, the profile is generated, normally when they progress through the checkout process. At the end of the checkout, order, profiles and user are linked together in case of an anonymous purchase.

The same way you can't create a node and assign the author to an unexistant user, you can't create a customer profile and expect that the references appear magically.

Of course you can build a workflow that makes more sense to you and build a useful solution for your use case, one thing you could do is use Rules to generate a user every time you create an anonymous customer profile, but this will probably conflict with the normal checkout process as customer profiles are assigned to anonymous users when there's an anonymous purchase.

I'd create a boolean field attached to the customer profile that reads "Create a user for this profile" or similar and on the Entity creation event in rules, you can add an action that creates the user. You've got a very similar example in the default commerce Checkout rule "Create a new account for an anonymous order" for how to create an user.
> 1 votes

---
Tags: commerce, users
---


title: Create an order for a specific customer

text:
# Question
Title: Create an order for a specific customer
I'm new to commerce, but I can't find a way to generate an order for a already existing customer via Admin Panel. Do I have to code that by myself or am I missing something?

I've tried to use Commerce Admin Advanced Order Module but this only seems to work with drupal users, not commerce customers.

# Answer
The simplest way to do this would be to create the order that you want until the step that you want with your admin/webmaster/whatever role that has enough permissions and then, edit the order and change the owner.

If you create an order so the customer can pay it, you just send them the checkout url, as you changed the owner, they will have access to finish the checkout.

If you process the payment as well, you need an extra step of configuration, in order to send the customer a proper notification that the order was made. Rules is a good way to do this.
> 0 votes

---
Tags: commerce
---


# Question
Title: Where do I put a custom function for multiple themes
I have two 2 themes so two template.php. I have a function that I use in both themes. I don't want to write it twice. Where do I put it ?

# Answer
> 3 votes
You can put it in a module, or set up your themes so that they are sub themes of a main theme.

# Answer
> -1 votes
What about creating a function.php and in default/settings.php writting "require 'function.php';" ?

---
Tags: theming
---


# Question
Title: Block drush rsync command when specific alias is set as destination
I already have `policy.drush.inc` inside my Drupal drush directory at `sites/all/drush`. Also, I have a policy set to prevent `sql-sync` if the `@staging` alias is set. Thus,

```
drush sql-sync @dev @staging

```

will fail with the output `Per sites/all/policy.drush.inc, you may never overwrite the staging database.`

This was done with

```
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@staging') {
    return drush_set_error('POLICY_DENY', dt('Per sites/all/policy.drush.inc, you may never overwrite the staging database.'));
  }
}

```

This function is working, and I want to do the same for the rsync command, so basically duplicated the function and replaced `sql_sync` with `core_rsync` as in

```
function drush_policy_core_rsync_validate($source = NULL, $destination = NULL){
  if ($destination == "@staging") {
    return drush_set_error("POLICY_DENY", dt("Per sites/all/policy.drush.inc, you may not sync external files to staging"));
  }
}

```

However, I still get the 'You will destroy data from $remote and replace with data from $local\` warning when executing

```
drush rsync @dev:%files @staging:%files

```

How can I block drush rsync from executing and why does this function work for `sql-sync` but not \`core-rsync'?

# Answer
In the case of rsync, `$destination` is equal to `@staging:%files`, which is different than `@staging`. `drush_sitealias_evaluate_path` is not called until after the validate function, and calling it twice would be slow. You could test to see if `$destination` is `@staging` OR if it begins with `@staging:`. That should work well enough for your purposes.

If you wanted your policy to depend on values set in your @staging alias, then it would be best to make Drush call `drush_sitealias_evaluate_path` before the validate function. That would be a feature request, and should be done by posting an issue (or better yet, a PR) on the Drush project on GitHub.
> 1 votes

---
Tags: drush
---


title: How to change how WYSIYG styles things?

text:
# Question
Title: How to change how WYSIYG styles things?
Instead of using HTML underline tags, I want the WYSIWYG editor (CKEditor) to wrap a span around the highlighted text. Does anyone know how I can achieve this? Thanks!

# Answer
> 1 votes
Sure see this great blog post titled WYSIWYG Module + CKEditor: Taming the Beast by Fuse Interactive. I am not affiliated with the company nor the author of it -- it's simply a great resource.

Linked in those blog comments is a link to the CKEditor Configuration Options documentation, which is what you'll end up altering to make this happen.

In the blog post they supply their own config settings for the editor in javascript. I believe you can set all these values in `hook_wysiwyg_editor_settings_alter`, the settings for the Styles look like:

```
  { name : 'Float Right', element : 'div', attributes : { 'style' : 'float:right;' } },
    { name : 'Float Left', element : 'div', attributes : { 'style' : 'float:left;' } },

```

Where this defines a style called `Float Right` that wraps the selected text in a `div` with some inline styling. I believe you can easily assign classes instead of inline styles as well.

This should be a huge jumping off point for you to figure it all out. Best of luck!

# Answer
> 0 votes
Go to admin/config/content/wysiwyg/profile/full\_html/edit and select "Font Style" then go to the bottom of the page to the "CSS" tab and add Span=span in the "CSS classes" box.

You should now see "Span" in the styles select box on your content edit page.

If you want to give the span a style add Span name=span.name into the "CSS classes" box

---
Tags: 7, wysiwyg, theming
---


title: Is someone trying to hack my site?

text:
# Question
Title: Is someone trying to hack my site?
I was looking at my drupal site log messages and I´ve been having very weird ones as the ones attached.

I was wondering if someone is trying to hack my site, if so, how can I prevent that? I have all my site up to date. But it seems I need to take more measures.

thanks in advance

# Answer
> 5 votes
What you see in the log is malicious, so: Yes, somebody is rattling the doorknobs on your site to see if some door is not locked.

However, what you see is nothing *unusual*. I think you'll find similar entries in *every* watchdog log for a Drupal site that is "in the wild" (i.e. outside of a firewall).

Should you take more measures? IMHO, no. There is nothing in the messages you've posted that indicates that you're being *targeted*. These are random shots in the dark by script-kiddies - and they're all misses.

One of the reasons we use Drupal is because the core is pretty resistant to this sort of thing out-of-the-box. Just make sure you keep your site updated. And don't install experimental or badly maintained contributed modules without checking them for security holes yourself.

---
Tags: security, users
---


# Question
Title: Building Social Network with retweet like functionality
I'm designing a social network that I'd like to build on Drupal 7. I'd like people to have a Twitter-like feed that they can follow people/orgs and see their own posts and "re-tweets".

I'm currently starting to look at Organic groups, I invision the owner(s) of the group posting content to a group and anyone visiting that group page would see the group's "feed"(a view). However, I'm not sure how to implement the "retweet" feature that allows a piece content to be viewed by a retweeter's set of followers.

Any hints would be appreciated.

# Answer
You can use the statuses module for this. See this post for discussion of retweet functionality with statuses.
> 1 votes

---
Tags: 7
---


# Question
Title: Why does all links of homepage redirects me to Xampp homepage ( Took backup from Godaddy )
I took backup of SQL from Godaddy and copied all the data from my Godaddy hosting account through FTP. I imported the SQL in my machine's mysql ( no issues ). I copied the files to my htdocs/subdir1/drupalDIR/ and made changes in settings.php ( updated mysql connection details ). Homepage is showed in a perfectly fine way but whenever I click on any link, it takes me to Xampp Homepage.

Perhaps it's a htaccess issue.

What should be the Rewrite rule to make it okay ?

# Answer
> 0 votes
I tried copying the .htaccess file available inside the Drupal package and pasted into my htdocs drupal folder. Works like charm till yet.

---
Tags: .htaccess
---


# Question
Title: How to use date_make_date() in drupal 7?
I am porting custom module from drupal 6 to drupal 7 I have the following code:

```
 $local_date = new DateTime($dateTxt);
 $iso_date_string = date_format_date($local_date, 'custom', 'Y-m-d\TH:i:s');
 $utc_date = date_make_date($iso_date_string, $user_timezone_name, DATE_DATETIME);

```

What can be the alternative for date\_make\_time() in drupal 7?

https://www.drupal.org/node/1075476

> this error is due to a change in the Date API module, instead of date\_make\_date you need to use the new DateObject class. see "D7 Changes" here: http://drupal.org/project/date
>
> I fixed this as follows, but not sure if I'm using the DateObject properly.
>
> Edit this block of code in agenda.module, line 354

```
  // If the Date API is installed, we can do better at DST times   if (module_exists('date_api')) {
    $start               = date_make_date($event['start timestamp'], NULL, DATE_UNIX);
    $event['start time'] = date_format_date($start, 'custom', $block->timeformat);
    $end                 = date_make_date($event['end timestamp'], NULL, DATE_UNIX);
    $event['end time']   = date_format_date($end, 'custom', $block->timeformat);   }

```

replace with

```
  // If the Date API is installed, we can do better at DST times   if (module_exists('date_api')) {
    $start               = new DateObject($event['start timestamp'], NULL);
    $event['start time'] = $start->format($block->timeformat);
    $end                 = new DateObject($event['end timestamp'], NULL);
    $event['end time']   = $end->format($block->timeformat);   } alternatively, just comment out the whole block.

```

I looked in the above node but not sure about the new DateObject() ?

new DateObject()

---

# Answer
The alternative to the date\_make\_date function in D7 is the DateObject, which extends the PHP DateTime class.

To make your code work properly, you'd do something like this (untested):

```
$local_date = new DateTime($dateTxt, $timezone); //$timezone can be string or object
$iso_date_string = $local_date->toIso(); //returns the ISO string for the date
$utc_date = clone $local_date; //don't want pass by reference
$utc_date->setTimezone(new DateTimeZone('UTC')); //set the new timezone to return
$utc_date_iso = $utc_date->toIso(); //returns $local_date converted to UTC as an ISO string.

```

I'm not totally sure what you want to do, but this, hopefully, will get you on the right path.
> 2 votes

---
Tags: datetime
---


title: Find role based on list of permissions

text:
# Question
Title: Find role based on list of permissions
Is there any way of finding the role given a list of permissions?

I.E.:

```
$permissions = array('administer content', 'access content');
$role        = find_related_roles();

// $role = array(4 => 'client')

```

# Answer
Something like this should do it:

```
  $permissions = array('administer content', 'access content');
  $query = db_select('role', 'r')
    ->fields('r', array('name'));
  $alias = 'rp';
  foreach($permissions as $perm){
    $query->innerJoin('role_permission', $alias, 'r.rid='.$alias.'.rid');
    $query->condition($alias.'.permission', $perm);
    $alias = $alias . 'a';
  }
  $result = $query->execute()->fetchAllAssoc('name');

```

It's doing separate inner joins with the role\_permission table for each permission, to ensure that the role has all the permissions.
> 0 votes

---
Tags: users
---


title: Dynamic views for categories

text:
# Question
Title: Dynamic views for categories
I'm really stuck on a problem that I'm seeking assistance on. I have 3 categories under the same Taxonomy Vocab for a specific content type .

Taxonomy: \- category 1 \- category 2 \- category 3

Now I need to make a view that when i click the link for category 1 it will show all content under that category . same as the other category . Im currently using D7.

I thank you much in advance for any assistance you can provide!

this is a follow up question ...

contextual filter saves me from this filter but when I try to access it in the url the layout of the page is not like the views ... it gets the views for the taxonomy

# Answer
Suppose u have a content type called as Article. So simply add the fields in the view that you wish to show.

After adding the required fields add a contextual filter for the taxonomy term (Content: Has taxonomy term ID). In the contextual filter, select provide default values "Taxonomy term id from the url".

Save the view and it would serve your purpose.
> 0 votes

# Answer
The Taxonomy Views Integrator module will help you.

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.

Install this and change tid accordingly.
> 0 votes

---
Tags: views
---


# Question
Title: Rules: How to access field values by language
I have content in two languages (entity translation). If I want to use it's field values in PHP, I can access them by code like this:

```
$node->field_name['en'][0]['value']

```

or

```
field_get_items('node', $node, 'field_name', 'en')

```

But Rules load only currently active language. How to access field value in particular language in Rules data selectors?

# Answer
> 0 votes
Use foreach loop for field\_name\['und'\]\['value'\]

---
Tags: 7, entities, rules, i18n-l10n
---


# Question
Title: Add text above the registration form on user/register page
Is there a way to add a message above the Registration Form?

I know you can edit the field by going to "Configuration/People/Account Setting/Manage Field", but how about a message above the form?

Thanks

# Answer
The simplest way would probably be to create a block that is only displayed for that page, and position it above the content.
> 3 votes

# Answer
You could do that with hook\_form\_FORM\_ID\_alter() in a custom module:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#prefix'] = '<div><p>'. t('Add your message here'). '</p></div>';
}

```

Read also Customizing and Overriding User Login page, Register, and Password Reset in Drupal 6 and 7 : another way to add your message and whatever you'd like:

> Customizing the user login, register, and password reset pages is fairly simple, and uses the following concepts:
>
> * preprocessing to set variables
> * registration of functions in the theme registry
> * creation of one or more theme templates.
> 1 votes

# Answer
You can also use markup like this

```
<?php

 function first_admin_setting_form($node, &$form_state) {
      $form = array();
      $form['overview'] = array(
        '#markup' => t('Interface for setting for first module'),
          '#prefix' => '<h4>',
          '#suffix' => '</h4>',
        );
?>

```
> 0 votes

---
Tags: forms, users
---


# Question
Title: Is it possible to change the tab order of MENU_LOCAL_TASK items on a given page?
I have created a couple MENU\_LOCAL\_TASK items for my advanced search page in Drupal 6, but they appear at the end of the tab list on the far right. I would like my new items to appear first in the list of tabs.

Is there an easy way to accomplish this? I tried setting the weight of my new task items to -99 but this appeared to do nothing.

# Answer
> 3 votes
An easy and correct way is to change the weight as you do. Did you clear menu cache?

# Answer
> 3 votes
You can also use `hook_menu_alter()` to change the weight of the links.

And of course, clear the menu cache.

Here's the snippet.

```
    /**
     * Implements hook_menu_alter()
     *
     */
    function mymodule_menu_alter(&$items) {

      $new_weight = 10;

      $items['mymenu/path']['weight'] = $new_weight;

    }

```

---
Tags: hooks, routes
---


# Question
Title: creating and theming register form in drupal 7
There are many links in websites that talk about this question, but I'm really bewildered how to do it, I've tested many solutions but I failed.

this is my code to add register form into a page

```
<?php
    if(user_is_anonymous()) {
    $form = drupal_get_form('user_register_form');
    print drupal_render($form);
    }
?>

```

it is all I know of register form ! it prints all the fields of registered users. I also added other fields like mobile, phone and ... from admin/config/people/accounts/fields.

what is the most straightforward solution to theme the form? text fields and ... ?

# Answer
> 3 votes
You can try this one

To implement `hook_form_alter()` in a module and set the form's #theme property:

```
    function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

```

and add this code to template.php

```
    function mytheme_theme($existing, $type, $theme, $path){
      return array(
        'user_register' => array(
          'render element' => 'form',
          'template' => 'templates/user-register',
        ),
      );
    }

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

```

Also, create a user-register.tpl.php in

> sites/all/modules/YOUR\_module/templates/user-register.tpl.php

to add the 'markup' for the desired output and

```
<?php echo $rendered; ?>

```

to print the form.

For more information, follow this https://www.drupal.org/node/1211520

Hope, it works.

# Answer
> 0 votes
Open template.php of your theme

```
function YOURTHEMENAME_theme($existing, $type, $theme, $path) {

 $hooks['form_id_of_form'] = array(
    'template' => 'path_to_tpl_file',
    'arguments' => array('form' => NULL),
  );
  return $hooks;
}

```

Also you can try

```
function hook_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'form_id_of_form') {
    $form['#theme'] = 'path_to_tpl_file';
  }
}

```

OR

Take a look at the #theme key in the Form API Reference. Take a look at the code for theme\_form() for the default implementation.

---
Tags: theming, users
---


# Question
Title: Creating the custom url aliases for nodes?
I had a problem with making custom url aliases for drupal node pages.Basically my website have two articles types parent articles and child articles. Each parent article contains many child articles. So the each parent articles shows all it's child articles in pagination. current format parent article : http://example.com/parent-title child article : http://example.com/parent-title?page=1, http://example.com/parent-title?page=2 go to each child artilces of parent article.

however I want to insert title of the child article as url alias so expected format is http://example.com/parent-title/child-title?page=1

How can i insert that child article title as url alias? I need this because this is very good for SEO purposes.

# Answer
> 0 votes
You can use the Path Auto module for this purpose. It has many patterns options for each content type.

You can generate alises pattern for child articles and parent article separately. I have added a screenshot that how it looks in the back end.

If it does not fulfill your requirement then we can customize the urls on saving with hook\_url\_inbound\_alter() function in our custom module.

---
Tags: uri
---


# Question
Title: How to Add Taxonomy Vocabulary in Rules when User Registers
Using the Drupal Rules module, I'm trying to create a rule whereby when a user registers, a taxonomy vocabulary is created.

So far, I've done the following:

EVENT: After saving a new user account

ACTIONS: Create a new Entity, value Taxonomy vocabulary. I enter a name using tokens but it doesn't seem to accept tokens for the machine name. The machine name obviously has to be unique to each vocabulary.

Just to give you a bit more info, each member registering is a Tutor (needs to be the taxonomy vocabulary) and each Tutor will create multiple Students (taxonomy terms).

Can anyone help me with this please? I'm using Drupal 7. Thank you :)

# Answer
> 1 votes
I have checked the rules and I couldn't find a `Data Selector` for user name. But if you are fine with achieving the same using custom code then you can use the following code.

```
function YOURMODULENAME_user_insert(&$edit, $account, $category){
   $vocabulary = new stdClass();
   $vocabulary->name = $account->name;
   $vocabulary->machine_name = "tutor_".$account->uid;
   $vocabulary->hierarchy = 0;
   taxonomy_vocabulary_save($vocabulary);
}

```

---
Tags: taxonomy-terms, rules
---


title: Integer field radio buttons doen't save

text:
# Question
Title: Integer field radio buttons doen't save
I have integer field with 3 radio button options. When I select one of the option try to save new content it doesn't save the integer value. Field is not required and options are like this:

```
car|Car
plane|Plane
boat|Boat

```

After saving node and going back to edit none of the radio buttons is selected. Not even the default N/A which should be automatically selected if nothing else is selected. Anyone else had this problem?

# Answer
You are using an integer field and the key should be an integer.

Try

> 0|Car
> 1|Plane
> 2|Boat
> 1 votes

---
Tags: 6, entities
---


# Question
Title: Product reference field causes $title to be empty
**Update: After removing fields one by one, I've discovered that the Product reference field caused `$title` to be empty.**

I have several content types which are displaying both the `<title>` and `$title` well, but in my "Product Display" content type (of commerce kickstart) I find that the `$title` header is missing, although the `<title>` tag is there, i.e. the title bar of my browser is displaying the page title correctly. The contents of `<title>` and `$title` are similar. Excep that `<title>` has the site name added to the end of the node title.

I've viewed page source it shows that h1 isn't printed. I've never written any code to hide any h1 tags. I'm using Display suite on that page and I've disabled it on that content type and it didn't help. I am not using Context on that page. Please advise me on how I should proceed, thanks!

Update: Devel-\>load shows that the title is set correctly, but when I created a template for that node (page--node--42.tpl.php), and tested if it worked by hiding the header and footer, I added this line of code

```
<h1 class="page--title title" id="page-title"><?php print $title; ?></h1>

```

but all I got is am empty `$title`

Update 2: I've inserted a block using \[current-page:title\] and it works, however I'd prefer not to stick with this duct-tape solution if possible

# Answer
> 0 votes
After 5 to 6 hours of searching for the answer with Emko, we found that commenting out line 67 to 76 of this module fixed the problem.

```
profiles\commerce_kickstart\modules\commerce_kickstart\commerce_kickstart_product_ui
\commerce_kickstart_product_ui.module

/**
* Override or insert variables into the page template.
*/
function commerce_kickstart_product_ui_preprocess_page(&$vars) {
$product_display_types = commerce_product_reference_node_types();
if (isset($vars['node']->type) && isset($product_display_types[$vars['node']->type])) {
$vars['title'] = "";
}
}

```

# Answer
> 0 votes
Check the content types display tab. It may be set to hide the title.

# Answer
> 0 votes
Product Reference module pulls fields from the product entity to your product display (node), this naming has been simplified in Commerce Kicsktart and you can find the product displays as simply products and your products as product variations, more on this here: product vs product type vs product display in drupal commerce

So in your kickstart installation, the product title is coming from the product entity, if you go to `admin/commerce/config/product-variation-types` you'll see all your product types and then you can configure your field for each view mode to control the title display.

Hope this is what's troubling you.

---
Tags: 7, nodes, commerce
---


# Question
Title: Is there a difference between "Clear cached data" button on the performance page and drush cc all?
Is there a difference in what caching is cleared between

```
drush cc all

```

and

```
Admin > Site Configuration > Performance > Clear cached data button

```

?

# Answer
> 9 votes
Short answer: There is no significant difference.

Drupal:

```
function system_clear_cache_submit($form, &$form_state) {
  drupal_flush_all_caches();
  drupal_set_message(t('Caches cleared.'));
}

```

Drush:

```
function drush_cache_clear_both() {
  drush_cache_clear_drush();
  if (drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL)) {
    drupal_flush_all_caches();
  }
}

```

Both end up calling drupal\_flush\_all\_caches, which clears the standard Drupal caches, cached CSS/JS files, and everything declared by a hook\_flush\_caches.

`drush_cache_clear_both` is what is called by 'cc all'. `drush_cache_clear_drush` clears some drush caches that have no effect on the Drupal site.

# Answer
> 0 votes
There is no difference in source code, but sometimes we get a problem with clearing the cache by running drush cc all that only can be solved by clearing the cache from the admin menu or by dumping the cache tables.

I guess that flushing caches by using the admin menu does ignore those errors while drush doesn't

Those Errors look like this. Caused by a buggy hack in feature.

WD node: PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'node-23-23-default' for key 'PRIMARY': INSERT INTO {panelizer\_entity} (entity\_type, entity\_id, revision\_id, name, no\_blocks, \[error\] css\_id, css, pipeline, contexts, relationships, did, view\_mode, css\_class, title\_element, link\_to\_entity, extra) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13, :db\_insert\_placeholder\_14, :db\_insert\_placeholder\_15); Array

# Answer
> 0 votes
I see only two differences, but rather significant:

* When I clear caches using GUI, then most of them gets regenerated during my own request, to show me Drupal page again, so everything happens with my credentials.
* When I clear them using drush, they are regenerated by the first natural request, usually by anonymous user.

This difference is only important during development, but it may hide serious permission/caching issues if forgotten.

On production machines, or when you're developing something that does not cache and does not use permissions, it's not an issue.

---

* Cache clear using GUI may sometimes timeuot, if cache is big and database is slow (or just under heavy load)
* Command Line Interface PHP usually has much longer timeout set, if any at all, so even if cache clear is slow, it will most probably finish without being interrupted.

This difference should not be of importance on a healthy production server, but in perfect world we would never need to clear caches manually anyway.

---

Usually answer by greg\_1\_anderson is perfectly good - no significant difference.

---
Tags: 6, caching, drush
---


# Question
Title: How to set one path alias as the canonical alias?
I use the Tags taxonomy on several of my content types. In order to assist with a site-wide filtering mechanism, I'd like to be able to create additional path aliases for each piece of content.

For example, if my tags include `baseball`, `football`, `soccer`, and I post a news Article, I would like to have a primary path alias to that node using:

`/news/my-article-1`

but I'd also like to create a path alias to it for:

`/baseball/news/my-article-1`

`/football/news/my-article-1`

`/soccer/news/my-article-1`

However, when I create these programmatically, drupal seems to choose one of them, arbitrarily, to be the canonical alias. Is there any way I can control which alias is the canonical one?

# Answer
> 2 votes
Metatg seems to be your answer:

> Currently supported meta tags:
>
> * Abstract
> * Author
> * **Canonical URL**
> * Copyright
> * Description
> * Dublin Core (sub-module)
> * Generator
> * Image source
> * Keywords
> * News Keywords
> * Open Graph Protocol (sub-module)
> * Original Source
> * Publisher URL
> * Robots
> * Shortlink URL
> * Title (e.g. Page titles)
> * Twitter Cards (sub-module)

# Answer
> 1 votes
Mołot's answer does offer a way to set which url is canonical, so I've accepted it.

I also found a workaround which is simply to create my canonical path alias last. Whichever path alias has the highest path id appears to be the one chosen as the canonical path.

# Answer
> 1 votes
Could you use the Redirect module to redirect the non-canonical aliases?

This would give you pages that were available under your non-canonical aliases, albeit by a redirect.

# Answer
> 0 votes
From what you say in the comments, here's an alternative proposal: create a view which takes the arguments as contextual filters and have it display just the one node in full mode. That way you don't have to deal with multiple aliases and you can use the path arguments cleanly.

---
Tags: 7, path-aliases
---


# Question
Title: Using Entity Reference field, get the parent NID in referenced entity (node)
I have a node that holds an entity reference field (multi value) to other nodes, all the referenced nodes of the same type.

In the referenced nodes I have a computed field that do some calculations. Also, in the parent node I have a computed field that takes calculated values from referenced nodes and do other calculations. All the values are stored in DB.

What I need is every time a referenced node is saved, also to re-save (update) the parent node, so that computed field can make the calculations using the new values from the referenced node.

**Is it possible to get the NID of the parent node in the referenced node computed field, so I can add some code to launch the parent re-save?**

All I can think right now is using SQL or adding a field (in referenced nodes) that will hold the parent NID when the referenced nodes are created; is it another way?

Thanks.

# Answer
With the logical structure that is mentioned, it is possible that a node may have more than one parent. Wouldn't it be wiser to make a reference upwards than downwards? You would end up with an entityreference field of granularity 1. Unless there is some other reason for which to keep this structure.

There is no explanation on the specifics of this calculation that takes place. Is it in a custom module, is it rules, is it some other contrib module?

In any case, you can use an EntityFieldQuery in order to get a list of all nodes that reference the particular node. More details about how to use here. There is a particular reference for entityreference fields:

> Likewise an image field would use 'fid', 'alt', and 'title' as column names; an entity reference field would use 'target\_id' and 'target\_type' as column names.

Example (in CAPS the variables that you need to handle):

```
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MY_CONTENT_TYPE')
  ->propertyCondition('status', 1) // published? yes
  ->fieldCondition('field_MY_ENTITYREFERENCE', 'target_id', $MY_CURRENT_NODE_ID)
  ->range(0, 10); //do not forget the semicolon at the end of the query conditions
$result = $query->execute();
if (isset($result['node'])) {
  $items_nids = array_keys($result['node']);
  $items = entity_load('node', $items_nids);
}
?>

```
> 4 votes

---
Tags: nodes, entities
---


# Question
Title: How to configure annotator and annotation modules in Drupal 7?
I would like to provide an MS Word -like **annotations** (review comments) functionality in some text areas of my Drupal 7 website.

I have experimented with the co.ment and annotator \- annotation Drupal 7 modules, and the second solution seems lighter and more appropriate for my requirements.

Unfortunately there is very poor documentation on the annotator and annotation modules and I **cannot configure the storing** of my annotations.

I have read the annotator library documentation but I do not know how to implement either the store or authentication and permissions plugins on my Drupal 7 website.

From the Annotator module page, what I understood is that by installing the **Store plugin** together with the Annotation module you use your own storing and not Annotateit.org service.

I have downloaded and installed the required libraries (annotator and Gettext) and from the Annotator configuration page I have enabled the Store plugin with the default Store url options. But my annotations do not get stored and I do not get any exceptions or other info, so that I can see what is going wrong.

Any suggestions please on what may be missing? I can provide more details where needed.

# Answer
I stumbled across the same problem today. Proper way to install everything:

1. Download the annotator libraries in /sites/all/libraries/annotator
2. Download jquery\_update and set jquery v.1.8 to be used
3. Download and enable the annotator module and its dependencies (e.g. libraries)
4. Download and enable the annotation module
5. Do not change any configuration options

For a minimal installation, I have just used the `markup` and `store` plugins. Some things that might get in the way of the annotations being saved:

* You need to have Clean URLs installed
* If Drupal is not installed in the root of your domain (for example if it's in http://example.com/subsite instead of http://example.com) you may have to change the configuration of the store plugin to point at /subsite/annotation/api instead of /annotation/api

You can manage the permissions to create, edit, view or delete annotations through the permission system of the annotation module.

Also, keep in mind, that if you create the annotation while you are browsing node/3 through the URL: `http://test.drupal/node/3#overlay-context=node/6`, the annotation **WILL NOT** appear if you visit: `http://test.drupal/node/3`. That caused me a lot of headaches. You can check whether your annotations have been saved in the `admin/content/annotation` path.

***NOTICE:*** When downloading the annotator library from github make sure that you download the annotator-full.1.2.9.zip not annotator.1.2.9.zip.
> 1 votes

---
Tags: 7, javascript, comments
---


title: Add classes to login form fields D 7

text:
# Question
Title: Add classes to login form fields D 7
I ma trying to add foundation classes to my #user-register-form fields in D7

```
<div class="form-item form-type-textfield form-item-name">
  <label for="edit-name">Username <span class="form-required" title="This field is required.">*</span></label>
 <input class="username form-text required" type="text" id="edit-name" name="name" value="" size="60" maxlength="60">
<div class="description">Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.</div>
</div>

```

I have tried using template overrides like I have with my other custom fields

field--field\_homepage\_body.tpl.php

But with no luck any help would be appreciated.

# Answer
You can do this by altering the form in your custom module **hook\_form\_alter(){}** or in template.php of your active theme.

Just add the classes in the attributes array().

Or you can create a user-login.tpl.php file following this link, Its already answered here with this code.

```
<?php
    function operationscheck_theme_theme() {
    $items = array();
    $items['user_login'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-login',

    'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_login'
   ),
);
    $items['user_pass'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-pass',
   'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_pass'
  ),
);
 $items['user_register_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
'template' => 'user-register-form',
'preprocess functions' => array(
'operationscheck_theme_preprocess_user_register_form'
 ),
);

return $items;
}
?>

<?php
   function operationscheck_theme_preprocess_user_login(&$vars) {
      $vars['intro_text'] = t('This is my awesome login form');
    }
   function operationscheck_theme_preprocess_user_login(&$vars) {
     $vars['intro_text'] = t('This is my awesome pass form');
   }

function operationscheck_theme_preprocess_user_register_form(&$vars) {
    $vars['intro_text'] = t('This is my super awesome reg form');
   }

 function operationscheck_theme_theme(&$existing, $type, $theme, $path) {
  $hooks = operationscheck_theme_theme($existing, $type, $theme, $path)

  $hooks['user_login_block'] = array(
 'template' => 'user-login',
 'arguments' => array('form' => NULL)
 );

// @TODO: Needs detailed comments. Patches welcome!
return $hooks;

}

function operationscheck_theme_preprocess_user_login_block(&$variables) {
  $variables['intro_text'] = t('This is my awesome login formX');
  $variables['rendered'] = drupal_render($variables['form']);
}
 ?>

```

Please check if it is the code snippet you were looking for.
> 1 votes

# Answer
Will be best if you use hook\_form\_alter() function. In the hook you can set needed template for the render, form add needed class or any wrapper element
> 0 votes

---
Tags: theming, users
---


title: Working with views and revisions

text:
# Question
Title: Working with views and revisions
I need to display field data for a given revision in a view for example the body.

To archive this I created a `view` which displays `content revisions`.

This view has a relationship by default: `The revision ID of the content revision.`

I then added the body field using this relation.

When i run the view the body field is empty for all revisions but the active one.

When I change the relation to `The revision NID of the content revision.` I get all fields filled out, but they are all filled with the data from the active revision.

I don't know if this a bug or the expected behavior.

Is there a way to get the field data for revisions that are not active or do I need to rewrite the queries?

I'm using the `revisioning` module, but it doesn't make a difference if it's active or not. The results of the views are the same.

# Answer
> 3 votes
While adding fields to your view, you will see fields named like `Content (historical data) : Field name` select those and you will get the revision data.

---
Tags: 7, views
---


title: Guide on How to Load CSS File Per Role

text:
# Question
Title: Guide on How to Load CSS File Per Role
I'm looking for the simplest solution to allow a custom CSS page to load per role. I have to the CSS pages done, but just need to load them and ensure they are only loaded based on user role.

I'm guessing it should be about three lines of PHP to go at the bottom of the template.php, but not sure what the code should be. Any advice?

Thanks.

---

With relation to the answer and my comment below, tried the beneath code unsuccessfully using the bamboo theme

```
function bamboo_preprocess_page(&$variables) {
  global $user;

  if (in_array('testtest', $user->roles)) {
    drupal_add_css(drupal_get_path('theme', 'bamboo') . '/roleedits.css');
  }
}

```

If my code wrong or is it a problem with the theme?

(for the record I did create a role called testtest.)

The error I get is:

```
Fatal error: Cannot redeclare bamboo_preprocess_page() (previously declared in E:\Test\sites\all\themes\bamboo\template.php:231) in E:\Test\sites\all\themes\bamboo\template.php on line 385

```

---

NOTE: Both the solution below work. I just accepted the one I used. However both have been tested and work fine, just the second solution offered me more flexibility to call roles again in future.

# Answer
> 2 votes
User slivorezka posted the answer before me, and I'm just adding some of my own amendments.

**1. Body classes**

First, I think using separate files for this is wrongg. Drupal core comes with a nice feature that it adds "logged-in" class to the body tag if the user is logged in. Similarly, you could use a preprocess function to add a class to the body tag, which lists user role IDs. Then, merge and optimize your CSS to use this class to change the appearance.

```
function THEMENAME_preprocess_html(&$vars) {
  if (!empty($GLOBALS['user']->roles)) {
    foreach ($GLOBALS['user']->roles as $rid => $role_name) {
      $vars['classes_array'][] = drupal_clean_css_identifier("drupal-role-$rid-$role_name");
    }
  }
}

```

Copy the above snippet to your theme or to a custom module, and change "`THEMENAME`" to the name of module/theme.

You will see class names like `drupal-role-2-authenticated-user` in the body tag, which you can use to change appearance.

**2. hook\_page\_alter() or hook\_preprocess\_page() (there are other hooks too)**

See the this answer.

# Answer
> 4 votes
Add the next code to you **template.php**

```
/**
 * Implement hook_preprocess_page().
 */
function THEME_NAME_preprocess_page(&$variables) {
  global $user;

  if (in_array('DESIRED_ROLE', $user->roles)) {
    drupal_add_css(drupal_get_path('theme', 'THEME_NAME') . '/YOUR_CSS_NAME.css');
  }
}

```

---
Tags: 7, theming, users
---


# Question
Title: Node View Permissions module prohibits list of nodes in Views module
I created a custom node type called 'Video' in D7, and in it are three fields, 'YouTube ID', 'Video Title', and 'Video Description'. Basically, I have a template for this node type that puts the YouTube ID into the YouTube iframe to show the video. Not a problem. It works. These videos are for authenticated users only, and I can paste the url of one of the video pages on my site, and if I am logged in, I can see it.

**The problem isthat I cannot see my list of videos when logged in, *unless* I am logged in as admin**. The View to see the list of videos (/user-area/video) is accessible, but there is no list displayed unless I am logged in as admin.

It is something with the view and permissions, because I can see the video list page (/user-area/video ~ created by Views module), but without the list on it ... and I can see the video content page (/user-area/video/\[video-id\] ~ drupal node, themed by .tpl.php).

Any suggestions?

---

**UPDATE**

I figured out that it has something to do with the Node View Permissions module that I am using for the 'Video' node type. Although the setting in that module for the 'Video' node type is 'View any', Views must have a difficult time with that. I can still access the video content page, but not the list of video generated by the Views module. I have to figure this out. I updated the title of this question.

# Answer
The problem *was* the 'Node View Permissions' module not playing well with the 'Views' module (or the other way around). I removed the 'Node View Permissions' module and replaced it with the 'Restrict Node Page View' module. Did not work right away...had to rebuild permissions for the site. Problem fixed!
> 0 votes

---
Tags: 7, views
---


# Question
Title: Different commerce payment paypal settings on dev and live sites
The problem is similar like here: How to force rules configuration to load

I planned to use hook\_default\_rules\_configuration\_alter(), but after this:

```
  if (isset($configs['commerce_payment_paypal_ec'])) {
    foreach ($configs['commerce_payment_paypal_ec']->actions() as $action) {
      dsm($action);
    }
  }

```

I don't see any $settings\['settings'\] array:

How can I change the saved commerce\_payment\_paypal\_ec rule's settings by code?

# Answer
This is a question that has came in different shapes, I'd recommend reading https://drupal.stackexchange.com/a/118316/2322 answer to get a better understanding on how drupal commerce and rules store this information. I don't know how to access the UI form the action itself.

Instead of trying to modify specific values, what I'd do is to try to replace the whole rule object with the one you want using entity\_import of the rules\_config object, something like:

```
if (isset($configs['commerce_payment_paypal_ec'])) {
    $configs['commerce_payment_paypal_ec'] = entity_import('rules_config', '{ "commerce_payment_paypal_ec" : {
        "LABEL" : "PayPal Express Checkout",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "TAGS" : [ "Commerce Payment" ],
        "REQUIRES" : [ "commerce_payment" ],
        "ON" : { "commerce_payment_methods" : [] },
        "DO" : [
          { "commerce_payment_enable_paypal_ec" : {
              "commerce_order" : [ "commerce-order" ],
              "payment_method" : { "value" : {
                  "method_id" : "paypal_ec",
                  "settings" : {
                    "api_username" : "1",
                    "api_password" : "",
                    "api_signature" : "",
                    "server" : "sandbox",
                    "currency_code" : "EUR",
                    "allow_supported_currencies" : 0,
                    "txn_type" : "auth_capture",
                    "ec_mode" : "Mark",
                    "shipping_prompt" : "0",
                    "log" : { "request" : 0, "response" : 0 },
                    "ipn_logging" : "notification",
                    "receiver_emails" : "",
                    "reference_transactions" : 0,
                    "ba_desc" : "",
                    "show_payment_instructions" : 0,
                    "update_billing_profiles" : 1,
                    "enable_bml" : 0
                  }
                }
              }
            }
          }
        ]
      }
    }');
  }

```
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Does node_delete() delete node_revision and comment as well?
I want to delete the node\_revisions and comments with `node_delete()`. Is this possible, or do I need to write custom code?

# Answer
> 2 votes
Little more context on this one since I had to answer this myself recently. The node.module code starts the delete operation by invoking all HOOK\_node\_delete functions it is aware of:

```
  foreach ($nodes as $nid => $node) {
    // Call the node-specific callback (if any):
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }
  }

```

One of which is the comment\_node\_delete() function in comment.module (clearing comments):

```
/**
 * Implements hook_node_delete().
 */
function comment_node_delete($node) {
  $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();
  comment_delete_multiple($cids);
  db_delete('node_comment_statistics')
    ->condition('nid', $node->nid)
    ->execute();
}

```

After it has finished with the modules that have references to these nodes, it then clears its own node tables for the NID:

```
  // Delete after calling hooks so that they can query node tables as needed.
  db_delete('node')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_revision')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('history')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_access')
   ->condition('nid', $nids, 'IN')
   ->execute();

```

So - yes, node\_delete clears both comments and revisions, as well as other node data and references.

---
Tags: nodes
---


# Question
Title: Exposed filter with "inverted" checkbox: Checked = view all, Unchecked = filtered
I have a view that shows commerce products, with an exposed filter to show only items with stock \>= 0. So, if the checkbox is checked, it will hide out-of-stock items.

I would like to reverse this so that if the checkbox is checked, all items are shown, and if it is not checked, only the filtered items (stock \>= 0) are shown.

The label could then be changed to "Reveal items that are currently not available".

Any idea how to do this? I could probably do this with some hook\_form\_alter() and stuff, but I am more interested in something to configure with the Views UI.

(Not that I shy away from custom modules in general, but I like to avoid stuff that is hardcoded to one specific view name and display id and field name..)

# Answer
I have not tested this but you might be able to do it by using 2 filters. Add a non exposed filter that filters by stock \> 0. Make sure it is below your current filter. Views filters in order from top to bottom. So if the page loads and that check mark is un-checked you will only see products with a stock greater than 0. If they then check the box it will re-load and filter by your stock \>= 0. That might work. As I said I have not tested this.
> 0 votes

---
Tags: views
---


title: TRUNCATE error -1 obliterating my sites

text:
# Question
Title: TRUNCATE error -1 obliterating my sites
I keep getting a cache related error.

> PDOException: SQLSTATE\[HY000\]: General error: 1030 Got error -1 from storage engine: TRUNCATE {cache} ; Array ( ) in cache\_clear\_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc).

The issue is tied to the query file. The fix is to replace `TRUNCATE` with `DELETE FROM` in a *query.inc* file. That's all fine and dandy, and that error is gone. But, now I have a new one: The site is completely broken and thinks that the cache database folder still exists, which prevents me from importing the backup database, even if I drop the whole database. In short: Backups are useless, as this error seems to do some heavy damage. As well, it shuts down the EasyPHP server.

To make things even worse, I was going over the huge site-crashing error report I just got, and it looks like the fix doesn't even work.

In regards with the above, I think it worked, but something else tied in with it is causing more cache errors.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'webone.cache\_views\_data' doesn't exist: DELETE FROM {cache\_views\_data} ; Array ( ) in cache\_clear\_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc).

I applied the fix I first mention to a new website, as a preventative this time. Low and behold, it came back on the first module install.

# Answer
> 1 votes
Why are these paths different when you talk about "your project":

path 1: `C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc`

path 2: `C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc)`

This smells like something is *horribly* misconfigured.

I've made dozens of drupal sites, typically under Linux, but I have used WAMP myself in the past (not EasyPHP-DevServer). This makes me think it's an issue with the EasyPHP-DevServer and *not* drupal itself.

While you may not be familiar with it ... have you tried like copying your site files and DB to a Drupal 7 Quickstart project VirtualBox virtual machine, or DrupalPro ... another off the shelf VM drupal-in-box ...

---
Tags: database, caching
---


title: Create personality quiz

text:
# Question
Title: Create personality quiz
i'm looking for solution on how to create personality quiz. The Quiz module doesn't have an option to label answers - I need to find the most popular label checked and not the total amount of points.

It could be like this: 2 questions, 3 answers each. Each answer for each question has labels: "label one", "label two" and "label three" and they are randomized. I answer both questions and get "label two=2", which is the most popular label and therefore I am forwarded to node2 with some description.

Is it possible to do this with forms?

# Answer
> 1 votes
The webform module would work for you. It gives you a nice interface to fetch the results so you can do some meaningful post analysis on your results too.

# Answer
> -1 votes
Someone wrote a great module for it

Personality Test

> This module allows you to easily create a personality test that visitors can take.
>
> After you installed it a new node type becomes available, when you create a node of this type you can add questions and their possible answers; you can also define a score for each answer.

---
Tags: quiz
---


# Question
Title: How to display single fields in multiple line in VIEWS?
How to display single fields in multiple line in view.

Example : Address contain multiple lines so each items show on line by line.

# Answer
> 0 votes
Use "Views fields combine" Module

---
Tags: views
---


title: Remove main menu title from page

text:
# Question
Title: Remove main menu title from page
Hi i'm just starting out with Drupal, Have what I think is a really simple question and it has been asked a lot but the answer dont work for me.

I am using the Stark theme to start to buid a theme. I am trying to remove the main menu text from above the menu, please see

I have tried How to remove "Main Menu" title from Stark Theme but this does not work, infact if I remove the block from admin/structure/blocks the menu still shows.

Does any one know how I can fix this?

Thanks.

# Answer
> 1 votes
For blocks, **Title** fields is optional so it is not required to enter. However **Description** field is mandatory to enter but it displays in the admin side listing only.

So you can keep title blank or use `<none>` as Patrick mentioned in his comment.

# Answer
> 1 votes
What the other answers suggest is valid for most themes or at least for those themes that render the main menu via a block, but the Stark theme doesn't.

The Stark theme renders the main menu fixed through it's template files and there are other themes that do it that way.

Furthermore Stark is made for demonstration and debugging purposes:

> The Stark theme is provided for demonstration purposes; it uses Drupal's default HTML markup and CSS styles. It can be used as a troubleshooting tool to determine whether module-related CSS and JavaScript are interfering with a more complex theme, and can be used by designers interested in studying Drupal's default markup without the interference of changes commonly made by more complex themes.

So I wouldn't recommend it as as a normal theme. If you wan't to create a subtheme there are better options.

# Answer
> 0 votes
Make sure you have the correct theme tab selected when you go to `/admin/structure/block`

Then edit the block and set the block title to `<none>`

Flush your caches at `/admin/config/development/performance`

---
Tags: theming
---


# Question
Title: What entity should entity_id be joined on?
I'm writing a complex custom query to get order information from a Drupal Commerce install for export.

The table `field_data_commerce_customer_address` has a column `entity_id.` I've tried to join that field on `order_id`, but my results are incorrect. It doesn't match to user id... hmm.

What field should I join `entity_id` on?

And, more generally, is there a drupal entity informational function that would tell me what columns should be joined to what? Or a master entity table, or anything? Some central location that would tell me things like this so I don't have to dig around?

Looking around the database and googling but haven't found it yet.

# Answer
> 0 votes
The `entity_id` is the ID of the Commerce customer profile (which you can find in the `commerce_customer_profile` table).

This makes more sense when you look at the `type` column in the same field table, as it will likely be one of "shipping" or "billing", the default bundles available to the profile entity type.

Profile entities have a `uid`, which links back to the related user.

So if you're building a manual query, and want to involve the user id, you also need to join in `commerce_customer_profile` on `commerce_customer_profile.profile_id = field_data_commerce_customer_address.entity_id`. You'll then be able to use `commerce_customer_profile.uid` for further joins/constraints.

# Answer
> 2 votes
The customer addresses are linked to the user, see https://drupal.stackexchange.com/a/121356/2322 for more details on this, so you've got an order that references a customer profile and this references a user.

It doesn't show this part, but find a more complete description about the commerce entities in this documentation page: http://www.drupalcommerce.org/user-guide/products

In any case, I'd definitely use Entity Field Query for this, it will save you from digging in the database and it will give you a more consistent way to access your data.

# Answer
> 1 votes
It's a field table, so, in principle, *any* entity bundle could use use the field and store data to it. The entity\_type column should give you the type of entity. If it is "node", then you need to join with the node table on nid, etc.

---
Tags: commerce, entities, database
---


# Question
Title: Loop trough a list of referenced nodes, "entity_metadata_wrapper()" style
I have a Template node that holds an Entity Reference multivalue field to a series of other nodes, all referenced nodes of the same type. The referenced nodes have a text field whose value I need to get.

In template node I have a computed field that do some calculations using the values from referenced nodes.

Now I have:

```
$tpl = field_get_items($entity_type, $entity, 'field_plan_tpl');
$values = array();
foreach ($tpl as $field_item) {
  $values[] = node_load($field_item['target_id'])->field_some_field[LANGUAGE_NONE][0]['value'];
}

```

How can I load the referenced entities in order to get field values, using `entity_metadata_wrapper()`?

# Answer
`entity_metadata_wrapper()` has you covered, the entities will be lazy-loaded as you'd expect:

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);

foreach ($wrapper->field_plan_tpl as $related_entity) {
  $foo_field_value = $related_entity->field_foo->value();
}

```
> 3 votes

---
Tags: entities
---


# Question
Title: What's the correct relative path to a local image?
I've created a topbar for my website that's displayed the whole time and added an image to it with

```
<img src="sites/default/files/MYFOLDER/IMAGE.png">

```

It looks great on the homepage, but when I for example visit a node, the image isn't found anymore. I guess this problem is caused by a wrong path, but I don't know how to fix it.

What's the correct relative path?

# Answer
> 2 votes
Mainly it is the issue with your **site root**. If your site is on root not in any subdirectory then you can use it like **/sites/all** with front slash in the begining.

You must use the base url variable '**`$base_url`**' to the source of an image that defines the base path of the site. It will works always wherever the irrespective of the root of the installation

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

<img src="<?php echo $base_url; ?>/sites/default/files/MYFOLDER/IMAGE.png">

```

Hope it works.

# Answer
> 2 votes
In this case it is NOT: `<img src="sites/default/files/MYFOLDER/IMAGE.png">`.

It should be: `<img src="/sites/default/files/MYFOLDER/IMAGE.png">`.

The issue you're having is Relative Path URLs vs Absolute Path Urls, see this stackoverflow in-depth answer.

By having `/sites/default/files/FOO/bar.png` as the `PATH`, you're informing the browser the file is found from the root of the website within the `/sites/default/files/FOO` folder and is called `bar.png` as an example.

By omitting the leading slash, you are saying the file resides in the folder path `sites/default/files/FOO` *within the current directory*. As you navigate the website, node paths and other URLs are rooted in other base directories.

# Answer
> 0 votes
I've found the solution for my problem, combining the answers from @tenken and @TBI Infotech. Using `<img src="/sites/default/files/MYFOLDER/IMAGE.png">` didn't work, because the system was trying to retrieve the image from `localhost/sites/default/files/MYFOLDER/IMAGE.png` \- obviously an non-existing directory.

Finally, `<img src="/MYSITE/sites/default/files/MYFOLDER/IMAGE.png">` did the trick.

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


title: Installing ckeditor youtube plugin

text:
# Question
Title: Installing ckeditor youtube plugin
Does anyone know how to extend the ckeditor to add the youtube plugin in Drupal-7? I am talking about this plugin http://ckeditor.com/addon/youtube. What is the drupal way of adding this?

# Answer
> 1 votes
https://www.drupal.org/project/wysiwyg\_mediaembed Might be what you're looking for and it has a useful issue board if you run into trouble...

---
Tags: 7, wysiwyg
---


# Question
Title: views with multiple contextual filters - should return data only when both or any one filter is present
Views of content is having two contextual filter. For some reason node object is available to views so it is passing through url's 7th argument.

1.Content: Has taxonomy term ID Configuration: Php Code

```
$nid = arg(7);
$node = node_load($nid);
if($node && isset($node->field_tags)) {
      $related = field_get_items('node', $node, 'field_tags');//dpm($related);
      foreach($related as $tag) {
          $view_par[] = $tag['tid'];
          //dpm($tag);
      }
return implode(',', $view_par);
}
else{
return 0;
}

```

2.Content: Nid (Ref: entity-reference-and-nested-arguments-in-views)

```
$nid = arg(7);
$node = node_load($nid);
$Related_ids = array ();
    $Related = field_get_items ('node', $node, 'field_some_er')    // Get the entity reference scope
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related[$ i]['target_id'];
      }
    }
    return implode ('+', $related_ids) // It returns the values of the field entity reference

```

Relationships:

```
Content: Taxonomy terms on node (Require this relationship :TRUE)
Content entity referenced from field_er_in_content (Require this relationship :TRUE)

```

With above configuration/**modifying** how to retrieve views's data only when

```
1. Any one of the filter should be present i.e either field_tags(term reference field) or field_some_er (entityreference field)
2. Both filter could be present.

```

but **should not retrieve when both value is absent**. Is there something can be done using common variable like *found flag* that can be shared to both php code and break the view operation.

# Answer
> 0 votes
Perhaps this is what you're looking for: https://www.drupal.org/node/1871388

Otherwise, it looks like you might want to set up what your contextual filters do when the arguments are not available:

https://www.drupal.org/node/1578574

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


title: Filtering view by the referenced field

text:
# Question
Title: Filtering view by the referenced field
I have a content type of `Company`, which can have multiple `Image`s. In the company node, i want to display a slideshow of the images which belong to the company.

For some reasons, instead of storing the `images` in a field of `Company`, i created another content type of `Image`, which references the `Company` through an `Entity Reference` field type.

So now i have a view of `Image`s which i want to filter using the reference field. I tried adding an `Contextual Filter`, but the filter cannot find the related images, which i think because the url is transformed. For example if the company has the name *The Company*, the path becomes */company/the-company* (i am using automatic alias).

How can i filter the images correctly in the company page? Thanks.

# Answer
To get your NID back (after it has been aliased) one of the solutions here is for you:

Drupal 7 Contextual Filter on URL Alias

But first I'd make sure your view is set up correctly with a contextual filter that has a relationship to the entity reference field ...

On your "view" click "Advanced". Click the "Add" button to the right of Relationships.

Find the "Entity Reference: Referenced Entity" relationship and check the box. Click "Apply". On the next screen, click "Apply" right away unless you want to change the identifier or make the relationship required.

Once you are back to your view's 'advanced options' Click the "Add" button to the right of Contextual filter and select "Content: Nid".

Under "Relationship", ensure that the entity reference relationship you added previously is selected. Next, select "Provide default value" and then set the type to "Content ID from URL". Click "Apply".

Stolen from here: https://www.drupal.org/node/1841004
> 2 votes

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


# Question
Title: How to programmatically add/modify a rule?
Hello,
I have the Rules module. I tried to programmatically create or modify a rule but it doesn't work. What I tried so far : I created the MY\_MODULE.rules\_defaults.inc file and wrote this code :

```
function MY_MODULE_default_rules_configuration() {
$configs = array();
$rule = { "rules_name" : {
  "LABEL" : "rules ",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "mimemail", "uc_cart" ],
  "ON" : { "uc_checkout_complete" : [] },
  "DO" : [
    { "component_rules_commerce_order_status_pending" : { "order" : [ "site:current-cart-order" ] } },
    { "mimemail" : {
        "key" : "[site:name]",
        "to" : "mail@mail.com",
        "subject" : "[site:name]",
        "body" : "Random text",
        "language" : [ "" ]
      }
    }
  ]
}
}
 $configs['rules_name'] = rules_import($rule);
  return $configs;
}

```

Yet it doesn't work. I also tried with MY\_MODULE\_default\_rules\_configuration\_alter() but to no avail.

# Answer
> 6 votes
You have to create new Rule via the provided APIs and HOOKs from the Rules module.

From creating rules through the UI you have seen their configuration attributes, such as

1. Rules Event
2. Rules Condition
3. Rules Action etc.

Now you have all the useful HOOKs to create new ones. If you want to add a new Rules event to your System then go for **hook\_rules\_event\_info()**

```
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_custom_event' => array(
      'label' => t('A custom event happened in your application'),
      'module' => 'your_module',
      'arguments' => array(
        'param1' => array('type' => 'user', 'label' => t('The user object')),
      ),
    ),
  );
}

```

You can invoke this event also from custom code in your module as

```
rules_invoke_event('your_module_custom_event', $param1);

```

If you want to add some custom conditions to a pre defined rule then use **hook\_rules\_condition\_info()**

```
/**
 * Implements hook_rules_condition_info().
 * Checks if the given user is male or not.
 */
function your_module_rules_condition_info() {
  return array(
    'user_is_a_male' => array(
      'group' => t('test'),
      'label' => t('If user is male'),
      'parameter' => array(
        'user' => array(
          'type' => 'user',
          'label' => t('Validate registered users if male'),
        )
      ),
    ),
  );
}
function user_is_a_male($user) {
  // your custom condition to return boolean TRUE or FALSE
}

```

To alter pre-defined Rules you might use **hook\_rules\_component\_alter** or **hook\_default\_rules\_configuration\_alter** but again depending on needs these will vary. Go through via the link above and you will find all.

FYI, you can export Rules via Features module with your custom HOOKs as well. And these custom HOOK's should be placed on a file as "your\_module.rules.inc" so Rules module will include these automatically.

# Answer
> 0 votes
Try entity\_import like this:

```
  $items['rules_take_cr'] = entity_import('rules_config', '{ "rules_take_cr" : {
      "LABEL" : "Take CR",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Customization request", "Logo NG" ],
      "REQUIRES" : [ "rules", "flag" ],
      "ON" : { "flag_flagged_take_customization_request" : [] },
      "DO" : [
        { "data_set" : { "data" : [ "flagged-node:author" ], "value" : [ "flagging-user" ] } }
      ]
    }
  }');
  return $items;

```

---
Tags: rules
---


# Question
Title: data selector not working in custom Module
I am working in a module and I have added custom date **data** attribute to ubercart order.

Now, I would like to create a **data selector** in rules for custom date attribute of the order.

I have implemented `hook_rules_data_info()` into my custom module but its not showing in data selector in rules.

```
/**
 * Implements hook_rules_data_info().
 */
function uc_datepicker_rules_data_info() {

  $entities['uc_datepicker'] = array(
    'label' => t('Ubercart Delivery Date'),
    'group' => t('Ubercart'),
    'wrap' => TRUE,
    'token type' => FALSE,
  );

  return $entities;
}

```

I have also added implemented `hook_rules_condition_info()` hook and its showing date condition into rules correctly.

Please suggest, how can I add data selector in rules for date attribute of the order in my custom module.

Thanks,

# Answer
> 0 votes
Have you tried with the options as 'getter callback' & 'setter callback'? It seems that these data selectors that you are creating needs to pass the values to the already implemented hook\_rules\_condition\_info as parameters.

---
Tags: 7, rules, ubercart
---


# Question
Title: Including multiple authors in Authoring information for a Drupal 7 node
I have a CMS to which many people can possibly provide data. So, I would want to include all the users who have contributed the data for a node by adding new data or moderating existing data, because everyone who contributed for a node deserve themselves to be undersigned. Right now, only the first person who creates the content would be the rightful author.

How can I achieve this?

I have googled but could not get much help. The closest I could find was this, which still goes unanswered. I have checked Entity Reference module but I could not get it to auto-fill the author whenever a user edits an existing node.

I have automatic revisions enabled, which means I do have the information of each author for a node who have contributed. But how do I pull each author out of the revision information and display the collection of all authors & contributors in a nice manner at the end of each article?

Please help me find a solution, I am not that well versed with PHP programming.

Thanks & Regards,
Raj Pawan G

# Answer
> 4 votes
I accomplished this by the following steps:

1. Download and enable the Rules module and the Entity Reference module.
2. Add a field called "Foo" to your content type. Field type: Entity Reference. Target type: user.
3. Create a new Rule.
    1. Add event: "Before saving content"
    2. Add condition: Data comparison. Parameter: Data to compare: \[node:type\], Data value: bar (Where "bar" = your content type's name)
    3. Add action: Add an item to a list. List: \[node:field-foo\], Item to add: \[site:current-user\]

Now every time content is saved, the user who saved it will be added to the list of editors of that page.

# Answer
> 1 votes
Here is a custom .module that does the task for a content type called wiki\_page. The content type has a multi-valued text field called field\_editors. Put field\_editors on a display mode, and the list will appear. No Views work needed.

`/**
 * @file
 * Keep track of the users who have edited a wiki page.
 *
 * @todo Check whether the page content has changed.
 */`

`/**
 * Implements hook_form_FORM_alter().
 */
function cyco_remember_editors_form_wiki_page_node_form_alter( &$form, $form_state ) {
 $form['#submit'][] = '_cyco_remember_editors_wiki_submit';
 $form['field_editors']['#access'] = FALSE;
}`

`/**
 * Add current user to list of editors if not already there.
 */
function _cyco_remember_editors_wiki_submit( $form, &$form_state ) {
 global $user;
 //Editor is current user.
 $editor_name = $user->name;
 //Flag to show whether the editor is already in the list.
 $editor_in_list = FALSE;
 $language = $form['#entity']->language;
 $num_editors = 0;
 //Are any editors listed?
 if ( isset($form['#entity']->field_editors[$language][0]['value']) ) {
 //Yes - see whether the current editor is already in the list.
 $current_values = $form['#entity']->field_editors[$language];
 $num_editors = sizeof( $current_values );
 for( $index = 0; $index < $num_editors; $index ++ ) {
 if ( $current_values[$index]['value'] == $editor_name ) {
 //Editor is already listed.
 $editor_in_list = TRUE;
 break;
 }
 }
 }
 if ( ! $editor_in_list ) {
 //Current editor is not in the list. Add him/her.
 $form_state['values']['field_editors'][$language][$num_editors]['value']
 = $editor_name;
 }
}`

---
Tags: nodes, entities, users
---


title: Hook_menu to Form with %node wildcard

text:
# Question
Title: Hook_menu to Form with %node wildcard
I have a content type 'school' and an entityform that's called 'contact'...

I would like the URL path for the contact form to be:

www.example.com/node/nid/contact

It's important that the node ID be passed in the link to the entityform in this format rather than:

www.mysite.com/eform/submit/contactform?some\_custom\_field=\[nid\]

so that people can share the contact form easily.

It's also important that the contact form be an entityform

Any pointers to set up my entityform url so that it reflects the NID of the content that linked to it?

I am trying to set up URL alias for the entityform but am having trouble setting up the NID as a wildcard.

> EDIT for my helper module I have...(we can ignore the entityform part of my question because I'll probably re-build the form) ... I am trying to get the letter generator to appear at /node/%node/lettergen but the %node wildcard isn't working ...

```
function lettergen_menu() {
$items = array();
$items['node/%node/lettergen'] = array(
'title' => 'Letter Generator',
'description' => 'Generate a Letter'
'load arguments' => array(1),
'page arguments' => array('lettergen_form', 1),
'access callback' => TRUE,
);
return $items;
}

```

> THIS WORKS

```
function lettergen_menu() {
$items['node/%node/lettergen'] = array(
'title' => 'Lettergen',
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form',
'page arguments' => array('lettergen_form', 1),
'access callback' => TRUE,
);
return $items;
}

```

# Answer
> 2 votes
One of the option is:

1. create a entity reference field in 'school' content type to reference associated contact form.
2. write a helper module that adds a menu item node/%node/contact.
3. Make sure access\_callback check for your content type and return false for other node type to avoid any perf issue.
4. In menu callback function, render the entity form to display.

Here is an example of "node/%node/something" pattern from token module.

```
/**
 * Implements hook_menu().
 */
function token_menu() {
  ...
  ...

  $items['node/%node/devel/token'] = array(
      'title' => 'Tokens',
      'page callback' => 'token_devel_token_object',
      'page arguments' => array('node', 1),
       // 'node' => token_devel_token_object function gets a string 'node' as argument 1
       // 1 => token_devel_token_object function gets a node object of node id given in url. for mode details refer https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_load/7.
      'access arguments' => array('access devel information'),
      'type' => MENU_LOCAL_TASK,
      'file' => 'token.pages.inc',
      'weight' => 5,
    );

// page callback definition
/**
 * Menu callback; prints the available tokens and values for an object.
 */
function token_devel_token_object($entity_type, $entity) {
...
...
}

```

---
Tags: uri, entities
---


# Question
Title: Output ctools_modal_form_wrapper() with translatable items in the form
i have translation strings already for this form. if i output it with:

```
  return drupal_get_form('user_login');

```

then the translation works

but if i render it for the modal form then the translation doesn't work.

```
return ctools_modal_form_wrapper('user_login', $form_state); with translatable items

```

so how can i enable the tranlation for the ctools\_modal\_form\_wrapper also?

# Answer
> 0 votes
This is an open issue for ctools modal\_form and is in need of some more data / feedback to push the issue forward. The specific bug is called out here and appears to be related to the language header that is used in the modal form window:

https://www.drupal.org/node/2160293

There is a potential patch for this here:

https://www.drupal.org/node/2245123

---
Tags: javascript
---


# Question
Title: Caching issue with class extension of RulesDataUI
In my custom module I am trying to extend RulesDataUI class as below in the code which works fine just after clearing the caches, but on the next page reload I get warning as "Warning: class\_implements(): Class RulesDataUICheckboxes does not exist and could not be loaded". I am not getting a clue how the class functions are invoked only just after cache clear.

The below code is present in my module name.rules.inc(nodequeue\_rules.rules.inc)

```
 function nodequeue_rules_rules_data_info() {
      $return = array(
        'checkboxes' => array(
          'label' => t('checkboxes'),
          'ui class' => 'RulesDataUICheckboxes',
          'token type' => 'rules_text',
        )
      );
      return $return;
    }

class RulesDataUICheckboxes extends RulesDataUI implements RulesDataDirectInputFormInterface {
  public static function getDefaultMode() {
    dpm("hi");
    return 'input';
  }
  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    dpm("called");
    if (!empty($info['options list'])) {
      // Make sure the .rules.inc of the providing module is included as the
      // options list callback may reside there.
      $element->call('loadBasicInclude');
      $form[$name] = array(
        '#type' => 'checkboxes',
        '#options' => call_user_func($info['options list'], $element, $name),
      );
    }
    else {
      $form[$name] = array(
        '#type' => 'textarea',
      );
      RulesDataInputEvaluator::attachForm($form, $settings, $info, $element->availableVariables());
    }
        $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    $form[$name] += array(
      '#title' => t('Value'),
      '#default_value' => $settings[$name],
      '#required' => empty($info['optional']),
      '#after_build' => array('rules_ui_element_fix_empty_after_build'),
      '#rows' => 3,
    );
    return $form;
  }
    public static function render($value) {
    return array(
      'content' => array('#markup' => check_plain($value)),
      '#attributes' => array('class' => array('rules-parameter-text')),
    );
  }
}

```

# Answer
I think you need to add your rules.inc file to the info files\[\] array to ensure that the file is included while rebuilding the UI.

See more related: https://www.drupal.org/node/1275958 & https://www.drupal.org/node/1276606
> 2 votes

# Answer
It would be the problem that modulename.rules.inc invoked (or included) just to get all rules hooks. Worth trying to add the class definition in separate file (e.g. includes/rules\_ui.inc) and include in nodequeue\_rules.info file as

files\[\] = includes/rules\_ui.inc
> 2 votes

---
Tags: 7, rules
---