# Question
Title: How to remove the ADD USER in the “admin users area” in Drupal 7
I already did the admin only register but I would like to remove this tab if anyone can help me

Thanks

# Answer
> 0 votes
this can be done using template\_process\_page() by adding this code to the template.php of your admin theme:

```
global $user;
$thisPath = current_path();
if($user->uid != 1 && strpos($thisPath, 'admin/people') !== false && strpos($thisPath, 'admin/people/create'))
{
    if(in_array('admin/people/create', $variables['action_links'][0]['#link'])) unset($variables['action_links'][0]);
}
else if($user->uid != 1 && strpos($thisPath, 'admin/people/create') !== false)
{
    drupal_set_message("Sorry, You Don't Have Permission to Access That Page", 'warning');
    drupal_goto('admin/people');
}

```
* this first checks the url for admin/people and looks for the action link associated with the Add User page element - if it finds one, it removes it
* the second checks the url for admin/people/create and sets a warning message, then redirects to the main admin/people page - in case someone manually tries to enter the address. This part could instead be included in any number of other hooks, including hook\_boot() if you want it to trigger earlier in the process
* in either case it is set up to restrict access to everyone but user 1. You can change this to include specific roles if you prefer using in\_array() on $user-\>roles

If you use Seven as your admin theme, copy the theme folder to sites/all/themes and then reset it as your admin theme so you can make the necessary changes

# Answer
> 1 votes
That link is available to users with the "Administer users" permission enabled. You can disable that permission for all roles other than a role you create, and then give your account that role (or users you want to delegate this to), which would result in only you (or a limited number of people) with access to that link. Hope that helps!

---
Tags: 7
---


# Question
Title: Views HTML List displays empty random regions
I created a View with a HTML list format showing Rendered entities. The first row displays 3 items properly, the 2nd row displays only 1 item, rows 3&4 are good, row #5 displays only 1 item...

You may see it at: http://dtodonline.com.au/30nYj/product-index

Would you know how to not have those "empty slots"? Thanks

# Answer
> 0 votes
Not able to access your URL. May be it is because of width of the item. Adjust the width of the items, it will display properly for you.

---
Tags: views
---


# Question
Title: How to apply an image style based on a condition?
I've been following this discussion: How to apply an image style based on a condition (a date for ex.)? but unfortunately it has not been a success.

I would like to have the image to change based on a boolean field type being checked or not. When I check the On Sale checkbox, I would like the product image to be displayed with a different image-style.

My boolean field is named field\_commerce\_saleprice\_on\_sale. 1st image style is product\_grid. 2nd image style on\_sale. In node--product.tpl.php I found the line

Thanks in advance for your help.

# Answer
> 0 votes
If you want to do it in template file, you can access your boolean variable using `$node` object. You can do following way :

```
if ($node->field_boolean[LANGUAGE_NONE][0]['value']) {
  print theme('image_style', array('path' => $node->field_image['und'][0]['uri'], 'style_name' => 'style1_name'));
}
else {
  print theme('image_style', array('path' => $node->field_image['und'][0]['uri'], 'style_name' => 'style2_name'));
}

```

**Or :**

If you are using `panels`, then you can use `visibility rule` to the fields by adding it twice with different image style.

---
Tags: commerce, rules, media
---


# Question
Title: Fixing D7 Bug: Block caching within views breaks JS
I have a number of block on pages throughout my site which use views. Within these blocks I have slideshows(flexslider) or use masonry to produce a dynamic layout. If I enable block caching the JS within these blocks does not function correctly. Disabling caching on these blocks restores the functionality.

I am hoping to fix this problem and have a cached blocked with it's JS functioning normally.

I have found some information on this exact issue for the flexslider module (https://drupal.org/node/1873970) but it is not a complete fix. It states that the issue is within views and points to an issue there: https://drupal.org/node/1460766 . There is also the SE Q&A at https://stackoverflow.com/questions/9788138/jquery-flexslider-not-loading-verytime which provides some insight to the issue when flexslide is used as stand alone rather than with views.

There are dozens of issue, especially within Views Slideshow (probably because it is one of the most popular Views Plugins) which make reference to this issue all the way back to 2009 but the are no actual fixes.

It is also worth noting that the page can be cached without JS breaking. It is only when the block is cached that things go wrong. In my current implementation cached page but not block adds ~1.5 seconds in load time.

With Views and JS being so widespread and caching being as important as it is I am surprised this issue has not been solved, or maybe I am misunderstanding the issue.

Has anyone encountered this issue and found a fix for it?

I welcome any comments or feedback that would improve this question or help move towards a solution for this widespread issue.

# Answer
> 1 votes
This is indeed an annoying bug.

I'm still looking for a permanent solution as well. Meanwhile, I have been able to mitigate the effects of this bug by doing the following:

1. Install and enable Cache Expiration module
2. Setup the expiration setting of your content types or taxonomy terms so that cache for the problematic pages is expired on insert/edit/delete (adjust to your needs)
3. Implement hooks: `hook_entity_insert`, `hook_entity_update`, `hook_entity_delete` and manually delete panels / views / block cache of the problematic blocks/content.
For example: `cache_clear_all('my_view:my_display', 'cache_views_data', TRUE);`

This is obviously far from perfect, since it forces regeneration of cache at every update but it does help in displaying content properly.

---
Tags: views, javascript, caching
---


# Question
Title: How to (reliably) add jQuery plugin to Drupal
This question has been asked, but not really answered. It is NOT as simple as has been suggested in

This response

If it were, there would be no reason to have a module like jquery\_plugin

Simply putting a line in the theme info file like

```
scripts[] = js/jquery.scrollme.js

```

Does not work. In the case above, the script does actually show up on the rendered page, but the function(s) within it result in "undefined".

In the case of scrollme.js, are there dependencies that need to be included?

I fought this thing with hoverintent for a day or two, and finally just punted and added the module "hoverintent". And incidentally, the fact that the hoverintent module exists suggests strongly that one can not simply throw the hoverintent.js code into a directory and load it with a script from the theme info file.

Any experienced direction would be really appreciated!

# Answer
> 1 votes
You embedded your module the right way. The error stems probably from the fact, that ScrollMe needs jQuery 1.8 minimum, whereas Drupal 7 only ships with 1.4.

You have many options of updating your jQuery version in Drupal.

---
Tags: javascript
---


# Question
Title: how to enable access to a webform only from a link sent to user
i'm planning to create a form with the webform module on D7. i would like to be able to send via e-mail a link to that webform, but only those who receive that link (non-registered users) could access and fill the form. i don't like to expose the form to general public of the website.

i know how to do this with registered users, it would be straight forward with permissions, but don't know how to achieve this with non-registered ones.

what would be the way to do this?

# Answer
You can do this by help of Deeplink module. Module page explains -

> Sometimes you want to be able to give simple URL access to content that would not normally be available to a particular user (or perhaps someone not even registered with the site).
>
> Deep link module allows the direct access to a specific item of content under certain circumstances and limitations. Such as one-off or time-limited deeplinks.
> 2 votes

# Answer
You can use Webform per Email module to send one time links to anonymous users via email.

> This module implements a permit based access system to allow anonymous users submit a Webform only if they display a valid one-time access permit.
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: User permissions on a costum content type
I've created a custom content type with fields (it's like a form), I've already added permission to logged users to use my form(content type) but I want to hide some checkboxes on this form only when user is not admin. so how to hide (remove) a part of fields of a content type ?

# Answer
> 0 votes
You can use Field Permissions for this

Features

* Enable field permissions on any entity, not just nodes.
* Role-based field permissions allowing different viewing patterned based on what access the user has.
* Author-level permissions allow viewing and editing of fields based on who the entity owner is.
* Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
* Field permissions overview

---
Tags: nodes, users
---


title: how to add UTM Source to RSS Links?

text:
# Question
Title: how to add UTM Source to RSS Links?
I have pressflow 6.22 website (drupal 6.22). I need to add UTM Source to RSS links so i can track the page views that come from RSS in google analytics.
how can i do so? Thanks for your help

# Answer
I would recommend using Google's feedburner to consume your feeds, and then having the feedburner feeds versions listed on your site.

This way all the hard work is done for you.

There is a tutorial on this on google's help page
> 0 votes

# Answer
You can create an RSS feed of your own using the Views module. It may seem a bit overkill to redefine the entire feed for just an extra parameter, but you may need more customization in the future, and having your feed served using Views allows all kinds of customizations in the future.
> 0 votes

# Answer
if you use RSS via Views Module you can customize the link by creating and editing the appropriate template (views-view-row-rss.tpl.php) link: https://api.drupal.org/api/views/theme!views-view-row-rss.tpl.php/7

If you try to rewrite the output of the link in Views, symbols as ?, &, # are converted in entities and wont help you to track links (actualy they will cause 404).
> 0 votes

---
Tags: feeds
---


title: Sending emails in user migration

text:
# Question
Title: Sending emails in user migration
I have some troubles with D7 migrate module and sending emails.

I made a migrate class to import users via CSV files. The import works well, all my users are created. But I need to send emails when the new user is created.

So I have implemented the migrate complete() function in my class like this:

```
public function complete($entity, stdClass $row) {

    // some stuff here

    // Operation.
    $op = 'register_admin_created';

    // Send an email.
    _user_mail_notify($op, $user);
  }

```

It's here were troubles comes, I use the \_user\_mail\_notify() function to shoot the mail to the new created user.

The process looks good, the mail logger module shows me the mail result, but in fact the user don't receive the mail.

I already try to create a user via the administration people menu and when a check the "Notify user of new account", I do receive the mail notification.

In Fact, the process that I have implemented in my migrate class looks like the process when you create a user manually via the admin interface and when you check "Notify user of new account".

I have to tell you that I also implement a mail interface, to be able to shoot emails with HTML / CSS. In this case, I just add a header and footer to the mail. All emails sending via my custom mail interface are sent and render properly. Only the emails sending during migration process are not send.

If you have some ideas about that problem, or if you need more information don't hesitate :)

Thank's,

Vali.

# Answer
> 2 votes
Ok found it, the migrate module have a custom Mail Class that blocked all emails send during migration process.

The migrate Mail Class is

> MigrateMailIgnore

To bypass that migrate mail class you can simply do that :

```
public function complete($entity, stdClass $row) {

    // some stuff here

    // Bypass migrate MigrateMailIgnore Class
    global $conf;

    $conf['mail_system']['default-system'] = 'MyOwnMailClass';

    // Operation.
    $op = 'register_admin_created';

    // Send an email.
    _user_mail_notify($op, $user);
  }

```

---
Tags: users, migrations
---


# Question
Title: Commerce coupon only one coupon active at a time
I have 3 types of coupons on my site, 2 of them are contrib(fixed amount and percentage amount) and 3rd one is custom(pretty much copy of percentage). I need to make sure, that only one coupon of custom type can be active at given time. Which hooks should I use to make sure that when one coupon of custom type is made active, the other one becomes not active?

Thanks in advance

# Answer
> 1 votes
My solution is as follows.
1. Check if entity created is a coupon and that coupon type is the one im checking using hook\_entity\_insert and hook\_entity\_update
2. Check if coupon changed or inserted has been put active if yes then load all other coupons of right type and turn them inactive

---
Tags: commerce
---


# Question
Title: How to print taxonomy term name with views PHP?
I have a views that include node title, a text field and a taxonomy term reference field.

I need to print the **taxonomy term name** via Global: PHP field (Views PHP) but I couldn't.

**How to print taxonomy term name with Views PHP?**

---

I can print the node title with that code:

**Value Code:**

```
return $row->title;

```

**Output Code:**

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

```

or without Value Code:

**Output Code:**

```
<?php print $row->title; ?>

```

And I could print the taxonomy term ID with that code:

**Output Code:**

```
<?php print $data->field_field_my_taxonomy_term[0]['raw']['tid']; ?>

```

But using **name** or **value** instead of **tid** doesn't return anything.

I also tried to print the term name with these ones but unfortunately none of them worked:

```
$data->field_my_taxonomy_term[0]['raw']['value'];

```

(Above code prints nothing.)

```
<?php $data->field_my_taxonomy_term[0]['raw']['taxonomy_term']->name; ?>

```

(Above code prints nothing.)

So, I'm confused now and not know **how to print taxonomy term name with Views PHP?**

Note: I looked at these but still couldn't solve the problem:

1. Views Php how to select actual term name not term ID
2. https://www.drupal.org/node/1707002
3. https://www.drupal.org/node/1516348

# Answer
Unless the term name is in the query for the View, you'll need to load the object to get its properties:

```
$term = taxonomy_term_load($data->field_field_my_taxonomy_term[0]['raw']['tid']);
$name = $term->name;

```

That will incur a performance cost, so it would be better to add the relationship to the term in the View itself, and add the name as a hidden field. Then you can refer to it without having to load any entities.
> 1 votes

# Answer
Storing PHP code directly on database is not a correct method, it causes many issues. Better you can add the relations on your views - "Content: Taxonomy terms on node". and then add the taxonomy term name field as a "hidden field"

Print the value via "Global: Custom text" field if required any custom wrapper around of it.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to show registration page in another language, maintaining its natural behaviour?
I need to show my registration page in another language, keeping this separate from his natural behaviour. In particular this page must be showed in English on the page of the site it owns to, but i need to show it in Italian on another site into an iframe. Now, common sense tells me i need a page

```
 www.example.com/user

```

and a

```
 www.example.com/it/user

```

and i tried to achieve this by "admin/config/regional/language/configure" and the option "Determine the language from the URL (Path prefix or domain)." and all works fine, but, for some reason, as i activate this option, ALL my site pages get a "/en/" in their url, breaking a lot of things into the site (that is extremely complex). There's a way to achieve this behaviour for the registration page only? (be able to call a page www.example.com/it/user to show registration in italian and having www.example.com/user and all other pages in the site work without any changes?)

# Answer
> 1 votes
Navigate to `/admin/config/regional/language` within your site, and verify these things (and correct where appropriate):

* Use "*English*" as your default language
* use the "*Edit*" link for "*English*" on that page, which will bring you to "`/admin/config/regional/language/edit/en`". On that page, make sure the value for "*Path prefix language code*" is "blank".

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


# Question
Title: How to create one entity and assign the same entity as field to new entity programatically
-I need to create one entity (need to do coding)- that I created already, now want to create another entity, lets say "Entity 2"( term(taxonomy, param1, param2, description( it will have multiple values- multiple description). Now I need to add entity 2 as field for entity 1. Entity 1 can have multiple entities of type "Entity 2"

# Answer
Once you have the ID of the new entities, it's as simple as:

```
$new_entity->field_foo[LANGUAGE_NONE][0]['target_id'] = $other_entity_id;
$new_entity->field_foo[LANGUAGE_NONE][1]['target_id'] = $yet_another_entity_id;

```

I've assumed the field type is Entity Reference, YMMV for other types.
> 0 votes

---
Tags: entities
---


# Question
Title: How to render a views title in .tpl file?
I embed a view in a .tpl file but it doesn't show the title. It only shows the content.

How to render the **title** of the view?

I'm using the code below:

```
<?php
print views_embed_view('dummy');
?>

```

# Answer
> 2 votes
Try following way :

```
$view = views_get_view('view_name');
$view->set_display('display_id');
print $view->get_title();
print $view->preview('display_id');

```

---
Tags: views, theming
---


# Question
Title: Add value to existing field value db_update
How can Add value to existing value of field using db\_update ?

I have a field in custom table amount which will be incremented by a function

# Answer
> 2 votes
I think you mean something like this:

```
db_update('custom_table')
  ->expression('count', 'count + 1')
  ->condition('id', $id)
  ->execute();

```

---
Tags: 7
---


# Question
Title: How to merge loggedin and annoymous user's cart in drupal commerce
To merge loggedin and annoymous user's cart for same session.

User (username:jone) adds something in the cart (Product 1). Before add to cart: Cart is empty User adds something in the cart (Product 1). After add to cart: Order ID 15821 Line item IDs 159808

User registers and logins User logs out

Annoymous User adds something in the cart (Product 1). Before add to cart: Cart is empty Annoymous User adds something in the cart (Product 1). After add to cart: Order ID 15822 Line item IDs 159809

Annoymous User adds something in the cart (Product 2). Before add to cart: Order ID 15822 Line item IDs 159809 Annoymous User adds something in the cart (Product 2). After add to cart: Order ID 15822 Line item IDs 159809, 159810

Viewing the above log, somebody would assume that this user has bought 2 different products.

Now User checks out and login with username : jone
we want to after the login show/add last order product (159808) However, currently we have the following situation.

Order 15821 Line item IDs 159808 are exist in database in checkout\_checkout mode(status). Order 15822 exists with 2 line items, 2 different products. Line IDs are 159809, 159810.

I want to be displaying all line items 159808, 159809, 159810. but line item 159808 are not display

please suggest any solution.

# Answer
> 0 votes
I have solved this, by custom code. First you create a login handler like.

```
<?php
function custom_module_form_alter(&$form, $form_state, $form_id) {

    if($form_id == 'commerce_checkout_form_checkout'){
        $form['buttons']['continue']['#submit'][2] = 'paypal_check_handler';
    }
}

function paypal_check_handler(&$form, $form_state){

    $order_number = $form_state['order']->order_number;
    $return = _get_current_stock($order_number);

    if($return['status']=='goto_paypal'){

     }else{
       db_query("UPDATE commerce_order SET status = 'cart' where order_id='$order_number'");
       drupal_set_message("We are sorry - Following items are no longer available in stock after you added them in shopping cart. <br/>".'“ '.$return['product_name'].' ”');
       drupal_goto('cart');
    }
}

/**
 * This function check current stock.
 */
function _get_current_stock($order_id) {

    global $user;
    $order = commerce_cart_order_load($user->uid); // get user order details
    // get all product id of current order
    $results = db_query("SELECT cp.product_id AS product_id, cli.quantity AS order_qty,fcs.commerce_stock_value AS stock_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id WHERE cli.order_id='$order_id' AND cli.type IN ('product','commerce_auction_lineitem') ")->fetchAll();
    $product_ids = $qty = $stock_qty = array();
    /*
     * @var $product_ids            : Product ID array.
     * @var $qty[$product_ids]      : get each Product order quantity.
     * @var $stock_qty[$product_ids]: get each Product stock quantity.
     */
    foreach($results As $value){
        if(!empty($value->product_id)){
            $product_ids[] = $value->product_id;
            $qty[$value->product_id] = (int)$value->order_qty;
            $stock_qty[$value->product_id] = (int)$value->stock_qty;
        }
    }
    // product id array convert in string forn sql.
    $product_ids_query = implode($product_ids, ',');
    /*
     * Here get product remaining stock
     * @stock   : Stock
     * @order   : Order qty in order table ( status is checkout_payment).
     * @avail   : available qty
     * @stock - @order = @avail
     */
    $results2 = db_query("SELECT cp.title AS product_name, cli.line_item_label AS line_item, cp.product_id AS product_id,cli.quantity AS order_qty, FORMAT(SUM(cli.quantity),0) total_order_qty,  FORMAT(fcs.commerce_stock_value,0) AS total_stock_qty, FORMAT((fcs.commerce_stock_value - SUM(cli.quantity)),0) As available_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id LEFT JOIN commerce_order AS co ON co.order_id=cli.order_id WHERE co.`status`='checkout_payment' AND fcs.commerce_stock_value!=0 AND cp.product_id IN ($product_ids_query) GROUP BY cp.product_id")->fetchAll();
    $available_qty = array();
    foreach($results2 As $value2){
        $available_qty[$value2->product_id] = $value2->available_qty;
        $available_product_name[$value2->product_id] = $value2->product_name;

    }
    $redirection_var = array();
    $redirection_var['status'] = 'goto_paypal';
    foreach($product_ids AS $product_chk){
        if(!empty($available_qty[$product_chk])){
            $current_stock_qty = (int)$available_qty[$product_chk];
        } else {
            $current_stock_qty = (int)$stock_qty[$product_chk];
        }

        $ordered_qty = $qty[$product_chk];
        if($current_stock_qty > 0){
            // go to paypal
             $redirection_var;
        } else {
            $current_product_name = $available_product_name[$product_chk];
            $redirection_var['product_name'] = $current_product_name;
            $redirection_var['status'] = 'not_goto_paypal';
            return $redirection_var;
        }
    }
    return $redirection_var;
}
?>

```

Thankyou :)

---
Tags: 7, commerce
---


# Question
Title: Prepopulate entity reference field from url in node create form block
please help. I have tried so many ways to solve the following problem but did not succeed. I really need your support on this one.

Here is the problem: There are 2 content types : Fruits and Apple.

Apple content type has an entity reference field to fruits content type.

Now, whenever I view a node of type fruits, the entity reference field in apple add form should prepopulate to fruits node title.

Please see the image below. It will make everything clear.

Is it possible to prepopulate the field? If yes, how? Thanks.

The modules I am using right now: 1.Panels 2. Entity reference 3. Form Block 4. Entity reference prepopulate.

As per the suggestion from Sinan Erdem , I checked http://drupal.org/node/494008 . The code is below . It still doesn't work. :( Can you tell me why?

```
    <?php
/** hook_form_alter **/

function pp_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form. Form name is [content_type_name]_node_form
  if ($form_id == 'apple_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'pp_after_build';
  }
}

/**
* Populate entity reference field
*/
function pp_after_build($form, &$form_state) {
  // Obtain node object from nid in url
  $entityreference_field_category = node_load(arg(1));
  //populate autocomplete entityreference field with node title. Name of field is field_[field_name].
  $form['field_category'][0]['nid']['nid']['#value'] = $entityreference_field_category->title;

return $form;
}
?>

```

# Answer
> 1 votes
Please check the following issue: http://drupal.org/node/494008

# Answer
> 0 votes
Looks like I need to not scan so fast. I see you are already using entity prepopulate. In order to prepopulate it your entity reference field, you will need to pass the value by URL. Meaning you need to create a custom node/add/contenttype link from your origin page.

For example: From Fruit you include a add link `http://url.com/node/add/type?field_category=1` or `http://url.com/node/add/type?field_category=[node:nid]` or whatever token value you need.

You can also use the Prepopulate module (different module) to do this on almost any field including entity reference, although the syntax is a bit longer.

Good luck!

# Answer
> 0 votes
For the benefit of those who encounter this same problem without a solution, this module: Entity Reference Prepopulate Token will provide a perfect solution. Please make sure you are using the latest dev version of Entity Reference Prepopulate module (as at 2015-Jun-10 or higher).

After enabling the module, go to the content type edit page and scroll down to where you have "Provider" and enter the following comma separated values in the text box provided under "Tokens and panel pane context":

> %node:nid, \[current-page:url:unaliased:args:value:1\]

Just enter the above values in the box and **select the optional checkbox for this provider option to activate it**, hide the field from the user also if desired, to avoid editing. I've tested it, It works!

According to the module page:

> This module supplements Entityreference prepopulate module (dev version is required) by adding prepopulate provider which sets default field values using tokens and replacement patterns of panel pane contexts.
>
> Two kind of patterns can be used for prepopulating entity reference fields:
>
> Tokens, e.g \[current-page:url:unaliased:args:value:1\] (it returns value "100" for address "node/100", Token module is required). Replacement patterns of panel pane contexts, e.g. %node:nid (it returns node identifier if the form containing entity reference field is placed on node view page created by Page manager). Panels module is required for using these patterns.

---
Tags: panels, forms, entities
---


# Question
Title: Entity reference value from url in node add form block
I have a content type book and another content type pages. A page has a entity reference field to book. Now, I want to allow users to create pages on the same page as book. So, I created a page add form using formblock module.

I would like to have the entity reference field auto generated and pointing to the book.

Is it possible? Thanks. :)

# Answer
> 1 votes
Node Reference URL Widget can help you :)

# Answer
> 0 votes
I have answered this question already on another question. Here is the full answer i provided there:

For the benefit of those who encounter this same problem without a solution, this module: Entity Reference Prepopulate Token will provide a perfect solution. Please make sure you are using the latest dev version of Entity Reference Prepopulate module (as at 2015-Jun-10 or higher).

After enabling the module, go to the content type edit page and scroll down to where you have "Provider" and enter the following comma separated values in the text box provided under "Tokens and panel pane context":

> %node:nid, \[current-page:url:unaliased:args:value:1\]

Just enter the above values in the box and **select the optional checkbox for this provider option to activate it**, hide the field from the user also if desired, to avoid editing. I've tested it, It works!

According to the module page:

> This module supplements Entityreference prepopulate module (dev version is required) by adding prepopulate provider which sets default field values using tokens and replacement patterns of panel pane contexts.
>
> Two kind of patterns can be used for prepopulating entity reference fields:
>
> Tokens, e.g \[current-page:url:unaliased:args:value:1\] (it returns value "100" for address "node/100", Token module is required). Replacement patterns of panel pane contexts, e.g. %node:nid (it returns node identifier if the form containing entity reference field is placed on node view page created by Page manager). Panels module is required for using these patterns.

---
Tags: forms, entities
---


# Question
Title: How to resolve the "undefined variable" notce when I put a flag on a Views page?
I want to place a flag link on a page, as suggested on that page: https://www.drupal.org/node/295383

The flag will subscribe the user to the most recent content page, which is done in Views.

I have the Flags: subscribe (by current user) Relationship.

I have installed Views PHP and I want to add to the header of the view a Global:PHP with the code `<?php print flag_create_link('subscribe', $node->nid); ?>`

Unfortunately I receive an error:

> Notice: Undefined variable: node in \__lambda\_func() (line 1 of .../sites/all/modules/views\_php/plugins/views/views\_php\_handler\_area.inc(39) : runtime-created function). Notice: Trying to get property of non-object in \__lambda\_func() (line 1 of .../sites/all/modules/views\_php/plugins/views/views\_php\_handler\_area.inc(39) : runtime-created function).

What could be the reason for that?

Any help appreciated.

# Answer
> 0 votes
As I understand it, OOB it won't work because Flags require an entity to function, but Views pages are simple menu callbacks, not actual entities (such as nodes, users, comments, etc). So, in order to do this, you would need to trick it into think it is an entity:

* create a content type, `Dummy Page` for this example
* remove the body and restrict editing, deleting, etc to admin only
* Create a node with this content, using the title you want for the View, `Recent Content` for this example, give it a path alias `/recent`
* create the view as a block, and in the block UI, set it to show only on the `recent` page
* Create a flag for Nodes, `Favourites`
* create a page--recent.tpl.php file and override the `$action_link` for the page (or modify it drastically however you want), but include:

`<?php print flag_create_link('favourites', $node->nid); ?>`

Or use the built in flag link that comes with the Flag

* then do whatever you were going to do originally with the flag. You can include it in other Views pages by creating new nodes of that content type and include the View as a block, etc.

This will trick the Flag into thinking the page is an entity and track it properly, as well as display it on the page wherever you decide to put it

# Answer
> 0 votes
The error arises because there is no $node variable defined in the scope. Try looking inside the $results variable; something like this should work:

```
<?php print flag_create_link('subscribe', $results[0]->nid); ?>

```

This will print a subscribe link for the first row of the view. Also, you have to ensure that the nid is present in your result object. It should be already there, but if not, add the "Content: Nid" field and hide it by checking the "Exclude from display" option.

---
Tags: flags, views
---


title: Default image is not generated

text:
# Question
Title: Default image is not generated
I have a `case` content-type that has an `image_field`. I have configured the field to use a default image in cases when no image is upload for a case. I then try to render the image using the following code:

```
<?php $view = node_view($node); ?>
<div class="search-result-case">
    <div class="search-info"><?php print t('Publicerad'); ?>: <?php print date('d - M - Y', $node->created); ?></div>
    <div class="search-snippet">
    <?php print render($view['field_image']); ?>
</div>

```

If the case has a connected image then the field is rendered as expected, but in other cases nothing in displayed. When I check under recent log messages I see this:

```
Location   http://localhost/test/sites/default/files/styles/case_170x107/public/default_images/default_case_pic_0.png?itok=CWr6R4Rs
Referrer   http://localhost/test/search/node/case
Message    Unable to generate the derived image located at public://styles/case_170x107/public/default_images/default_case_pic_0.png.

```

I don't understand why it fails to generate a style for my default image when it works fine with user supplied images.

I have checked the permission on the folder and everything seems fine, so I really don't understand why this is not working?

Notice that **all** other images that is uploaded gets their image styles generated without any problem. The error **only** gets triggered in case of a default image connected to the `field_image` field.

# Answer
For what it's worth and consideration. Make sure your php.ini is configured correctly and that your. upload\_max\_filesize and max\_file\_uploads settings are adequate. My numbers are arbitrary, but I've had similar issues that require this general adjustment.

```
Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 200M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 200

```
> 1 votes

---
Tags: 7, media
---


# Question
Title: Language cookie module not working in Safari?
I use language\_cookie module to safe the users preferred language with a cookie. E.g. The default site language is English. But i am from Holland so i want always the Dutch version of the site: http://landberg.at/nl. But the cookie is not working on Safari MAC?

In `Configuration » Regional and language » Languages` i have:

* **URL** (enabled)
* **Cookie** (enabled)
* **User** (enabled)

How can i make it work also for Safari?

(i use this module instead of IP redirect because with IP redirect you can not switch the language after you are redirected..? So the only solution in my opinion is to do it with a cookie. Or does somebody has another idea about this?).

# Answer
I think you should further verify/tune your configuration at *Configuration -\> Languages -\> detection and selection*: the order you mentioned (= 'URL, Cookie, User') seems a bit strange to me. I.e. it'd be interesting to see what results you get by specifying "Cookie" BEFORE "URL" in your case.

Because with your current order, "Cookie" will only be used to select your preferred language if from the "URL" it's impossible to decide about which language should be shown. Though "User" is probably fine to leave it as the last one.
> 0 votes

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


# Question
Title: How can I change the order of the list of countries provided by the Countries module?
I have a Drupal 7 site that uses the Countries module. I would like to show the United States first in the list and the rest of the countries then in alphabetical order (by default, the module displays all countries in alphabetical order). This is a common feature on many sites so I'm hoping there's an easy way to do this.

# Answer
> 4 votes
It's a shame Sumeet didn't continue his answer, as he got so close, but here is the alter hook:

```
function HOOK_countries_alter(&$countries) {
  $US = $countries['US'];
  unset($countries['US']);
  array_unshift($countries, $US);
}

```

It copies US, removes it from the list, and attaches the copy back to the top.

You don't say in what context you use the module. I verified that it does what it should on a country-field.

# Answer
> 3 votes
With the first solution, the country key is missing, so you can't save this country field because the country key doesn't match. I suggest that (similar to the second solution) :

```
function hook_countries_alter(&$countries) {
  $country_key = 'FR';//eg. your country key
  $country_data = $countries[$country_key];
  unset($countries[$country_key]);
  $countries = array_merge(array($country_key=>$country_data),$countries);
}

```

# Answer
> 2 votes
I took a quick look under the hood of the countries module and found that the right place to do this change would be to use the hook - hook\_countries\_alter() in a custom module.

```
function countries_countries_alter(&$countries) {
  $enabled_countries = &drupal_static(__FUNCTION__, array());
  if (empty($enabled_countries)) {
    $enabled_countries = countries_get_countries('name', array('enabled' => COUNTRIES_ENABLED));
  }
  $countries = array_intersect_key($enabled_countries, $countries);
  $countries = array_merge($countries, array_diff_key($enabled_countries, $countries));
  uasort($countries, 'countries_sort');
}

```

The `uasort` towards the end does the alphabetical sort as shown below (in the same module)

```
/**
 * A helper uasort callback function to sort an array of countries or names.
 */
function countries_sort($a, $b) {
  $a = countries_transliterate(is_object($a) ? $a->name : $a);
  $b = countries_transliterate(is_object($b) ? $b->name : $b);
  return strnatcasecmp($a, $b);
}

```

I would suggest adding and enabling the devel module \> then add a `dsm($countries)` at the end of `countries_countries_alter()` to check out the structure of the array \> then write a small custom module where you implement the `hook_countries_alter()` and bring USA on top while the rest are sorted alphabetically.

---
Tags: location
---


# Question
Title: format_date() seems to ignore the time zone
I am having issues with dates and time zones in Drupal 7. I have created a content type that stores the date in `$field_event_date`. When I use the Views module this works correctly. However, I am using a template file to manipulate the display of this data. When I output the raw value, it is correct, so is the time zone; when I attempt to format it with the time zone `format_date()` seems to ignore the time zone value. Is there a proper way to do this in Drupal?

```
    print '<br />' . $field_event_date[0]['value']; // outputs 2011-11-04 21:30:00
    print '<br />' . $field_event_date[0]['timezone']; // outputs America/New_York
    print '<br />' . date('g:ia', strtotime($field_event_date[0]['value'])); // outputs 9:30pm
    print '<br />' . format_date(strtotime($field_event_date[0]['value']), 'medium', 'g:ia', $field_event_date[0]['timezone']); // outputs 9:30pm (????)

```

I have done this with just pure PHP this way:

```
// Get the timezone offset
$timezone = $field_event_date[0]['timezone'];
$remote_dtz = new DateTimeZone($timezone);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $remote_dtz->getOffset($remote_dt);

// Get the date
$start_date_string = $field_event_date[0]['value'];
$end_date_string = $field_event_date[0]['value2'];

// Apply the timezone offset
$start_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value'])) . " " . $offset . " seconds");
$end_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value2'])) . " " . $offset . " seconds");

// Build the date
$start_disp_date = date('l, F j, Y', $start_date_string);
$end_disp_date = date('l, F j, Y', $end_date_string);
$start_disp_time = date('g:ia', $start_date_string);
$end_disp_time = date('g:ia', $end_date_string);

```

This was working fine until recently a few dates started showing up about one hour off. I would prefer to use a Drupal centric solution (like format\_date) since it might help me avoid odd occurrences like this one. Any advice for either approach would be appreciated however. This is all on a production site, so I just need to get it working.

Thank you for your time.

EDIT/UPDATE:

My PHP only solution was broken because of daylight savings time. So I replaced that code with this:

```
// Get the timezone offset
$offset = date('Z', strtotime($field_event_date[0]['value']));

// Apply the timezone offset
$start_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value'])) . " " . $offset . " seconds");
$end_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value2'])) . " " . $offset . " seconds");

// Build the date
$start_disp_date = date('l, F j, Y', $start_date_string);
$end_disp_date = date('l, F j, Y', $end_date_string);
$start_disp_time = date('g:ia', $start_date_string);
$end_disp_time = date('g:ia', $end_date_string);

```

Granted, this doesn't solve the problem with `format_date()`. While I'm going to stick with my PHP centric solution, others might have the same problem. Perhaps I am using the function incorrectly.

# Answer
> 4 votes
Yep, i was having similar problems, but in Drupal 6.

I'm surprised your `$field_event_date[0]['value']` was in New York time. My understanding is that that value comes straight out of the database, and it's pretty standard to keep all times in the db as UTC times, and only use local times when displaying them (since local times go crazy a couple of times a year).

`$field_event_date[0]['timezone_db']` will tell you for certain what timezone `$field_event_date[0]['value']` is in.

And `$field_event_date[0]['timezone']` will tell you what timezone it should be displayed in (according to your site's 'default timezone'). If you look at `$field_event_date[0]['view']`, it should be in the display timezone.

When i'm trying to display dates from the raw 'value', i do something like...

```
/**
* @param
*     $date A CCK date field, like you'd get in your node templates,
*     e.g. $field_event_date[0]
*/
function get_display_date($date) {
    $date_convert = new DateTime($date['value'], new DateTimeZone($date['timezone_db']));
    $date_convert->setTimezone(new DateTimeZone($date['timezone']));
    return $date_convert->format('Y-m-d H:i:s');
}

```

I've yet to find any documentation which can confirm all this, so i may be totally wrong! But it works for me so far. Hopefully Drupal 7 isn't too different.

# Answer
> 3 votes
In addition to Chichilatte's answer: If you're using the date\_api module (part of the date project) you can also do this:

```
$date_object = new DateObject($date['value'], new DateTimeZone($date['timezone_db']));
$date_object->setTimezone(new DateTimeZone($date['timezone']));
return date_format_date($date_object, 'custom', 'Y m d');

```

# Answer
> 0 votes
Working with a Drupal 6 site this helped me get a reliable solution to display the date with correct timezone

```
// Get the timezone offset
$offset = date('Z', strtotime($node->field_date[0][value]));
// Get the date from datebase using database timezone
$unixdate = strtotime($node->field_date[0]['value'].' '.$node->field_date[0]['timezone_db']);
// Apply timezone offset and format display datetime
$time = format_date($unixdate, 'custom', 'g:ia', $offset);

```

---
Tags: datetime
---


title: Give unique class to last item in view

text:
# Question
Title: Give unique class to last item in view
**UPDATE:** I now see that drupal has a built in setting you can check to add even/odd,first, and last classes to the items in the view. Is there a way I can append another class to the last item using this?

---

For responsive purposes I was planning on adding the bootstrap .hidden-lg class to the last item in a view. This is in order to display more items when I go from a 3 column to a 2 column view. I did see that there was a style output template for views that iterates through each of the rows (as you can see below) but I wasn't sure how to take advantage of that.

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Unless the only option is to perform some regex on the last item of the foreach statement.

As a heads up, I'm already outputting the content and applying custom classes using a view field output template.

# Answer
> 2 votes
You may try next code snippet

```
/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
*/
end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
    <?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

---
Tags: views, theming
---


# Question
Title: How to make one field automatically have the date-time of the last change of another field
I need to make one field have the date-time of the last change of another field in a drupal 7 content type. I tried using a computed field but the calculation is complex and I am having trouble. Is there an easier way to make one field reflect the date of the last change of one other field? thanks

# Answer
> 2 votes
You may use hook\_node\_presave to save time in the field

```
/**
 * Implements hook_node_presave().
 */
 function jysk_reviews_node_presave($node) {
  if ($node->type == 'my_type') {
    if ($node->my_changed_field[LANGUAGE_NONE][0]['value'] != $node->original->my_changed_field[LANGUAGE_NONE][0]['value']) {
      $node->my_time_field[LANGUAGE_NONE][0]['value'] = time();
    }
  }
}

```

---
Tags: nodes
---


title: Add html to wrap views programaticly

text:
# Question
Title: Add html to wrap views programaticly
I need to wrap field in views. I use views with module Responsive grid and have this html.

```
 <div class="services">
  <div class="row">
    <div class="col-xs-12 col-md-3">
      <h3 class="services-heading" data-thmr="thmr_16"><div class="field-title-for-view" data-thmr="thmr_4 thmr_1">Responsive <span>html</span></div></h3>
      <div class="services-img" data-thmr="thmr_16"><a href="/responsive-html" data-thmr="thmr_5 thmr_6 thmr_8"><img src="http://dvlk/sites/default/files/services_img_2.png" width="101" height="66" alt="" data-thmr="thmr_7"></a></div>
      <p class="services-p" data-thmr="thmr_16"><span data-thmr="thmr_9" class="devel-themer-wrapper">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.</span></p>

```

I want to have this html

```
<div class="services">
  <div class="row">
    <div class="col-xs-12 col-md-3">
    <article class="mycustomclass">
         <h3 class="services-heading" data-thmr="thmr_16"><div class="field-title-for-view" data-thmr="thmr_4 thmr_1">Responsive <span>html</span></div></h3>
      <div class="services-img" data-thmr="thmr_16"><a href="/responsive-html" data-thmr="thmr_5 thmr_6 thmr_8"><img src="http://dvlk/sites/default/files/services_img_2.png" width="101" height="66" alt="" data-thmr="thmr_7"></a></div>
      <p class="services-p" data-thmr="thmr_16"><span data-thmr="thmr_9" class="devel-themer-wrapper">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.</span></p>
    </article>
 </div>

```

I know that i should use this function hook\_preprocess\_views\_view, hook\_preprocess\_views\_view\_fields or hook\_preprocess\_views\_view\_field but i don't know how to do it correctly. So how can i have this html **without creating \*tpl.php file**

# Answer
> 0 votes
It can be done in the views admin interface in the next way:

1. Exclude existing fields from display
2. Add new field Global: Custom text
3. Display new fields in Custom text filed using tokens

See example

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


title: Theme hook MENU_CALLBACK not found

text:
# Question
Title: Theme hook MENU_CALLBACK not found
I am seeing this error in my logs:

```
Theme hook MENU_CALLBACK not found

```

What are the causes? I cannot find this exact phrase in google or d.o. This is an example menu item:

```
$items['user/%user/integration/%integration'] = array(
    'title' => 'View An Integration',
    'page callback' => 'integration_view_page',
    'page arguments' => array(3),
    'access callback' => 'is_owner',
    'access arguments' => array(1, 3),
    'type' => MENU_CALLBACK,
);

```

Yes, cleared caches, including menu cache. The actual page appears to load ok.

# Answer
> 0 votes
In my case, this was a mistake on my part. I recently performed a find and replace on my codebase to change all my menu hooks from MENU\_LOCAL\_TASKS to MENU\_CALLBACK.

I clearly did this ignoring case, and also did not check properly as in my template.php, I now had...

```
$vars['secondary_local_tasks'] = array(
    '#theme' => 'MENU_CALLBACK',
    '#secondary' => $vars['tabs']['#secondary'],
);

```

instead of...

```
$vars['secondary_local_tasks'] = array(
    '#theme' => 'menu_local_tasks',
    '#secondary' => $vars['tabs']['#secondary'],
);

```

Because it was now called MENU\_CALLBACK in caps, it confused me and I was looking in the wrong place. It is only when I went back and diff'd my entire backed up codebase did I notice it.

Lesson Learned: Find & Replace is not always a good idea :)

---
Tags: 7, routes
---


# Question
Title: Creating followups to Commerce Orders for each Line Item
I had asked a question in another thread, and thought it might be helpful to create its own thread just in case it could be helpful to any other developers out there:

"I am trying to create a rule which follows up on existing orders of specific products. Each product has a different time interval for "follow up reminder", and my rule should trigger an email to be sent to a customer at a date which is calculated Order Creation Date + Follow Up Interval.

ie Order Creation + Value provided from Products in the order"

# Answer
> 1 votes
I wanted to share how I solved this problem: I created a rule which is dependent on an Order's Status being "Completed". This rule runs a custom PHP script which loads the Completed order Entity, retrieves each Line item and checks for its field called "Follow-up", which gives a time value in weeks

---
Tags: rules, commerce
---


title: Creating Related Content views

text:
# Question
Title: Creating Related Content views
I have watched and read quite a few guides/tutorials on this subject and they each leave me with a blank block.

I am trying to create a related content module. My content is tagged with multiple terms.

I go and create a block view and go to contextual filters. I add the content: has taxonomy term ID. Then I add the "Taxonomy term ID from URL", slect the correct vocabulary, filter to items that share any term, click reduce duplicates and click apply.

Then I create the content:nid contestual filter and the block wont appear.

I have pathauto installed and I have a feeling it might be an issue with that. I cannot use the term id in my content paths.

I have been at this for a while. Any help on what I am doing wrong is greatly appreciated.

# Answer
> 1 votes
Pathauto module doesn't have to do anything with this view. I think you are not supplying any default value to contextual filters used in your block type of view.

For creating the related content view, please try following steps

1. Create a Block type of display.

2. Add Contextual filter for the taxonomy term -\> goto settings of this filter -\> select "default value" -\> select "taxonomy term id from url" -\> select limit by vocabulary -\> select "vocabulary" -\> select appropriate option from "Multiple-value handling" -\> expand "more" fieldset and set allow multiple values.
3. Enable Aggregation settings, and add the same taxonomy field in sort criteria and from aggregation settings select "COUNT DISTINCT"
4. Add "Nid" as contextual filter -\> go to settings -\> select "default value" -\> select "Content Id from URL" -\> From "more" fieldset -\> select "Exclude" - now results will not show the current node.

Place this block now on your node page, and this block will list all the related content.

---
Tags: views, path-aliases
---


# Question
Title: How change widget of a "between exposed filter" to combo box?
I have a view that has some exposed filters. One of the filters is on the price of the content type. I want to filter contents by price when price is between two known value. For example I want to filter all the content that their prices are between 0 and 5000. The other thing I want is a select box for this filter. So the filter is a select box with some options like below:

```
<option>0-5000</option>
<option>5000-10000</option>
<option>10000-15000</option>
<option>15000-20000</option>

```

I add a filter to the view and mark it as exposed filter, then change its operator to between. Now what should I do to change the widget from two text box to a single select box?

# Answer
You're close. After you expose the filter, change it from Single filter to Grouped filters using the radios right below the expose checkbox. Then you can define what each option is and make it a select box.
> 1 votes

---
Tags: views
---


# Question
Title: How to manipulate some fields using Views PHP?
I'm trying to manipulate some fields on Views with Views PHP.

I have a (term) field for author(s). It can have one author or more.

Normally it looks like as that:

## Book Title | Author

My First Book | Name1 Surname1, Name2 Middle2 Surname2

My Second Book | Name3 Surname3

etc.

What I want to do is to print names as that:

## Book Title | Author

My First Book | **Surname1, Name1 - Surname2, Name2 Middle2**

My Second Book | **Surname3, Name3**

In order to do that, I used **Global: PHP** field with Content: Authors.

**Value** code inside Global: PHP is that:

```
$names = $row->field_authors;
foreach ($names as $name) {
  $parts = explode(' ', $name);
  if (count($parts) == 1) {
    $wanted = print($name);
    continue;
  }
  $last = array_pop($parts);
  $wanted = print ($last  . implode(' ', $parts));
}
return $wanted;

```

Output code is:

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

```

But it doesn't return anything. I tried some other similar code but nothing changed.

**Is it about the Content: Authors field (multiple field settings etc.) or am I wrong about the code I used in the Global: PHP field?**

# Answer
Based on the answer of the question "How to print taxonomy term name with views PHP?", I could manipulate the term fields as I wanted with that code:

**Output Code:**

```
<?php
foreach($data->field_field_authors as $author) {
$term = taxonomy_term_load($author['raw']['tid']);
$name = $term->name;
$parts = explode(' ', $name);
if (count($parts) == 1) {
    print ($name);
    continue;
  }
  // get last word
  $last = array_pop($parts);
  // Print last one, comma, and rest of name
$authorManipulated = ($last .", "  . implode(' ', $parts) . " - ") ;
print $authorManipulated;
}

?>

```
> 1 votes

# Answer
You'll want to put that code into a view template. Go into your admin, where you can edit that View, click on Advanced, and then Theme: Information. That will give you suggestions on the file naming conventions for the row style output for your view.

But as for your PHP code, Drupal uses a lot of nested multi-dimensional arrays, so it's not as simple as `$row->field_authors` being an array of strings of author names (unless you're doing some preprocessing). If `field_authors` is a term reference, you'll need to load the taxonomy term in order to get the actual author name.

This should get you the `$names` array:

```
$names = [];
foreach($row->field_field_authors as $author_tid){
   $term = taxonomy_term_load($author_tid[0]['tid']);
   $names[] = $term->name;
}
(... the rest of your code...)

```
> 1 votes

# Answer
An option you can try is by using the Views Field View module. This allows you to call/render the output of another view as fields in the parent view.

Here we will be creating a View to display your authors. Here's that can generate a simple output of the authors list for a node.

1. Create a view, for the Show setting use Content and uncheck Page and Block.
2. Under the *Advanced pane*, Add a Contextual filter named **Content: Nid**. For the settings: (1) Select **Provide default value**, (2) Type would be **Provide default value from URL** and set Path component to **1**.
3. Under the *Advanced pane* again, Add a Relationship named **Content: Taxonomy terms on node**. For the settings: (1) Select the vocabulary you want to refer and check **Require this relationship**.
4. Under the *Format pane*, for now we'll just use the **Unfiltered List** format.
5. Under the *Fields pane*, assuming your taxonomy author structure has a Last Name field, add **(term) Taxonomy term: Last name** and **(term) Taxonomy term: Name**.

This will be the expected output.

Next we need to update the parent view. Before doing this please install the Views Field View module.

1. Under the *Fields pane*, add **Content: Nid**. For the settings, check **Exclude from display**.
2. Under the *Fields pane*, add **Global: View**. For the settings: (1) View would be the "Author taxonomy" view (2) Display can just be **Master** since we didn't create any View Display for the "Author taxonomy" view (3) Contextual filters would be **\[!nid\]** which is the node id that we pass into the view so it gets only the "authors" of the current node of the row.

This will be the expected output.

*An alternative option though if you like coding is using the Views hooks. You would need to create a custom field or alter and add functionality into the multiple field view handler.*

**NOTE:** Also wanted to stress that placing PHP code inside the database is not a best practice.

Hope this helps or give you an idea.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I get $form_state from hook_entity_update()?
I've manipulated the edit node form via `hook_form_BASE_FORM_ID_alter()` to insert a select pull-down menu.

In my module, I've implemented `hook_entity_update()` to fire when the edit node form is submitted. How do you get the form\_state in `hook_entity_update()`? I want to save the user's choice from the select pull-down.

# Answer
$form\_state is not available there.

You might want to consider using fields and widgets, then you get a lot for free.

If that's not an option then you can register a so called `#entity_builder`:

```
function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
}

function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
  $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
}

```

The example is for the node type config entity, but it should work pretty much the same way for a content entity. `book_form_node_form_alter()` is an example for nodes.
> 2 votes

---
Tags: forms, hooks, 8
---


# Question
Title: Why would an error persist after after uninstalling the module?
I created a module for Drupal 8 and when I try to add it to the menu it throws this error

```
 Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("Route "hello_world.content" does not exist.") in "core/modules/toolbar/templates/menu--toolbar.html.twig" at line 36."

```

everything fell apart after this. All of my site was unreachable because of an error page.

I tried removing the module and clearing the cache and the error is still there. What do I have to do to fix this error?

# Answer
> 1 votes
This is 'normal' as your Twig files are being cached by Drupal. The easiest way to fix the issue is to run `$ drush cache-rebuild` (with Drush 8 which is the only release compatible with Drupal 8) which will handle all cache rebuild, including Twig cache. Alternatively, under `sites/default/files/php` you can safely delete the `twig` directory. If you're not in a multi web server environment, you can delete the `php` directory altogether, which will both delete the Twig cached files and the Service Container.

---
Tags: 8, theming
---


title: Where do I include css file?

text:
# Question
Title: Where do I include css file?
As a total newbie in Drupal I asked myself where do I include a css file? (Using Drupal 6)

I wrote a web application with javascript, php and mysql and now I'm trying my first steps in migrating this application to Drupal. I already found out on Stackoverflow How to include css and javascript files.
Since i know now which function to use to include my css file, I don't know *where*.
Do I have to simply create a new module (named "mymodule" like in the example from stackoverflow)?
Or is the css file only applied to the module "mymodule"? If so, how can I apply it to a page filled with plain HTML?

# Answer
> 1 votes
As with anything, there's a few different ways to do it.

If you have a custom module (which IMO, you should, since you're porting a custom app), you can add any CSS required for your module in your module's page callback functions. CSS added this way only applies to that particular path. Just FYI if you want to have css apply to the entire site, you should put it in a theme.

So your module would look something like this:

```
function mymodule_menu() {
  $items['mymodule/blah'] = array(
    'page callback' => 'mymodule_page_blah',
  );
  return $items;
}

function mymodule_page_blah(){
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/file.css', 'module', 'all', TRUE);
  ...
  return "<your blah page's html>";
}

```

# Answer
> 4 votes
To include your custom css say demo\_global.css in your theme write following line in theme\_name.info file of your theme folder-

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

```

**Note**: You must clear the cache to see the changes. For more information please refer https://drupal.org/node/171209

# Answer
> 1 votes
This is for a custom module, you put this in your .module file

In Drupal 6:

```
/**
 * Implements of hook_preprocess_page()
 */
function <YOURMODULE>_preprocess_page(&$variables) {
  $module_path = drupal_get_path('module', '<YOURMODULE>');
  drupal_add_css($module_path . '/css/file.css');
  $variables['styles'] = drupal_get_css();
}

```

In Drupal 7:

```
/**
 * Implements hook_preprocess_page().
 */
function <YOURMODULE>_preprocess_page(&$variables) {
   $module_path = drupal_get_path('module', '<YOURMODULE>');
   drupal_add_css($module_path . '/css/file.css');
}

```

# Answer
> 0 votes
For creating a custom module please refer to following links:

To include a CSS file for all the pages of site you can do either of the following:

1. Include it in the theme's info file as: **stylesheets\[all\]\[\] = FILENAME.css**
2. Include it in the module's info file as: **stylesheets\[all\]\[\] = FILENAME.css**

**Don't forget** to **clear the cache** after adding the CSS file in the `.info` file.

However if you are including it in the module file than remember than it will get loaded only if the module is enabled.

To load the CSS file for particular node you can do the following in the module file:

```
/**
 * Implements hook_preprocess_node().
 */
function MODULE_NAME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Check if the node is the one on which you want to include the CSS file.
  if ((!empty($node)) && ($node->nid === $NODE_ID_ON_WHICH_YOU_WANT_TO_LOAD_CSS)) {
    drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . "/FILENAME.js", "module");
    drupal_add_css(drupal_get_path('module', 'MODULE_NAME') . "/FILENAME.css", "module");
  }
}

```

Also you may check this link:
Adding style sheets
drupal\_add\_css

---
Tags: 6, theming
---


title: Drush not selecting database

text:
# Question
Title: Drush not selecting database
I'm using a Vagrant environment generated from https://puphpet.com/ for a Drupal project & it is all going well except for Drush which gives me an error any time I try running "drush cc -all", see the error below.

```
<h1>Additional uncaught exception thrown while handling exception.</h1><h2>Original</h2><p>PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected: SELECT 1 FROM {blocked_ips} WHERE ip = :ip; Array
(
[:ip] =&gt; 127.0.0.1
)
in drupal_is_denied() (line 1933 of /var/www/includes/bootstrap.inc).</p><h2>Additional</h2><p>PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected: SELECT * FROM {system} WHERE type = &#039;theme&#039; OR (type = &#039;module&#039; AND status = 1) ORDER BY weight ASC, name ASC; Array
(
)
in system_list() (line 165 of /var/www/includes/module.inc).</p><hr />Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]

```

From what I gather the problem is that it isn't selecting a database. Does anyone know where the details for this would be stored? The Drupal site itself is connecting & using the database fine.

I'm not sure if this would cause and issue but the database details for the Drupal site are stored as an Apache environmental variable.

# Answer
What you are seeing above is a bug in Drush where Drush cannot bootstrap the database of a Drupal site if the database credentials are correct, but the database itself is empty. To fix this problem:

1. If your database is empty, run "drush site-install" to create a database.
2. If your database is not empty, check the settings of your database prefix, and make sure that it is correct.

This was recently fixed in https://github.com/drush-ops/drush/pull/1442.
> 0 votes

---
Tags: 7, drush, virtual-machine
---


# Question
Title: Date field displayed with wrong timezone with PHP's date_create + date_format
I have an `Event` content type with a `Date` field with a start and end date.

When this field is being displayed in a view, it displays properly, with the time matching the value that was entered.

On a different page, I am overriding `field--field-date.tpl.php` and using `date_create` and `date_format` to print out the date and time separately.

```
$start_date = date_create($node->field_date['und'][0]['value']); //dont hate me
$end_date = date_create($node->field_date['und'][0]['value2']);
//...
print date_format($start_date, 'g:i A') . ' - ' . date_format($end_date, 'g:i A');

```

As you can see, it is displaying **4:00pm** instead of **12:00pm**. It looks like a timezone translation is happening (or not happening) somewhere. I tried to screw around with the time zone argument for `date_create` but nothing actually changed the way the date displayed.

When I dump the date field out with devel, I get,

```
dpm($node->field_date['und'][0]['value']);
dpm($start_date);

```

How do I actually display the proper timezone for my date with PHP in my `field--field-date.tpl.php`?

# Answer
> 1 votes
Looks like your date field is configured to use either site zone or user time zone configuration.

So, while saving the node drupal expects the entered value in usertime zone or site time zone and then convert it to UTC before saving it to database.

While showing it views consider the timezone configuration and format the date as per current user viewing the date field.

The timezone you see as 'America/NewYork' in the dpm result is the timezone configuration of the user created the node.

In order to show the date with format you can use format\_date, something like below.

```
$user_time_zone = drupal_get_user_timezone();
format_date(strtotime($node->field_date['und'][0]['value']), 'custom', 'm/d/Y h:i:sA', $timezone = $user_time_zone);

```

**Important thing is to choose the right configuration for your field timezone settings, if the date field is irrespective to current user timezone keep the timezone configuration to UTC.**

---
Tags: datetime
---


# Question
Title: How to add an 'if' statement for a content type in a custom views-view.tpl.php?
Is it possible to add an 'if' statement for a content type in a custom `views-view.tpl.php`?

This is just so I can add text to show if the post in the view is either an 'episode' or an 'announcement'. The content type is called announcement.

I want to do this because I need to identify and style differently based on the post type:

* If it's from an episode, it displays the episode number.
* If it's an announcement, it says announcement.

So basically something like so:

```
<?php if (content_type='whatever') {... code goes here ...} ?>

```

If this is possible, can you provide an example?

**Note**: I have a custom theme called `views-view-field--first-post--block--created.tpl.php` and all it has is `<?php print $output; ?>`. It's called a field content date.

Also, this is what the output of the entire view looks like: `stdClass Object ( [node_created] => 1434783086 [node_title] => CTRL Daily Episode 11 [nid] => 11 [node_type] => ctrl_daily )`. \[node\_type\] is what I want.

# Answer
Improving your own code a bit, it'd be better to not set the dummy variable, since you probably won't use it again. To make it a bit cleaner:

```
<?php if ($row->node_type === 'announcements'): ?>
  <?php // This shows up for node->type of announcement. ?>
<?php else: ?>
  <?php // Everything else. ?>
<?php endif; ?>

```

Note that it's usually more readable (and thus considered best practice) to use alternative control syntax when in a view.

For additional smart checking, you should probably create a check to make sure that the node\_type property is set on the $row object before checking it...

```
<?php if (isset($row->node_type) && $row->node_type === 'announcements'): ?>
  <?php // This shows up for node->type of announcement. ?>
<?php else: ?>
  <?php // Everything else. ?>
<?php endif; ?>

```
> 1 votes

# Answer
You can access it by adding `Node Type` field to views and access it using `$row` variable in `views-view.tpl.php`.

```
$rows: The results of the view query, if any

```

Or `$views` is also accessible in each and every views template file.
> 1 votes

# Answer
I figured it out. An if statement doesn't work on \[node\_type\] unless it has something to look at. Give it something to compare it will make it work. Also make sure your using row output on themes template in order for the following code to work.

Example: `<?php $value = ($row->node_type) ; ?>
<?php if($value == 'announcements') { ?>
yes
<?php } else { ?>
nope
<?php } ?>`
> 0 votes

---
Tags: views, theming, nodes
---


# Question
Title: Create "suggest an edit" functionality for anonymous users on nodes
I'd like to provide a way for anonymous users to submit nodes, but also provide suggested edits to existing nodes. The core node revision system cannot support this.

How would one implement a revisioning system that allow anonymous users to save updates which moderators approve. I'm assuming Workbench might get me halfway there.

Edit: like you find on Foursquare and Yelp, for community suggestions on editing venues.

# Answer
> 0 votes
I think you may want to check out the Workbench Moderation module. Basically, you'd configure a workflow that allows anonymous users to 'edit' a node, but their edits would trigger the workflow. From an admin experience perspective, you may want to configure it to trigger an email notice whenever updates have been made, or otherwise alert content admins that suggestions have been made.

One potential gotcha is the way that Workbench handles revisions -- it doesn't fork. Meaning that if you publish a node, that becomes revision 1. If someone comes along and edits it, they suggest revision 2. If a third person comes along, they'll see that the node is on revision 1, but when they go to edit the node, they'll see it's on revision 2. Any changes would be saved as revision 3, and so on. You may need to extend the module with your own custom workflow if you're looking for forking behavior (think pull requests on GitHub).

---
Tags: 7, nodes, users
---


# Question
Title: How to combine content from two different environments?
We have two Drupal environments: dev and prod. We use dev to stage content before it goes to production. We also have prod, where content is created and then have to manually re-create those changes back on dev.

Is there a way to combine/merge content changes between the two environments simply/easily? This is purely content (i.e. nodes) and not code or configuration.

# Answer
# Node Export

The Node Export module might be used for this. Here is an excerpt from its project page:

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
>
> Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.
>
> You will need the same content types for the imports to work (unless using Feeds to import), and ideally relevant compatibility with fields, and modules.

# Feeds

Another option that might work is to use the Feeds module. Here is an excerpt from its project page:

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.

# Bundle copy

Yet another approach is to use the Bundle copy module. Here is an excerpt from its project page:

> Has export/import support for:
>
> * Node types
> * Taxonomy
> * User
> * Field API fields
> * Field groups
>
> You can find the export/import links for the supported entities on following paths:
>
> * Nodes: admin/structure/types
> * Taxonomy: admin/structure/taxonomy
> * Users: admin/config/people/accounts
> 1 votes

# Answer
You may also try Deploy module

> The Deploy module is designed to allow users to easily stage content from one Drupal site to another. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.
> 1 votes

---
Tags: nodes, staging
---


# Question
Title: Hide conditionally hidden fields from custom node template
**Case:** I am using conditional fields module to hide some dependent fields based on the value of its dependee field. I have created a custom `node--content-type.tpl.php` template for my content type.

```
Field1

Field2

```

Here, `Field2` is dependent on the value of `Field1`. Suppose in this case, `Field2` is rendered only if `Field1` has value 'jobs'. Otherwise, it is hidden from both node edit form and node page.

When using seven theme and its display(default or teaser) to view node, if the `Field2` is hidden or the dependency was not triggered the `Field2` is not rendered on the node page, which is correct.

But, when using my custom template, I am not been able to prevent the rendering of `Field2` on my node. It is shown with its default value on the node.

Please help.

template code:

```
<?php if(isset($content['field_job_type'][0]['#markup'])):?>
              <li>
                <p class=" no-margin "><strong>Job Type:</strong> <?php print $content['field_job_type'][0]['#markup'];?></p>
              </li>
            <?php endif;?>

```

# Answer
Based on the comments:

* generic template works, but custom does not
* custom template overrides visibility rules

I would surmise that the problem is with the visibility, since the conditional field is likely only hidden, and not actually being removed - this would cause the code to execute every time, while in a standard render() it would remain hidden

Using Devel and specifically the dpm() function, I would find the element in the field array that manages the visibility of the field and use that as the basis for the if statement.

> A suite of modules containing fun for module developers and themers
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Views - group/aggregate by field with multiple content types
I currently have a block view that I am using as an index. I have 2 content types that I am displaying in this block, and these are grouped together by their type, as an unformatted list of fields. The types are not displaying the same field.

The second content type needs to be grouped further, as they represent items relating to the same thing which will be displayed together on the page.

I am struggling to perform the second grouping. I have tried the unformatted list settings and adding in a second group, but that removes the items for the first group. I have also tried playing with aggregation and the query distinct settings, but that doesn't seem to do anything. I have also tried the Views Distinct module, also with no success.

**Edit:** It's the *value* of the field that's duplicated.

What I've got:

```
*Group1
    -Title1
    -Title2
*Group2
    -FieldValue1
    -FieldValue1
    -FieldValue1
    -FieldValue2
    -FieldValue2

```

What I would like:

```
*Group1
    -Title1
    -Title2
*Group2
    -FieldValue1
    -FieldValue2

```

Is this possible, and if so, how would I go about doing it?

Thanks

# Answer
I would suggest using the default **Views attachment display** so you can have different queries and/or fields next to each other.
> 0 votes

---
Tags: entities, views
---


title: Setup links for pagination pages

text:
# Question
Title: Setup links for pagination pages
I have `articles/?page=2`, I need to make it like `articles/page/2` or `articles/page-2`

How to do so?

The Clean Pagination module is enabled and on `admin/config/system/cleanpage` I added "articles".

`articles?page=1` is the second page in the pagination link and it looks like in this screenshot:

>

The module changes the reference to `articles/page/1`, although it would be logical to do so also for `articles/page/2`.

How can it be implemented? What alternative methods are there?

# Answer
> 0 votes
The configuration is in Drupal itself. Just visit `/admin/config/search/clean-urls` and enable it :

**Note :** It needs to be enabled in Apache as well. In Apache **rewrite** module should be enabled.

---
Tags: navigation, paging, uri
---


# Question
Title: Return to views navigation list of nodes after editing a node in the list
I am using Views Navigation module. I have created a list of articles using views and selected "Add navigation links on node pages accessed from this view" under "Views Navigation" in Advanced. The views navigation is working fine and I can go back and forth in the views list of articles.

Now if I edit the node (while viewing a views navigation list) and submit the edited node, I was returned back to the node page **without** the "views navigation" links appended to the URL. Hence I cannot move back forth in the list (the list is gone; it behaves like a simple node view).

The scenario is that this views navigation list will be used by editors and moderators who may edit an article while viewing the list so they should be redirected back to this list once they edit an article.

One of the solution I am thinking is to alter node edit link using hook\_menu\_alter(). Is there any ***non-programmatic*** way of doing this? I have tried Rules and captured the appended URL parameters but I don't know how to alter a node edit link. Can someone please point me in the right direction?

Many Thanks

# Answer
I found a solution, through code unfortunately, using hook\_url\_outbound\_alter().

For anyone trying this, I have implemented the following code and it is running perfectly:

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
// get current position and list token
$position = isset($_GET['position']) ? $_GET['position'] : NULL;
$list = isset($_GET['list']) ? $_GET['list'] : NULL;

// only when viewing nodes through views navigation
if ( $position && $list && preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    $path = 'node/'.$matches[1].'/edit';
    $options['query']['destination'] = 'node/' . $matches[1] . '?position=' . $position. '&list=' .$list;
    }
}

```

Thanks
> 0 votes

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


# Question
Title: Show facet filter even if there is no result
Is there a way to show the facet filter, even if the Search API module returns no result?

# Answer
> 3 votes
Not really, the facets (both search api and solr) are made up from the results of the search, therefore if there are no results then it doesn't know what to populate the facets with.

Depending on your expected output you may be best creating a custom/views block to display some relevant content then re-write the urls to conform with the search query, acting like a search facet.

# Answer
> 1 votes
If you're using search\_api\_db, then you could use this patch :

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

It will add an option in your search server settings tyo allow a facet block to display facets even if there's no results !

---
Tags: search
---


# Question
Title: Updating node field value using custom module validation
I currently have a custom module which calls a submit custom validation function. I am trying to update a value after the validation is run. Basically, if a value is present, update a field to say "Yes".

```
function sitefuncs_form_alter(&$form, &$form_state, $form_id){

if( $form_id == 'stage_2_node_form') {
   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';
}

} // end hook_form_alter()

function sitefuncs_custom_submit($form, &$form_state) {

        $banned = array(
        'better cures',
        'better nhs',
        'because it',
        'so what'
        );

  if (in_array($form_state['values']['field_stage_two_question_one']['und'][0]['value'], $banned)) { // if a banned word is the value of the input

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "No"; // set the value of the text input to No

} else {

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "Yes";

$messages = drupal_get_messages('status');
drupal_set_message(t('Your changes have been saved.'));

}

}

```

If anyone has any idea why the `$form_state` isn't updating the fields after I save the node, any help would be great!

# Answer
I worked out that I was using

```
   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';

```

When it should have been

```
   $form['actions']['submit']['#validate'][] = 'sitefuncs_custom_submit';

```

Then all my data saved using

```
$form_state['values']['field_stage_complete_text']['und'][0]['value']['#value'] = 'No'; // set value to No

```
> 0 votes

# Answer
Use hook\_node\_insert instead of alter the form.

> This hook is invoked from node\_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called.
>
> Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and node\_save() goes out of scope. You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately. Check node\_save() and db\_transaction() for more info.

**Example :**

```
function modulename_node_insert($node) {
  // Just change the node object and value will be saved.
}

```
> -1 votes

---
Tags: 7, nodes
---


title: Altering CSS markup

text:
# Question
Title: Altering CSS markup
I would like to add custom property on drupal's stylesheets `<link />` tag. I tried following in `hook_css_alter`:

```
foreach ($css as &$style) {
  $style['#attributes']['property'] = 'stylesheet';
  $style['#attributes'] = ['property' => 'stylesheet'];
  $style['property'] = 'stylesheet';
  $style['element']['#theme'] = 'stylesheet';
  $style['#markup'] = '<stylesheet />';
  $style['element']['#markup'] = '<stylesheet />';
}

```

Nothing seeps to do any changes, and I feel like I am guessing around. So how to properly alter `<link />` elements markup?

Second question would be how to get all stylesheets as array in theme. It seeps that in Drupal 8 beta 10 you cloud just do `{% for style in styles %}` in Your twig template, but with beta 12 update this does not work, `styles` returns placeholder element.

# Answer
> 4 votes
# Drupal 8

`$css` variable is converted to an array of \<link\> tags through `CssCollectionRenderer::render()`, so you just have to swap this service (https://www.drupal.org/node/2026959) and override render function:

```
class MyModuleCssCollectionRenderer extends CssCollectionRenderer {
  /**
   * {@inheritdoc}
   */
  public function render(array $css_assets) {
    $elements = parent::render($css_assets)))
    foreach($elements as &$elements) {
      $element['#attributes']['property'] = 'stylesheet';
    }
    return $elements;
  }
}

```

# Drupal 7

The CSS files are managed by `drupal_get_css`. After being altered by hook\_css\_alter(), `$css` is passed in a render array:

```
// Render the HTML needed to load the CSS.
$styles = array(
  '#type' => 'styles',
  '#items' => $css,
);

```

This render array is declared in system\_element\_info() as:

```
$types['styles'] = array(
  '#items' => array(),
  '#pre_render' => array('drupal_pre_render_styles'),
  '#group_callback' => 'drupal_group_css',
  '#aggregate_callback' => 'drupal_aggregate_css'
);

```

As you can see there is a pre-render callback `drupal_pre_render_styles()`, this is the function responsible for converting the `$css` variable to \<link\> tags. This is where you can work, just add you own callback in a `hook_element_info_alter()`:

```
/**
 * Implements hook_element_info_alter().
 */
function mymodule_element_info_alter(&$types) {
  // Add a pre_render callback to styles.
  $types['styles']['#pre_render'][] = 'mymodule_pre_render_styles';
}

/**
 * Append property to stylesheet <link> tags.
 */
function mymodule_pre_render_styles($elements) {
    foreach($elements as &$element) {
        $element['#attributes']['property'] = 'stylesheet';
    }
}

```

---
Tags: theming, 8
---


# Question
Title: What is the best way to theme page--front with twitter bootstrap?
I am trying to create a user dashboard by design a flat menu for page--front.tpl.php, and the twitter 3.0 bootstrap. My current site is using Omega's OHM responsive theme as default, so my question is, how do I apply twitter bootstrap to just a SINGLE tpl file?

There's a part 2 if its related, copying page.tpl.php and calling it page--front.tpl.php isn't being recognized (I do this within ohms templates/system dir, and cleared cache). I've read through Drupal.se, and googled it and tried the variety of things - but I guess I don't understand how drupal recognizes page--front. Do I assign a piece of content as home page then it gets applied? If so, that's the page I need specifically themed with bootstrap only.

# Answer
You might want to switch the theme entirely. You could simply use something like: https://www.drupal.org/project/themekey

Regarding the regcognition of page--front.tpl.php, rename your existing page.tlp.php to page--default.tpl.php
> 2 votes

# Answer
It's going to be hard to do because there is still div wrappers in the html.tpl.php that going to show depending on your theme settings.

But if you clone your page.tpl.php to be page--front.tpl.php and then flush your cache, that template should be active. It will always theme the home page, regardless of what type of page it is set as (i.e. the default node listing, a node or view).

However, I would recommend using something like themekey as Jbartsch suggested, or just switch the entire site theme to a bootstrap based one, which is what I just did.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Enable new modules dependencies on deploy
How can I automatically enable new dependency added on a custom feature (or standard modules) with drush?

After getting the new code, my deployment script basically run:

```
drush cc all
drush fra

```

But I need to visit the admin/structure/features page if I added new dependencies otherwise those modules are not enabled. How can I avoid it? Is there a drush command? I can't use `drush en thenewmodule` because I want to keep my deployment script generic.

# Answer
There is a feature request issue in a Drush queue, just stumbled on it. In donquixote's Drux project are commands you need:

> drux-enable-dependencies (dep-en) - Download and enable dependencies of existing modules. drux-find-obsolete (obs) - Find modules that are not direct or indirect dependencies of the modules given as arguments drux-generate (obs-gen) - Generate a list of dependencies\[\] = .. to copy+paste into a module info file. drux-list-dependencies (dep) - List dependencies that would be enabled with `drush dep-en`. (The help text seems to be wrong).

So for the task at hand, `drush dep-en` should do the job.

You can download it here.

UPDATE: Now available on github: https://github.com/donquixote/drupal-drux

## Alternatives, part I

As pointed out by Jesse Pinho in another answer, you can also run `drush fr DEPENDENT_MODULE`.

Or you can run `drush en DEPENDENT_MODULE`.

The difference is that for these commands you need to know the "DEPENDENT\_MODULE" which has the added dependencies.

With `drush dep-en` you can just run the command without any arguments, and it will check all enabled modules for dependencies.

## Alternatives, part II

Instead of such drush commands in combination with dependencies, you could also use hook\_update\_N() to enable additional modules. This seems a common technique for Drupal 7 projects.

See the answer by reubidium.
> 6 votes

# Answer
I don't think there is a way to get this task completely automated.

But you could use the Master Module to write your dependencies into code. Master provides a framework for module-dependency configuration in automated deployment settings.
> 5 votes

# Answer
Note that you can also revert just the dependencies feature of the module whose dependencies you've changed, then run `drush fra`:

```
drush fr -y [feature-module-name].dependencies && drush fra

```
> 4 votes

# Answer
You could create a custom module and list all the modules you want to enable on deploy as dependencies of that module in its .info file. Then just enable that module on deploy to enable all the other modules. Drupal will handle their dependencies. If your module always has the same name, you could `drush en custom-dependencies -y` or whatever you want to call it, and make the contents of that module's .info file specific per-project.

If you're trying to enable new modules on deployment to an already-built site, you can put `module_enable()` inside an update hook in an already-enabled module. This will go away in Drupal 8, but for current Drupal sites it works fine. So if you have updated an existing module, X such that it introduces a new dependency on module Y, an update hook in module X's .install file that enables module Y would solve the problem.
> 0 votes

# Answer
I solve this problem by creating a custom .install file for my feature module, and implement hook\_enable(). You can enable each dependency via something along the lines of:

```
if (!module_exists('dependency')) {
  module_enable(array('dependency'));
}

```

I've also used this method to enable new dependencies via hook\_update\_N()
> 0 votes

# Answer
Try doing `drush rq` and implement `hook_requirements`:

```
function MODULE_requirements($phase){
    if($phase != 'install'){
        $module_info = drupal_parse_info_file(drupal_get_path('module', 'MODULE').'/MODULE.info');
        $dependencies = $module_info['dependencies'];

        $enable = module_enable($dependencies);
        if(!$enable){
            throw new Exception('Unresolved dependencies', 1);
        }
    }

    return array();
}

```
> 0 votes

---
Tags: drush, features, deployment
---


# Question
Title: How to implement a horizontal set of translation links for every node?
I want to add a hardcoded translation block to my `page.tpl.php`, to link to a translated version of every node + a translated interface.

The Language Switcher Dropdown module did the trick, but I want a horizontal set of links and need something simpler.

# Answer
Maybe Displaying and configuring a drop down using Language Switcher Dropdown helps to achieve what you're trying to do with this module anyhow.

If not then the answers to the question about How to theme language translation links in Drupal? may help to actually answer your qestion. Though that question is for D6, and hence its answers might need some review to also make it work in D7. Here is the relevant part of it that might do the trick:

```
$node = menu_get_object();
if ($node->links) {
  print theme('links', $node->links);
  }

```
> 0 votes

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


title: How to modify field group markup?

text:
# Question
Title: How to modify field group markup?
`field_group.module` defines a function as follows:

```
function field_group_pre_render_accordion_item(&$element, $group, &$form) {
  $element += array(
    '#type' => 'markup',
    '#prefix' => '<h3 class="field-group-format-toggler ' . $group->format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '"><a href="#">' . check_plain(t($group->label)) . '</a></h3>
    <div class="field-group-format-wrapper ' . $group->classes . '">',
    '#suffix' => '</div>',
    //'#attributes' => array('class' => array($group->format_type)),
  );
  if (!empty($group->description)) {
    $element['#prefix'] .= '<div class="description">' . $group->description . '</div>';
  }
}

```

Which is an instance of `field_group_pre_render_<format-type>`.

What I want to do is change that prefix code from an h3 to a div. But I'm not sure what the appropriate function/hook would be to use.

The Field Group API defines a `hook_field_group_pre_render` function but the $element argument in this function doesn't supply the `#prefix` element - so I'm not sure.

Ideally I could just totally override the function `field_group_pre_render_accordion_item` in my own code...

# Answer
> 3 votes
Implementing `hook_field_group_pre_render_alter()` seems the way to go, it's called just after `field_group_field_group_pre_render()` which calls `field_group_pre_render_accordion_item()` and receives the correct info.

It should be like this:

```
function mymodule_field_group_pre_render_alter(&$element, $group, &$form) {
  if ($group->format_type == 'accordion_item') {
    $element['#prefix'] = '<div class="field-group-format-toggler ' . $group->format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '"><a href="#">' . check_plain(t($group->label)) . '</a></div><div class="field-group-format-wrapper ' . $group->classes . '">';
    if (!empty($group->description)) {
      $element['#prefix'] .= '<div class="description">' . $group->description . '</div>';
    }
  }
}

```

Remember to implement it in a module, as a hook\_\*_alter() implemented in a front-end theme may not be discovered while flushing cache via drush or in the back-end theme.

---
Tags: 7, entities
---


title: How to override a node using alias?

text:
# Question
Title: How to override a node using alias?
I have created node there path is "`content/book/book-name-alias`". Where I have override a node using view page "`content/book/%`" where contextual filter using "Node Id".

When I have request a page using "`book/content/9`" a node will override but same node "`book/content/book-name-alias`" it is not working.

How to override a node using an alias?

# Answer
> 2 votes
The path where a node is rendered is at `node/%node`, where `%node` is the nid of the node.
Example : `http://example.com/node/1`, and the path which is displays `book/content/book-name-alias` is an alias of the `node/%node` path.

So, to implement this override the `node/%node` path using either a view page (how to), or a panel page (how to) with the same path.

---
Tags: views, 7, hooks, path-aliases
---