title: hook_user_insert get form values?

text:
# Question
Title: hook_user_insert get form values?
I defined a field `myField` through admin/configuration/manage fields. Then I implemented hook\_user\_insert because I want to do something with this field after the user registration. How can I access to `myField` value? I was trying with `$edit['field_myField']` but I get an array.

Any help will be appreciated.

# Answer
> 2 votes
My advice for you is to install devel module and then run this code:

```
function MY_MODULE_user_insert(&$edit, $account, $category) {
  dsm($edit);
  dsm($account);
}

```

Create new user and you will see output with structure of variables $edit and $account - this will incredibly help you to find out structure of data.

# Answer
> 2 votes
Field data is stored in arrays.

Here is a sample user account information I save from information retrieved elsewhere:

```
 $roles = user_roles();
 $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      'roles'        => array(array_search('student', $roles) => 1),
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['last_name']))),
      'field_secret_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['secret_number']))),
      'mail' => $ldap_details['mail'],
    );

```

So as you can see field data is stored as: `array(LANGUAGE_KEY => array(INDEX => array('value' => 'SOMETHING HERE')));`

You just access/set it as you would any PHP array.

You may get stuck if you find your fields arent in the user record -- attached fields are not eagerly loaded you have to call a function to be sure they are attached to the User entity:

```
// For speed, typically Drupal does not attach additional fields to $user
// objects, if they are not found we request attached fields now.
if (!isset($account->field_first_name ) || !isset($account->field_last_name)) {
  field_attach_load('user', array($account->uid => $account));
}

```

# Answer
> 1 votes
You need to use something like:

```
$edit['field_myField'][$edit['language']][0]['value']

```

But you should really use dsm($edit); so you get the structure of the array correctly

---
Tags: 7, hooks, users
---


title: Delete drupal content page

text:
# Question
Title: Delete drupal content page
How can one Delete Drupal content page (article/basic page) without actually visiting the page. Without Drush or visiting the database (which is a little complicated in D.7).

# Answer
goto `admin/content` and press `delete` per page next to its title. You don't have to Edit the page. You will have to `confirm` your delete choice.
> 0 votes

---
Tags: routes, nodes
---


# Question
Title: Panels view settings - how to preprocess the 'more' link
I have block views added to a panel, and the panel is set to display the 'more' link. How can I change the text for this link?

# Answer
Change the text of the link in the views module. On your views block admin page. Click on more link and change text there
> 2 votes

---
Tags: views, panels
---


# Question
Title: Probable database character encoding error with chinese multilingual translation
I am doing translation of a site's content from English to Chinese but upon saving the translation for a node(I previously did a few blocks) I get the error below. My search led me to questions like configuring drupal to use unicode characters but I just need another perspective to see if this is a different type of problem (because I already translated blocks and menus with the chinese characters) and how would I solve it.

```
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value:
'\xF4\x8F\xB0\x80\xE5\x8D...' for column 'field_overview_value' at row 1:
INSERT INTO {field_data_field_overview} (entity_type, entity_id, revision_id,
bundle, delta, language, field_overview_value, field_overview_format) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7); Array (
[:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 1547
[:db_insert_placeholder_2] => 7588 [:db_insert_placeholder_3] => product
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] =>
<h3> 业内最可靠的视频服务器平台</h3> <p>作为视频服务器和存储系统的市场领导品牌,
SpectrumTM 是一 体化制作和播出系统以及完全基于文件的工作流程的理想平 台。
模块化的系统架构可以保证最大的稳定性和灵活性,使 得全球的制作人和电视专业人员都选用
Spectrum 来实现高效 的无带化工作流程。这个系统可以完全胜任于下列范围的工 作:</p> <ul>
<li> 从模拟到数字的设备改造,完全遵从国家标准</li> <li> 从磁带到硬盘播出的改造,升操作效率
</li> <li> 从标清到高清的升级,升广播质量</li> <li> 从单频道播出升级到多频道播出,遵从市场需
求</li> </ul> <p>整合了广播视频技术领域的专家与信息技术方面的最佳实 践,Spectrum 供了最具
性价比,开放和灵活的视频服务 器,满足播出环境的严苛需求。 ￼￼￼￼ ￼<br />  </p> <h4> 主要特点
</h4> <ul> <li> 独立的可扩展通道、存储、带宽并且保证冗余,智能、高 性价比架构。</li> <li>
在已有系统中添加新的组件即可实现高清或者 3D 播出, 确保完全的投资保护。</li> <li> 在传送、
演播室制作、新闻和体育集锦、分布式播出工作 流程中是最好的基于文件的解决方案。</li>
<li> 可以从几百种播出应用中自由选择,基于开放标准和开放 API。</li> </ul> <p> </p>
<h4> CNN - Aquisition, Playout and Storage Case Study</h4> <p><iframe
allowfullscreen="" frameborder="0" height="360"
src="http://www.youtube.com/embed/KBrAqR7P8DU?rel=0" width="640"></iframe></p>
 <p> </p> <h4> NAB 2013 Enter...the Spectrum!</h4> <p>
<iframe allowfullscreen="" frameborder="0" height="360"
src="http://www.youtube.com/embed/p82nloy1JT4?rel=0" width="640"></iframe></p>
[:db_insert_placeholder_7] => full_html ) in
field_sql_storage_field_storage_write() (line 451 of
 /var/www/html/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

# Answer
> 1 votes
Ok So the problem was actually not the Chinese text but that I was copy-pasting from a PDF file that seemed to have injected some unwanted characters in the body that the database was rejecting.

---
Tags: database, i18n-l10n
---


# Question
Title: how to custom position drupal login field
How do I custom position default login form that (in my case with BLUEMASTERS theme) pops up down below the title of the content page like: ABOUTUS. I want to position it in the sidebar.

# Answer
> 2 votes
Go to "Blocks" under "Structure" (admin/structure/blocks if I'm not wrong). You'll find the "User Login" block and you can position it where you want, depending on the theme you have. It might be named "Sidebar" or "Sidebar Left (Right)" or "Sidebar First (Second)".

---
Tags: users, theming
---


# Question
Title: Change a multiple value field to use divs instead of a table in node/add?
I have the # of values set to 10, which I want to put in 2 columns of 5 each, but I don't know how to change the table structure to accomplish this, or perhaps preferably, just change it to use divs so I do it with css.

# Answer
You can override `theme_field_multiple_value_form()`, e.g.

```
function MYTHEME_field_multiple_value_form($vars) {
  // Copy code from theme_field_multiple_value_form() and change as appropriate
}

```

It's not a short function, and you'll probably be reproducing a bunch of code, but it uses `theme_table()` directly so it can't be solved with a preprocess function.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Errors when trying to send e-mail when using Ubercart
I am aware of the many other:

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

Questions that have been asked however, I believe my situation to be a bit different.

Situation:

I have been tasked to make some updates to my companies website. They are hosted and use cpanel for management. I have been working with the Drupal portion of the site and have been getting the Unable to send e-mail error when trying to do any of the following:

* Create a user account
* Retrieve lost password
* Use any of the e-mail functions in Ubercart (order confirmation ect..)

Question:

Are there any settings that I should be looking to change or is this something that needs to be configured in a config file. I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart.

Things I have tried:

I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart. I have also set up the site e-mail (Home » Administration » Configuration » System).

# Answer
> 1 votes
So after much searching I came across this post:

http://shutterfreak.net/blogs/olivier-biot/2010-06-24/configuring-smtp-server-sending-mail-drupal

Apparently issues with the default SMTP are quite common. This post explains how to install and configure "SMTP Authentication Support module" and PHPmailer to basically override the default.

Worked great for me.

---
Tags: 7, users, emails, ubercart
---


title: view access permission

text:
# Question
Title: view access permission
I have a problem with view permission, when I make a view in drupal 7 there is an option "access" when I specify the option eg:"view published content" all users that has the role of published content can see all the content that are belongs to that view. But I want some thing else, I want to give the permission for users to access just his/her own published content not all published content that are belongs to that view. cheers

# Answer
You can add a contextual filter "Content: Author uid" which defaults to "User ID from logged in user". Or you could also try to add a relationship to the author of the content and compare it's uid to the uid of the logged in user.
> 0 votes

---
Tags: 7, views, users
---


title: Conditional Flags in Panels

text:
# Question
Title: Conditional Flags in Panels
I have created two flags using the Flag module and they are placed on my custom content type, 'Challenge'. Both the flags can only be flagged but not unflagged. The first flag is "Accept". The second flag is "Complete". These two flags i have created normally through the UI. However to display them in panels, i have used the following code in a custom text area in panel as flags are not displayed automatically there.

```
<div id="accept-flag">
<?php
   print flag_create_link('flag1', %node:nid);
?>
</div>
<div id ="complete-flag">
<?php
  print flag_create_link('flag2',%node:nid);
   ?>
</div>

```

This displays both the flag on my Panel Page. However, my use case is something different. At first only, the "Accept" flag should be visible. Then, when the user clicks on "Accept", then only the other flag, "Complete" should appear. Any hints on how to achieve this. I have also tried using Rules, giving the event: A node has been flagged and then the action for a new flag. It does not work. Then i tried using flag actions as well, i.e., on flagging of first flag, display another flag.It does not work. Any ideas, suggestions are appreciated.

Thanks

**Edit**

i thought of a way to do this using JavaScript and css. When the first flag is visible, the second wont show. The code i am using is :

```
if($("#accept-flag").is(":visible")){
    $("#complete-flag").css('display','none');

```

This i have placed inside js/script.js in my theme folder.

```
(function ($, Drupal, window, document, undefined) {

if($("#accept-flag").is(":visible")){
    $("#complete-flag").css('display','none');
}

})(jQuery, Drupal, this, this.document);

```

When i view the page source, the script is loading however both the flags are still showing.

Please advice

Thanks again

# Answer
Since you are using Panels, you could create two variants. One of them would have a selection rule that says only select this variant if "accept" is flagged, and in it your display only the complete flag. The other variant wouldn't need selection rules (but would need to be placed under the first one in the variants order) and it would display only the complete flag.
> 1 votes

---
Tags: 7, users, flags
---


title: Hook to add new field to node form

text:
# Question
Title: Hook to add new field to node form
I have a blog content type which has a field for authors- (these are pull from a separate content type). multiple values are allowed. i am trying to develop a module that will pull the authors email address and display it next to the authors name when ever a new author is added in the blog create form so users can edit the email on the fly while creating a new blog post.

i need some pointer as to the right hooks to use for these. Thanks in advance. See screenshot below of what am trying to archive

# Answer
I've never used it myself -- but see Inline Entity Form which should allow you to reference an existing author, or implement that modules form controller class to show an author and email field to create the new author as needed.

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

From the README

```
Integrating with Inline Entity Form
-----------------------------------
An entity type can add support for this module by declaring the
inline entity form controller class in its entity info:

$entity_info['commerce_line_item']['inline entity form'] = array(
  'controller' => 'CommerceLineItemInlineEntityFormController',
);

The controller needs to extend EntityInlineEntityFormController and at least
override entityForm() to provide a function entity form.

```
> 0 votes

---
Tags: hooks, forms
---


# Question
Title: how to programmatically alter the rendering of a field in Views
I have a content type called 'Ping'. It has several fields and one of them is a url by the name 'filename'. I want the View of all such pings, names 'user-pings' to display not the url itself, but a link to it. How do I do that?

I've tried the following, but it doesn't work:

```
function feedback_views_pre_render(&$view)
{

    if( $view->name === 'user_pings' )
    {

        foreach( $view->result as $key => $val )
        {
           $lang = $view->result[$key]->_field_data['nid']['entity']->language;
           $field = $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0];
           $filename = $field['value'];
           $link = "<a href='$filename'>(download)</a>";
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['value'] = $link;
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['safe_value'] = $link;

        }

    }

}

```

Additionally, if this code is a try in the right direction, I would very much like to learn how to do the same thing in less code.

Cheers and thanks in advance, Alan

# Answer
> 1 votes
You can do that in the views interface, no need for pre- or post- processing on the theme level (as your script snippet suggests).

I assume that you are using Drupal 7.x and Views 7.x-3.x.

Go to the UI for the view you want to change:

```
http://example.com/admin/structure/views/view/yourviewname/edit
or Home » Administration » Structure » Views » Yourview

```

Make sure you are on the Display that you want to change (towards the top: Display has tabs "Page", "Add" and maybe others like "Block" or similar)

Under "Format", it shows "Format" and "Show". "Show" needs to be set to "Fields".

The click on the field with your url, like:

```
 Content: URL (URL)

```

A popup window will open with:

```
 Configure field: Content: URL

```

Click on "Rewrite Results" - a number of options open, check:

```
 Rewrite the output of this field

```

A couple of additional fields now open up.

Click on "Replacement patterns" and identify your url field, for example:

```
[field_url]

```

Now, enter the text you want to display into the "TEXT" field (can be html tags like an image tag):

```
An image tag
Some text

```

Check "Output this field as a link", and enter the replacement pattern into the "Link path " field \[field\_url\].

If you want to use another field from your content type to show instead of something generic, that field needs to be on the "Fields" list BEFORE the field\_url field, but can be marked as "invisible" if you don't want to display it otherwise.

---
Tags: views
---


title: Contact form does not work

text:
# Question
Title: Contact form does not work
I configured the contact form module core for drupal 7, But the messages are not sent, whitout any error message. I work just in local.

# Answer
> 0 votes
Did you check if your localhost is capable of sending e-mails? (probably not, mine for example can't send an email)

---
Tags: forms, emails
---


# Question
Title: How to restrict anonymous users to a single product and quantity 1 using Commerce and Rules?
I have a slightly unusual use case in that I want to allow authenticated users to order multiple products and use the shopping cart but I want to limit anonymous users to purchasing products individually (no changing quantities, no adding multiple products to the cart).

I am using Commerce and Rules on Drupal 7. Because I do not want anonymous users to access the cart, I want to redirect them to the checkout page if they attempt to access the cart (I know this is not the most foolproof method, but it is sufficient for my purposes).

I tried creating a rule triggered on the event **Content is viewed** with the condition **Path has URL alias** of *cart*. However, this rule is not triggered; when I add a **Path redirect** action and then visit the *cart* path, I am not redirected. What event should I use in Rules to do the redirect? Or is there some better way to do this?

# Answer
These rules can be used to restrict number and quantity of products available by role.

They can be imported in Rules admin.

**Restrict to single product:**

Basically, before adding to cart, if anonymous, remove existing products from cart. The effect is only the latest product is added to the cart.

```
{ "rules_single_product_order" : {
    "LABEL" : "Single product order",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : [ "commerce_cart_product_prepare" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }
}

```

**Restrict quantity to 1:**

On order presave, if anonymous, loop over the line items and set quantity to 1

```
{ "rules_restrict_quantity_to_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_order_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [ { "data_set" : { "data" : [ "list-item:quantity" ], "value" : "1" } } ]
        }
      }
    ]
  }
}

```

Anon can still view the cart, but they will be restricted to one product and quantity of 1 - a preferable solution here. You could also show a message about the benefits of registering, if required.
> 5 votes

---
Tags: commerce, rules
---


# Question
Title: Drupal 7 and google maps v3. Which is the module to use ?
I need to store lat/lng into a content type for the obviously normal thing: display a google maps. But for the moment I have see that the better modules for google map integration using v2 that it is deprecated.

In my content type I request the others data (street, city, country, county) so I do not need a module that need to insert this data. This because I need to insert this data into a SOLR server.

So, which is the best module for Drupal that use google maps v3 ? Or I need to create one custom that use (for example) gmap3.net's js script ?

Thanks.

M.

# Answer
The approach should be map agnostic. You need to break things in two parts:

1. Storing location data
2. Displaying this data on a map

1) **Data storage.**

You'll need three modules here:

It may look difficult, but it is really easy to configure these three modules to play nicely.

2) **Data display.**

Now having data stored in database we can choose any display approach we want. Here you have two+ choices: \- GMap (http://drupal.org/project/gmap) \- OpenLayers (http://drupal.org/project/openlayers) \- As a third option, you can have a custom js code which plays with Google Maps

Everything depends on your final goal. OpenLayes plays with different map engines and to me it looks a bit bloated. If you go with GMap you'll get Google Maps V3 support which is better to stick with instead of Google Maps API V2. Google Maps API V2 development has stopped, no new features are being rolled and it can be abandoned at any moment, so why to risk?

Go with custom js maps code if GMap module doesn't give you what you need. But I do really suggest you to look at GMap module a little bit closer.
> 8 votes

# Answer
Getlocations Module (https://drupal.org/project/getlocations) has been the first to bring the GMAP/Location Module (Google Maps V2 Api based) to Google Maps API 3 version. It has rapidly developed and extended its functionalities and is still actively developed … At the same time I would recommend the IP Geolocation Views & Maps (https://drupal.org/project/ip\_geoloc) that integrated with the Getlocations Module and that is able to nicely work with Google API 3 Maps …
> 3 votes

---
Tags: 7, google-maps
---


# Question
Title: Add a trademark to a word everywhere on a site
I've tried a few different techniques now but I can't get one to work reliably across all content. What I need to do is have all instances of the business name include a trademark symbol:

ie -\> `DinosaurCakes` becomes `DinosaurCakes<sup>&tm;</sup>` or `Would you like some DinosaurCakes?` becomes `Would you like some DinosaurCakes<sup>&tm;</sup>`

The javascript version I was trying to do was looping through the page on load and replacing the string with the function I found here-\> http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ But it isn;t digging in to all of the child nodes for some reason and so some versions of the string don;t get replaced.

I then tried to do it in Drupal via hook\_page\_alter with:

```
function dinosaur_page_alter(&$page) {
    // attempting to add the DinosaurCake (tm) marks using page_alter
    // find all '#markup' and then scan for terms
    function display_array(&$your_array){
      foreach ($your_array as $key => &$value){
        if (is_array($value)){
          display_array($value);
        }
        elseif (is_string($value) && $key === "#markup") {
          $value = str_replace(array('DinosaurCakes"), array('DinosaurCakes<sup class="reg">&tm;</sup>'), $value);
        }
      }
    }
    display_array($page);
}

```

However, using this method, it doesn't work on headings and does apply to title attributes and pathnames which of course breaks everything.

Any ideas on the best way to attack this?

# Answer
> 0 votes
I ended up falling back to a javascript solution. It provided the most reliable solution across all content on the page. There are still a few weird quirks with it not working in some specific html scenarios, but it works well enough.

Snippet in case anyone else would like to use a similar solution - it's not elegant, but it works:

```
/* Find and add in registered trademark and trademark symbols where needed. */

//get ALL the text nodes - adapted from http://stackoverflow.com/questions/9178174/find-all-text-nodes
function recurse(element) {
    if (element.childNodes.length > 0) {
      //there are additional children, send them back through for exploration
        for (var i = 0; i < element.childNodes.length; i++) {
            recurse(element.childNodes[i]);
        }
    }

    if (element.nodeType == 3 && /\S/.test(element.nodeValue)) {
      // we have a text node, send it off for processing
      doReplacements(element, element.parentElement);
    }
}

var html = document.getElementsByTagName('html')[0];
recurse(html);

function doReplacements(element, parent) {

    var html = element.data;
    //ensure we only process each chunk of text once.
    if (element.nextSibling){
        if (element.nextSibling.nodeName.toLowerCase() === 'sup'){
        //do nothing, this one has been done.
        //console.log('bailing');
        return;
        }
    }
    // Do the following replacements:
    //add reg marks
    html = element.data.replace(/\bPuppyDawg\b|\bFeisty(\s)Clown\b|\bRabid(\s)Dinosaurs\b/gi, "$&<sup>®</sup>");
    //add trademarks
    html = html.replace(/\bMad(\s)Cat\b/g, '$&<sup>™</sup>');

    //now rebuild the html with the new tags in place (via http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/)
    //note, since I started this, I have found this: https://github.com/padolsey/findAndReplaceDOMText which may work if we need to start over...
    var frag = (function () {
        var wrap = document.createElement('div'),
            frag = document.createDocumentFragment();

        wrap.innerHTML = html;
        while (wrap.firstChild) {
            frag.appendChild(wrap.firstChild);
        }
        return frag;
    })();

    parent.insertBefore(frag, element);
    parent.removeChild(element);
}

```

# Answer
> 4 votes
You can use "String Overrides" (http://drupal.org/project/stringoverrides) module to accomplish what you want to do and it will work even if JavaScript is disabled and the changes will be cached as well by the Drupal cache.

**Note:** This will work with content pass by the t() function, if you have the word hard coded on the theme or module it will not work. Also it is CaSe SeSiTiVe.

# Answer
> 0 votes
I ran into this exact problem recently on a Drupal 6 project. Drupal 7 could be handled the same way.

In my case, I needed to put the ® Registered Trademark on Drupal output H1 Page Titles wrapped in `<sup></sup>` tags. I understand html is not allowed in titles, but my specific solution is not subject to problems introduced by not escaping html, and it still does escape user-provided content intially:

The underlying issue is that because all page titles go through drupal\_set\_title(), they also get passed through filter\_xss. Understanding this, I am comfortable with the cleanliness of my page titles. The user actually types the (R) symbol (not html `&reg`). Then, in the theme, I re-scan the text and string-replace the cleaned HTML in the part that outputs page title:

In page.tpl.php, the `<h1></h1>` page title bit:

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

```

becomes:

```
<?php print strstr($title, "®") ? str_replace("®", "<sup>®</sup>", $title) : $title; ?>

```

Did a check for strstr() for efficiency: If it doesn't exist, don't bother processing str\_replace. In your case, if *all* page titles have it, you might just do a straight up str\_replace and take it home in one fell swoop.

A bit better and more generic solution would do it regex and for all registered and copyright symbols.

---
Tags: 7, javascript, theming
---


# Question
Title: Updating computed field's value without needing to clear cache
I have a computed field that lists content related to a node, so it's value should be changed when I add a new node. Whenever, I add a new node I need to clear the cache to update the computed field's value.

How do I prevent caching value of the computed field OR re-compute the value after adding a new node?

# Answer
> 1 votes
Check out the rules module (http://drupal.org/project/rules):

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

You could add a rule to clear the cache whenever a new nodes has been added.

It's not exactly the way you asked for, but it gets the job done - updating the computed field's value whenever a new node has been created.

# Answer
> 1 votes
I haven't used this module in a while, and don't have the quick ability to do so now, but I recall you can set the fields up two ways, one that relies on the database and cron/caches, and the other that runs on each node view.

A quick look at the module page has this snippet:

> You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views.

so I would look into that option. I am pretty sure that if you store it in the database it only updates when that particular node is updated, but if you don't store it in the database, it is run on each node view. (Somewhat obviously this will have a performance impact if the computations are complex.)

---
Tags: 7, entities
---


title: Open node as popup with Lightbox 2

text:
# Question
Title: Open node as popup with Lightbox 2
I recently upgraded my site to Drupal 7 and felt a need for opening some specific node as popup using Lightbox 2.

I have been through the documentation, and I found out that in Drupal 7 this feature can be implemented by adding a new template file in theme's directory named page--node--\[nid\].tpl.php.

The problem is that, when I implemented it this way, I wasn't able to view the node content properly as in the template I removed the header, sidebars etc.

So when I try to access the node via www.example.com/node/\[nid\] only content would appear without showing any headers or sidebars.

So has anyone implemented this feature using Lightbox 2 in Drupal 7?

# Answer
> 1 votes
In your tpl.php file only have the following

```
<?php print render($content); ?>

```

If you want to style it you can wrap divs around.

Then add a `rel="lightframe"` attribute in your link that will trigger lightbox.

```
<a href="http://www.example.com/node/[nid]" rel="lightframe">Link</a>

```

# Answer
> 1 votes
To achieve this goal you can use Colorbox module + Colorbox Node module.

You also should take a look at the following question:

How to display a node in overlay popup effect?

---
Tags: 7, javascript
---


# Question
Title: Getting parent enitity of enitityreference field
Is there a function to get parent enityinfo to which entityreference field is attached. Similar function is hostEntity() provided by field\_collection.

I created the content type which has enityform as enitityreference field.Enityform contains basic contact field with additional computed field. In that field I need nid of node to which entityform is attached.Using entity\_metadata\_wrapper I am able to get info about entityform object using below code.

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$info=$wrapper->entityInfo();

```

Any idea how to further backtrack and get parent node id?

Update : Entityform is attached to a node(ref).
1.Node contains entity reference field, to which enitity form is attached.
2.Enityform contains computed field.
3.In computed field when the above mentioned code executed, field $wrapper gets the details about enitityform object(should be because computed field belongs to this entity).
4.As there will be no relation between node and the attached entityfrom after submission, I am trying to capture the NID of node during the form submission.

# Answer
Check out this issue in Entityform queue https://drupal.org/node/2041349

This person had the same problem. You can do this without programming if you use the Entity Reference Current module.

You will need to attach an Entity Reference field to the Entityform Type and have the field use the **Entity Reference current behavior**.
> 0 votes

# Answer
Something like this should work:

```
// Load wrapper
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// Load parent entity
$parent = $wrapper->field_entityreference->value();
// Get nid
$nid = $parent->field_computed_field->value();
// Debug output
drupal_set_message(t('Parent NID: @nid', array('@nid' => $nid)));

```
> 0 votes

---
Tags: entities
---


# Question
Title: Views Slideshow - showing only one slide
I've the content type, from which I want to take one field: title and present it as a block somewhere on the page. Sounds rather easy, but maybe my brain has melted already.

I installed Views Slideshow, created new view and it seems to work. To some degree, because it's only showing me one slide (title) and when it's fading, nothing new appears. When I choose the format for example to unformatted list, it shows all the titles it should, but in slideshow format it just doesn't work. What I'm missing here?

This is how it looks right now:

# Answer
> 1 votes
The possible directions you can look into :

1. You need to install the jQuery cycle plugin. Create a directory in sites/all/libraries called jquery.cycle, and then copy jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find the plugin at http://malsup.com/jquery/cycle.
2. In views slide show settings check for the 'Timer delay' in 'View Transition Advanced Options'.

Also, check for the other options in views slide show settings.
3. In the views settings, you are only showing published contents for a particular type of content. Make sure you have more than one such content. (Based on your screen shot)
4. Considering you have enabled 'Views Slideshow: Cycle' module

(Answer is based on trial to regenerate the issue in D7, 7.22)

Hope it helps

---
Tags: views, javascript
---


title: Set default language for domain

text:
# Question
Title: Set default language for domain
I have one site with 2 domains one `example.de` and one `example.com` its a multilanguage site, so i have urls like this `example.de/de/content` and `example.de/en/content` etc, and same on `com` domain.

Default language is `de` for this two domains, but for `example.com` i need `english` to be default language.

i thought i can change it in `settings.php` with `$conf['language_default']` like this:

```
$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

```

its working but for both domains... . also i managed to redirect users to `en` on `example.com` (my home page is a node with nid `89`)

```
function MYMODULE_node_view($node) {

        if ($node->nid == 89) {
            if ($_SERVER['SERVER_NAME'] == 'www.example.com') {
             header('Location: http://www.example.com/en');
            }
        }

    }

```

**but its not an option**

Is there any solution to change default language for my `example.com` domain?

# Answer
Though I'm surprised if there's not an option in the user interface, according to `language_default`, it appears you could set the default language as a $conf variable in the shared settings.php file.

Something like

*settings.php:*

```
switch($_SERVER['SERVER_NAME']){

  case 'www.example.com':

    $conf['language_default'] = (object) array(
      'language' => 'en', 'name' => 'English', 'native' => 'English',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Example per-domain cache prefix if using memcache
    $conf['memcache_key_prefix'] = 'en_';

  break;
  case 'www.example.de':

    $conf['language_default'] = (object) array(
      'language' => 'de', 'name' => 'German', 'native' => 'German',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.de', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Ensures cache varies by domain
    $conf['memcache_key_prefix'] = 'de_';

  break;

}

```

**Update**: Added example `memcache` cache key prefix setting - to ensure cache varies per domain, if required.
> 6 votes

# Answer
Why do you want to change the default language? It would be enough to change current language depending on the domain. I think the best way is, to alter the current language of all types with the function: hook\_url\_language\_init. This would be an code example:

```
function custom_api_language_init() {
  // Current path
  $url = $_SERVER['SERVER_NAME'];
  $domains = array('www.example.com' => 'en');

  // Global language object and get languages
  global $language;
  $languages = language_list();

  if (isset($domains[$url])) {

    $langcode = $domains[$url]

    $new_language         = $languages[$langcode];
    $new_language->domain = $url;

    // Set url options
    $options['language'] = $new_language;
    $types = language_types();

    // Set all language types and language domains
    foreach ($types as $type) {
      $GLOBALS[$type] = $new_language;
      $GLOBALS[$type]->domain = $new_language->domain;
    }
  }
}

```

Here you find a similar thread: How to set multiple domains for one language
> 1 votes

# Answer
I wrote it in a comment, but I believe it may be the correct way to do it, so I post it as an answer. In

```
/admin/config/regional/language/configure

```

you can set both User interface text language and Content language based on URL, session, user preference, browser language and default language.
> 0 votes

# Answer
in your template.php use the following code. :

```
function THEME_preprocess_page(&$vars) {
   global $language;
   if ($_SERVER['SERVER_NAME'] == 'www.example.com' && $language->language != 'de') {
       header('Location: http://www.example.com/en');
   }
}

```
> -1 votes

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


# Question
Title: hierarchical select to display taxonomy tree
I need a similar module as hierarchical select to display taxonomy tree in my view because hierarchical select to drupal 7 doesn't work with views module.

Please help me !

# Answer
```
ASSIGN $child to an select list just set taxonomy id :
$taxonomy_vid = 3;
   /*** A HEADACHE CODE :p arrange the parent child taxonomies****/
 /*      $tree_type =  taxonomy_get_tree($taxonomy_vid);   // taxonomy id here
    $childs["selected"]="Select a Value";
    //$childs[45]="New Launches/Projects";
    foreach($tree_type as $key =>$value) {
$temp_ = taxonomy_term_load($value->parents[0]);       //IF parent is set already
                if($value->parents[0]==0) {                   //if no any parent taxonomy
                        if(is_object($temp_)==TRUE) {
                        if(isset($childs[$temp_->name])) {  //if array key is already set
                                if(is_array($key)!=FALSE) { //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                        }else {
                                if(is_array($key)!=FALSE) {    //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                            }
                        }else
                        {
                            $childs[$value->name]=array();
                            $childs[$value->name][$key]=$value->name;
                            //drupal_set_message("-------<pre>".$value->name."</pre>-------");
                            }
                    }else {
                        //$temp_ = taxonomy_term_load($value->parents[0]); //IF parent is set already
                        $childs[$temp_->name][$key]=$value->name;       //$childs[$temp_->tid]=$temp_->name;
                    }
        }

```
> 1 votes

# Answer
A very quick google search "views tree" will point you to this module, which most probably will get you going.
> 0 votes

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


# Question
Title: CSV import ends up in unresolvable state
I'm having a problem with Feeds and Commerce Feeds in D7.

I am using Feeds and Commerce Feeds to import products into my Drupal Commerce store.

The CSV import was failing with a 403 error. Once this happened the import button was greyed out with text showing "importing 21% complete". Initially I cleared the message by running a delete and then reuploading. Now the delete tab has the same problem! It says "deleting 51% complete"

I have added a support request for this on drupal.org; but I think that the question may be better suited here as a "how-to" type answer would seem more appropriate.

Any ideas on how I can sort this out?

# Answer
I solved the problem by cloning my import.

When I selected the cloned import it wasn't hampered by the progress information and greyed out import button. I could just upload my csv via the new import.
> 1 votes

# Answer
I have experienced the same case, I just delete the imported item then import button enabled again.
> 0 votes

---
Tags: feeds, commerce
---


# Question
Title: Overwrite a specific field on a specific node
We have a content-type of 'offices' locations. There is a View that pulls all of them together and that view is used on a contact page, a buy and a representative page. It's also used on job postings as a field 'location'.

Now they want to post a job with at "TBD" location. If I add a "TBD" node type, it will then display in all of the places where that view display 'offices' is pulled.

So I need to tell Drupal "On this job posting only, show "TBD" in the location Field. That's the ideal thing ... to rewrite that field on a specific job posting. In this case, the node is specifically 11071, if that helps?

Can I use a page-node-11071.tpl.php and some function there?

# Answer
> 0 votes
Instead of treating this one node in a special way (there will be more job postings in the future with location TBA), you could filter out the location by adding a filter in your views that pull locations.

In you views, under "Filter criteria" click add, choose the field type of your location, choose Operator "not equal to" and Value "TBA".

That should do the trick.

# Answer
> 1 votes
As I understand, you want a to display the same block which lists some node information in different pages and want to avoide listing some specific nodes in some specific pages. You can make use of views filter with 'Global: PHP' and have code similar to as below :

```

if (arg(0) == 'node') {// Set your condition here.
  if ($data->nid == NID_YOU_WANT_TO_RESTRICT) {// Set the NID you want to restrict
    return TRUE;
  }
}

```

Note : To consider multiple job postings in future, you just need to set the path condition accordingly.

Hope it helps

---
Tags: views, nodes
---


# Question
Title: List all nodes by logged in user in a custom module
I am creating a module in Drupal 7, where I need to have a list of all nodes created by a logged in user of specific content type. How can I achieve this? It is easy to do it in view but I need to do it in a custom module. Can anybody help?

Thanks

# Answer
There is module available https://drupal.org/project/usercontent still if you want to do it in custom module then here is the code:

`global $user;
 $node_query = db_select('node', 'n')
->fields('n',array('nid'))
->condition("type", "node type")
->condition("uid", $user->uid)
$node_result = $node_query->execute()->fetchAll();`
> 1 votes

---
Tags: views, 7
---


# Question
Title: What is the correct way to programatically set node type options?
I learned yesterday that the correct way to create a node type is by implementing `hook_node_info` inside a .module file. Before I had been programatically creating node types in a .install file via `node_type_save`, like this:

```
// Create node type
$type = array(
  'type' => 'fruits',
  'name' => st('Fruits'),
  'base' => 'node_content',
  'description' => 'Contains information about fruits.',
  'custom' => 1,
  'modified' => 1,
  'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);

```

I had also been setting the node type options in the .install file, like this:

```
// Set 'fruit' options.
variable_set('node_preview_fruit', 0);                     // Set 'Preview before submitting' to 'Disabled'.
variable_set('node_options_fruit', array('status'));       // Set 'Default options' to 'Published'.
variable_set('node_submitted_fruit', 0);                   // Unset 'Display author and date information'.
variable_set('comment_fruit', COMMENT_NODE_CLOSED);        // Set 'Default comment setting for new content' to 'Closed'.
variable_set('menu_options_fruit', array('navigation'));   // Set 'Available menus' to 'Navigation'.
variable_set('menu_parent_fruit', 'navigation:0');         // Set 'Default parent item' to '<Navigation>'.

```

Is this the correct way to programatically set node type options: like this, inside the .install file, even though the node type itself is created inside the .module file?

# Answer
> 2 votes
Looking at the code for `node_type_form_submit` you can see that the variables are set before the `node_type_save()` function is called. Thinking about it a bit, it doesn't really matter as the node type info is saved into a different table than variables. So as long as the variables are being set synchronously with the creation of the node type, it shouldn't matter. Even then, the worst case scenario would be you'll have some redundant variables in the `variables` table. Which is not a big issue.

So to answer the question, yes that's the proper way. However I'd do it in the same function call in the .install file, maybe implement it in `hook_install` or `hook_enable` depending on what you need.

# Answer
> 0 votes
if you wanted to know the best way to create node on enabling the Drupal module

1. create a feature containing content type you want to create on module enable
2. check the code it generate

-\> hook\_field\_info is defined in separate inc file and include it in .module by require once

as feature follows all the best drupal technique to code so i think this is the best way

---
Tags: nodes
---


# Question
Title: Make Openlayers center & bounds context aware
I'm creating geospatial database for multiple municipalities. Each should be able to work in it's own context (not only see only own data, **but also have custom center & bounds for input and output maps**).

I tried to find this functionality in OpenLayers module, but wasn't successful. I only found "zoom to layer" functionality, which isn't applicable, because there will be different layers for each municipality.

The most straightforward way I can think of is using geofield-defined bounds in user entity, which OpenLayers could use.

Do you know about any solutions?

# Answer
> 0 votes
I figured it out. The key is adapting https://drupal.org/node/904898 by switching Geo Taxonomy to Geofield or Postgis for Drupal 7.

---
Tags: javascript, location
---


title: How do I hide  the main menu items?

text:
# Question
Title: How do I hide  the main menu items?
I have users who are the owners of some nodes, and each node has a menu link in the main menu. Users can only see the nodes they own, and they cannot see other user's nodes.

The problem now is that the menu is displayed like in the following image, for all the users; it shows links for both the nodes owned by the current user, and the nodes the current user doesn't own.

I would like to display only the menu items corresponding to the nodes owned by the logged in user. How can I do this?

# Answer
Drupal will hide menu items for paths that users don't have access to. But for this to work, it requires that the access callback for that menu item returns `FALSE`. If you handle access control in the menu callback instead, Drupal won't know that the user doesn't have access and will display the menu.

A solution would be to implement a custom access control module/function if you can't use any of the existing for the nodes.
> 4 votes

# Answer
For each menu entry you want to control access to I assume you have a hook\_menu (http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_menu/7) array value setup? The property that you're interested in for each of these array entries is "access callback" - a function returning TRUE if the user has access rights to this menu item, and FALSE if not.

Use user\_access($string, $account = NULL) (http://api.drupal.org/api/drupal/modules--user--user.module/function/user\_access) with a target access permissions value of your choosing based on this reference: (http://drupal.org/node/132202)
> 2 votes

# Answer
You may find the following answers (that give modules to do this functionality) in...

How can I show/hide just one menu item based on user role?

...useful:

Drupal menu\_per\_role module:

https://drupal.stackexchange.com/a/29545

Drupal Menu Item Visibility.

https://drupal.stackexchange.com/a/30934
> 0 votes

---
Tags: 7, routes
---


title: How to include node title in teaser

text:
# Question
Title: How to include node title in teaser
I am using Display Suit module to enhance the apache solr search results page. I use the Teaser view mode, but I don't get the node title in the teaser, because the node Title field is not available in the Content type display setting under teaser settings.

Is there any alternative way to add the node title as part of teaser view?

# Answer
> 4 votes
Even when Display Suite is enabled, you need to set a layout for it to be enabled for that particular content type. If you just want one column you can select the "One Column" and it will add all the fields available with Display Suite.

It should look something like this:

---
Tags: nodes, search, display-suite
---


# Question
Title: Getting IMCE to accept multiple file uploads at one time
I am currently using the IMCE module for uploading files but it only allows 1 file to be uploaded at one time. We have tried the plupload and the imce\_plupload modules together but those modules sometimes corrupt the files once uploaded. The only other module called "IMCE Multiple Upload" that claims that it can work with IMCE as an add-on module to IMCE and allows multiple uploads at one time costs $36.
I don't know if the "IMCE Multiple Upload" module will work correctly since the demo site only allows 5 files at once and once over a certain file size it scales it down.

Has anyone used the "IMCE Multiple Upload" module with IMCE and does it restrict how many files can be uploaded at once and does it restrict the file size?
Also does anyone know of an alternative way of getting IMCE to accept multiple file uploads at one time.

# Answer
> 1 votes
I don't know what version of Drupal you are using, If you are working with Drupal 7 you should take a look at: IMCE plupload that helps you to use IMCE with Plupload .

But in Drupal 7 the best option is Media module.

---
Tags: 7, files
---


# Question
Title: Clear Varnish Cache (and maybe Views?) for Home Page when new story posted
Drupal 7.

I run a site for a large publishing company. We're on Acquia Cloud, using Varnish to serve cached pages to anonymous users. Home page has a couple Views - one is a running list of news stories, and the other a Featured slider.

My minimum cache lifetime is set to 5 minutes, and Expiration of Cached pages to 15 minutes. On each View I have Content-based caching enabled.

I'd like to have new stories immediately shown on the home page. I believe I should only have to worry about the Varnish cache, that Content-based caching on the Views should be handling those caches, though to be honest I'm unsure of how to accurately test all this.

I read up on some things, and I found modules like Cache Expiration or Purge, and I think I'll also need to install Rules and maybe Cache Actions. I just figured I'd post here to see if someone else had experience with this and could offer some direction.

# Answer
Install the varnish module and set the minimum cache lifetime to **none** at admin/config/development/performance Also be sure to add the tweaks to the settings.php from the varnish module page.

This should ensure that the cache is flushed when new content is added. You may want things to be a little more granular (if a complete cache clear at every content update would overload your server and cause performance problems) so using here are some other steps you can take:

I found a nice article about using varnish which you might consider checking out.

The author recommends:

* Go to the Varnish settings page (admin/config/development/varnish) and select "None" under "Varnish Cache Clearing". This will make sure that all pages are not flushed when content is altered.
    + Enable the Cache actions and the Rules UI module
    + Go to Administration =\> Workflow =\> Rules and click "Create a new rule"
    + Select "After updating existing content" under "Node" as the reacting event
    + Add the "Clear a specific cache cid" action
    + Select cache\_page as your cache bin.
    + Put "node/\[node:nid\]" in the value text area.

Try to edit one of your nodes, everything should still work. The difference now is that we are actually only purging the entry of the particular node that has been edited not the whole page. You can try this by visiting another node, notice that it is still cached by looking at the Varnish headers.

You will probably also want to clear the views cache (for your relevant views) so they are updated instantly. Testing should be relatively easy by adding new content in a browser and refreshing another browser window that isn't logged in. You should see your new content appear immediately at refresh.
> 3 votes

---
Tags: 7, views, caching, proxies
---


# Question
Title: Use node title as page title in views full node page display
I'm using views to link a menu-item to the last node added of a certain content-type.

To accomplish this, I've set up a view to display a 1 full node sorted by post date.

this all works just fine, but now I want to use the node title as page title () instead of the view page title. I also don't want the node title to link to the node again.

Does anyone know how I can do this?

Thx in advance.

# Answer
I finally managed to pull this off by writing a small module using following code:

```
function MYMODULE_preprocess_views_view(&$vars) {
  // Get my view
  if ($vars['view']->name == 'MY_VIEW_NAME') {
    //get the title of the node shown in the view
    $nid = $vars['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $vars['view']->build_info['title'] = $my_title;
  }
}

```

This module changes te views page title and uses the nodes title as page title instead.

Now you can remove the linked nodetitle in the node--YOURTYPE.tpl.php
> 5 votes

# Answer
This is a great way if you want to address all displays of a view, but what if you want this only for one specific display?

I found an answer to this on http://dropbucket.org/node/194.

```
// first implement hook_preprocess_views_view() which is called for each view.
function HOOK_preprocess_views_view(&$variables) {
  if (isset($variables['view']->name)) {
    $function = 'HOOK_preprocess_views_view__'.$variables['view']->name;
    if (function_exists($function)) {
     $function($variables);
    }
  }
}

function HOOK_preprocess_views_view__MY_VIEW_NAME(&$variables) {
  //alter here that specific view
  if($variables['display_id'] == 'page_1') {
  // here it will alter specific display of that view.
    //get the title of the node shown in the view
    $nid = $variables['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $variables['view']->build_info['title'] = $my_title;
  }
}

```

Now only the page\_1 display of a view gets it’s title from the node. All other displays just get the title defined in the display.
> 1 votes

---
Tags: views, 7
---


# Question
Title: How to separate UI language from node's language?
I have a site that uses 3 languages, namely English, Polish and Russian. And we have content editors with 3 native languages. Now, most of the times Russian guy will want Russian UI and will be editing Russian nodes. But sometimes he will need to correct nodes written in Polish. He will not want his UI to turn to Polish when doing that, of course.

Is there a way to allow users to select their default admin language? Desired effect for nodes is:

If possible, I want this globally, for all admin pages, not only node edits, but of course node edits will be most common = most important to me.

# Answer
I forgot this in my initial comment but you can actually solve this by installing Entity Translation!

It separates entity and interface translation. With both you can specify different language negotiation schemes. In *admin/config/regional/language/configure* simply set the user's language setting as the highest priority in the interface language negotiation queue.

By having URL as the first criteria and user preference in the content language negotiation queue you can attain this functionality you documented.
> 3 votes

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


# Question
Title: Writing a custom Rules Action for VBO- do I need to use Entity?
I have a list of email addresses displayed in a view. I'd like to parse those email addresses using a rules action, via VBO.

I'm trying to pass the email address to my rules action as a parameter, but it seems the only way I can do this is if I declare the email address as an entity first. Is that right or am I missing something? If there's an easier way, please let me know.

# Answer
\[I'm assuming you have a custom table to store these email addresses and are not related to any other entity\] With the latest version of VBO, yes, you have to define an Entity. See this issue in the VBO queue for more information.

FYI, the below steps worked for me.

```
function module_entity_info() {
  return array(
    'MY_NEW_ENTITY_TYPE' => array(
      'label' => t('MY_NEW_ENTITY_TYPE'),
      'base table' => 'MY_NEW_TABLE',
      'entity keys' => array(
        'id' => 'your_tables_primary_key',
      ),
    ),
  );
}

```

Note that in `entity keys` array, set the table's column as the key, and VBO will pick it up and will pass as an object to the action. See below:

```
function module_action_info() {
  return array(
    'module_remove_something' => array(
      'type' => 'MY_NEW_ENTITY_TYPE',
      'label' => 'Remove URL',
      'configurable' => FALSE,
      'behavior' => array('deletes_property'),
    ),
  );
}

```

In your views integration file, you will probably need to define the tables as an entity too.

```
function mymodule_views_data() {
  $data['mymodule_emails'] = array(
    'table' => array(
      'base' => array(
        'field' => 'eeid',
        'title' => 'Extracted E-mails',
        'help' => 'Email addresses collected by parsing the remote URL',
      ),
      'group' => 'E-mail',
      'defaults' => array(
        'field' => 'email',
      ),
      'entity type' => 'MY_NEW_ENTITY_TYPE', // attention here!
    ),
   // Rest of the table definition...

```
> 3 votes

---
Tags: rules, views, actions
---


# Question
Title: Is it possible to limit which products users can purchase by role?
I have three products, A B and C. Anyone can buy products A or B, but only users with the *VIP* role should be able to buy product C.

How can I make sure users don't see product C if they don't have the *VIP* role? (It would be best if they could not buy it at all, but I will settle for a solution that simply hides it.) My products are displayed in a view using a *Product display* content type.

# Answer
You should create an additional "VIP ONLY" product display - a node type that aggregates products and effectively shows them in the front-end.

With this new content type you could tap into its permission system using Content Access and limit the "View" permission to the "VIP user role".

When you want to create a VIP product simply create a new "VIP ONLY" node.

Steps:

1. Create a new node type in admin/structure/types . Call it "VIP ONLY".
2. Add a product reference field to the node. Use the existing field. It will now be listed in views that list product display types.
3. Setup the permissions as per above.
4. Profit.
> 3 votes

---
Tags: commerce
---


# Question
Title: Using hook_form_alter on exposed view filters on Drupal 7
I'm having some trouble using `hook_form_alter()` with Views 3 and Drupal 7.

I'm unable to add an if statement to uniquely identify a view; whatever I put in, the if statement is never found to be true. However, I can easily use the form\_id using the following so I'm not sure where I am going wrong!

```
if ($form_id == 'views_exposed_form') {
}

```

How do I use `hook_form_alter()` to uniquely alter a single view of mine?

# Answer
You can get access to the view object within hook\_form\_alter by accessing `$form_state['view']`. That allows you to identify a specific view:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
        }
    }
}

```
> 26 votes

# Answer
What i would do is take it a step back and see if you're even registering this hook. Often `$form_id`'s change.

**Debugging process:**

* Turn on devel
* Insert dsm($form\_id) inside your hook as you used to with D6
* Clear your cache

**Example code** (inside `mymodule.module` or `template.php` file) from drupal.org:

```
<?php
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_views_exposed_form') {
    drupal_set_message("Form ID is : " . $form_id);
  }
}
?>

```

You'll see a bunch of form id's printed out then select your views exposed form hook and work from there.

Also, with drupal 7 you're able to target specific forms by ID directly.

**Example:**

```
<?php
/**
 * Implements hook_form_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
}
?>

```

Note that if you're using multiple exposed forms you can check for a specific view by examining $form\['#id'\] in the form alter function.

Finally, if that doesn't work i would recommend reviewing this issue queue: How to alter filter in exposed filters form trough form\_alter hook
> 19 votes

# Answer
recently I've bumped in this issue too, but I'm using feature module instead of custom one. This helped for me to solve the issue.

```
/**
 * Implements hook_views_api_alter()
 */
function MY_FEATURE_views_api_alter(&$vars) {
  if (isset($vars['MY_FEATURE'])) {
    $vars['MY_FEATURE']['path'] = drupal_get_path('module', 'MY_FEATURE');
  }
}

```

And then You can use your hook\_form\_views\_exposed\_form\_alter() :

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_FEATURE_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'views-exposed-form-search-products-page') {
    $form['price'] = array(
      '#type'    => 'select',
      '#size'    => NULL,
      '#options' => _getPriceOptions(),
    );
  }
}

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: Writing a patch on a sandbox/dev install using a git branch
I'm working with a Sandbox/Dev hosted VM with Drupal 7 and Commons 3. I want to write and perhaps contribute a patch. Having the site under local version control with git, I create a new branch write and test the code.

However, I'm at a loss how to create the patch file between the two branches (master and writing-patch).

Do I switch back the master? How do I compare two branches and properly put that into a patch file with the intention of sharing with a module maintainer? I'd like to do this properly and put as little work on the maintainer as possible.

# Answer
> 0 votes
Go to the module you want to patch and do a:

```
git diff original_branch final_branch > /path/to/file.patch

```

Test it by applying the patch to the initial module:

```
patch -p1 < /path/to/file.patch

```

or

```
git apply --index /path/to/file.patch

```

More info:

http://linux.about.com/od/commands/l/blcmdl1\_patch.htm

https://drupal.org/node/707484

---
Tags: version-control
---


title: User logout on browser / tab close

text:
# Question
Title: User logout on browser / tab close
How to modify Drupal user's cookie so the cookie is not available anymore after a predefined time or when the user close his web browser or close all of the websites pages open in tabs ?

After some online searches i found that by setting the cookie lifetime to 0 should create temporary cookies that would be deleted once the browser is closed:

I first tried by modifing some ini\_set() values in the settings.php :

```
ini_set('session.cookie_lifetime',  0);
ini_set('session.gc_maxlifetime',   0);

```

I created a php.ini file located at the drupal site root, containing:

```
session.cookie_lifetime = 0;

```

But it does not work on my test site. Any ideas?

# Answer
You can change this setting directly in the settings.php. You've a line that looks like that :

`ini_set('session.cookie_lifetime', 2000000);`

Change `2000000` to `0` and you will get what you want.
> 2 votes

# Answer
Since Chrome 22 any extensions or apps that run in the background prevent Chrome from purging session cookies. This is by design, but they admit it's a potential issue and will consider a redesign. https://code.google.com/p/chromium/issues/detail?id=142555
> 2 votes

---
Tags: cookies, users
---


title: Views Data Export field format?

text:
# Question
Title: Views Data Export field format?
I have created data export view. I need to include a date field in this format: Y-m-d (yyyy-mm-dd). I went to 'Date and Time', then added a new format and assigned it to the short format.

In views, I then select the date field, and select 'short' as the format. The new format (Y-m-d) displays in the view preview correctly.

I download the XLS and open it up, but the date field is defaulting to m/d/y (1/10/13). Why would the date appear correctly in the views preview but not in the download? I also verified all the correct formatters are set in the CCK date field settings. If I just show the fields in a plain old table view layout, it is also displayed correctly. the only incorrect format is in the XLS I download.

Please note: If I change the date field to include a 'From date' & 'To Date' and display both To and From dates in one column, the XLS then displays the dates correctly but unfortunately, I can't have these sets of dates in one column. I need them in 2 columns and in the 'Y-m-d' format.

To further troubleshoot, I also tried selecting the same date field in views and only displaying one date per column. One column to display From and the same date field to display To. This also results in m/d/y (1/10/13).

Is this a bug? I can replicate this on my local environment as well. Basically, the custom date formatters are not being portrayed on the export.

I am using:

* Linux CentOS
* PHP 5.3.3
* MySQL 5.1.61
* Drupal 6
* Views 6.x-2.16
* Views Export 6.x-2.0-beta6

# Answer
The date format was being set via the Operating System. OS X's default language and text preferences was re-formatting all dates I type.

With OS X 10.8.3 the preferences are on "System Preferences \>\> Language and Text \>\> Region \>\> Dates \>\> Customize." There, you can enter your preferred date format.
> 1 votes

---
Tags: views, 6, datetime, importing-exporting
---


# Question
Title: How to get the Object based on File ID (FID)
I'm inside mytheme\_image\_formatter($variables) function and I got the image's FID (from $fid = $variables\['item'\]\['fid'\]).

Question: Is there a way to know which object is using the image file?

Using file\_usage\_list(file\_load($fid)), I can see which objects may use the file. But I want to know which one is using the image file, inside my function.

Tried to use mytheme\_preprocess\_image(&$variables), but I also found the same situation.

This is the same problem as discussed here, without a solution.

Thanks

# Answer
> 3 votes
You can use an `EntityFieldQuery`, e.g.

```
$field_name = 'field_something';
$fid = 123;

$query = new \EntityFieldQuery();
$query->entityCondition('node')
  ->propertyCondition('type', 'the_type')
  ->fieldCondition($field_name, 'fid', $fid);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // $nodes contains all nodes that reference the given file via field_something.
}

```

---
Tags: 7, files
---


# Question
Title: Hosting a directory of legacy static HTML files on Drupal
My clients has a folder of static HTML files from 1999. I want to upload the folder to Drupal and then use an iframe to frame it in. I know it sounds awful but that's all he has the budget for. How can I get Drupal to ignore the entire directory and serve up the files "as is"? It is required that the files be hosted on the same domain.

# Answer
> 2 votes
As long as you're using the default rewrite rules you don't need to do anything.

Drupal's .htaccess file contains this:

```
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

So requests for existing files won't be re-written, the file will just be served.

---
Tags: routes
---


title: Form API multiple #validate records

text:
# Question
Title: Form API multiple #validate records
I have an interesting question. There is a custom module that defines form -\> form validate and form submit

I am not allowed to touch this module, still I want to execute another custom action on submit (OR validate).

I have added `$form['#validate'][]='_custom_validator';` in my hook\_form\_alter So the $form array has two functions that validate. And that seems to work, the problem is I have to "copy-paste" the validation code from the other module (the code inside hook\_form\_validate).(To prevent any incorrect form validation). This is considered as a bad design pattern.

Question: Is there somewhere a property that defines the order of the validations ?

Cheers

# Answer
You can use `array_unshift` to make sure your validation is called first:

```
array_unshift($form['#validate'], '_custom_validator');

```
> 4 votes

---
Tags: forms
---


# Question
Title: Creating a rule to display Terms Of Service upon Ubercart checkout
I have a small web store running Ubercart and with one of the items I must display a terms of service agreement. I have it displayed upon checkout as a requirement to proceed. Some of my other items do not need this service agreement to be purchased.

**Question**: Is it possible to set up a rule to display the Terms Of Service up check when only certain items are in the cart?

# Answer
So after a lot of failed methods and frustration I found a solution.

You will need the following modules:

First install the Terms of Service module and set up your terms accordingly. Then install the Ubercart Product Checkout Pane and set the TOS to appear at checkout with the specified product(s).

This allows you to display the terms for each product that requires them.
> 2 votes

---
Tags: ubercart, rules
---


title: High performance DB Cluster with Drupal

text:
# Question
Title: High performance DB Cluster with Drupal
I am looking for a system where I can cluster MySQL. I saw an article which guided me to custom Drupal schema for NDBCluster engine for MySQL clustering, Btw. I am using Drupal 7 with Varnish, memcache etc.

Drupal MySQL NDBCluster High availability

And I also saw another solution for clustering MySQL using Galera Cluster

(MarinaDB and Percona also uses this for Clustering) Scaling Drupal stack with Galera

The reason why I need a cluster is because my fields are over 8 kilobytes There will be a minimum of 15.000 Users visiting the site at the same time.

what is the performance expectations? and what would be the ideal DB to choose?

# Answer
Galera Replication for Drupal

Things you need to watch out for:

1. Caching Sounds like you are using memcached, that good because drupal caching needs to be disabled because if one drupal node modifies the cache stored in the db and that change replicates the other drupal nodes don't know about it creating conditions in which the drupal cache can serve stale content. Most people use memcached for caching to get around this.
2. Deadlocks On websites that are high writes you can incur deadlocks when two drupal nodes try to update the same row at the same time. In this case you would want your app to retry the action but Drupal doesn't always do that. In the Galera settings you can set up some settings in my.cnf (wsrep\_retry\_autocommit=n) to enable retries at the Galera layer to prevent deadlocks being sent to drupal. Although for a website with low writes and mostly reads you may never encounter the issue.

Other than perf testing a realistic workload I don't know of a formula for performance expectation.

For Galera I've used both MariaDB and Percona. Percona does have additional information it can expose for performance and troubleshooting. Not a lot of difference in how they use Galera replication. I've moved innodb databases between percona and maria and had no issues.

I've found a Percona whitepaper on galera performance and best practices for drupal. It seems to cover all the issues I've encountered plus some additional info: http://www.percona.com/files/presentations/percona-live/nyc-2012/PLNY12-galera-cluster-best-practices.pdf

At this time I would use Percona Galera or Maria Galera. I don't touch mysql from Oracle anymore.

hope that helps
> 3 votes

---
Tags: database
---


title: Dynamicly generated block_info?

text:
# Question
Title: Dynamicly generated block_info?
I am writing a module that enables admins to create entities. One of the fields on the entity is a cut-off date.

For each entity within the cut-off date a block is produced. I do this by means of a `EntityFieldQuery` inside `hook_block_info`.

The user can then configure those blocks to appear on certain paths.

This approach seems to be working, but I'm a little unsure:

1. is it safe (i.e. reliable)? I'm unsure how drupal handles all the config for blocks - if the block does not exist any more is its config all deleted?
2. is it an efficiency nightmare? Currently it's only searching a handful of entities for in-date ones, but I'm interested to know if there could be a more efficient way because I guess this will run for every single page load.

Thanks,

# Answer
> 1 votes
RE 1: If the block no longer appears in the hook\_block\_info(), then yes, the block's config will eventually be removed. I'm a little unsure of the timing (clearing cache / cron operation). You can use \_block\_rehash() to force an update of the available blocks.

RE 2: Not a nightmare, no. Keep an eye on your entities to ensure the list doesn't get out of control, but that's all you need to worry about. hook\_block\_info() doesn't get called on every page load, but rather only when:

* the cache is cleared
* the blocks administration page is loaded
* another module calls \_block\_rehash().

---
Tags: 7, blocks
---


# Question
Title: How to alter the title of a views exposed form block with code
The title says it all really. My views exposed form block has no title but I want to add one through code. I have been looking through the api for hours and am totally lost. I have tried tons of things but my drupal and php chops are limited.

# Answer
> 1 votes
```
function hook_block_view_alter(&$data, $block) {
  if ($block->bid == $id) {
    $block->title = $title;
  }
}

```

Where `hook` is the name of your module, `$id` is the numeric ID of the block and `$title` is the desired title.

You can find the ID with the Devel module by putting `dpm($block);` inside the `hook_block_view_alter()` function and then looking at the output for each block to see which one matches. It'll have a `delta` attribute on the `$block` object something like `-exp-your_view_name-display` where `your_view_name` is obviously the name of the view, and `display` is the type of display, e.g. page or block. Or you can just pattern-match the `delta` value instead of selecting by ID, up to you.

---
Tags: views, blocks
---


# Question
Title: Ask user for URL on registration and create feed from the URL on his/her profile page
I know i should be using the Feeds module for this but i want to know how will i turn that particular URL into feed automatically when user enters his feed URL.

Basically i want to let users show their github activity feed on their drupal profiles. URL for it is something like this https://github.com/githubusername.atom So in a feed, the URL still remains standard and if i just ask them to enter their github username and generate the feed accordingly, that would be really amazing. I know how to do it in php but i don't know drupal moduling. It would be great if anyone could help me with it or give me ideas on how to do it.

# Answer
> 0 votes
Since you already know how to do it in PHP, you could use the Panels module. You can then use a Panel to display the user's profile, and you can add a "Custom" field with your php inside.

You could also do something similar by using the Display Suite module and adding a custom code field.

Of course that would require you put php directly into the UI, which isn't always considered the best approach but can be done. To get the user's username, you'd put a field in their profile asking them the user name. That value would then be stored in the $account object.

---
Tags: feeds
---


# Question
Title: Trigger a pop-up or recenter in Openlayers (version 7.x-2.0-beta5) from outsite the map
Is it possible to trigger the pop-up of a marker or center the marker in an Openlayers map through an anchor-tag outside the Openlayers map.

Example:

* Create a view that lists some nodes
* Click on the title of a node
* Recenter the map or open the pop-up of the marker of that node.

I found this solution but they work with an older version of Openlayers and can't get it to work...

# Answer
If you are using the standard popups that come with OL, you can make use of `Drupal.openlayers.popup.popupSelect.clickFeature()`.

The way I did this was to assign an html attribute "nid" to each node in the list of nodes that you are going to use for the click navigation. You can grab the nid from the clicked node any way you like, this is just the way I had done it.

So, now you have your list of nodes with an nid attribute and your map full of markers. Here's one way you can use `Drupal.openlayers.popup.popupSelect.clickFeature()` to open the popup when you click one of the nodes in your list:

Make sure namespace exists:

```
Drupal.settings.nid = Drupal.settings.nid || [];
Drupal.settings.getAllFeature;

```

Make Drupal aware of all layers features:

```
function my_map() {
  var all_layers = Drupal.openlayers.popup.popupSelect.layers;
  for(var key1 in all_layers) {
    var current_layer = all_layers[key1];
    var all_features_in_layer = current_layer.features;
    for(var key2 in all_features_in_layer) {
      var current_feature = all_features_in_layer[key2];
      Drupal.settings.nid[current_feature.attributes.nid] = current_feature;
    }
  }
}

```

Function to grab the map object:

```
function getMap() {
  return jQuery('.openlayers-map').data('openlayers');
}

```

Click function for each node in your list of nodes:

```
jQuery('.eachNodeInYourList').click(function(e) {
  var nid = jQuery(this).attr('nid');
  show_popup(nid);
});

```

Show the popup on the map:

```
function show_popup(nid) {
  if (Drupal.settings.nid) {
    var feature = Drupal.settings.nid[nid];
    Drupal.openlayers.popup.popupSelect.clickFeature(feature);
  }
}

```

Make sure a layer is visible: (get the layer name from the "Title" field on the views overlay)

```
function activate_layer(aLayer) {
  var ol = getMap();
  var layer = ol.openlayers.getLayersByName(aLayer)[0];
  layer.setVisibility(true);
}

```

Initialize:

```
if (jQuery('.openlayers-map').length > 0) {
  my_map();
  activate_layer('myLayer');
}

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Filter criteria not working on new field because data table is not storing data
I have a view based on a content type. I added a new boolean field `Premium` to the content type that I wanted to add to the view as filter criteria. However when I added it I got no results in my view, no matter whether I set its filter value to '1' or '0'.

After doing some investigation, I queried the tables and found that `field_data_field_premium` had no values, while `field_revision_field_premium` was storing values. I tested checking and unchecking the `Premium` checkbox on various nodes. The state of the checkbox was preserved on the node, and I confirmed that data was being stored in the revision table, and still there were no rows in the data table. After checking and unchecking the box and saving several times on a single node, the data only stays in the revision table and rows are never inserted in the data table.

This causes my view not to work, because the query that views creates does a join on the data table, not the revision table. Since there are no rows in the data table, the query returns no rows overall since there is nothing to join to.

Thinking that the field was somehow broken, I deleted it and re-created it, but I am still getting the same behavior of data only being stored in the revision table. For further testing, I created another stock Drupal site, with a content type that has a boolean field. My test site is storing data in both the data and revision table.

What is going on? Is the field screwed up somehow on this site? The content type I'm adding this field to is in a feature -- could that be the source of the problem?

*Edit* I just exported and reverted the feature with my field added, and I still get the same behavior of values, either 1 or 0, only being stored in the field's revision table.

# Answer
Okay, I figured it out. We have the workbench module installed on this site for multi-stage moderation, and the node I was editing was not the published version of the draft :þ
> 0 votes

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


# Question
Title: Having trouble understanding hook_theme()
I'm going through the Drupalize.me tutorials on module development, but I've come across something that has me a little stumped. In the module, called "spy\_glass", we created a basic theme hook like so:

```
function spy_glass_theme() {
  return array(
   'spy_glass_item' => array(
       'arguments' => array('title' => NULL, 'data' => NULL),
       'template' => 'spy-glass-item',
    ),
  );
}

```

Which is all well and good. It eventually gets called by spy\_glass\_page() which uses the theme hook to create to loop through an $information array, which is formed elsewhere and consists of 2 keys: title, and data.

```
function spy_glass_page($node) {
    $information = _spy_glass_serious_spying_business($node);

    $content = array();
    foreach ($information as $item) {
        $content[] = array(
            '#type' => 'markup',
            '#markup' => theme('spy_glass_item', $item),
        );
    }
    return $content;
 }

```

All good. Everything works as expected later when its passed to a spy\_glass\_preprocess\_spy\_glass\_item() function and printed to a template. But here's what I don't understand. What the heck is this line of code doing in spy\_glass\_theme():

```
 'arguments' => array('title' => NULL, 'data' => NULL),

```

I've removed it and it literally changed nothing at all. Everything still works perfectly. What is the purpose of this?

# Answer
> 4 votes
I think this is a typo on your part or Drupalize.me. You should supply a `variables` array that defines the default values of the variables passed to your theme function if the calling function does not supply them. It's not necessary, but seems to be good practice to `NULL` at least `title` and `data`.

From the api:

> variables: (see above) Each array key is the name of the variable, and the value given is used as the default value if the function calling theme() does not supply it. Template implementations receive each array key as a variable in the template file (so they must be legal PHP variable names). Function implementations are passed the variables in a single $variables function argument.

```
function spy_glass_theme() {
  return array(
   'spy_glass_item' => array(
     'variables' => array('title' => NULL, 'data' => NULL),
     'template' => 'spy-glass-item',
    ),
  );
}

```

And then your theme function:

```
function theme_spy_glass_item($variables) {
  $title = $variables['title'];
  $data = $variables['data'];
}

```

Or, if you're using .tpl.php, you simply have access to the variables `$title` and `$data`.

---
Tags: hooks, theming
---


# Question
Title: How to resolve Integrity constraint violation: 1062 Duplicate entry on node_access?
So I am looking all over and have yet to find out how to remedy this table issue.

Rules is the likely culprit because the violation occurs when creating a new node (with Workflow) and trying to have it move forward to a state called publish. It fails with PDO Integrity Constraint Violation 1062.

Now the problem is that NO new nodes can be created without error, by any user. How can I fix this? The error message references a node ID that doesn't exist in any table rows, I guess because the node was never actually saved.

I have adjusted Rules so this doesn't happen again on new nodes, but I need to get that error off without losing data.

The error message is the following one:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry "694-7-workflow\_access" for key "PRIMARY": INSERT INTO {node\_access} (nid, realm, gid, grant\_view, grant\_update, grant\_delete) VALUES ....

This is weird because I have completely truncated the table, deleted and added it back, and tried to build a new copy of the DB all without success. I can't for the life of me find the primary key duplicate in ANY table. These nodes, node revisions, or node access records simply don't exist for nid 694 (or anything above 660 really).

So far I have traced it to Workflow's use of `hook_node_access_records()`. If I comment out `module_invoke('node_' . $op, $node)` the nodes will submit, so it is definitely the access table/process causing the problem. Workflow returns a `$grants` array just fine.

# Answer
For posterity, I did not figure out the line of code that were causing this but the issue is that node\_save was being called *twice* on a new node, which DID create a legitimate duplicate key, but then it would also delete the offending row. This drives the developer bonkers.

It has something to do with Workflow (probably), and I am not particularly proud of this but you can remedy by making one small change to node.module:

```
/* ADDED SPR */
$delete = true; //$op == 'update';
/* END ADDED SPR */

```

Top and bottom lines are for easy searching of code tweaks for upgrades.
> 0 votes

---
Tags: rules, users, workflows
---


# Question
Title: Create a block with a list of all pages tagged with a taxonomy vocabulary
I'm new to drupal, so please be gentle with your answers, and I apologize in advance if this is something I could have found elsewhere, but I've been searching for several hours now...

I'm using Drupal 7.

I want to create a block (based on a view, I am assuming) that will display all of the pages that are tagged with a particular taxonomy vocabulary. Here's what my taxonomy looks like right now:

Main Menu
-Fruit
--Apples
--Oranges
--Bananas

I want a block that displays all the stories tagged with "Apples." I thought this would be easy, but for the life of me I cannot figure out how.

I've been trying to create a view, based on Taxonomy Terms, that filters to "people" but when I set the filter criteria, what I get is the word "apple," which when clicked, leads me to the page that shows all the pages (nodes?) tagged with "apple" I want that in a block format to begin with!

In other words, I want the information on the page that right now I can get to by going to /taxonomy/term/# to display as a block, showing only the title fields in a list. HOW?

Thanks for your help on this. I'm sure I'm missing something simple.

# Answer
> 1 votes
> I want to create a block (based on a view, I am assuming) that will display all of the pages that are tagged with a particular taxonomy vocabulary.

You are absolutely correct that your problem can be solved with a view.

From the way you worded it, though, I sense that you don't understand the difference between nodes and page, and between taxonomy vocabularies and their terms. So let's address that first.

## The difference between nodes and pages

A *node* in Drupal is a single bundle of content. I use the word bundle in the sense that there are multiple pieces of information which all describe the same object. So, for example, the pieces of information "red", "180 horse power", and "manual transmission" could be bundled together to describe a particular car, and then stored as a node in Drupal. Nodes are most commonly used to store information that describes a Web page, which is where the confusion comes from.

A *page* in Drupal is, well, trickier to explain. Drupal, being a CMS, doesn't really deal with pages so much as it deals with programmatic functions which create pages on demand that are then sent to an user's browser. When you click on a menu link (or, more correctly, when you request a URL) in Drupal, you're not asking for a page, you're actually asking to run a particular programmatic pathway in the gigantic, dynamic program that Drupal really is.

So, we'll be talking about nodes from here on out. We want to create a view of nodes, including links to the URLs which cause Drupal to run in a way that returns the "normal" web pages that we expect and use every day.

## The difference between taxonomy vocabularies and taxonomy terms

This is easier to explain. Taxonomy terms are the "words" or "tags" you want to use categorize your nodes. Taxonomy vocabularies are the named containers that we put terms in. So, we could have a taxonomy vocabulary named "Fruit" that contained the terms "Apple", "Tomato", and so on.

## Building your view

OK, so your view is going to list nodes. That means you need to set up your view to show "content". I'd show you a picture right here, but apparently I can only link to one.

Once you've got that, set up your view's filter. You want to add some filter criteria, using the "Content: Has taxonomy term" filter. You'll be asked what vocabulary you want this filter to use, so select the vocabulary that contains the terms you're interested in. You can also pick if you use a dropdown menu or an autocomplete text box for the filter to enter the filter's parameter into. I recommend using the dropdown.

Next, you can choose a logical operator and the taxonomy terms on which to apply it. If you want to show only nodes that are tagged with Apples, then you would choose the "Is one of" operator and select only the Apples term.

And there you go. The view is now showing you all content nodes on your site that are tagged with Apples in the vocabulary that Apples is in. You can finish customizing the rest of the view however you like now.

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


# Question
Title: Recommend nodes based on current node field value in view block
I have made a view block to show on each node for recommending other node of similar interest type.

Every node have a field called **Main Category**, which is taxonomy.

I want to show those node title which has similar category where view block is attached(I mean at node page).

Note - I have attached view block into node by EVA field.

# Answer
There is a module for that: Similar by Terms

However, it's possible with views as well: Creating list of similar nodes in Drupal 7/Views 3

Alternatively, you can use my configuration:

**An example of view block with related nodes based on 'tags'.**

1. Create a block (take a look at screenshots below)
2. Add a relationship: *Taxonomy term: Content using: Tags*
3. Add contextual filter: *(field\_tags) Content: Nid*
**When the filter value is NOT available**
Provide default value -\> Content ID from URL
**MORE**
check: Exclude
*this contextual filter will remove current node from the view*
4. Add contextual filter: *Taxonomy term: Term ID*
**When the filter value is NOT available**
Provide default value -\> Taxonomy term ID from URL
check: Load default filter from term page
check: Load default filter from node page, that's good for related taxonomy blocks
choose the vocabulary (tags in this case)
Multiple-value handling -\> Filter to items that share any term
**When the filter value IS available or a default is provided**
Specify validation criteria -\> Basic validation
**MORE**
check: Allow multiple values
5. Define the fields (only titles in this case)
6. Make the view display only distinct items
**Other -\> Query settings:**
check: Distinct
check: Pure distinct

---

**Screenshots:**
> 4 votes

---
Tags: views, nodes
---


# Question
Title: Is there a Node Reference URL Widget module for entity references?
I just learned that there is the nice Node Reference URL Widget module. Basically, it allows you to add a *add a A* link in the node view pages of content type B, if there is a node reference A-\>B. When you are viewing a B node, clicking on the *add a A* link would lead you to the node creation page of content type A, with the A-\>B field populated with the B node you were just viewing. That way the user do not need to figure out "which node B am I adding this node A to?"

Our sites mainly use Entity Reference. Is there a module that provides similar functionality for entity references?

# Answer
> 2 votes
OK. I see there is Entityreference prepopulate.

> Allow prepopulating any Entity reference field via URL

Going to try it now.

---
Tags: nodes, entities
---


# Question
Title: How can one module's template file be overriden by another module?
I'm trying to use a custom template file within my Features module to handle a Views exposed form, but have been unable to figure out how to do so. I've seen a couple of other questions on here which seem to be the very same class of problem, but who's solutions have not worked for me.

I have been successful in getting both my template file and a preprocess function to take control, but it appears that they completely disable View's own preprocess function, which is necessary for the form to be generated correctly.

Presently, I am creating a theme hook in my custom module:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'views_exposed_form__people__page' => array(
      'base_hook' => 'views_exposed_form', // BTW, am I using this thing right?
      'template' => 'views-exposed-form--people--page', // (hook--view--display)
      'render element' => 'form',
    ),
  );
}

```

I understand that this means my preprocess function will now be called, and I use that to add my template file into the mix:

```
function mymodule_preprocess_views_exposed_form__people__page(&$vars) {
  $vars['theme_hook_suggestions'][] = 'views_exposed_form__people__page';
}

```

This works, but now it looks like View's default preprocessor `template_preprocess_views_exposed_form(&$vars)` in Views' `theme.inc` isn't firing, and that's bad because that function needs to run for this to work properly.

I'm also struggling to understand the rules behind what functions and templates get used when. The system doesn't seem overly complicated, I've just had to piece how it works together from disparate sources. I may be operating under one or more misconceptions here, so let me know if you want to probe what I *think* I'm talking about.

# Answer
Views provides an even easier way to do this via its views\_api() hook:

```
function YOURMODULE_views_api() {
  return array(
    'api' => 3, // most probably 3 by this point in time
    'template path' => drupal_get_path('module', 'YOURMODULE') . '/theme',
  );
}

```

After a cache/theme registry clear, this will incorporate any Views templates found in the `theme` directory of your module (For further reading, multi-year discussion here.)
> 1 votes

# Answer
Rather than outright overriding the theme item implementation (via your hook\_theme()), you could use hook\_theme\_registry\_alter() to add your preprocessing function to the theme item.
> 1 votes

---
Tags: theming
---


# Question
Title: How to use same view.tpl for some taxonomy terms
I have few taxonomy terms (taxonomy/term/1 taxonomy/term/2 ...etc ). Every of that term has a different view.

I want to be able to use the same views-view--\[myview\]--page.tpl.php for more than one view.

The easiest way is just to copy the file and alter the myview name to be the same of the each view.

Is another solution?

I use different taxonomy views because i have a FILTER CRITERIA of Taxonomy term: Parent term (= x) for every one.

Example: taxonomy/term/1 has Taxonomy term: Parent term (= 1) to show all taxonomy terms that is child of taxonomy term 1.

Drupal 7

# Answer
After some try and error and for the hint Jack-PL tell me i figure this out.

I make a new view with taxonomy terms. I set the Field (taxonomy name and taxonomy id) .Contexual filters i set the Taxonomy term: Parent term \>Provide default value\>Taxonomy term id from url.

So know i only have to use Displays \>Add\>Page\>And that did the trick!

Now i can theme with one tpl all the taxonomy pages!
> 1 votes

---
Tags: views
---


# Question
Title: User relationship requests in a view block with accept and decline links
I have a node in which i want to show a user all the relationship requests the current user has received and a status link below that so that the user can accept or decline the request then and there itself without needing to go to the boring Drupal default user relationship page. I am obviously using the user relationship module for this purpose. Anyways, i set out to create a view but after tinkering enough i was unable to do so. What i was able to do was to get a list of all relation requests (also made by the logged in user) I want only the received request. How can i do this? If it helps, here's my view

# Answer
> 2 votes
Add requestee relation. Add context filter by user id (set it on current user with requestee relation). Add filter criteria by relationship status.

Here you can see screenshot of view.

---
Tags: 7, actions, users
---