# Question
Title: Do tokens work with Rules "Set a data value"?
I have a simple Rule created in which the action is that a particular entity is created (a node) and then another action is called to "Set a data value" of one of this node's field (a standard text field). In the Rules action I setup the tokens that I want to be put as data into this field. For some reason the tokens are not showing up properly when the entity is created:

I have tried a few different combinations but as you can see above the token I am using (node:author:link) does not display properly when the node is created. What is the reason for this? I have experimented with all of the different input filters but it does not seem to work for any of them.

# Answer
> 0 votes
I have found the answer to my own question and thought I'd share. The solution is to use Token Filter module. Once you have installed this module got to: Admin \> Config \> Content Authoring \> Text Formats. Create a new Text Format or edit an existing one and you will see an option called "Replace Tokens", check this and save your format. Now when your are using "Set Data Value" make sure that the text field has the input format that you just created/changed.

You should now be able to pass tokens successfully using Rules Set Data Value and they will format correctly.

---
Tags: entities, rules, tokens
---


# Question
Title: Can local actions have multiple parents?
I have a module that I am working on that defines some local tasks and local actions for node pages, eg

```
$items['node/%node/foo'] = array(
  'title' => 'Foo',
  'page callback' => 'foo',
  'type' => MENU_LOCAL_TASK,
);

$items['node/%node/bar'] = array(
  'title' => 'Bar',
  'page callback' => 'bar',
  'type' => MENU_LOCAL_ACTION,
);

```

This works mostly great. 'Foo' appears as a new tab on node pages, and 'Bar' shows up as a local action on the 'node/%node' page.

I would like my 'node/%node/bar' local action to also show up on the 'node/%node/foo' page as a local action. Is this possible? I have tried playing with the 'tab\_parent' and 'tab\_root' parameters, but this only seems to work with local tasks and it also doesn't seem to allow multiple parents.

# Answer
I believe it's always Many (Local Actions) to one (Parent Item) relationship as hook\_menu documentation says

> MENU\_LOCAL\_ACTION: Local actions are menu items that describe actions on the **parent item** such as adding a new user or block, and are rendered in the action-links list in your theme.

If you want to change the parent of local action you can do it using tab\_parent

```
  $items['node/%node/bar'] = array(
      'title' => 'Bar',
      'page callback' => 'bar',
      'access callback' => TRUE,
      'tab_parent' => 'node/%/foo',
      'type' => MENU_LOCAL_ACTION,
  );

```

Above displays action link in node/%/foo instead of node/% , tab\_parent accepts single string argument... So we can rule out option of sending multiple parents using array.. For deeper analysis you can refer

function menu\_local\_tasks() in menu.inc which is responsible for action items and local tasks rendering..

If you would like to see it in action both places you can try below..

As @awm pointed out in comment we can add it to other pages using hook\_menu\_local\_tasks\_alter, Here is how node module does to include node/add menu item as local action to admin/content using hook\_menu\_local\_tasks\_alter

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'admin/content') {
    $item = menu_get_item('node/add');
    if ($item['access']) {
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
}

```

So you can do same for your own implementation using below code

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function YOURMODULENAME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'node/%/foo') {
    $nid = arg(1);
    $item = menu_get_item('node/'. $nid . '/bar');
    if ($item['access']) {
      $data['actions']['output'][] = array(
          '#theme' => 'menu_local_action',
          '#link' => $item,
      );
    }
  }
}

```

Results in
> 3 votes

---
Tags: 7, routes
---


# Question
Title: Drupal Commerce - How do i specify a user name for new account other than the email address on an anonymous order?
Ok so here's the use case:

Our site also includes phpBB forums, which of course display the user name in posts... most people don't like their email address being displayed, for obvious reasons.

Orders placed by anonymous users automatically generates an account with the username the same as the email address. I want to keep the auto account creation, but have the user enter a UserID when they enter their billing info.

So i've created a field on the billing profile (field\_account\_name is the machine name). How do i reference that field in the entity creation rule? I looked at this topic: http://www.drupalcommerce.org/questions/5370/how-do-i-base-new-account-u... but that doesn't show me how to reference a field i've created, only ones that already exist in the commerce-order entity.

This might be a stupid question, but i'm still relatively new to drupal... any help would be HUGELY appreciated.

I also posted this on the Commerce site, but it doesn't look like that gets tons of answers.

# Answer
> 2 votes
On the create user Rule you need to bring `field_account_name` into scope by running condition "Entity has field."

First run EHF on Commerce Order to bring the billing profile reference into scope. Then you can EHF your account name field.

You then will have the ability to have access to that field's token and use it as the new account's username.

Note: this is more a Rules usage technicality, which Commerce uses heavily.

---
Tags: 7, rules, users, commerce
---


title: How do I update weight using Rules?

text:
# Question
Title: How do I update weight using Rules?
I am creating a sampler pack of all my products. I have a product display with several *node* reference fields (not product reference) so that whenever a new product is added, that reference field is updated.

I have Rules set up to automatically price those selections (each selection has a different price).

Now I'm trying to use Rules to update that line item's weight (for use with Commerce UPS). However, I can't seem to find a way to update the weight. Is this possible in Rules? Or am I going about this in the wrong way?

# Answer
You'll have to add a condition to your Rule.

Make an "Entity has field" condition that checks for your weight field.

You'll now be able to use that data value.
> 1 votes

# Answer
If a product's weight is not being exposed to rules, you may need to have rules trigger a php snippet.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Display formresults in same block as form
I have created a module that writes a block with a very simple form in it.

The purpose of it is calculating distance between 2 adresses, one fixed, one asked by the form.

Now I can't get the results to show in the block itself, and I can't find any tutorials on how to do that.

The block shows, the form is in it also, but when i submit a postalcode it seems that nothing happens (also the postcode input field resets to emtpy).

the code that retrieves the distance works also (tested on commandline).

How can I approach this?

The code for my block:

```
  function reiskosten_block_view($delta = '') {
  $block = array();

  switch ($delta) {
  case 'reiskostenblock':
  $block['subject'] = t('Reiskosten berekenen');
  $block['content'] = drupal_get_form('reiskosten_form');
  break;
  }

```

The code for submitting the form:

```
function reiskosten_form_submit($form, &$form_state) {

/* REPLACE SPACE OR HTTP-REQUEST WILL BE MALFORMED */
  $postcode = str_replace(' ','',$form_state['values']['postcode']);

  $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=1024AA|Netherlands&destinations=$postcode|Netherlands&mode=car&language=nl-NL&sensor=false&key=myKey";

$data = drupal_http_request($url);
$result = drupal_json_decode($data->data);

$destination = $result['destination_addresses'][0];
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$duraton = $result['rows'][0]['elements'][0]['duration']['text'];

  drupal_set_message("$distance");
  $form_state['rebuild'] = TRUE;
}

```

I want the output of $result to be shown below the submitbutton. It is driving me crazy this one, been puzzling for 5 hours now on this thing (what should be relatively simple imho).

edit: I also validate on postalcode with:

```
function reiskosten_form_validate($form, &$form_state) {
  if ( empty($form_state['values']['postcode']) ) {
    form_set_error('postcode', t('Postcode mag niet leeg zijn'));
  }
}

```

It doesn't throw an error so it seems to me that 'postcode' has a value and the function should be processed.

# Answer
> 1 votes
Solved it. Solution:

in function reiskosten\_form\_submit($form, &$form\_state) {

```
$result = drupal_json_decode($data->data);
$form_state['results'] = $result;

```

in function reiskosten\_form($form, &$form\_state) {

```
$form['destination'] = array(
  '#markup' => '<div>' . $form_state['results']['destination_addresses'][0] . '</div>',
);

```

Wrap t in an if to see if the values are there and the magic happens. Pfff

---
Tags: 7, forms
---


title: Registration pop up for new guest users

text:
# Question
Title: Registration pop up for new guest users
I have a drupal 7 site.

I have users that are coming to many pages of my site (not only home page) from different sources on the internet.

My goal is that when a guest user is entering the site, no matter which page, he will get nice popup that will offer him to register to the site. On the popup, I will write short text explaining the benefits of the site, even put a video (if possible).

I saw that in many sites, I get a popup message on top on the site (the rest of the site becomes dark) that offer me to register. I want to do something similar.

Can someone help me achieve this goal?

# Answer
You could give a try to splashify:

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.
> 1 votes

---
Tags: users
---


# Question
Title: Different Site name and slogan for Organic Groups based multisite architechture
I am using OG based multisite in Drupal. I need to override sitename and slogan of default values so that each organic group has its own set of system values like Sitename and slogan etc.Also I am using Variable and OG Variable modules which seem to be for this purpose, but changing variable Realms in Organic groups variables doesn't save the values, the admin form for changing variable values doesnt save values. What am i missing?any help?

# Answer
Open Atrium (6.x) uses spaces to save different configuration for each og, this may be helpful.

> Spaces is an API module intended to make configuration options generally avaliable only at the sitewide level to be configurable and overridden by individual "spaces" on a Drupal site. It has been described as:
>
> A way to make one Drupal site act like several sites A way to provide much more configurable, full-feature Organic Groups or user homepages A generalized API for contextual configuration
> 1 votes

# Answer
You can use og\_context() in preprocessing or page.tpl to check if the node is a group or groupcontent and override slogan/name that way.

(this is for og 2 /drupal 7 btw. You didn't mention your version)
> 0 votes

---
Tags: organic-groups
---


title: Core overlay on path defined in views

text:
# Question
Title: Core overlay on path defined in views
Anyone know how to render a path defined in a view in the core overlay.

hook\_admin\_paths\_alter() does not work in that instance. I can only think that it has to do with the execution pipeline.

overlay\_paths module also does not work.

# Answer
First you have to Change the overlay permissions and make the overlay view accessed by Visitors and users

lets Implement Hook\_admin\_path\_alter in your custom module...

```
function YOURMODULENAME_admin_paths_alter(&$path) {
  $path['VIEWPATH'] = TRUE;
}

```

Clear Drupal Cache..
> 1 votes

---
Tags: views, modal-dialogs
---


# Question
Title: Simplenews logs out when sending test newsletter
I am trying to send a test newsletter through simplenews and it logs me out from my website everytime I hit the send button. I am logged in as admin. I have successfully sent test newsletters before and I dont think it is a permissions issue since I have necessary permissions. The only thing I changed was install simplenews related modules like simplenews-statistics,etc. I also copied the .tpl.php files from simplenews's module folder to my theme folder.

What could be the problem?

# Answer
> 0 votes
I found out that the problem occurs when I use custom .tpl.php templates. I deleted the statistics module and .tpl.php files from my theme's folder. So, I am using the default .tpl.php files provided by Simplenews and it works.

Now, I need to figure out why I can't use custom template files.

# Answer
> -1 votes
I had the same problem after upgrading to Simplenews 2.x. Turns out there was a conflict with Simplenews Analytics. Once I disabled Analytics, the problem went away.

---
Tags: emails
---


# Question
Title: change the list option based on the selection type
In a form, user have an option to choose the submission type. Based on the selected submission type, user should get an option to choose sub-type. Please let me know how this is done in Drupal 7. Please suggest a module.

If user select e-book, sub-type should change to case:1 (see image)
If user select e-project, sub-type should change to case:2
If user select e-lab manual, sub-type should change to case:3

# Answer
Seems like you are looking for Conditional Fields module...

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

See below image displayed in project page which suits your requirement.. Hope above module solves your problem..
> 0 votes

# Answer
If this is taxonomy term based, try using Simple hierarchial select. Details from project page:

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
>
> This module has been inspired by Hierarchical select but is much simpler.

It provides a field widget that can force deepest level selection, so your nested terms are fully utilized.
> 0 votes

---
Tags: theming, forms, nodes
---


title: Translate links in Drupal menu page

text:
# Question
Title: Translate links in Drupal menu page
I have a maybe rather silly question. I have a test website and a live website (both Drupal 7)

In the test website I have setup translations for my main-menu using the module "Menu Translation" (it is a sub-module of i18n) and at mydomain.com/admin/structure/menu/manage/main-menu I see a third column with the option to "translate" the menu options in the first column.

At my live website I want to do the same, but can't figure out what setting I have to change in order to get these " translate" links appear in the same page?

The settings in the testwebsite are done more than half a year ago and I cant remember how I did that. The Multilangual option -\> Translate and Localize is set for the main-menu on both sites.

This is what my live website looks like \[1\]: https://i.stack.imgur.com/p0L2y.jpg This is what my test website looks like \[2\]: https://i.stack.imgur.com/1BvNz.jpg

I assume that this has nothing to do with the "reset" link? (no idea what the purpose of that link is)

# Answer
I have asked an Drupal website design company which searched for the difference between live and test site. The solution was that the permissions for my own role as designated admin (not the main admin role) where not set the same regarding: under String translation the settings for "Translate user-defined strings" and "Translate admin strings" must be enabled in order to show the "translate" column, which I was looking for.
> 0 votes

# Answer
In General Usage of Contributed Modules first steps to use any module is

* Read Documentation of Project Page in D.O . You will find the link in the right side bar.

* Readme or Install files inside Module Folder
* Still if you are unable to figure out.. Visit .module file and focus on hook\_menu implementation which lists menu paths as keys of $items array.. By visiting those pages you will get a chance to see configuration pages given by that particular module.

In your case

* Enable i18n\_menu module which has following module dependencies. I enabled using drush which automatically downloads and enabled below modules. In your case make sure below modules are present in your instance.

The following extensions will be enabled: i18n\_menu, i18n\_translation, i18n\_string, variable, locale, i18n

* Once you enable you can see "Translate" setting in any menu page. I just verified no other changes are required. Just clear cache once you enable module in case.
> 0 votes

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


# Question
Title: Drupal 6 Ubercart - cancel/remove payment on order
I have an older Drupal 6 site using Ubercart. We were recently doing some work to the payment gateways and upon the completion of the work we neglected to remove the test payment gateway and there were several orders that were submitted for which no actual payment was ever made.

My question is - is there a way to remove the erroneous payment and set the order back to non-paid? I know I can change the status, but I need to adjust off the amount that was actually paid in this scenario instead of the customer having to go through the whole purchase again. My thought is that they can just log back in and re-complete their order with the test gateway payment having been removed.

# Answer
Rob, I'm afraid it may not be possible. In Ubercart, we handled shopping carts as pseudo order objects, tying cart items directly to a session. Once that cart has been checked out, as I recall, there's no way to run through checkout again with it. You may just need to contact the customers to resubmit the order or process their payment some other way (PayPal money request?).

Fwiw, this is why we made the decision in Commerce to manage all shopping carts as full order objects and use the order ID in the checkout URL. Much cleaner to support this type of behavior.
> 1 votes

---
Tags: ubercart
---


title: Views PHP references

text:
# Question
Title: Views PHP references
I would like to use Views PHP module in my Drupal Site.

But I don't have any idea on how to use this and I can't find good tutorial for this module. Anyone who can suggest any references or videos for Views PHP Tutorial?

# Answer
There exists good documentation in Project Page of Views PHP module and Documentation under Read Documentation link in project page..

Some existing answers and tutorials which can explain better you can find below..

How can I insert PHP code in Views?

http://eureka.ykyuen.info/2012/03/10/drupal-7-add-php-field-to-view/
> 2 votes

---
Tags: views
---


title: Hooks placements in Drupal

text:
# Question
Title: Hooks placements in Drupal
I am trying to place some hooks, but I don't even think they are being called.

THEMENAME\_menu\_alter(&$items)

and

THEMENAME\_user\_view\_access($account)

are the hooks I am placing in my template.php file. However, they don't seem to be reacting to it. And yes, I am converting the dummy THEMENAME placeholder to the name of my theme in use.

But my real question is: are these hooks just for use in Custom Modules? Or can they be called in from template.php too?

If its just for custom modules then I guess that would explain why it's not reacting. But even so how is one suppose to know if a certain hook is only for a module or not?

P.S: I have also tried clearing the cache several times.

# Answer
By Default you can consider all hooks can be extendible using custom modules...

Hook Documentation says

> Hooks are how **modules** can interact with the core code of Drupal. They make it possible for a module to define new urls and pages within the site (hook\_menu), to add content to pages (hook\_block, hook\_footer, etc.), to set up custom database tables (hook\_schema), and more.

In template.php you can override functions which are exposed by hook\_theme or functions like theme\_\*

There exists a good documentation that explains which functions you can override using template.php..
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How to move drupal site from remote server to localhost?
I have a drupal site running currently on bluehost. The site is big and I want to test every thing I change on local host before doing it on production site.

Unfortunately, I can not move it to from the remote server to local host.

Can someone give me the basic steps needed to move site from remote server to my local host (aquia dev desktop)?

# Answer
> 2 votes
I am not sure your site has SSH access and you can access it, but certainly you have FTP access to your site.
Suppose your drupal directory is /public\_html/mydrupalsite/; with FTP managers like FileZilla or CuteFtp access your site. Download all the files that are in the mydrupalsite directory, then go to phpmyadmin on your site, and select your database; open the export tab, and export your database without changing any setting.
Install PHP, Apache, and MySQL server on your computer, copy the files to the directory that can run in your local host, create a new database, import the database, and change the parameters in the settings.php file.

---
Tags: migrations
---


# Question
Title: IIS - how to handle file permission problem
Here is a generic error message, shown several times on each page :

> Warning: file\_put\_contents(temporary://fil25BC.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream\_open" call failed in \> file\_unmanaged\_save\_data() (line 1935 of C:\inetpub\www-v2.3\includes\file.inc).

What can I do ?

EDIT I stopped struggling with that problem by changing my temporary directory on this server It was C:\Windows\temp (or C:\Windows\temp\drp-tmp) It is now sites/default/files/drp-tmp Note : on another server, the first setting is not giving warnings... Well, looks like I do not master that topic ! THANK YOU FOR your answers and attention

# Answer
> 1 votes
Seems like issue is that Drupal is trying to write a temporary file somewhere it cannot write, like in the site's docroot...

Try running below commands using drush and make sure write access is available for temp directories..

```
~$ drush vget file_directory_temp

~$ drush vget file_temporary_path

```

---
Tags: files, iis
---


# Question
Title: How do I change the order of the form elements?
I am using Drupal 7, and trying to make a custom register form to fit my needs.

I am also using a contrib module named "Auto Assign Role" to let the user choose his role.

Now heres the issue, the fields are appearing on the form but the order is messed up.

I have 5 fields on the form total:

1. First Name
2. Last Name
3. Role
4. Username
5. Password

The first i added via the manage fields section of Account area, the role field is added by the contrib module, and the other two field are built-in, I guess..

Above is the order i seek, but its not doing that even though i think it should. I ordered the field like that in the manage display screen, yet it still doesn't do what i want it to.

The order i get is:

1. First Name
2. Role
3. Last Name
4. Username
5. Password

If i set the weight of the above two fields (first & last names) to 0 instead of dragging and dropping to order in the manage display screen i get the following order:

1. Last Name
2. First Name
3. Role
4. Username
5. Password

This is almost what i want, but i want first name to be above last name.

Is there some way i can accomplish this?

Thanks!

# Answer
> 0 votes
@AjitS Credit to you for resolving OP's issues.. Adding more details so that it will be helpful for others..

Drupal weights works using below logic...

> Lighter weights Float.... Heavier weights sink...

That means field weight with low value comes to top... Field with Weight high values goes to bottom...

You can also set Negative weights to Fields...

Please find different scenarios of ordered fields with weights below..

Field A : 0

Field B : 1

Field C : 2

Field D : 3

Field E : 4

Field F : 5

---

Field A : -5

Field B : -4

Field C : -3

Field D : -2

Field E : -1

Field F : 0

---

Field A : -2

Field B : -1

Field C : 0

Field D : 1

Field E : 2

Field F : 3

In your case Click on Show Row Weights to edit Weights and set weights base on above logic and click save..

---
Tags: 7, forms
---


# Question
Title: How to read a Entity reference node's fields?
I had a field using entity reference in my site. I'm trying to develop a module can read/use it.

```
$wrapper = entity_metadata_wrapper('node',$node);
dpm($wrapper->myRefField->getPropertyInfo());

```

This returns a error page, but dpm($wrapper-\>myRefField) shows that it's a standard EntityDrupalWrapper, though nothing in it.

How can I read $nid of the referenced node?

Errors below:

```
 Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "node" does not exist LINE 3: node base ^: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp, revision.uid AS revision_uid FROM {node} base INNER JOIN {node_revision} revision ON revision.vid = base.vid WHERE (base.nid IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] => 1 ) in DrupalDefaultEntityController->load() (line 191 of /var/www/site2/includes/entity.inc).

Additional

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "filter_format" does not exist LINE 3: filter_format ff ^: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] => 1 ) in filter_formats() (line 427 of /var/www/site2/modules/filter/filter.module).

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "semaphore" does not exist LINE 1: DELETE FROM semaphore ^: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 18701629495353e89467a483.34692095 ) in lock_release_all() (line 269 of /var/www/site2/includes/lock.inc).

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "sessions" does not exist LINE 3: sessions sessions ^: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] => sLS3fA1YAd1u1G6_xC1yxg0Ba6Kgrus6oXDBm4Wpuww [:db_condition_placeholder_1] => ) in _drupal_session_write() (line 209 of /var/www/site2/includes/session.inc).

```

# Answer
> 3 votes
```
<?php

/**
 * We define a new function in our MODULE and will simply use it where needed.
 *
 */

/**
 * @param (object) $node
 * @param (string) $field_name
 * @return false|null|integer
 *    The target id. FALSE on error. NULL when no reference found.
 */
function _MODULE_get_node_reference($node, $field_name) {
    $target_id = null;
    if (!isset($node->type)) {
        return false;
    }
    // In case of any exception we simply return false.
    try {
        $entity_wrapper = entity_metadata_wrapper('node', $node);
        if (isset($entity_wrapper->{$field_name})) {
            $target_id = $entity_wrapper->{$field_name}->value();
        }
        // maybe we are in the middle of a DB transaction. In that case entity_metadata_wrapper() would not work
        if (empty($target_id)) {
            // So, we try using Fields API. This always works.
            $items = field_get_items('node', $node, $field_name);
            if (isset($items[0])) {
                $target_id = $items[0]['target_id'];
            }
        }
    } catch (Exception $e) {
        return false;
    }
    return $target_id;
}

?>

```

---
Tags: 7, entities
---


title: Can't update drupal core to 7.27

text:
# Question
Title: Can't update drupal core to 7.27
I'm tring to update using drush, with the command `drush up`, but core is not updating. it says on the drush output:

`Project drupal was updated successfully. Installed version is now 7.27.`

but it's not! the status report clearly says the version is still 7.26. Also, I tried running drush again, and it updates successfully from 26 to 27 every time I run it...

**UPDATE**

I did this command:

`drush up drupal -v`

and this was the output:

```
Initialized Drupal 7.26 root directory at /www/permalink.hashworld.co/docs

    [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
Loading release_info engine.                                                                                [notice]
Loading version_control engine.                                                                                [notice]
Loading package_handler engine.                                                                                [notice]
Executing: wget --version
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off /usr/share/php/drush/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d    [notice]
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2 --verbose --root=/www/permalink.hashworld.co/docs --uri=http://default  pm-updatestatus drupal 2>&1
 Name    Installed Version  Proposed version  Message
 Drupal  7.26               7.27              SECURITY UPDATE available

Update information last refreshed: Fri, 04/18/2014 - 20:06
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Executing: svn info /www/permalink.hashworld.co/docs/drupal-7.27
Executing: bzr root /www/permalink.hashworld.co/docs/drupal-7.27
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_fileN0AtzR http://ftp.drupal.org/files/projects/drupal-7.27.tar.gz
Downloading drupal-7.27.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-7.27.tar.gz verified.                                                                                [notice]
Mime type for /www/permalink.hashworld.co/docs/drupal-7.27.tar.gz is application/x-gzip                                                                                [notice]
Executing: tar -C /www/permalink.hashworld.co/docs -xzf drupal-7.27.tar.gz
Executing: tar -tzf drupal-7.27.tar.gz
Project drupal was updated successfully. Installed version is now 7.27.
Backups were saved into the directory /home/ubuntu/drush-backups/permalink/20140421094219/drupal.                                                                                [ok]
Command dispatch complete                                                                                [notice]
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off /usr/share/php/drush/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d    [notice]
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2 --verbose --root=/www/permalink.hashworld.co/docs --uri=http://default  updatedb 2>&1
Initialized Drupal 7.26 root directory at /www/permalink.hashworld.co/docs                                                                                [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
No database updates required                                                                                [success]
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off /usr/share/php/drush/drush.php --php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d    [notice]
magic_quotes_runtime=Off -d magic_quotes_sybase=Off'  --backend=2 --verbose --yes --root=/www/permalink.hashworld.co/docs --uri=http://default  cache-clear all 2>&1
Initialized Drupal 7.26 root directory at /www/permalink.hashworld.co/docs                                                                                [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
'all' cache was cleared.                                                                                [success]
Command dispatch complete                                                                                [notice]
Finished performing updates.                                                                                [ok]
Command dispatch complete                                                                                [notice]
Command dispatch complete

```

# Answer
It might be issue with permissions of Drupal root directory.. Try running them as sudo

> sudo drush up

Above command updates all enabled modules and core in Drupal...

Try using

> sudo drush up drupal

which updates only core.. It worked for me.. I Updated from 7.22 to latest 7.27..

Try with -v for more information..

> sudo drush up drupal -v

To debug use below command with --debug option

> sudo drush up drupal --debug
> 10 votes

# Answer
Update drush to the last stable versión an try again.

If it doesn't work do it manually: (this is tedious but not hard);

1. Make a backup of your Drupal instance. (For ex: with MySQL)
2. Download the latest release of your current Drupal version.
3. Extract the \[tar ball or zip\] Drupal package.
4. Set your site on maintenance mode (For ex: How on D7)
5. Delete all the files & folders inside your original Drupal instance except for /sites folder and any custom files youmadded elsewhere.
6. Copy all the folders and files except /sites from inside the extracted Drupal package \[tar ball or zip package\] into your original Drupal instance.
7. If the update release includes changes to settings.php replace old settings.php in .../sites/default/ with the new one, and edit site-specific entries (eg database name, user, and password)
8. If you modified files such as .htaccess or robots.txt re-apply those changes to the new files.
9. Login to your site as administrator or as user no 1 Run update.php by navigating to /update.php
    1. Follow the process to update your Drupal instance Disable maintenance mode.

more info
> 2 votes

---
Tags: 7, drush, updating
---


# Question
Title: How to view PDF files in a modal/overlay
I have pdf (managed) files on the server that I want users to view in a modal. This will be part of a module I'm creating. There are a couple of modules that help with this, but I haven't found a good way to incorporate those yet.

One of the most promising seems PDF Reader, but it requires you to create a node before it will do its magic. I would like to just use the file (managed file, stored using Drupal) and not create a separate node for each file.

I'm open for any suggestion. I have already implemented some CTools modals and Modal Forms (for easy display of Webform content) so I can work with that. But maybe it would be easier to create a node on the fly of the content type created for PDF Reader (say pdf file) and show that with a custom node--pdf-file.tpl.php. But how to create such a node then and how to get it in a modal?

Or maybe there is a more simple solution altogether. I'm using Drupal 7.

# Answer
PDF Reader does not require you to create node. It only requires you to have file in a field, in any kind of entity. If your file is managed, something uses it (in usage table). just expose that data to entity api, make file a field and you are good.

If you want to avoid entities, this module is open source. Use it as a learning tool. Borrow it's code. Give credit where credit is due, and use as you need.
> 3 votes

# Answer
You can use the native browser solution to render the PDF and colorbox for the popup (using the iframe method).

> Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.
> 3 votes

---
Tags: 7, files, javascript
---


title: Node Creation Paths

text:
# Question
Title: Node Creation Paths
I added a custom node-type (content-type) called Document (for example), i also allowed it to create a menu item for navigation purposes.

Then assigned a non-admin role the permission to create new content/edit own content and delete own content.

But the problem here arises that Drupal is automatically creating the paths to create node page.

In simpler terms, its creating a menu item with the path /node/add/document

but this is something i have to avoid, I instead want something like this /add/document

I can't find any way to do this, a Google search also led to nothing helpful. Is it not possible to customize/modify this behavior? my main problem with the default path structure is the "node" being displayed.

## **UPDATE**

I managed to find a way to make the path work with my choice of path structure by going to the URL aliases section (admin / config /search / path ), and assigning the old path a new alias, but like i guessed its still letting me access the add page with the "node" intact as well.

Thanks in advance

# Answer
> 1 votes
It's by design... You can able to access path using normal path and aliased path...

However, you can change this behaviour using Global Redirect module which redirects to aliased path if available...

Project page says

> Once enabled, an alias provides a nice clean URL for a path on a site. However Drupal does not remove the old path (eg node/1234). The problem is that you now have two URLs representing the same content. This is dangerous territory for duplicate pages which can get you sandboxed by the search engines!

# Answer
> 1 votes
You can also use pathauto (URL Alias) which allows you to chose a particular path for your custom content add. Enable this module and go to yourdomain/admin/config/search/path where you can add a path for your custom content type.

Add Existing system path like : node/add/document and Path alias as : add/document

---
Tags: nodes, uri
---


# Question
Title: How to theme PDF generated by Print module?
I would like to theme the PDF generated by the Print module. I would like to add header, footer, margins, border to the generated PDF.

The certificate module in Drupal provides theming to the certificate, but my site is almost like a read and get certified site, so I wish not to change print module.

I tried the form alter and other stuffs, but not sure from where the PDF can be changed.

# Answer
> 2 votes
Drupal 7 allows to alter how content is rendered with `theme_print_pdf_tcpdf_content()`. This should be fairly simple: Just place this hook in the template.php file, and add a new function where the PDF file is rendered. Use the following code as reference.

```
function theme_print_pdf_tcpdf_content(&$vars) {
  return new_function_that_prints_the_content($vars);
}

```

# Answer
> 2 votes
You should on your creation of node call a function which will generate a pdf. Use tcpdf class for it generate pdf and download tcpdf functions./ Check also the link

```
 class my_pdf extends TCPDF { //Page header public function Header() { } // Page footer public function Footer() { } }

$pdf = new my_pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, UTF-8', false);

$pdf->setPrintHeader(true);
 $pdf->setPrintFooter(true);
$pdf->SetMargins(25.0, 40, 25.0);
$pdf->SetFooterMargin(1.5);
$pdf->SetAutoPageBreak(TRUE, 50);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('my_document.pdf', 'D');

```

# Answer
> 2 votes
Print module comes with a print-pdf.tpl.php template as well as a print.tpl.php template (or use the one in your theme). Since this is all about styling, rather look at editing these and put them in your theme folder.

# Answer
> 1 votes
It's actually possible using a hook for TCPDF:

```
/**
 * Implements hook__print_pdf_tcpdf_alter()
 */
function MODULENAME_print_pdf_tcpdf_alter($pdf, $html, $meta) {
  $pdf->setPrintHeader(FALSE);
  $pdf->SetPrintFooter(FALSE);
}

```

---
Tags: 7
---


# Question
Title: Redirect the title field of a content type to some external url in a view
I am using drupal 7 with view3

I have content type named **News** having many fields along with a taxonomy field named **News Type**, News type have terms: '**Free**' and '**Premium**', I am displaying News on my page through view, the problem i am facing is I need to redirect the news node to some external url like popup, if its premium news, means if its **News Type** field is set to **premium** it should not be **redirected** to its content, In short when premium news is viewed it should popup some message instead of showing the content of that news,and for free news it should go to the news node detail page. Please find the screenshot of view attached. Please help will be greatly appreciated. If I need to clarify please comment.

# Answer
> 0 votes
To change content link... You can try using Views Conditional Module...

Project page says

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> Equal To
>
> Not Equal To
>
> Greater Than
>
> Less Than
>
> Empty
>
> Not Empty
>
> Views conditional allows you to output text based on the result of the condition.

If it doesn't work then you can solve it using views php module..

---
Tags: nodes, redirection
---


# Question
Title: Which module supports select or other option for Term reference type?
Is there any module to support select or other option for Term reference type?

I tried with the Select (or other) module but its not working in Term reference type

# Answer
There is a sandbox module available that adds this functionality: https://drupal.org/sandbox/cameronbprince/1895832

Also there is an issue in the issue queue to incorporate this into the module itself: https://drupal.org/node/1716764

Alternatively, the hierarchical\_select module also provides the option to let users add new terms to vocabularies on the node edit form.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: how to fetch webform records from table by using drupal db_select
i want to display the output in the following format by using the following source code but the following source code shows error

> Notice: Undefined offset: 0 in eval() (line 20 of /....----modules/php/php.module(80) : eval()'d code).

```
<?php
include_once(drupal_get_path('module', 'webform').'/includes/webform.submissions.inc');
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','1','=');
$results =$query->execute();

echo "<table>";
echo "<tr>";
echo "<th>  Profile Photo </th>";
echo "<th> Faculty  Name and Department  </th>";
echo  "</tr>";

if($record = $results->fetchAssoc())
{
$sid = $record['sid'];
$nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "<tr>";
$val = $submission->data[15][0];

$query1 = db_select('file_managed', 'u');
$query1->fields('u', array('fid','filename'));
$query1->condition('fid',$val,'=');
$results1 =$query1->execute();

if ($record1 = $results1->fetchAssoc())
{
$path = $record1['filename'];

echo "<td> <a href ='http://../content/detailed-information/?val=$sid'  target='_blank'><img src ='../profile/$path'   width = '100' height='100' /> </a> </td>";
}
echo "<td><b>" .  "Name : " . $submission->data[1][0] . "</b><br>" .  " Designation : " . $submission->data[2][0] . "<br>" . " Department : " . $submission->data[3][0] ."<br>" . " E-mail : " . $submission->data[4][0] .  "</td>";
echo "</tr>";
}
echo "</table>";

?>

```

# Answer
Just as it says, the error is in the line

```
$val = $submission->data[15][0];

```

so the variable `$submission->data[15]` does not contain a value \[0\]. Most likely the array is empty.

Of course, it's probably a bad idea to go to the database yourself, rather than using Webforms API functions. A little searching can get you started.
> 2 votes

---
Tags: webforms
---


# Question
Title: Is there a way to add bulk operation options to the admin/content list's 'Update Options'?
I have downloaded the views bulk operations module and activated it. I offers me many new options for changing the settings on my nodes/entities. I would like to know if there is a way to add these options to the "update options" which is available on the content page of Drupal admin (location: admin/content.)

This menu already lets you do things such as publish, unpublish and delete. It also picks up options from add-on modules. It seems that views bulk operations should appear in this menu too.

# Answer
> 1 votes
Bulk operations provided by that module only make sense in the context of a view, so you won't see them on a non-view page like the standard admin content page.

You can install the Administration Views module to replace that page with a View, and then you should see the options you're expecting. Most (all?), of the core actions from the original page should be available. To add more, you can edit the View and change the available actions in the VBO field.

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


title: Tuning with New Relic

text:
# Question
Title: Tuning with New Relic
So I've finally delved into tuning up my aging Drupal 6 site using NewRelic and like most I'm amazed at what their product has to offer. Very useful for honing in on problem areas. However, being new to this I'm not fully sure what the correct actions are to fix my particular problem.

According to NR my biggest issue right now is the \_revisioning\_view (Revisioning Module) function. Digging through the trace reveals A LOT (1218) of calls to the url\_alias table (which currently has 75,000+ records in it) I've read a few things suggesting running memcache or some form of Path Caching. 1218 Calls to url\_alias certainly seems like a lot but before I go down the road of installing more modules I'd like to get a better grasp of what's going on here. Does anything jump out to anyone?

My other big item seems to be the time it takes to Insert and Update the cache\_content table. See the attached screenshots from NR and let me know where you think I should go first.

# Answer
For the url\_alias issue, I'd strongly recommend moving over to Pressflow which provides the path\_alias\_cache module along with support for it.

> Pressflow is a distribution of Drupal with integrated performance, scalability, availability, and testing enhancements.

I'd also recommend installing DB Tuner on your site to catch any missing indexes.
> 0 votes

---
Tags: caching, performance, debugging
---


# Question
Title: How to create a component which has specific content on each page
I'm a novice at drupal, so I'm still figuring things out. I'm looking for a way to accomplish the following the 'drupal way'.

I want to create a component, or a block, or something that allows the end user to enter a url to a page, a description, a title and an image. This component would be visible on the page as a clickable item.

I've tried using a custom content type, and used the views module to create a block out of these. This works, but it displays the same items as a block on each page. I need a way to make them different on each page. I'm not sure blocks is the way to go.

# Answer
> 1 votes
So, you need admin to be able to add one or two piece of content to a specific page.

Let's say you have content type **Product** content type. For the custom content you can create a new content type, let's say **Banner**. Consists of these fields:

* Title
* Description
* Image
* Link
* **Reference to Product**

Then you can simply create a Views which lists all **Banners** which have a reference to the current **Product** in the page. (Using contextual filters and the referenced field)

All Admin needs to do is to creates a **Banner** and indicate the **Product** to be displayed in.

You can also check Prepoulate module, for letting admin create the Banner straight from the Product edit page.

---
Tags: nodes, 7
---


# Question
Title: List registered users who are currently viewing a page
I'm looking for a module that, given a page URL, returns the list of users who are currently viewing it. The list should be dynamically refreshing to show page view activity in real-time.

Is there a module for that?

# Answer
Check the viewers module. Here is an excerpt from ots project page:

> Viewers is a small module, which builds a block showing which other users are viewing the same page as the current user. The 'other' users are logged in users or anonymous users or both users. You can set for how long you want a user appear on the viewers list of each page. And finally you can choose the position of the block from the admin/build/block page.

As stated it won't provide you the functionality of dynamically refreshing to show page view activity in real-time, but you can modify it through the custom code by refreshing the block after a required interval of time. Or you can try the Block Refresh module. Here is an excerpt from ots project page:

> Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.
>
> Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".
>
> Block refresh can be handy to serve fresh content in certain blocks on otherwise cached pages. You can opt to bypass drupal's cache for the refresh callbacks for each block.
> 3 votes

---
Tags: 7, javascript
---


title: Show specific url path in admin theme

text:
# Question
Title: Show specific url path in admin theme
I want to edit in admin theme some editing pages like "entityform/\*/edit". How can I do that?

# Answer
I find what exactly I want.

Administration theme module is great for using admin theme selected URL path.
> 1 votes

---
Tags: theming, entities
---


title: TB mega menu does not work anymore

text:
# Question
Title: TB mega menu does not work anymore
I'm working with the *TB mega menu* module. Two days ago it worked perfectly; now I have this error:

> Fatal error: Call to undefined function libraries\_get\_path() in C:\wamp\www\drupal\sites\all\modules\tb\_megamenu\tb\_megamenu.admin.inc on line 45

How can I fix it?

# Answer
libraries\_get\_path() is provided by the Libraries module. That error indicates that the Libraries module is either missing or not enabled.
> 6 votes

---
Tags: theming
---


# Question
Title: Drupal site does not show well when SSL is enabled
We have our site hosted on our Virtual Ubuntu 12.0 LTS. I am converting it to HTTPS. We are using Secure Login so that anonymous sessions are via HTTP or HTTPS and authenticated sessions only via HTTPS.

When I enable /var/etc/apache2/sites-available/site-ssl -\>

On IE, I get this message "Only secure content is displayed" Click here to show all content for every page we navigate to. When I accept to show all content, the website renders on IE 11.

The CSS is not being picked up at all on a chrome browser ( Version 34.0.1847.116)

I have attached the screen of the site. You will see the menus are not in place. The flex slider images are one below the other.

Any ideas or help to fix this is appreciated !

# Answer
You get this message from MSIE because the page has a mixture of secure and insecure content.

The culprit is usually inline/embedded content (images, iframes, javascript, css, etc.) that originate from a non-secure URL. Chrome just refuses to load it, causing the error you see To fix it, you need to locate those elements of the page, and replace them with secure versions.

To locate for these elements of the markup (unless they are obvious now that you know what to look for), use *FireBug* (requires that you use FireFox instead of MSIE/Chrome) or just press `CTRL+u`in MSIE to analyze the markup. In the markup, search for inline/embedded content hyperlinked with URLs starting with `http:` (instead of `https:`).

If all your links are *internal* (i.e. pointing to stuff below the webroot of the *same server*), you can eliminate the problem by dropping the *scheme* element of the URL (as suggested in a comment below by @JohnathanElmore).

In other words: if your server is `example.com` and you currently have the following URL reference as part of your theme:

```
src="http://example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

```

you should replace it with the following:

```
src="//example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

```

or even:

```
src="/sites/all/modules/spamspan/spamspan.js?somequerystring"

```

I can't tell you exactly how to go about making these replacements without knowing what you can and cannot do on your site. (If it was *my* site, I would simply edit the theme templates and clear alll caches. But I've no way of knowing whether this option is available to you.)
> 1 votes

# Answer
Thank you all for all your responses. The issue was fixed by commenting on the base\_url specified in the settings file.
> 1 votes

---
Tags: ssl
---


# Question
Title: Avoiding content-type overkill: 5 slightly different pages = 5 different content types?
My drupal 7 site mainly consists of a main menu with 5 entries, each linking to a more or less simple page. These 5 pages have a lot of common fields, simply some fields are slightly different. Normally, i would have to create a content type and an actual node to accomplish this — but since there is only one actual node for each of the content types, it feels like an overkill to me. One alternative is to handle all fields in one singe node, separating the 5 areas in the edit-form by fieldgroup-tabs, and generate the pages with views … Downside of this approach: instead of using display suite to do the theming, i would have to theme using views-fields, which is a pain.

The node field module, which allows you to add custom extra fields to single drupal nodes doesn’t work for me, since i am using entity-reference fields, which aren’t supported.

So what’s your best practice?

(Annotation: The content isn't very often updated and the content of the fields hasn't to be used in tokens, but i have to use a more or less "rigid" field structure in order to make editing content an easy no-brainer for the content maintainers. using „wide open“ WYSIWYG textareas isn’t a way to go, because maintainers will alternate often and will have only little knowledge about the project.)

# Answer
> 0 votes
Answer is it depends.

How often is the content in these nodes being updated? Does the content in the different fields need to be used in tokens, views, etc?

If it's never updated OR if you can use wysiwyg to edit the body to position things where they need to go and make it easily editable then use one node type.

If the info needs to be put into fields so views/tokens can pull bits out of the nodes then creating fields for those values is important.

---
Tags: entities, nodes
---


# Question
Title: Why do we use "target_id" as the name of the index in php instead of "entity_id"?
I'm finding that while I'm coding that I type in things like $entity-\>field\_fieldname\['und'\]\[0\]\['entity\_id'\] and that this doesn't work. When the Drupal 7 developers were developing it, why did they select 'target\_id' as the index instead of 'entity\_id' (or even better, why not try eid? ) I don't know how to contact the Drupal Coders who made this decision, do does anyone know who made this decision?

Drupal 7 has become quite harder to write code in.

Is there a better way for me to be coding that would avoid this problem?

# Answer
target\_id is generally used in entity references. So if you have an entity reference to another entity the target\_id is the id of that entity. This depends if it is a node or an entity though. But I will mention that generally you want to avoid `$entity->field_fieldname['und'][0]['entity_id']` but instead using the entity\_metadata\_wrapper to target values instead:

```
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

$mytitle = $node_wrapper->title // Title
$myfield = $node_wrapper->field_my_field->value(); // Value of the field, cleaner

You can also use the set method
$node_wrapper->field_my_field->set("My value"); // If single value

$node_wrapper->save(); // Save my entity

```
> 2 votes

---
Tags: 7
---


# Question
Title: How to backtrace a variable in php template
Currently I am in a .tpl.php file, and have the following piece of code:

```
  <?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>
  <?php elseif ($empty): ?>
  <div class="view-empty">
    <?php print $empty; ?>
  </div>
  <?php endif; ?>

```

It seems extremely difficult to figure where the $rows variable comes from. Any good idea?

# Answer
> 2 votes
You can do it using devel module and ddebug\_backtrace() api function exposed by devel..

Below is the function call stack for page.tpl.php executed using below command..

```
<?php dpm(ddebug_backtrace());?>

```

I believe above tpl is related to views module... **$rows are generated dynamically by views module based on your views settings...**

---
Tags: theming, debugging
---


# Question
Title: How can I programmatically override the title tag from within custom module?
I have a custom module that creates a search form and displays search results. We have a need where we want the title that displays in the browser tab to change depending on the search criteria. This particular search searches jobs that are available in specific specialties. I know you can use drupal\_set\_title() to change the title that gets displayed to the user in the H1 tag on the page, but what I am talking about is changing the title in the browser. The actual title tag for SEO purposes. So by default, the Browser tab title says "Job Search | My Site Here" ("My Site Here" is a place holder for the actual name of my site). When they perform a search we want the title to change to "{Specialty Name} Jobs | My Site Here". So for example if they search on the specialty "Cardiology", the browser title will be "Cardiology Jobs | My Site Here". I know there are custom modules to handle changing the page title dynamically, but those are for existing content types. This job search has been created completely from within a custom module, so ALL of the pages are dynamic. Is there a way to edit the browser page title independently of the drupal\_set\_title() function from within the custom module?

# Answer
See this question and answer. In short, I think your might be looking for something like `hook_preprocess_page()`.

```
function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Some links in admin not working correctly
I know this is a pretty "broad" issue, but I have several links in the admin interface that are not working correctly. One place in particular is in the Rules section of admin. When I edit a rule and add a new Condition, the "Data Selectors" fieldset text is not clickable (so I cannot expand it to see all of the available data selectors. Also, when I click in the "Data Selector" textbox field, the autocomplete is filled with "`<div></div>`" html wrappers around the data selectors. The attached screenshot shows both of these issues.

What would cause this? So far I have tried switching to Bartik theme (I use Seven as my default admin theme)... no change. I also updated all modules and updated Drupal core to the most recent version (7.27). My next step will be to disable modules, but I am quite hesitant to do so since I "need" all of the modules that are currently installed. I would appreciate any feedback and ideas on what might be causing this, and how it can be fixed.

Thanks!

# Answer
> 0 votes
I finally got an error message to work with (`TypeError: this.jqObject.data(...) is undefined`), which led me to this solution: https://drupal.org/comment/8677587#comment-8677587:

> Hi guys, I am pretty new to Drupal and programming in general, so pleas bear with me... I got the data selector working by configuring the jQuery\_update module:
>
> Default JQuery Version: 1.7
>
> Alternate JQuery Version: 1.7
>
> JQuery Compression Level: Development (I doubt this should make any differences)
>
> JQuery and JQuery UI CDN : JQuery

---
Tags: 7, users
---


# Question
Title: Moving the Up/Down Vote Widget to end of content
I am brand new to Drupal but not to OOPHP. I am assuming responsibility for a site which uses Up/Down Vote 6.x.

The issue is that the posts are very long and hold many many images and it doesn't look like the module supports any widget position other than at the top of `<div class="content">`.

I would like to move it to just above the footer links of the node, after the content.

I have been googling this without success. Can anyone advise me or direct me to the relevent docs?

# Answer
> 1 votes
Widget is getting displayed using hook\_node\_view code in vud\_node.module...

```
/**
 * Implementation of hook_node_view().
 */
function vud_node_node_view($node, $view_mode, $langcode) {
  // avoid showing the widget in some node builds
  $exclude_modes = array(
    NODE_BUILD_PREVIEW,
    NODE_BUILD_SEARCH_INDEX,
    NODE_BUILD_SEARCH_RESULT,
    NODE_BUILD_RSS,
  );
  if (in_array($node->build_mode, $exclude_modes)) {
    break;
  }
  if (($can_edit=user_access('use vote up/down on nodes')) || user_access('view vote up/down count on nodes')) {
    $node_type = in_array($node->type, variable_get('vud_node_types', array()), TRUE);
    $widget_showmode = variable_get('vud_node_widget_show', VUD_NODE_DISPLAY_BOTH);
    $tag = variable_get('vud_tag', 'vote');
    $widget = variable_get('vud_node_widget', 'plain');
    $vote_on_teaser = (bool)variable_get('vud_node_widget_vote_on_teaser', TRUE);
    $teaser = $a3;

    $widget_message_code = VUD_WIDGET_MESSAGE_ERROR;
    if (!$can_edit) {
      $widget_message_code = VUD_WIDGET_MESSAGE_DENIED;
    }
    elseif (!$vote_on_teaser) {
      $widget_message_code = VUD_NODE_WIDGET_MESSAGE_TEASER_DENIED;
    }

    if ($node_type) {

      switch ($widget_showmode) {
        case VUD_NODE_DISPLAY_TEASER_ONLY:
          if ($teaser == 1) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$vote_on_teaser || !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_FULL_ONLY:
          if ($teaser == 0) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_BOTH:
          if ($teaser == 1) {
            $readonly = !$vote_on_teaser || !$can_edit;
          }
          else {
            $readonly = !$can_edit;
          }
          $node->content['vud_node_widget_display'] = array(
            '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, $readonly, $widget_message_code),
            '#weight' => -10,
          );
          break;
      }

    }
  }
}

```

Implement hook\_node\_view\_alter in your custom module and change the weight to higher value so that it will be displayed at bottom...

In Drupal modules extends permissions by defining them using hook\_permission.. You can find list of permissions in "admin/people/permissions" ..

For vote up / down set permissions in above page.. See screenshot below..

---
Tags: 6, theming, rating
---


# Question
Title: drupal_set_message() shows a message twice when called from hook_init()
Basically the issue is that `drupal_set_message()` shows a message twice on some pages, when it is called from `hook_init()`.

How can I avoid it happens?

# Answer
> 5 votes
It's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.

To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.

It happens because `hook_init()` is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.

For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:

```
function is_ajax_request() {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

```

# Answer
> 4 votes
The easiest way to avoid the messages are repeated is setting the `drupal_set_message()` `$repeat` parameter to `FALSE`.

```
 drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'), 'status', FALSE);

```

---
Tags: 6
---


# Question
Title: Views: how to achieve automatic pagination?
I currently have a view that shows some content displayed in the right sidebar but now I have a pager that shows 4 items on every page. The user has to click next every time he wants to see the next 4 items but I want that this paging goes automatically. So instead of clicking next each time, the next page has to show after 30seconds for example.

Any ideas?

# Answer
Try Views infinite scroll module.

> Views Infinite Scroll provides a #586668: Pluggable pagers that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.
> 2 votes

---
Tags: views, paging
---


# Question
Title: Module Installation: Unable to create directory 'temporary://update-extraction-f781a69c/
I have searched the answers on this site and have found threads like Configuring the temporary directory which refer to this issue but could not arrive at a solution. My setup is Linux (Fedora), Apache, PHP 5.4.22 with Drupal 7.24 and I've done the following to ensure a correct configuration of the Drupal file tree:

```
1) chown -R apache:apache Drupal
2) cd Drupal
3) mkdir tmp
4) chmod 777 tmp
5) Change temporary directory in drupal admin/config to "tmp"

```

When I try to install a module (either through direct file upload or via URL) I get the error:

```
Module Installation: Unable to create directory 'temporary://update-extraction-f781a69c/

```

Now, the curious thing is that when I look in Drupal/tmp I see the following:

```
[root@localhost tmp]# ls -l
total 1448
-rw-rw-r-- 1 apache apache 1476650 Dec 13 23:24 bcommerce.tgz
drwxr-xr-x 2 apache apache    4096 Dec 13 23:24 update-extraction-f781a69c

```

So the extraction folder is created and seems to have proper ownership and permissions yet I'm still getting this error.

I've also ensured that the files in my tgz archive have proper permissions and are owned by apache, so their permissions should also be OK.

Any ideas on what might be wrong here would be much appreciated; I've been banging my head against this issue for a few hours now and have gotten nowhere.

# Answer
For me, things like these were caused by selinux. Either disable it, or add appropriate policy:

```
grep httpd /var/log/audit/audit.log | tail -n 50 | audit2allow -M drupaltmp
cat drupaltmp.te

```

Look inside, may be tune a little. I've got this:

```
module drupaltmp 1.0;

require {
        type httpd_t;
        type var_lib_t;
        type etc_t;
        type etc_mail_t;
        class file { write setattr };
        class dir { search create getattr setattr };
}

#============= httpd_t ==============
allow httpd_t etc_mail_t:dir { search getattr };
allow httpd_t etc_t:dir setattr;
#!!!! This avc is allowed in the current policy

allow httpd_t etc_t:file { write setattr };
allow httpd_t var_lib_t:dir create;

```

Then install it inside selinux

```
semodule -i drupaltmp.pp

```
> 1 votes

---
Tags: installation, files
---


title: Prevent / stop user_save

text:
# Question
Title: Prevent / stop user_save
Our current setup involves a multisite for different parts of our company. We need all sites to share a single user pool for various reason, but each site has slightly different user profile regulations that we need to adhere to. We have different permissions for profile fields on each site, so I need to prevent user profiles being saved if a user isn't on their home site.

I have a field in every profile called "Domain". I intend on pairing this to the current site url to determine if the user is on their home site or not. If not, I need to stop all user\_saves from completing. What would be the best way of going about this?

I've found in D6 hook\_validate('user') would have done the trick, but there doesn't seem to be anything in D7 that I can use. Would hook\_presave work, if I throw an exception?

# Answer
> 1 votes
You could also try to alter the "*user\_register\_form*" and "*user\_profile\_form*" and add a custom validation. So in that validation you'll be able to check the domain and set an error if it's wrong.

---
Tags: multi-sites, users
---


# Question
Title: Module Views automatically replace underscores in css classname to hyphens?
The situation is like this: I created an article list block with Views, and I want give the list row a custom css classname, ex it's called "focus\_img", but when I saw the output, "focus\_img" was converted to "focus-img" automatically. How can I turn off this annoying feature? I don't get it, why it made this change, I just need it output what I want..

# Answer
> 2 votes
It's by design... Views module is cleaning class in views\_plugin\_style.inc..

```
  /**
   * Return the token replaced row class for the specified row.
   */
  function get_row_class($row_index) {
    if ($this->uses_row_class()) {
      $class = $this->options['row_class'];
      if ($this->uses_fields() && $this->view->field) {
        $class = strip_tags($this->tokenize_value($class, $row_index));
      }

      $classes = explode(' ', $class);
      foreach ($classes as &$class) {
        $class = drupal_clean_css_identifier($class);
      }
      return implode(' ', $classes);
    }
  }

```

Below statement is converting _ (Underscore) to - (hyphens)

```
$class = drupal_clean_css_identifier($class);

```

If you see documentation of drupal\_clean\_css\_identifier by default filters replaces _ with -.

---
Tags: views, theming
---


# Question
Title: Transfer (export/import) url aliases and menu links automatically
I want to transfer/synchronize url aliases and menu links from one site to another. Is there any way (drupal module, drush command, script) to do it automatically? The module menu\_import looked promising but it does not take care of aliases.

# Answer
A good idea for solving this issue (at least until a more definite solution is implemented, with uuid etc.) is described in this article: http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal/

This is a related issue: data export import module how to keep alias drupal
> 0 votes

---
Tags: navigation
---


# Question
Title: data export import module how to keep alias drupal
I found `data_export_import` module very useful, however. It does not `import/export` url aliases and block content. Why I could live without the block content, I really would like to have nice way to `import/export` url aliases. Which module or which approach would you recommend to handle `import/export` url aliases? the same for blocks.

Thank You.

# Answer
The solution i did is created gradle script that import/exports url as following:

```
         task exportUrl(type:Exec){
            doFirst{println "exporting Urls..."}
                executable "sh"
                args "-c", "mysqldump -u ${user} -p${pass} ${db} url_alias>sites/default/files/data_export_import_${view}/url_${db}_import.sql"
         }

 task importUrl(type:Exec){
     doFirst{println "exporting Urls..."}
         executable "sh"
         args "-c", "mysql -u ${user} -p${pass} -h localhost ${db}<sites/default/files/data_export_import_${view}/url_${db}_import.sql"
  }

```

it works well because i can also use drush to do the node import/export in the gradle script as well.

```
            task exportNodes(type:Exec){
                   doFirst{println "exporting Nodes..."}
                       executable "sh"
                       args "-c", "drush dei-ex nodes --content-types=address,article,blog[other content types]"
                }

task importNodes() << {
       def dir = new File("sites/default/files/data_export_import/nodes").list().toList()
       for (fileName in dir ) {
              println "ipmorting file ${fileName}..."
                    exec {
                        executable "sh"
                        args "-c", "drush dei-im nodes --file=${fileName}"
                    }
       }
}

```

I hope its useful for anyone
> 1 votes

# Answer
This article is a good one: http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal

However I would like to point out that Part-I and Part-II can be accomplished by the module **menu\_import** (https://drupal.org/project/menu\_import). It can be done with **drush** (from terminal) like this:

```
drush menu-export $(pwd)/main-menu.txt main-menu
drush menu-import $(pwd)/main-menu.txt main-menu –clean-import

```

The module that you have created for custom aliases (https://github.com/kapasoft-config-scripts/designssquare\_alias\_path) is a good one too. However I think that it should go as a patch to the module **node\_export**: https://drupal.org/project/node\_export
> 1 votes

---
Tags: path-aliases, importing-exporting
---


title: Views: Arrange table elements

text:
# Question
Title: Views: Arrange table elements
I'm having problems with arranging elements in a Views Table and I hope you can help me with it. Instead of rendering each field in a separate column, I'd like to group some of them together in the same column as shown below:

# Answer
> 2 votes
Credit to @Felix Eve.... Adding more details so that it will be helpful for others..

* Edit Size & Price fields and check Exclude Checkbox
* Create Global: Custom Text field **below above fields** so that you can use replacement patterns
* Label it as Description
* Use Replacement patterns in "Global : Custom Text" something like below .. Use correct tokens from replacement patterns

Size : \[field:size\]
Price: \[field:price\]

---
Tags: views
---


# Question
Title: Create a list of events where an event can have more than one date
I am looking to create a view list of upcoming events but where each event may have more than one date as below:

Event 1 - 12th Jan

Event 2 - 12th Feb

Event 3 - 12th Mar

Event 1 - 12th Apr

Event 4 - 12th May

Event 5 - 12th Jun

Event is a content type with a Date field of multiple number values.

# Answer
Add the date field and then in that fields settings uncheck **Display all values in the same row** (found in the **Multiple Field Settings** section).
> 3 votes

---
Tags: views, datetime
---


# Question
Title: how to remove password confirmation field in user registration form?
I want to remove password confirmation field. Its ok if user enters the password only once. There is no need to confirm it again.

I am using this code

```
<?php
function dp_form_alter(&$form, &$form_state, $form_id)  {
    switch ($form_id)  {
        case 'user-register-form':
        $form['account']['pass']['#type'] = "password";
            break;
     }
  }

```

Please tell me where am I wrong. Its not working. :(

# Answer
The following code works for me in Drupal 7.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#title'] = 'Password';
}

```

Please note that the user registration form and the user profile form both have password confirmation fields and are not the same form. You will need to alter both forms if you wish to remove all password confirmation fields.
> 12 votes

# Answer
My solution which covers both forms and creates also accurate description.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_login_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#title'] = 'Password';
    $form['account']['pass']['#description'] =  t('To change the current user password, enter the new password.');
    if ($form_id == 'user_register_form') {
      $form['account']['pass']['#description'] =  t('Provide a password for the new account.');
    }
  }
}

```
> 1 votes

---
Tags: forms
---


title: How to add google translate to comments

text:
# Question
Title: How to add google translate to comments
I want to be able to have the ability to translate to comments only , is there any type of module I could use for this

# Answer
Use the \[Automatic\] Comment Translation module

> Comment translation utilizes the Microsoft Translator to create translations of submitted comments on nodes that have existing translations available. Translated comments are placed in moderation for review.
> -1 votes

---
Tags: 7, i18n-l10n
---


title: Login Error drupal

text:
# Question
Title: Login Error drupal
In 7.x-3.7 .Using POSTER add-on to post this data to service.

I try to use following command to create an user:

'Content-type: application/json'

'{"name":"u10", "pass": "123","mail": "user@a.om"}'

URL : ".../api/user/register"

return success:

{"uid":"11","uri":"../api/user/11"} But I try to login:

'Content-type: application/json'

'{"username":"u10", "password": "123","mail": "user@a.om"}'

URL : "../api/user/login" It alert me :

\["Wrong username or password."\]

Please help me.

# Answer
> 2 votes
The code in the login resource is very clear:

```
...
$uid = user_authenticate($username, $password);

// Emulate drupal native flood control
if (empty($uid) && variable_get('services_flood_control_enabled', TRUE)) {
  _user_resource_flood_control($username);
}

if ($uid) {
  $user = user_load($uid);
  if ($user->uid) {
    user_login_finalize();

    $return = new stdClass();
    $return->sessid = session_id();
    $return->session_name = session_name();
    $return->token = drupal_get_token('services');

    $account = clone $user;

    services_remove_user_data($account);

    $return->user = $account;

    return $return;
  }
}
watchdog('user', 'Invalid login attempt for %username.', array('%username' => $username));
return services_error(t('Wrong username or password.'), 401);

```

As you can see, the only way you can get the "Wrong username or password" error, is if `user_authenticate()` (or more specifically `user_check_password()`) fails.

So you're providing an incorrect username and/or password, as the error suggests. Make sure that your call to /user/register is actually registering the user account on the site, and make login into it manually to make doubly sure.

---
Tags: services
---


# Question
Title: Custom block template doesn't print content
I have custom block template built based on Drupal 7 examples, but it always returns empty content for me:

```
<div class="caption-text clearfix">
<?= $block->title; ?>
</div>
<div class="regular-text clearfix">
<?= $block->content; ?>
</div>

```

Though when I call it from my page.tpl.php it works well:

```
$block = block_load('block', '1');
    $output =     drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
    print $output;

```

I just need to control where I output the title and content, having my own HTML layout for them.

Please assist.

THanks

# Answer
> 4 votes
Avoid short tags as not all servers support them.

Use:

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

```

Instead of:

```
<?= $block->content; ?>

```

Also in block.tpl.php I would expect to see `<?php print $content; ?>` instead of `$block->content`.

---
Tags: nodes
---


title: Theme the User Edit Profile page

text:
# Question
Title: Theme the User Edit Profile page
I am using the Edit Profile module.

This module takes all the fields attached to a user profile and displays them on a separate tab located at yoursite.com/user/\[USERID\]/edit-profile.

I would like to theme the fields on this edit profile page. How can I do it?

I have tried two approaches but none seem to work:

**Approach 1: Tpl.php suggestion from theme developer**

Theme Developer suggests to use the following template: `page--user--edit-profile.tpl.php` This however has two problems: 1) It affects the whole page and not just the user profile form. 2) It doesn't seem possible to access the fields on the user profile from this template.

**Approach 2: template.php**

The form ID of the user profile edit form is `edit-profile-user-profile-form` so I used the following code in my template.php file to override it:

```
function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit-profile-user-profile-form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}

```

This, however, only over rides the main user profile page and not the fields on the edit tab. Can anyone help?

# Answer
> 2 votes
I have figured this out.

The solution is to use approach 2 (in my opening post). However, in the template.php file, you have to remove all the dashes from the form ID (`edit-profile-user-profile-form`) and replace them with underscores.

So the code in template.php would be as follows:

```
function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit_profile_user_profile_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

```

}

Next create a file called `user-profile.tpl.php` and save it in templates/edit.

In the `user-profile.tpl.php` file, use the following code to print out the fields:

```
<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>

```

# Answer
> 0 votes
I think, this may work. Little modification.

function THENAME\_theme(&$existing, $type, $theme, $path) {

```
return array(
    'user_profile_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'templates/edit/user-profile-edit',
        'render element' => 'form',
        ),
);

```

}

Next go to your theme (sites/all/theme/yourtheme/) and create file called user-profile-edit file inside templates/edit/. Try to dpm($form). You will get whole form elements. You can render one by one whichever you needed.

---
Tags: users
---


# Question
Title: How make patch in PHPStorm suitable for Drupal.org?
PHPStorm will create patch in this form:

```
Index: core/modules/node/templates/node-edit-form.html.twig
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- core/modules/node/templates/node-edit-form.html.twig    (revision 4652b443e9f89734487e225fb76829595b5239a1)
+++ core/modules/node/templates/node-edit-form.html.twig    (revision )
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

```

After I export it I always have to remove the header and add the a/.. and b/.. prefixes and convert to LF so it'll look like this:

```
--- a/core/modules/node/templates/node-edit-form.html.twig
+++ b/core/modules/node/templates/node-edit-form.html.twig
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

```

Is there a way to export patch that I can directly use for drupal.org?

# Answer
PHPStorm patching issues have a long history. I have corresponded with their staff more than once, about a year ago. They told me then, that my issue was taken up to developers, but never actually corrected it. Right now, PHPStorm issues patches incompatible with Drupal.org, and we can do nothing about it.

To create a working legit patch, you need git, and create a patch like this:

`git diff > patch_name.patch`

See http://drupal.org/node/707484

A number of PHP Storm request related to this issue have been merged into a single issue http://youtrack.jetbrains.com/issue/IDEA-92793
> 8 votes

---
Tags: community-official-site, version-control
---


# Question
Title: Change user roles based on profile field
I have an field role\_type with values - 0,1,2...

And I need to add role X to all users who have role\_type = 2?

How can I do that? Rules? SQL?

Thanks for your help.

# Answer
> 1 votes
I think you could write a little module.

1. `db_select()` all users with that role\_type entry
2. `user_load()` them and `user_save()` them with updated `$user->roles[]`

Maybe this thread HOWTO assign a user to a role programatically on drupal.org can give you a deeper insight.

---
Tags: 7, entities, users
---


# Question
Title: Vote Up/Down Widget only visible to admins
I have installed the Up/Down Vote module under Drupal 6.x and it is working fine when I use it under my admin login. However other logged-in users do not see the widget.

Below are screens of the installed modules and all of the config I can access.

What do I do to enable for other users?

# Answer
Set the permission for authorized users to be able to vote.

There will be a checkbox you need to tick.

Visit `/admin/user/permissions` and look for permissions relating to this module.

See this page for more help.
> 1 votes

---
Tags: 6, rating
---


title: Dropdown field listing all roles

text:
# Question
Title: Dropdown field listing all roles
Is there a way to populate a content type field with the custom roles registered in Drupal (minus authenticated and anonymous)???

I have googled and found only quick hacks using custom modules, etc. Any ideas?

# Answer
If your looking for a module then there is Role Field that creates a new field type that allows you to choose from the list of roles.
> 2 votes

---
Tags: users
---


# Question
Title: Remove id alias appending to confirmation page URL
I have created a basic page in Drupal 7 that acts as a custom confirmation page for a web form. The url needs to be clean and static because it will be tracked by Google Adwords.

The problem is that an id is appended to the url, see example below. http://www.dynasty-autoglass.com/contact-confirmation?sid=230

The URL is supposed to end with only /contact-confirmation

How am I able to remove this id?

Thank you.

# Answer
**Option 1 (preferred)**

This can be done with some code in a custom module.

You can use hook\_form\_alter to add an additional submit handler to every webform:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // All webform id's start with webform_client_form so check for that
  if(substr($form_id, 0, 19) == 'webform_client_form') {
    $form['#submit'][] = 'my_webform_redirect';
  }
}

```

And then in the additional submit handler strip the query string form the URL:

```
function my_webform_redirect($form, &$form_state) {
  unset($form_state['redirect'][1]);
}

```

`$form_state['redirect']` is an array that consists of 2 parts. The first is the actual URL, so in this case it will be 'contact-confirmation'. The second part is the query string (sid=12), so all we need to do is unset it and it won't be appended to the URL.

---

**Option 2**

If you are tracking lots of pages over your whole site then it may be desirable to implement a solution that ensures that no query strings will appear anywhere on the site. Do bear in mind that this will break any functionality that depends on query strings. For this solution you need to put the following in your .htaccess file:

```
RewriteEngine On
RewriteCond %{QUERY_STRING} !="" #if there is a query string
RewriteRule ^(.*)$ /$1? [R=301,L] #remove query string

```

For more information on this technique there is a blog article here.
> 1 votes

---
Tags: uri
---


# Question
Title: How do you customize the title of an RSS feed created by Views RSS?
I have an RSS feed for each user provided by the Views RSS module. The view uses

> users/$uid/feed

as the display path. The feed is titled "All articles by 34 on example.com". The "34" is the userid being viewed. I want the title to be "All articles by username on example.com". I can't set this to use a variable/data in the views title field, which does change the RSS title.

* I can't use `hook_preprocess_html()` or `_page()`, as these are not called for feeds
* I don't see a hook in the Views RSS module, but I may have missed something
* I don't want to do this in the theme templates for display, as this feels like the wrong place to put the logic

How do I change this? Is there another `preprocess` function I can use?

# Answer
Not sure how much this will help as its not exactly what you're asking (i think):

I was using views\_rss to show comment threads to a question\_answer module question. But I wanted the question to show up as the 1st time in the RSS feed (as RSS feeds) may only show 1 piece of data by their nature (eg, comments or new posts or blog posts) ...

I didn't muck with the title of the Feed because I saw issues with Firefox Sage vs. Google Reader as what the "title" of the RSS feed is -- so I stuffed the "FAQ question" to the comment thread at the top of the RSS feed ....

```
/**
 * Implementation of hook_views_pre_render().
 *
 * For the comment rss feed we want the description to contain something such
 * as "topic #N: topic text". These values are excluded in the view already.
 * The RSS feed supports a description field but cannot have PHP code in it,
 * it's just static text.
 *
 * This is a means to theme the RSS description field for valid RSS feeds. The
 * view enforces that the parent node is published, and that comments are
 * published as well.
 *
 * http://stackoverflow.com/questions/4011505/how-can-i-add-a-summary-row-to-a-drupal-view
 */
function MYMODULE_discussion_views_pre_render(&$view) {

  if ($view->name == 'MYVIEW_discussion_comment_rss' &&
        $view->current_display == 'feed_1') {
    # Insert the question as a leading comment for this feed.
    $question = node_load(array('nid' => ARG(3)));
    $qrow = new stdClass();
    $qrow->comments_subject = htmlentities('Question Was:');
    $qrow->comments_comment = htmlentities($question->field_topic_text[0]['value']);
    array_unshift($view->result, $qrow);
  }
}

```

**EDIT: My answer was coded for a D6 site, but the exact same principal applies to D7 (and I think the code as well).**
> 2 votes

# Answer
Many thanks to the answer from @tenken which led me to the answer. After parsing the depth of the views array in his hook, I found where I could set the title:

```
function mymodue_views_pre_render(&$view) {
  if($view->name == 'user_rss' && arg(0) == 'users' && is_numeric(arg(1))) {
    $account = user_load(arg(1));
    $view->build_info['title'] = t('All articles by !username on Example.com', array(
      '!username' => $account->name,
    ));
  }
}

```
> 1 votes

# Answer
Maybe you can use this:

```
/**
 * Implements template_preprocess_views_view_rss().
 */
function module_preprocess_views_view_rss(&$vars) {
  if ($vars['view']->name == 'view_machine_name') {
    $vars['title']       = $new_title;
  }
}

```
> 0 votes

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


# Question
Title: "SELECT DISTINCT node.nid AS nid" killing MySQL performance?
My database server's CPU has been pegged for the last two hours and the site is down as a result. Looking at the process list, I see dozens of queries that all begin "SELECT DISTINCT node.nid AS nid," and from my reading, it appears that this should not be a common occurrence because these queries are very expensive and this could be the source of my problems.

Is it safe to say there is a view or module making a query incorrectly and if so, how can I can track that query down?

# Answer
> 0 votes
from what I see, you may be running views, and complex views, that perform complex queries. **execute()** is a database abstraction layer function. I am deducing that you are using views from the image you sent, which lists queries that look like generated by the views module.

Luckily, if my supposition is correct, then your problem can be lifted. When editing the view, you can enable caching. Unless you have a constant flow of new view items, you can make caching time 10, 30, or even 60 minutes. Or more. Making these expensive queries cached will lift the overhead. Also, if you are using panels, you can cache panel panes as well, or whole pages for anonymous users, keeping in mind, that caching on the larger level (page vs a single view) is more preferable.

---
Tags: 6, database
---


# Question
Title: Missing argument in hook_theme and Ilegal offset
I have built hook\_themes many times and never encountered this before but I am getting the following errors:

Warning: Missing argument 1 for geocoder\_custom\_theme Warning: Missing argument 2 for geocoder\_custom\_theme Warning: Missing argument 3 for geocoder\_custom\_theme Warning: Missing argument 4 for geocoder\_custom\_theme Warning: Illegal offset type in isset or empty in drupal\_theme\_access() line 53

I have tried clearing cache, renaming the hook, registry rebuild and nothing works. I have another hook\_theme in a different custom module that is basically the same thing but works completely fine. Also if i simply return an empty array() it still does it. Its like drupal doesn't send any values to my hook for whatever reason.

Code:

```
function geocoder_custom_theme($existing, $type, $theme, $path)
{
  return array(
    'geocoder_custom_before_me' => array(
      'variables' => array('string' => array()),
      'template' => 'geocoder-before',
      'path' => drupal_get_path('module', 'geocoder_custom') . '/theme'
    ),
    'geocoder_custom_after_me' => array(
      'variables' => array('string' => array()),
      'template' => 'geocoder-after',
      'path' => drupal_get_path('module', 'geocoder_custom') . '/theme'
    )
  );
}

```

# Answer
> 3 votes
That function is taken from Drupal as an implementation of `hook_custom_theme()`, not `hook_theme()`. Since the former doesn't get any arguments, PHP is complaining about the function declaring arguments for which it doesn't get any value.

The fix is changing the short name of the module from geocoder\_custom to geocoder, for example.

---
Tags: theming
---


# Question
Title: The clean URL test failed Drupal and Openshift
I want to clean *URL* in Drupal but get the test failed, and that what I have done in my `httpd.conf` :

```
<Directory "/php/">
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

```

I have also enabled the `mod_rewrite` but got an error! Any idea?

# Answer
> 1 votes
It's a little hard to answer your question without knowing your setup, e.g. operating system, drupal version and the location, where your site is hosted (are you trying to view it on localhost or on a remote host?).

If you are running Drupal 7, clean urls should be enabled by default. So, maybe the following does help:

If the url you are accessing is

```
http://www.your-site.com/?q=admin/config/search/clean-urls

```

change it to

```
http://www.your-site.com/admin/config/search/clean-urls

```

... and test again. Does it still fail?

source: https://drupal.org/node/1572984#comment-6751806

---
Tags: uri
---