title: Drush not updating Drupal core

text:
# Question
Title: Drush not updating Drupal core
I've been wrestling with this since yesterday and have reinstalled drush 3 times, rebooted, restarted mysql(mariaDB) and a few other things but nothing works. I'm trying to update my core from 7.14 to 7.32 and really want to do it with drush instead of manually. The only thing I think might be causing this is that I am on Debian and my sites directory is a symlink from **/usr/share/drupal/sites** to **/etc/drupal/7/sites** or that I have drush installed for root only(composer and drush files in **/root**)

When I try and update the core with:

**drush up drupal**

I get back:

**Update information last refreshed: Fri, 10/24/2014 - 15:01**

**Name Installed Version Proposed version Message**

**drupal Unknown Unknown Specified project not found**

**No code updates available.**

Tried clearing my drush cache to no avail and when I check for releases with **drush rl** it manages to successfully lists the 7.32:

**Project Release Date Status**

**drupal 7.x-dev 2014-Oct-19 Development**

**drupal 7.32 2014-Oct-15 Supported, Recommended, Security**

I maintain a few Drupal sites with drush and have never had this problem before but this is my only server with Debian so maybe that has something to do with it. I've read a lot of the threads about issues resembling this going back all the way to 2011 but nothing seems to fix my issue.

If anyone can help then thanks and if not I guess I'll have to manually upgrade the core.

# Answer
> 2 votes
Try `drush pm-refresh`, and then run `drush pm-updatecode` again.

# Answer
> 2 votes
Thanks for all your help greg, turns out that 7.14 provided by Debian has this little line in **modules/update/update.compare.inc**:

**// \*** Debian specific check \*** Debian provides Drupal core updates, no need to check upstream**

**unset($projects\['drupal'\]);**

Commenting out that line fixes updating core with drush. Debian actually provides Drupal 7.14-2+deb7u7 but the only mention of that is here: https://packages.debian.org/wheezy/drupal7

---
Tags: drush
---


# Question
Title: Nivo Slider lists up the images instead of sliding
I download this module with `drush dl nivo_slider` Then enable and automatically download libraries with `drush en nivo_slider` Then clean cache with: `drush cc all` Then enable in block.

Then Firebug said: `TypeError: $(...).nivoSlider is not a function
$('#slider').nivoSlider({`

and chromium said: `Uncaught TypeError: undefined is not a function nivo_slider.js?ne2hej:11Drupal.behaviors.nivoSlider.attach nivo_slider.js?ne2hej:11(anonymous function) drupal.js?ne2hej:76b.extend.each jquery.min.js?v=1.9.1:3Drupal.attachBehaviors drupal.js?ne2hej:74(anonymous function) drupal.js?ne2hej:412c jquery.min.js?v=1.9.1:3p.fireWith jquery.min.js?v=1.9.1:3b.extend.ready jquery.min.js?v=1.9.1:3H jquery.min.js?v=1.9.1:3`

I'm using later version of Drupal 7

# Answer
> 1 votes
I think there's an installation priority issue with Nivo Slider module and Libraries API module or Nivo Slider library files.

Since you installed all required modules and placed Nivo Slider library files in the right location as explained in the installation steps:

> To install Nivo Slider:
>
> 1. Download the latest version of the Nivo Slider jQuery plugin and extract it to *sites/all/libraries* or *sites/sitename/libraries* as you require.
> 2. The extracted folder must be named nivo-slider. Enable Nivo Slider and all of the modules that it requires.
> 3. Configure the jQuery Update module to use jQuery 1.7 or higher.

Now you need to disable Nivo Slider module by running this command `drush pm-disable nivo_slider`, then you need to uninstall Nivo Slider module by running this command `drush pm-uninstall nivo_slider`, then install Nivo Slider again by running this command `drush en nivo_slider`.

Don't forget to clear Drupal cache after you finish uninstalling and installing the module; just in case.

---
Tags: 7, javascript
---


title: Menu links not being translated

text:
# Question
Title: Menu links not being translated
I have installed Drupal 7 and also the internationalization modules. I am able to add a basic site and translate it. I can even opt to add localized url aliases which work fine when switching language. The one thing not working is the menu translation. When translating an article I can choose a different menu name for each language - but only the english version is shown in the menu for all languages.

Anybody has a clue why this could be?

# Answer
Here is what I understand with the current Drupal 7.32. The behaviour of the i18n in Drupal heavily depends on the settings, so I mention the way I am fairly familiar with. If your settings are different, the behaviour can be different.

First, `i18n_menu` must be enabled, as well as `i18n_node` (I understand some people prefer Entity translation, whose behaviour must be different, but I don't know about it).

Second, give "URL" with "Path-prefix" the top priority at `/admin/config/regional/language/configure`. Also, personally I much prefer to explicitly set the path prefix for the default language (usually English, "en") at `/admin/config/regional/language/edit/en`. In default it is Null and that is I found quite confusing due to its inherently asymetric nature. Having said that, it is up to each developer, obviously!

Third, "Translation mode" at `/admin/structure/menu/manage/main-menu/edit` is the key. In default, it is "No multilingual options for menu items". Obviously that is no good for translatable menus. Choose either of the following two options, that is, (1) "Translate and Localize." and (2) "Fixed Language."

I think the second option (2) suits the most sites, unless the menu stractures for all the supported languages in the website are identical. If you choose (2), simply create another menu, say, "Main French Menu", tick the "Fixed Language" as French, and place it in the area you like in the block configuration `/admin/structure/block`

If you choose the first one (1) "Translate and Localize", you then will see "TRANSLATE" tab (near the top) in `/admin/structure/menu/manage/main-menu/edit` (for the main menu, for example) and can now translate each link from the "translate" column (right-most?) at `/admin/structure/menu/manage/main-menu`.

Now, there are more than one option, entirely depending what you want to achieve on the menu. For example, suppose there are a node "Hello" and its French translation node of "Bonjour" (they are two different nodes, say, nodes 1 and 2, respectively). Would you like to provide the two links for both "Hello" and "Bonjour" in the menu (when viewed in either language)? Or, would you like to provide the link for "Hello" for the English mode/readers, and that for "Bonjour" for the French mode? (Such is the complexity of multilingual sites...)

Suppose you prefer the second option. As an example, prepare a single menu link for "Hello/Bonjour" in the main menu; that is, the plan is, "Hello"-menu linked to "Hello"-node(=1) appears if viewed in English, and "Bonjour"-menu linked to "Bonjour"-node(=2) appears if viewed in French.

First you create the "Hello" menu link, linked to node 1. Second, via the above-mentioned "TRANSLATE" tab in `/admin/structure/menu/manage/main-menu/edit`, you input the translated title as "Bonjour", and don't forget to change the link to Node=2 to make "Bonjour"-menu correctly point to the French "Bonjour" article.

Now if you view a different French node ("Au revoir" for example) in French (the path-prefix must be `/fr/`), you will see the menu of "Bonjour", which is linked to the French "Bonjour" node. If you see its English translation ("Good Bye") in English mode (the path-prefix must not be `/fr/`), the menu above is "Hello", which is linked to the English "Hello" node. Job's done.

The thing is, I think it is simpler to set the path-aliases for each content (a single path alias for a set of nodes for all the translations), and basically to give up using the form of node-type links like `/node/2` entirely. In the above-mentioned example, say, suppose you set the path-alias of `artilce/hello` for the node 1 (English; don't set a different path alias for the node 2, French, as it would add a confusion). Now by accessing `/fr/artilce/hello`, you can see the node of "Bonjour" with the French menu. However, if you access `/fr/node/1`, what you will see is the English "Hello"-node(=1), while the menu above is French one "Bonjour". It is because the node=1 is written in English, while you are viewing the content in the French environment, which forces the menu to be in French (if you have enabled localising, other parts like user-menu become also French, but not the main content).

For some people, that may be what they want. For example, a French shopping site may offer an English interface for shopping-basket etc, while they can't be bothered to translate the description of each item to sell. I am guessing that is why the i18n in Drupal is designed like this.

Finally, you may want to "Flush all caches" frequently, while you modify the settings, to make sure any change you have made is reflected to what you see.
> 6 votes

# Answer
I am pretty sure you need to enable the **i18n Menu Translation** sub-module, which is part of the Internationalization module.

Edit the menu, and choose the translation mode you want. I use *Translate and Localize*.

Then, when you edit a menu link, there should be a new tab for **Translate**. From there you can add the translated menu entry. After that, you will see the menu entry. If you can't translate the option, edit the primary node and then re-save it. This will usually force the menu item to have a language assigned.

Afterwards, you can arrange your menu links as you need them. I use parent/child URL aliases based on menu hierarchy, so I make a mirror menu tree.

When you add the menu to a page, only the links for the current language will be shown.

As a side note, Drupal 7 Multilingual Sites is well worth the cost for working on your first multilingual site (assuming you already know Drupal well).
> 5 votes

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


title: Commerce Customizable Products

text:
# Question
Title: Commerce Customizable Products
I hope I could receive some help concerning Commerce Customizable Products. I am looking for a possibility to, when adding a product, selecting the options a customer could add on the 'add to card form'.

For example: Pizza A can have the toppings X, Y and Z. However, Pizza B can only have the toppings Y and Z.

How do I manage, when I add the pizzas to my store, that I can select which supplements can be added? When I have 100 pizza's, I can configure the toppings, but don't have to have 100 different taxonomy lists.

I hope my question is clear. I have watched Josh Miller his screencast on YouTube about customizable orders.

Kind regards, Tim

# Answer
> 0 votes
The only workable solution that I've come up with sits in a feature request in that module's issue queue; I haven't had a chance to try it out yet. Basically, I believe you can use a field on the product type as an options mask for the same field on the line item type. When a field is present on a line item type and shown on the Add to Cart form, its options will typically default to whatever is in the field settings. However, if you put that same field on the product type as a multi-value field, you could then use a form alter of the Add to Cart form to only show the options on the Add to Cart form that were selected for the product.

Again, this is just an idea - not implemented yet. But it seems like a very feasible way to accomplish what you want (and it's based on some architecture I actually helped a community member implement during a cocktail reception at DrupalCon Munich ; ).

---
Tags: commerce
---


# Question
Title: commerce show message if anonymous user adds product to cart
What I am trying to accomplish is :

If an anonymous user adds a product to the cart, I would like to display a message on the site that says : Login to check out

what I did is the following: Added a new rule with the event: After adding product to cart

Condition: Data comparison, Data to compare: site:current-user:roles, The value to compare the data with: anonymous user

Action: Show message on the site : Please Login or Sign Up in order to checkout

but the message still does not show if an anonymous user adds a product to the cart

# Answer
> 0 votes
OK things worked out when I changed the condition to : user has role and passed in the current user as a parameter

I would still love to know where I went wrong in my first approach

# Answer
> 0 votes
I think the condition check of current user has worked out.

But the rule which you have explained is fine.

# Answer
> 0 votes
Why don't you just use Commerce Checkout Redirect?

---
Tags: users, commerce
---


# Question
Title: how to automatically create other entities when creating an entity
I have 4 entity types. All types have a relation to each other. For now let's call them A, B, C and D. How can I allow a user (let's say userA) to create an entity of type A so that entities for B, C and D are also created at the same moment. UserA has the permission to create A entity types and is not the author of the automatically created entities of type B, C and D. Is there a way to automatically create these related entities?

# Answer
> 0 votes
If you were looking for a code solution, you can use hook\_entity\_insert() to trigger the creation of the other entities.

Your custom module code would look something like this:

```
function mymodule_entity_insert($entity, $type) {
  if ($type == 'typeA') {
    // entity type A is being inserted
    global $user;

    // now create type B
    $entity_b = entity_create('type_b', array(
          'uid' => $user->uid,
          'type' => 'type_b', //bundle
          'field_my_field_c' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => 'foo!',
              ),
            ),
          ),
        ))->save();

    // now create type C
    $entity_c = entity_create('type_c', array(
          'uid' => $user->uid,
          'type' => 'type_c', //bundle
          'field_my_field_c' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => 'foo!',
              ),
            ),
          ),
        ))->save();

    // now create type D, etc...
    }
}

```

I've borrowed from the code sample posted in the comment from Mołot and for simplicity sake, I made the author of A to be the same as B, C and D.

One more thing, the entity\_create() function is in the contrib module Entity API. Your custom module would have a dependency on Entity API.

# Answer
> 0 votes
Create 4 content types or your own entities. Create a field for each of the other three entities on the parent entity using the entity reference module. Use the inline entity form module to allow users to create the other three entities directly in the parent entity. Limit it to just one allowed value. If you are also limiting which entity can be created by role then use the field permission module to show/ hide accordingly.

# Answer
> 0 votes
Okay, I've worked it out with Rules and it works like a charm without the need for additional modules or additional php code.

Here's how to:

Step 1: create 1 generic user (fictitious author) for each content type

Step 2: create an empty (or prefilled) node for each of the 3 content types which need to be referenced and set the author to the generic user specific for that entity

Now in Rules create a new rule which acts on the event of creating a node of content type A and then add the following actions

Step 3: add an action: create a new entity for content type B where you set the title of the new entity with replacement patterns (as you like) and where you set the author to be the generic user of that content type B (use the direct input method: uid = "x") and provide a "created entity" variable label and name

Step 4: add an action: save the entity

Step 5: add an action: set the data value of the reference field on the node of content type A to that "created entity"

Repeat steps 3 to 5 for the content type C and D. You'll end up with 3 new nodes which all have a generic author and are immediately tied to the reference fields in the content of type A.

---
Tags: entities
---


title: views contextual filter second variable

text:
# Question
Title: views contextual filter second variable
I have a view that receives two variables like my-view-url/%/%. In a menu I have created a url something like my-view-url/animals/dogs. How do I get the contextual filter to see the second variable dogs and ignore animals.

The contextual filter is set to "Content: Has taxonomy term ID (with depth)" and I convert the taxonomy term to an id.

It think it must have something to depth but I am not sure.

# Answer
This option is available out of the box in view contextual filter settings. You can able to choose input to the contextual filter using checkbox setting "WHEN THE FILTER VALUE is not in the URL". Select Provide default value from URL and choose path component. In your case it is 3. See below screenshot for example.
> 2 votes

---
Tags: views
---


title: Hide tabs on all pages

text:
# Question
Title: Hide tabs on all pages
On every page on my site, there are always these tabs on display:

> News, Events, Grant.

I have been able to hide them on specific pages using CSS Injector however I want to disable these tabs from appearing.

How can I do this?

I have added a screenshot for reference:

# Answer
Are those tabs menu entries? Check the menus you have listed in `structure > menus`. I'm not sure what menu it would be in because it may depend on the theme so click through them all.

Those could also be potentially generated by a View so check entries in `structure > views` as well.
> 0 votes

# Answer
Try the Tab Tammer module

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
> 0 votes

---
Tags: blocks
---


title: How can I use hook_comment_view?

text:
# Question
Title: How can I use hook_comment_view?
I have added a new field to comment table, called "paragraph\_id", I have also added a field to comment form that ask users which paragraph they want to put comment on and what they enter will be saved in "paragraph\_id" field.

So now I want to show the value of "paragraph\_id" in the comments, beside showing the subject and the body of the comment.

There is a hook called "hook\_comment\_view" , and it can be used to add additional data to the comment before theming.

This is the hook:

```
function hook_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->time_ago = time() - $comment->changed;
}

```

I tested this hook by changing it to the following:

```
function Annotations_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->subject= $comment->paragraph_id;
}

```

and instead of subject it showed the data in paragraph\_id field. But how can I add a new field to comment display form, for example called : Comment on Paragraph

and then write this:

```
function Annotations_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->Comment on Paragraph = $comment->paragraph_id;
}

```

# Answer
> 0 votes
First, PHP is case sensitive - don't start your function names with capital letters, it's bad practice, capitals are generally reserved for Classes.

Secondly, if you haven't already, install the devel module, it's really useful.

Then you can look at the structure of the $comment object that is passed to the hook by putting `dpm($comment);` inside your hook. Make sure you give yourself the *permission* to view devel information.

Once you can see the structure of the variable it should make sense what drupal is doing with it. You can add a new element to the form simply by editing the $comment variable:

```
$comment[#myNewElement] = array(
  'property1' => 'value1',
  'property2' => 'value2',
  'property3' => 'value3',
);

```

You can learn about the various form elements and their properties at the Drupal form API.

You will probably need to query the database to get your display value before you set the element.

Happy coding!

---
Tags: hooks, comments
---


# Question
Title: Custom maintenance page breaks module install process
I followed the steps on this page: https://drupal.org/node/195435 to style drupal's maintenance page.

All well until the moment I try installing another module (doesn't matter which one) via an url. It does not install the module and it just shows me my maintenance-page--offline.tpl file (-which should only be shown when the database is offline).

The problem also shows up when installing a new theme. I'm running the latest drupal version (7.23).

Anyone having the same problem? What could I be doing wrong here?

# Answer
> 0 votes
Be sure to add the `$content` variable in the template even though you customized some texts in your template file. A sample would be:

```
<?php if ($content): ?>
<h1><?php print $content; ?></h1>
<?php else: ?>
<h1>Offline due to an unknown issue. Our engineers are working on it 24/7 to resolve this.</h1>
<?php endif; ?>

```

Apparently, Drupal limits/locks access to the database during module/theme install, thus triggering the maintenance-page--offline.tpl.php. Take note that if you don't have the mentioned file, it will trigger maintenance-page.tpl.php.

---
Tags: theming, installation
---


title: SearchAPI & FacetAPI: search box above

text:
# Question
Title: SearchAPI & FacetAPI: search box above
I need to have layout like this:

```
[search box]
[facet - taxonomy 1]
[facet - taxonomy 2]
[search results]

```

But there is no block for the search box itself and no block only for the results. Or can I somehow manipulate it in the template? I'd rather not use JS to move the components around.

# Answer
> 1 votes
You can use a view to display the search results, and exposed filters for the search box. You should set exposed filter of this view as block (in the view settings). Then you can set the form above the search results.

---
Tags: search
---


# Question
Title: Show total count of items on page created by views
What is it right way to show total count on views?

I found this `print count($view->results);`

# Answer
You could add an element on Header, from the interface. CLick "Add" in header section and then add a "Global: Result summary" field.

If you have to do it by code, the right variable should be:

```
$view->total_rows

```
> 1 votes

# Answer
Add this to your theme's template file:

```
function THEME_views_pre_execute(&$view) {
  if ($view->name == "MACHINENAME_OF_VIEW") { // can also check for display if need be
     $view->get_total_rows = TRUE;
  }
}

function THEME_views_post_execute(&$view){
  if ($view->name == "MACHINENAME_OF_VIEW") { // can also check for display if need be
     $view->attachment_before .= <div class="result">$view->total_rows</div>
  }
}

```

The first function enables getting the total rows if you do not have a pager set. The second adds it to attachment\_before. Attachment\_after is also available.
> 0 votes

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


# Question
Title: How to create a theme function for custom HTML markup and then call it in my node template?
Ive created an asses for my site in the content type tpl file. Its mainly HTML but also some simple PHP. What are the steps to move this to a theme function?

# Answer
> 0 votes
You should be able to use the template\_preprocess\_node function to move your logic from your tpl files into the theme function. In order to use the function, replace template with the name of your theme.

```
function mytheme_preprocess_node(&variables){
  if($variables['node']->type == 'my_content_type'){
    //change what you want to the node here.
  }
}

```

You could do the logic you need to inside this functionn, save the output to a variable in $variable (it's a reference var, so it dosn't need to be returned) and then just print out that variable in your tpl.php file.

# Answer
> 0 votes
Why not just put what you need in a regular PHP file in your theme directory. In the tpl file just do a PHP include call.

```
<?php include("your_html.php"); ?>

```

# Answer
> 0 votes
In template.php:

```
THEMENAME_theme() {
    $themes = array (
        'THEMENAME_FEATURENAME' => array(
            'template' => 'templates/TPL-FILE-NAME',
            'arguments' => array('id' => null),
        ),
    );
    return $themes;
}

```

In content type tpl file:

```
<?php print theme('THEMENAME_FEATURE'); ?>

```

In my templates folder is TPL-FILE-NAME.tpl.php

This does pull in HTML from the tpl.php file however PHP such as `<?php print $title; ?>` and `<?php print $GLOBALS['$base_url'] . $node_url ?>` no long work (they did when they were in the content type tpl file).

Also a paid video here: https://drupalize.me/videos/strategies-keeping-template-files-clean?p=1146

---
Tags: theming
---


title: Exposed filter slider for numbers

text:
# Question
Title: Exposed filter slider for numbers
I am creating real estate website and as exposed filter for search in views i have a price.

Core view options are sufficient but maybe not so user friendly (as i have to explain in details how to input price, like dont use dots or spaces) so i was thinking of using slider so user can pick price range (for example from 10.000 up to 100.000).

I am not good at coding so was looking for module that does this ?

# Answer
> 8 votes
There is also the Better Exposed Filters module.

If you use the latest dev version there is support for jQuery UI slider, which was recently committed from a patch at http://drupal.org/node/1627524

It allows the use of a jQuery UI slider for any numeric filter (except date filters, which are technically an extension of the numeric filter).

# Answer
> 4 votes
Select With Style

> When the widget is used as a filter (e.g. in combination with Views Global Filter) the slider becomes a range slider with two sliding handles to set "from" and "to" range values.

Contextual Range Filter

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter, not just by a single value, but also by range.
>
> Numeric (float, integer), alphabetical (string) and list ranges are all supported.
>
> Node ids, user ids and even taxonomy term ids are all special cases of integers so will work also.
>
> You may use the OR (+) and negate operators. You negate by ticking the "Exclude" box on the Views Contextual filter configuration panel, in the "More" section.

# Answer
> 1 votes
If you work with Search API, you can easily use module Search API Ranges.

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


# Question
Title: How to drop all MySQL tables using drush?
Normally I could drop and create database from scratch, but what if user doesn't have permission to do that?

Also I wouldn't like to specify my credentials in the command-line (1. it's hard to type, especially complex passwords, 2. it's not safe as it get stored in shell history files and on the process list).

Therefore how I can drop all tables using drush?

---

Related:

# Answer
> 27 votes
It seems there is a single drush command to Drop all tables in a given database. Just run:

```
$ drush sql-drop

```

---
Tags: drush
---


# Question
Title: Checking if a field is empty fails, on a node template file
Trying to use `empty()` on a "longtext" field in a custom node template, the field is always reported not to be empty (whatever the field is empty or not).

```
<?php if (!empty($content['field_myfield'])): ?>
  <p>additional content</p>
  <?php print render($content['field_landing_petition']);?>
<?php endif; ?>

```

Why doesn't it work? How else could I test for empty fields in the template file for a node?

# Answer
> 3 votes
`$content['field_myfield']` is an array containing some keys; if you pass that array to `empty()`, you would not get back `TRUE` as result.
For example, I added a three fields to a content type (their types are "taxonomy term reference," "decimal," and "list of float values"); what you see in `content['field_name']` is the following:

`$content['field_name']['#items']` contains the content of the field; it's an array, as in Drupal 7 fields can contain multiple values.

The generic code that allows to check if the field is empty, which works for any field, without to know details about how the field values are stored, is similar to the following one:

```
// $field_name contains the name of the field.

$field = file_info_field($field_name);
$function = $field['module'] . '_field_is_empty';

foreach ((array) $content[$field_name]['#items'] as $item) {
  if (!$function($item, $field)) {
    $result = TRUE;
  }
}

$is_empty = empty($result);

```

`$is_empty` is equal to `TRUE` when all the items of the field are empty, giving to *empty* the meaning given to the word from the module implementing the field. For example, the module could consider the field empty when its value is "none" or any similar value (e.g. "empty" or "`<none>`").

# Answer
> 0 votes
To improve kiamlaluno's answer - the really robust code to check if field is empty (in custom form validation) need to take care of languages as well:

```
$field = field_info_field('field_file'); // for example
$available_languages = field_available_languages($entity_type, $field);
$languages = _field_language_suggestion($available_languages, $options['language'], $key);
$valid = true;
foreach ($languages as $langcode) {
    if ($is_valid = my_validate_function($key, $field[$langcode])) {
        $valid = $valid && $is_valid;
    }
}
if ($valid) {
    // all lang fields are valid
}

```

---
Tags: 7, entities
---


# Question
Title: Webform - User to edit submission (admin can close)
I have a webform that a authenticated user can submit. Where is the page for the authenticated user to re-edited their submission? I can't find it?

I also want to extend a another function. I want to have the ability to close a submission (so the authenticated user) can't re-edit it anymore.

Any suggestions?

Thank you,

# Answer
> 1 votes
You have to view your submission and click on edit to update. Remember you can only edit your own submission.

---
Tags: webforms
---


# Question
Title: Using hook_query_TAG_alter to add 'OR' queries to EntityFieldQuery
I need to use the OR operator on an EntityFieldQuery which I understand can only be accomplished via addTag and hook\_query\_TAG\_alter.

My query at present:

```
$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_pub_year', 'value', $year, '=');
if(isset($_GET['country_id'])){
    $country = $_GET['country_id'];
    $query->fieldCondition('field_related_country', 'target_id', $country, '=');
}
if(isset($keywords)){
    $query->addTag('search');
}
$result = $query->execute();

```

Without much more than a rudimentary knowledge of Drupal, I would expect that the following function, inserted into my template, might work:

```
function hook_query_search_alter(QueryAlterableInterface $query){
    $or = db_or()
      ->fieldCondition('title', 'value','%'. $keywords .'%', 'LIKE')
      ->fieldCondition('body', 'value','%'. $keywords .'%', 'LIKE');
    $query->condition($or);
}

```

Yet, it seems to do nothing...

I'm having equal luck googling this problem. Appreciate any suggestions. Thanks.

Update:

I moved the alter function into a module and re-wrote it to look like:

```
function modulename_query_search_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $or = db_or()->condition('body', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->condition($or);
}

```

but I now get an `unknown column body` error. Removing that condition works correctly and results are filtered by title field. Not sure what the deal is with that...

# Answer
Solution to using 'OR' queries with EntityFieldQuery:

The query, note the addTag() and addMetaData():

```
$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1);
if(isset($keywords)){
    $query->addTag('search');
    $query->addMetaData('terms', $keywords);
}
$result = $query->execute();
if(isset($result['node'])){
    $nids = array_keys($result['node']);
} else {
    $nids = array();
}
$news = node_load_multiple($nids);

```

Then, within a module or something, the hook\_query\_TAG\_alter looks like:

```
function MODULENAME_query_TAGNAME_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $query->leftJoin('field_data_field_subtitle', 's', 'node.nid = s.entity_id');
    $or = db_or()->condition('s.field_subtitle_value', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->leftJoin('field_data_body', 'b', 'node.nid = b.entity_id');
    $or->condition('b.body_value', $words, 'LIKE');
    $query->condition($or);
}

```

Above example shows how to join custom field tables and query them using 'OR' along with title and body fields.
> 6 votes

# Answer
You want `hook_entity_query_alter`, your function signature is broken.

Also it's considered bad practice to use `$_GET` directly.
> 0 votes

---
Tags: database
---


# Question
Title: Commerce Products Display Page Using Views
The usual way to display Commerce products is

**1. Create Products using Commerce Module Interface**

**2. Create a Content Type for Products Line Items by referencing the products**

But I have too many different products... should I have to create contents after adding each commerce Products??

**I used two views for each products one to create a products listing and other for product display page using contextual filters and by passing the Product ID**

Product Listing Page path : /products-list

Product Display Page : /products/product1

By passing the product ID via URL.

Is this a write way to do it... Or is there anything efficient and meaningful than this method?

# Answer
You can use this module "https://www.drupal.org/project/commerce\_auto\_product\_display". then you can use Views to show the product display nodes.
> 1 votes

---
Tags: commerce, views
---


title: How is this themed when using views

text:
# Question
Title: How is this themed when using views
I have a single page template...there are 5 sections, each powered by a view bound to a single content type.

The first section has a dark blue background, the second green, third red, etc...

each section renders it's "rows" differently...first section might have the header as and the body wrapped as

. Ther second might have alternating left and right aligned images.

This visual layout that is so common today is quite difficult to accomplish (if not impossible?) using default drupal template suggestions.

What I have basically had to do is iterate $view-\>result inside views-view--block.tpl.php and render each section individually this way to achieve the desired effect...

Is there a different/alternative way of themeing views to match the markup provided by someone else?

Not sure if this question is appropriate here (borderline I am sure) however I am not sure where else to ask or look.

Alex

# Answer
> 1 votes
In static markup normally one has row level classes, element level classes and wrapper classes. By looking into those classes add exactly the same classes into your views interface, or override default template and add your markup and then render your block in appropriate region

---
Tags: views, theming
---


title: Programatically create a new role

text:
# Question
Title: Programatically create a new role
I am trying to create a module which will easily allow me to set up basic sites with specific settings on the fly for a project I'm working on. I am having trouble creating a new user role. I have tried the following code within `hook_update_N()`, but it doesn't seem to work.

```
$role = new stdClass(); // create your Class
$role->name = 'editor';
user_role_save($role);

```

How do I programatically create a new role?

# Answer
> 9 votes
```
$roles = array('role1','role2','role3');
foreach($roles as $name) {
 $existing_role = user_role_load_by_name($name);
 if (empty($existing_role)) {
  $role = new stdClass();
  $role->name = $name;
  user_role_save($role);
 }
}

```

I have placed the same snippet in module install file and it is working just fine. You need to enable and then uninstall the module and re-enable it, I hope it will work.

---
Tags: 7, users
---


# Question
Title: Error message when deleting folders/files on Maintenance mode
I turn the site in maintenance mode for update Drupal Core from 7.30 to 7.32. I follow the step on Drupal docmentation to delete all folders and files, beside "site" folder(on step 5). However, I got the error message and warning about missing files. I dont think that how maintenace mode should be. What am i missing?

PS:
1. the site does show in maintenance mode before I delete all the folders and files(beside site folder)
2. Site back to normal after copying v7.32 folders and files(beside site folder)

# Answer
Rather than the two step deleting the folders and then uploading the new ones, I would recommend just copying over the old ones with new ones. You'll probably have to tell your FTP program to overwrite but when I upgrade in this fashion, I select all the files and directories **except for sites folder** and push them to the server.

When possible, I use the Drush tool via a terminal window as it is a much quicker and easier solution.
> 2 votes

---
Tags: files, maintenance-mode
---


# Question
Title: Drupal 7 Internationalization - why are my admin menus still in English?
I'm trying to make a fully bilingual website that will be administered by French and English users.

I've installed the internationalization module and all its dependencies and the localization update module, which claims to have installed French language support. I've successfully got all the front-end content, menus and views translated and language switching working, but no matter what I do, the admin menus remain in English. It doesn't matter whether I change my default language in the user preferences or set the site to French with a url parameter, I can't get the admin menus to change language. Many of the tutorials I've seen online seem to gloss over this as though it happens automatically.

Is it possible to display Dashboard, Content, Structure...etc in French as well as the default English or am I going nuts?

# Answer
> 3 votes
If you swap from french to English the admin menu should also switch from french to English (Drupal 7).

In the tag "detection and selection" of Admin/Configuration/Regional and language/Languages" click the "Default" checkbox in order to use the default site language.

The "Localization update" module also helps you keep your interface translations for core and contributed modules up-to-date :

1. Enable the Locale (core) module
2. Download and enable the "Localization update" module
3. Go to the configuration page at admin/config/regional and language/translate interface/update
4. Wait as the module looks for translation updates
5. Click Refresh information button at the bottom of the page
6. Wait as the module gets all translations
7. Disable the Localization update module when finished to improve site performance.

# Answer
> 1 votes
Did you enable the sub-module menu translation of internationalization (if yes) go to your menu and click on translate. If not go ahead and enable it. It will work

---
Tags: i18n-l10n
---


# Question
Title: Select fields in multiple tables / change output value / compare fields
i want compare (=) two fields in two tables. In the first field, i have only a nid (e.g. 55) and in the second field, the value is formatted with "node/%" (e.g. node/55).

How can I created the join query for compare these two fields ?

I have tested this with this code without success :

```
$uid = arg(1);
$query = db_select('field_data_field_users', 'alias1');
$query
    ->condition('user_id', $uid, '=')
    //->addExpression('node/(fdfur.entity_id)', 'alias2'); // > not functionnal
$query->join('menu_links', 'ml', 'ml.link_path = alias1.entity_id');
// ml.link_path = alias1.entity_id > node/55 = 55 > no match...
$query
    ->fields('alias1', array('entity_id'))
    ->fields('ml' , array('language'))
    ->fields('ml' , array('link_path'))
$results = $query->execute();

```

Here an image that explains my problem

I start from the user id and I want to get the datas of the menu links. The first db\_select in the custom table is ok, i get the related nids with the user ids, but I can't to get the datas of the menu link.

Have you any idea to resolve my problem ?

Thanks for your help.

# Answer
> 0 votes
I suspect this is what you are looking for

```
db_query("SELECT * FROM node LEFT JOIN url_alias ON url_alias.alias=concat('node/',node.nid)");

```

---
Tags: database
---


title: Migration from Joomla

text:
# Question
Title: Migration from Joomla
I am going to start work on a website that is already developed in Joomla 1.5 What are the possible ways to migrate the contents from Joomla.

PS: I have looked into joomla module but no luck!

Any ideas will highly be appreciated!

# Answer
I've used Feeds and Menu Export/Import to migrate Joomla sites to Drupal a few times. It's a little tedious but it works.

I think the next time I have to migrate Joomla site to Drupal I will use the Joomla to Drupal module. It doesn't appear to be regularly updated but looks like it should work for Joomla 1.5 and less. I don't think it will be useful for Joomla 2.x and up though.
> 8 votes

# Answer
You can use Migrate module which provides a flexible framework for migrating content into Drupal.

There is one GitHub project available at piyuesh23/joomla\_drupal which has already some Drupal classes to migrate Joomla into Drupal.

For more technical details, check Joomla related Issues for Migrate or example code of migrating images, setting url, alt, title in prepareRow.

---

If you'd like to avoid coding classes, alternatively check Joomla to Drupal module or XJoomla at GitHub.
> 6 votes

---
Tags: 7, feeds, migrations
---


# Question
Title: Accessing text of a field with type "Text"
I fear that my question could be covered in detail already somewhere, but I did not find something useful. So appologies if this is the case.

I added a field of type "Text" to content type "Article". Now, I want to access the string of this field.

I want to access this in file template.php of the theme I use. To be precise, I want it to access in function "tb\_corpal\_preprocess\_page". (File from themebrain theme "tb\_corpal".)

I can see that in another function the "field\_image" is accessed like this:

```
if(isset($vars['content']['field_image']))

```

If I now want to extract my field\_banner, which is a field of type "Text", how do I do that? I guess it should also be stored in $vars, right? If yes, how do I access the string?

# Answer
start by downloading the devel module.

> A suite of modules containing fun for module developers and themers ...
>
> Devel
>
> Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries). Also a dprint\_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug\_backtrace() is offerred. much more.

This includes a function dpm() which allows you to navigate through complex variables including $vars. dpm($vars) will create a user interface for navigating through it - then you can find the specific location for the field you want.

I included this as an answer instead of the presumed actual location of the field within $vars since this allows you future access to any variables you need. You can use this for example to go through a $form, $content, etc.
> 1 votes

---
Tags: entities
---


title: Drupal, menu links multilanguage

text:
# Question
Title: Drupal, menu links multilanguage
I'm translating the site with my custom theme to another language. The problem is in menu links. On the original language they are fine, but with another one they are looks like "node/id". I've tried drupal\_lookup\_path with and without language, drupal\_get\_normal\_path, drupal\_get\_path\_alias but links are still the same.

I'm feeling like i've missed something in preference, but have no idea how to make links looks properly.

some code from my draw\_menu function:

```
$items = get_menu_weight($menuName, $language->language);
foreach($items as $item) {
   $alias = drupal_lookup_path('alias',$item->link_path,$item->language);

```

...

```
    if ($item->link_path == "http://"){
    $drawItems .= '<li><i>'.$item->link_title.'</i>';
   }else{
    if($alias == "/"){
        $drawItems .= '<li><a href="http://'.$_SERVER['HTTP_HOST'].'/" title="'.$item->link_title.'">'.$item->link_title.'</a>';
    }else{
        $drawItems .= '<li><a href="http://'.$_SERVER['HTTP_HOST'].'/'.$alias.'" title="'.$item->link_title.'">'.$item->link_title.'</a>';
    }
   }

```

...

```
}

```

Thank you for your advises.

# Answer
I don't know what `get_menu_weight()` returns (it is not in the standard Drupal API, is it?), so the following is the answer for a general case in Drupal 7.

In short, **as long as** the menu item is linked to a node, and **if** the node has at least one translation, the following code should work to get a path-alias of the node for all the translatable languages:

```
$hstpath = translation_path_get_translations('node/123');
array_walk($hstpath, function(&$v, $k){$v = drupal_get_path_alias($v,$k);});

```

gives an associated aray like:

```
Array(
  [en] => info/basic.html
  [fr] => info/basic.html
)

```

where both English (en) and French (fr) versions have the same path-alias of `info/basic.html`.

How to convert this path-string to a link to the node to view in the desired language depends on both your language-detection configuration and with which language environment you would like to display the node.

For example, if the URL with the path-alias is given the highest priority, then add the prefix of `/fr/` to the French node (as long as French is not configured to be the default language with no path-prefix defined). In addition, you may need to add `base_path()` at the head, if Drupal is not installed in the top directory of the website.

For a reference, a candidate answer to "Menu links not being translated" explains some basic for the Drupal menu with i18n.
> 0 votes

# Answer
The menu links are being shown without the URL alias because you are displaying them in a language which is not the language of the content. The alias is per-language, therefore it falls back to node/123.

One workaround would be to set the node as "language neutral" (the option must be enabled in your content-type settings). Then you can use a menu block or other Drupal methods to display the menu items without extra code.

Looking around, the only solution I found in order to have language-neutral aliases for language-specific content is this blog post.

If I understand correctly, the author proposes the following snippet in a custom module:

```
function mymodule_path_update($path) {
  db_update('url_alias')->fields(array('alias' => $path['alias'], 'language' => LANGUAGE_NONE))->condition('pid', $path['pid'])->execute();
}

```

This automatically sets the alias to language-neutral, but does so for all aliases. So if you have some aliases that do have translations, it's not optimal (for example, on a French+English website, the /contact alias can point to different nodes). I would modify that snippet to make it check if there are any translations already existing for the given node, if not, set as language-neutral. Also needs to check when creating a new translation, to remove the language-neutral alias.
> 0 votes

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


title: 7Random ASCII chars in footer?

text:
# Question
Title: 7Random ASCII chars in footer?
goes away when I clear the cache but comes back as soon as I visit another page.

* new standard installation (drupal 7.32)
* lighttpd + php 5.4 (fpm)
* mariadb

# Answer
> 0 votes
this looks like a `collation` issue in your database tables. Perhaps you copy and pasted some text from a Word file or other file that had a weird character set encoding and when it was saved to the database the proper text was lost in the transition.

I recommend looking at where the text in your footer is coming from originally, a foreign webpage, an MS Word file, an XML file -- and what encoding it has.

Then I would recommend you look at the Collation Fixer module which is designed to *help* with this issue. It will properly set your set tables to 1 Collation -- you must then provide the correct text/prose/verbiage into your footer so that its in the same character set the database expects.

> A 'runtime' requirements checker (admin/reports/status) for checking all database tables have the right database collation (probably very MySQL centric).
>
> Offers the ability to fix tables with wrong database collation.
>
> The collation is either specified in your database settings or in hook\_schema() or hook\_schema\_alter().
>
> This can be useful when developing non-english sites.
>
> Example of specifying in database settings in settings.php (will affect all tables - it's probably better to do it in hook\_schema() or hook\_schema\_alter()):

```
<?php
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'my-db',
      'username' => 'my-user',
      'password' => 'my-password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'collation' => 'utf8_danish_ci',
    ),
  ),
);
?>

```

---
Tags: 7
---


# Question
Title: How to create a single slideshow combining several image fields?
I have 3 image fields in a content type: img1,img2 and img3. img3 is multi valued while the rest are single valued, and I'd like to create a single slideshow containing img1, img2 and img3 to be showed on every node of that content type.

I tried using views slideshow with as block with contextual filters and managed to select images from a node correctly, but they weren't displayed properly as a slideshow.

The reason I'm not simply using one image field to make things easier is that I'm using the Custom Formatters module and I have problems with using just one field with that module:

Custom formatter for a multi-valued field

# Answer
```
  <?php if ( ($image_slide == 'true') ): ?>
        <div class="image-post-slider">
              <ul>
                <?php while ($img_count < $counter) { ?>
                  <li>
                          <div class="preloader">
                                <a class="bwWrapper single-image link-icon" href="<?php print $node_url; ?>">
                                    <img src="<?php echo file_create_url($node->field_image['und'][$img_count]['uri']); ?>" alt="" >
                                </a>
                            </div>
                  </li>
                  <?php $img_count++; } ?>
              </ul>
        </div>
        <?php endif; ?>

```

Put something like above snippet in your node.tpl.php This will create links of images and their links if any. Then apply normal css/js to make it in slideshow
> 1 votes

# Answer
Try the Jcarousel module.

> This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

Image from project page

If you want to add additional features have a look at Views Slideshow JCarousel

> Integrates JCarousel features into views slideshow version 6.x-3.x or 7.x. Currently provides a JCarousel pager widget.
> 0 votes

---
Tags: 7, media, views
---


# Question
Title: Automatically add taxonomy term based on state
Suppose I have a shopping website for a number of shops selling toys. Not each shop sells each toy.

Our solution is that there is a taxonomy 'shops' and toys have a field to assign toys to a particular shop (or multiple shops). This works ok, but has two major flaws:

* I dont want shop owner A to be able to change whether shop B sells a particular toy (they are competitors)
* I dont want shop owners to have to select their shop each time when they add a toy.

So what I want is that upon login, the shop owner gets assigned a particular shop. When adding toys, this shop is automatically being added to the toy's "shops" field.

Furthermore, the site administrator should be able to select a shop upon login, and then see only stuff belonging to that shop.

How to achieve this without writing my own module?

# Answer
some Drupals core features will deal with parts of this for you.

You can set up a Role and set boolean permissions for

'Create own value for' 'Edit own value for field' 'Edit anyone's value for' 'View own value for ' 'View anyone's value for

on fields of nodes/entities.

However with a project of this size you should expect to have to get your hands dirty and write code at some point ! IMHO
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Basic Multiple Image Upload to replace standard image uploader
First question on Drupal Answers, hi everyone. Starting off with a very basic question actually:

While the standard single image at a time uploader is swell and all, I've got the Galleria module installed, and we have hundreds of photos to upload across multiple albums, and a ton more to come along in The near future. Quite simply is there an existing package/mod that can transform that single image uploader into a multiple image uploader, One where you can select multiple images in the browse window?

# Answer
The best multiple image uploader that I have found is http://drupal.org/project/plupload (example widget is on their website)

Also if you are working with images and are using drupal 7, you may also wish to check out http://drupal.org/project/media \- this modules is looking more and more promising, and now has views integration as well. It also works with the above recommended plupload module)
> 1 votes

# Answer
Plupload does not work on its own. I suggest using a combination of Multiupload Filefield Widget and Multiupload Imagefield Widget. This is as close to the core as possible. It will allow you to hold `Ctrl` \+ select files, to upload multiple files.

Once the modules are installed, simply change the Widget Type of the image field to Multiupload.
> 1 votes

# Answer
You may try File Resumable Upload:

**File Resumable Upload** aka **file\_resup** adds large files multiple and resumable upload to the File and Image field widgets.
> 1 votes

---
Tags: media
---


# Question
Title: File in field_file disappears after saving a node
Like I wrote in the title. After I upload the file it is being saved in my folder correctly, but after I save the node, it just doesn't remember I have uploaded it. The file stays in the folder I uploaded it to.

Is there any way to solve it?

# Answer
> 1 votes
The File module enables you to upload and attach files to content and to manage these uploads if you have the appropriate permissions. This module is responsible for validating file content and managing uploaded files. It also provides options for displaying file content.

As a site administrator you will be able to control what type of files can be uploaded and their maximum size.

File module provides its functionality by defining a File field type for the Field module. File attachments are defined at the content type level (or other entities). To learn how to define a field and add it to a content type, see Working with Field UI.

Uses Adding a file field to a content type

Navigate to the "Manage fields" tab of the content type to which you wish to add the file field (Administer \> Structure \> Content types, and the link manage fields for your specific content type).

Select the field type file, give the field a label and machine name, click-and-drag it to the place you want to have it among your fields, and hit the save button.

As when adding any new field, you are first required to set the field specific settings. These apply for all places where you use the field. These cannot be changed per entity.

When checked, the Enable Display field option allows users to choose if a file should be shown when viewing the content. The Files displayed by default option makes the display file option checked by default, when users upload files to this field. The Upload destination by default only has the public files option available – making the files available right from the server (without Drupal checking any access). If you want to use private files, you must first change some settings at the file system administration page (Administer \> Configuration \> Media: File system). See below for details.

The next step is to set the field settings for this instance only. This can be changed between different content types (or other entities).

You can add validation options for the File field when you configure the content type. You must list all of the file extensions that the final user will need to be able to upload. The optional file directory where the files will be uploaded is a sub-directory of the file system path defined in the file system administration page (Administer \> Configuration \> Media: File system). You may specify a maximum file size for each file uploaded.

Managing attachment display

Once a file has been attached to content, you can specify whether it will be displayed in the list of attached files or not. Listed files are displayed automatically in a section at the bottom of the content; non-listed files can for example be embedded in your content, but are not included in the list. (Embedding a file in your content means you copy the path of the file and manually embed it where you want, for example, to insert in the content as a link tag. Note that the text format "Filtered HTML" by default refuses any image tags..)

Additional options for managing the display of the file list are available in the "Manage display" tab of the specific content type's administration page (Administer \> Structure \> Content types and the link field display for your content type).

For reference: Working with files in Drupal

---
Tags: entities
---


title: Override html.tpl.php per node type

text:
# Question
Title: Override html.tpl.php per node type
In my template.php file for my theme I have tried the following:

```
function media_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']))
  {
      // If the node type is "blog" the template suggestion will be "html--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'html__'.$vars['node']->type;

      // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->type;

      // If the node id is "33" the template suggestion will be "page--33.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->nid;
  }

    //Create page suggestion for first part of url-alias
    $url_alias = drupal_get_path_alias($_GET['q']);
    $parts = explode('/', $url_alias);

    $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__alias';
}

```

This works for page--nodetype.tpl.php, but not for html--nodetype.tpl.php

You may be asking why do you need to override the html.tpl.php template per node type. It is because there is markup that I don't want to include for this particular node.

# Answer
> 29 votes
The name of a preprocess function is based on the theme/template that is being processed. To preprocess the html.tpl.php file you'll need to use `hook_preprocess_html()`:

```
function media_preprocess_html(&$vars) {
  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }
}

```

# Answer
> 4 votes
@Clive approach is very smart.

Also do note when in html.tpl.php file, you can read the content type you are dealing with from `$variables['classes']`, which will give you something like `html not-front not-logged-in no-sidebars page-node page-node- page-node-5638 node-type-CONTENT-TYPE-NAME`

With that, you can change how html.tpl.php file is behaving with this:

```
if (strpos($variables['classes'],'node-type-YOUR-CONTENT-TYPE') == true ) {
  echo 'Do something special  for YOUR-CONTENT-TYPE ';
}

```

---
Tags: 7, theming
---


title: Searchable civiEvents in drupal7

text:
# Question
Title: Searchable civiEvents in drupal7
I have a site that is running on drupal 7 and uses civicrm 4.4.1. I need the events to be included in the search results.

So far all I have found was dated documentation on civicrm that required modules that are not available for Drupal 7.

I also tried the search page module and it is not grabbing the events.

# Answer
> 4 votes
I would use the CiviCRM views integration to create views of the events, and ensure that these are searchable by using the Search by Page module which according to the project page "allows you to index non-Node pages, including user profiles, file attachments, and Views".

---
Tags: search, civicrm
---


# Question
Title: How to add reCaptcha while doing comments on my drupal website
I am developing a drupal website. To avoid spam I have decided to use reCAPTCHA module while user registration and before putting comments on my website.

How to achieve this? Can I use reCaptcha while submitting comments?

# Answer
Thank you all, Its done. Procedure as follows :

I have downloaded 2 modules CAPTCHA & reCaptcha.

Then extract them into **/var/www/site/modules/** .

Then I have restart my web server. Then goto browser.

Next I have found CAPTCHA and reCaptcha options on **modules** section.

Then I configured CAPTCHA settings in configuration section according to my requirement.

Thats it !! When I try to do comment on my website it was given me captcha challenge This is what all i need.

Thanks!! :)
> 1 votes

# Answer
Just download & install reCaptcha module.

Goto Configuration setting & configure it.

Or you can use these modules also. I think this may help you.

1. Honeypot : They kill 99% of spam.
2. Mollom
> 0 votes

---
Tags: comments, captcha
---


title: adsense code does not work

text:
# Question
Title: adsense code does not work
I have put the following code from adsense in a block with full html filter.

```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newad -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-4076687304826472"
     data-ad-slot="1906412748"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

```

I don't see ads. The message comes with style :"display etc.. and some ads in very unformatted fashion.

Is there some other way to put adsense code in Drupal 7?

# Answer
> 2 votes
full html isn't always enough to provide the necessary access. go to /admin/config/content/formats and create a new format (I call mine 'Unaltered') with the following setup (make sure to restrict it to admin ONLY):

This will allow you to perform inline js, etc within a block, without requiring a new module. Also, make sure the style listed in the js you include matches the size of the block (or more accurately, that the block matches the size of ad you want to show), or you will have strange layouts where the ad doesn't fit the container.

# Answer
> 0 votes
As usual, there is AdSense module developed to take care of it.

> This module provides web content providers with the means to earn revenue from visitors by displaying ads from Google AdSense™ advertising service on their sites.
>
> Why should you use it:
>
> * The module provides easy-to-use ad blocks.
> * Provides simple controls for troubleshooting the ads before going live with the site.

*List trimmed by me, of course.*

---
Tags: 7, blocks, advertising
---


# Question
Title: Android submission: I get a "CSRF validation failed" error while using a cookie
The Drupal Version is 7 and the Services version is 3.4.

So, My login into Drupal goes like this:

* Fetch a token. (POST)
* Fetch a Cookie using the token. (POST)
* Make GET Requests using DefaultHttpClient class to download data. (GET). This uses a token and cookie

This all works fine. But when I try to post my submissions to drupal server, look at the code below

```
 DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(submissionURL);
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SurveyReviewActivity.this);
        String id = prefs.getString("sessid", "FAIL");
        Log.e("SRA", id);
        String name = prefs.getString("sessname", "FAIL");
         Log.e("SRA", name);
         //String token_test = prefs.getString("token", "FAIL");
        //Log.e("SRA", token_test);

          httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
         httpPost.setHeader("X-CSRF-Token", X_CSRF_Token);
         // httpPost.setHeader("X-CSRF-Token", token_test);
         httpPost.setHeader("Cookie",name+"="+id);  try {
             httpPost.setEntity(new StringEntity(message, "UTF8"));
         } catch (UnsupportedEncodingException e) {
             Log.d("Encoding Exception",e.toString());

        }
          try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
             if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == 401) {
                 Log.d("Submission failed ", httpResponse.getStatusLine().toString());

             }

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                String json = sb.toString();
                Log.d("Response", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
        } catch (ClientProtocolException e) {

            Log.d("Protocol Exception",e.toString());
        } catch (IOException e) {

            Log.d("Protocol Exception",e.toString());
        }

```

When I set the last header (the cookie header), I get a token invalid or CSRF Validation Failed Error to be specific. If I don not use a token the submission goes through, but submissions are shown as anonymous on the drupal CMS side. I thought that my shared preferences are crapping up my stored cookie, but they are not thats why I was verifying them by printing them to logcat. I can get a new cookie and even tried that, but its still the same error. Whats going on here? Here are my references to the previous posts I checked on various sites.

...so if you plan on giving a solution which says your shared preferences are giving you the wrong cookie back or your token is coming down with a new line....tried that all...not working. But its working great on the iOS side, the exact same logic and actions.Please also note that, my cookie was working in fetching the data (bolded that part on step 3), but not while uploading data, its giving me a CSRF validation failed or token failed error . Please help me out on this issue.....and yes for testing the current cookie lifetime is 2 years..

# Answer
> 0 votes
CSRF token error comes when user is allready login to drupal site just logout then send the request you wont give this error again..hope this will help.

# Answer
> 0 votes
For what it's worth, this is only possible when using a HttpURLConnection in Android.

A code sample in this regard can be found at How to automate login a website – Java example.

```
    URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();

// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "accounts.google.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
    conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

conn.setDoOutput(true);
conn.setDoInput(true);

```

---
Tags: 7, services, tokens
---


# Question
Title: Create referral url for user and add UID to hidden field when url used
I need to create referral url for authenticated user. This url should be url for webform, and it should include user UID.

When user shares this url and someone uses it to fill webform it should set UID to the hidden field in webform - so admin can see whose referral url was used.

How to create this url?
How to set referred user UID to hidden field?

Can someone point me to the right direction where to start implementing this?

# Answer
> 1 votes
If I understand the question correctly, you want something like:

h(tt)p://www.example.com/register?uid=25

where register is a webform that the incoming person can access?

* I would start by creating the form at the correct location with all of the elements you want
* use some javascript (or form override) to hide the relevant form item that will hold the uid
* override the form submit function to assign the uid in the url to the hidden element

take a look at the documenation for webform, and the Drupal Form API for specifics.

---
Tags: 7, users
---


# Question
Title: How to populate a node reference field based on the selected taxonomy term?
I have two content types and one vocabulary:

1. Service Categories - different categories of jobs. (VOCABULARY as the list is small and does not change)
2. Service Tasks - tasks that relate to an individual category
3. Services - record consisting of details related to a service performed

On the services page, I have a have a term reference field that allows the user to select the category of service. Below that I have a node reference field that I would like to have populate the related task from which to choose once the category has been selected.

Without involving programming, is there a solution to my problem? I am new to Drupal (using version 7) but am picking up the concepts quickly.

# Answer
I would accomplish this by arranging your vocabulary like so:

* Category 1
* + Task 1
* + Task 2
* Category 2
* + Etc.

I would probably just name it Service Tasks, but that's my preference. Then use the hierarchical select module.

Enable the module and it's Taxonomy Select sub-module, then add a term reference to Services using the hierarchical select widget. Now you can choose tasks related to their parent categories without having to make all sorts of references.
> 1 votes

# Answer
I recently ran into something similar to this. I had a Content Type called `Subsidiary`, and a related Taxonomy called `SubsidiaryType`. I was working on a map that plots out where all the offices of the Subsidiaries are (Many Offices to One Subsidiary), so I also had a `MapPoint` Content Type.

Structurally, that's the same: just as your `Service` had a `ServiceTask` through `ServiceCategory`, my `MapPoint` had a `SubsidiaryType` through `Subsidiary`.

I installed the References module, and that enables me to use a view to populate a select list in a Content Type.

Add a new View and choose the 'References' type, as well as the 'Fields' Row Setting.

Add the relationship for the Taxonomy terms, and add two fields:

* Title (Or whatever Human Readable ID you have)
* Term Name (but hide this)

Next, open the settings for the References List Format. You'll see a grouping option. Group by the Term name on the relationship.

Now, head back to the Content Type definition for Service, and add a field for Service Task. Choose `Node Reference` and then instead of using one of the presupplied relations, use a view.

Select the View we just created, and you should now have a select list that has grouped options. Here's an example of how it should look:

* **Web Development**

+ HTML/CSS Markup
    + Server Administration
    + PHP/JS Programming
* **Marketing**

+ Sales Call
    + Copy Writing
* **Administration**

+ Process Development
    + Meetings
> 1 votes

---
Tags: nodes
---


title: Node showing teaser, but not content

text:
# Question
Title: Node showing teaser, but not content
My view is showing the list of teasers correctly, but when I want to read more and see the full body text I get the "Page not found" error. I've been searching through all my settings, permissions etc. and can't find the error. It might have something to do with the view, but I can't see any error there either. Any ideas?

Screenshot of the view settings:

I can easily find the node body in the MySQL table `field_data_body`.

# Answer
> 0 votes
I have an alternative solution in case it is not working. Include title, body (trimmed) and global text contain

```
<a href=[node:url]>Read More</a>

```

Make sure include node path and drag it above so that it appears in replacement pattern down below

# Answer
> 0 votes
You can try this:

Add '**title field**' two times as shown in below image.

For last '**title field**', do the setting as shown in image below.

Make sure that "**Link this field to the original piece of content**" is checked. In Rewrite results your text could be anything like "Read more" or "Read full story"...

By this you will be directed to your original node page.

---
Tags: views, users, organic-groups
---


# Question
Title: How do I get drush to run remote drush not in a path?
A remote server doesn't have drush, so I put it in my `~`.

Adding a `$PATH` works fine for myself being logged in, but since `ssh [command]` wont open a shell, `$PATH` is never picked up when I use `drush @remote-alias status`.

# Answer
> 3 votes
The alias setting `%drush-script` is used to solve this.

```
$aliases['alias'] = [
  'path-aliases' => [
    '%drush-script' => '/home/[user]/bin/drush',
  ],
];

```

# Answer
> 2 votes
`ssh [command]` does source a bash resource file, but the rules for non-interactive shells are different than for interactive shells. If you have only a .bashrc file, then it will be sourced for both interactive and non-interactive shells. Most distros cause .bashrc to exit near the top of the file for non-interactive shells, so you have to set your $PATH at the top of the file for the changes to show up.

If you use .bash\_profile or .profile or other bash resource files, the rules are more complicated. See `man bash` for details.

Your workaround is also fine, of course.

---
Tags: drush
---


# Question
Title: Node Langauge needs to be undefinde by default
my website (Drupal 7) is available in German (?q=de) and English (?q=en) (i18n Module). Users can create own pins (nodes) (similar to pinterest). The default language of the website is set to german. So everytime somebody creates a new pin (node) the language of the pin is set to german.

The problem is, if somebody is using the english (?q=en) version and clicks on a pin he gets redirected to the german version (?q=de).

I can manually set the language of each pin to undefined. Then everybody stays on the right version, but this would be to much work to do, to change the language of each pin all the time.

I can't let the users chose the Language, because every pin needs to be set to undefinded.

How can I achive, that with every new pin the language is set to undefined automatically?

# Answer
> 0 votes
In the "Structure" \> "Content types" editing page (`/admin/structure/types/manage/article` — replace `article` to your *pin* content-type), you can switch on (=tick) `Set current language as default for new content` in the `Extended language options` sub-section in the `Multilingual settings` tab (near the bottom-left). Then when a user visiting your website is in the English mode and creates a new node (pin?), the language of the node will be English.

It is not Language neutral, but that may be what you can accept?

---
Tags: i18n-l10n
---


# Question
Title: "Preview before submitting" based on user role
So, you can make "Preview before submitting" optional or required for a node type. I would like to make it optional based on the user who is creating the node.

So, for example, a authenticated user has to view the preview of a node before he can save it, whereas a administrator user can save the node without previewing it beforehand.

Is there a module for that?

I tried it myself, hiding the submit button in hook\_form\_alter, depending on the current user's role:

$form\['actions'\]\['submit'\]\['#access'\] = false;

But i can't let the submit button appear again in hook\_node\_validate by doing:

$form\_state\['complete form'\]\['actions'\]\['submit'\]\['#access'\] = true;

Any help would be appreciated!

# Answer
You have to unset the button:

```
unset($form['actions']['submit']);

```

This will delete the submit button from the array, thus it won't show up. Be carefull bacause above code will hide your submit button. You will have to check the key for the "preview" button.
> 0 votes

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


# Question
Title: Why drush fails with undefined function conf_path() error?
Here's a weird one: I've got two nearly identical server setups, both running Drush 5.9. Both have been happy for a while. Went to use one today, and got the error:

`Drush 5.9 does not support Drupal . Use Drush 4 instead.
PHP Fatal error: Call to undefined function conf_path() in /var/opt/drush/includes/bootstrap.inc, line 786`

The other site runs Drush 5.9 just fine. Any ideas?

# Answer
Without knowing what command you're trying to run or your file structure, it's difficult to say.

Most commonly this happens when your `drush` has trouble bootstraping your Drupal root, either by corrupted Drupal core files or different loading the wrong files.

In example if you run `drush` inside Panels module directory it fails, because it contains `includes/common.inc` file and drush is confused that it's Drupal core version of `common.inc` so it's loading it and expects that `conf_path()` should be defined. The same with `core/includes/common.inc`. Check the \_drush\_bootstrap\_drupal\_site\_validate() function at drush API site.

I believe this has been fixed in the recent drush (see #60 at GitHub and original issue), so please upgrade it to the recent version (see the instructions).

However in some other circumstances the problem is still happening (#937) for some reason.
> 0 votes

---
Tags: drush, bootstrapping
---


# Question
Title: Change layout of views page based on taxonomy term field
I have a taxonomy term page being displayed via a Views 'page' display. I need to change a value in the header of the **site** (above the level of the view) based on the value of one of the fields in the taxonomy term.

The problem is that I can't find the right hook for this. If I hook into `hook_preprocess_views_view`, it's too late. The wrapper that includes the site header has already fired. If I try to run `hook_preprocess_page`, there isn't yet any information in the `$variables` arg to give me the taxonomy ID so I can look up the field value. Unless there is are variables available to the hook in addition those that are passed into function as args, I don't see how I can get the requisite information. Are there other variables I could use that are undocumented or global variables available that just aren't passed to the function/hook?

# Answer
> 0 votes
What you can do is in the `hook_preprocess_page` use the following code :

```
$arg = arg();
if (count($arg) == 3 && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2])) {
  $term = taxonomy_term_load($arg[2]);
  if ($term->vid == $my_vocab_id) {
    # code...
  }
}

```

Then change the value of the header as you want in the `# code...` part.

Basically you check if the URL is a taxonomy term page and then you can check that the term vid correspond to its proper vocabulary id.

Hope that will help you.

---
Tags: views, taxonomy-terms, hooks, theming
---


# Question
Title: How to extend/override Rest EntityResource Plugin in Drupal 8
I would like to extend/override the Rest EntityResource Plugin in Drupal 8. I have read everything I can find online and I can see how to create a resource plugin for something other than an Entity (such as dblog). However, I can't figure out how to extend/override the existing Entity resource plugin.

# Answer
To get this working I needed to:

1. Install the Rest UI module.
2. Go to /admin/config/services/rest and enable my new resource.
3. Also at /admin/config/services/rest, click the edit button next to the new resource and configure it.
4. Go to /admin/people/permissions and configure the permissions for the new resource (Access GET, Access POST, etc.)

Couple of notes... Both on the Rest UI config and permissions pages, it was difficult to distinguish between my new resource and the original. In addition, when I tried to disable the original resource from the Rest UI config page I got the following error:

```
Fatal error: Call to undefined function Drupal\restui\Controller\drupal_valid_token() in drupal-8.0.0-beta2/modules/contrib/restui/src/Controller/RestUIController.php on line 211

```

However, even though both resources are configured, the system appears to be using my resource and not the original.
> 1 votes

---
Tags: 8
---


# Question
Title: Embedding a view block in template files makes output disappear
I have a block that I need to embed in a node's Body field. I've tried `module_invoke()` \+ PHP Filter, and I've also tried the Insert Block module. In both cases, whenever I embed a Views block, it makes the entire Body field disappear from the rendered page.

Embedding a Block-module block does *not* make it disappear; the block renders normally. I should also note that when using `module_invoke()`, that function call itself is sufficient to break the page; even if I delete the `print render()` line, it's still broken.

More info as I find it:

* When the page is broken, `dpm()` calls in `node.tpl.php` do not output anything.
* Oh, and I forgot to mention that no PHP errors are being generated. Which I can barely believe too.
* When the my embed attempts are active, the `system_main` block array is entirely missing from `$page['content']` in page.tpl.php. The `#sorted` flag is missing from there as well.
* Shabir's method below yields the same behavior as the other two methods I've tried.
* `dpm()`ing the block array (or Shabir's function's return value) shows the block contents as expected. However, the act of rendering the block makes none of the page content get printed.

Anyone have any ideas as to what's happening?

Now I'm having the problem when I call `module_invoke()` inside the views-view-unformatted--%.tpl.php file. All the view templates will send `dpm()` calls where they should go, but the content just disappears.

Furthermore, when I `dpm($page)` in page.tpl.php, `$page['content']['system_main']['main']['#markup']` shows a bunch of content for the site's front page! It still doesn't show up, though.

# Answer
> 0 votes
Include the following snippet in your template.php

```
function YOURTHEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

```

This will ensure the block exist in next step call this function in your body

```
print YOURTHEMENAME_render_block('views', 'block-id',array('title'=>'your title of the block if any'));

```

I hope it will work fine in any case!

---
Tags: 7, views, blocks
---


# Question
Title: How to theme form elements in a custom field widget?
I'm creating a custom telephone field and I'm a bit confused at how to go about theming the widget.

I have four elements in my implementation of hook\_field\_widget\_form()...

1. A dropdown for the phone type, (i.e - phone, fax, toll-free).
2. A textfield for the phone number.
3. A textfield for the extension with the prefix "ext".
4. A checkbox to flag the number as the primary number, (the field has unlimited cardinality).

Functionally, the field is working great. It is saving the data in the database just how I would like. What I'm not figuring out is how to display the elements inline on the edit form. Right now, the form for the field looks like this...

I would like each of the elements to display inline. If I could just add a class to the div that wraps each of the elements, I'd be good to go. The closest that I've come is to add a class in my implementation of hook\_field\_widget\_form() to each of the elements, but that adds it to the element and not the wrapper div.

I have a feeling I'm going to need to implement a theme function or a template file, but I just don't know where to start. All the information that I find about theme functions and template files seem to be about what the elements look like rendered on the page, and not about what the form elements look like on the edit form. I know that the theme function that builds the form element is 'theme\_form\_element', but if I alter that, it alters all the form elements. I'm not sure how to target just the elements in my module or if this is even the route to go down.

Can someone please point me in the right direction? I have been stuck on this for days.

---

UPDATE 01Nov14

---

It's been a few days since I posted this question, and I'm still very stuck. Here's another screenshot that may be able to clear up what I'd like to do. How do I add a class in the wrapper divs pointed out in this screenshot?

# Answer
> 3 votes
To add class to wrapper div of a form item you have to use the following theme function : `theme_form_element`

Copy and paste the entire `theme_form_element` function and rename the function with `mytheme_form_element` in your `template.php` and add your custom code like this (you may adjust to your own id) :

```
/* CUSTOM */
if (module_exists('mymodule')) {
  if (isset($element['#id']) && ($element['#id'] == 'phone' || $element['#id'] == 'ext' || $element['#id'] == 'primary')) {
    $attributes['class'][] = 'my-class';
  }
}
/* END CUSTOM */

```

It's always difficult to change the structure of forms because it's in theme function and for that you have to add conditions.

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


# Question
Title: SimpleTesting-PDOException: SQLSTATE[42S02]
I am in the processes of developing a module. I am trying to incorporate SimpleTest module in order to have a separate place that contains my code tests.

However, when I try to run a query against the tables in the database, which are build by me, I get: **PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'playground.simpletest311135TABLENAME** It tries to find a table simpletest311135TABLENAME while it should look for TABLENAME. It always adds simpletest and some random number.

When I run queries against drupal default tables, like users and sessions, everything works perfect. Any workaround?

Giannis

# Answer
> 5 votes
This behavior is correct. SimpleTest sets up a new site environment for every test case, using a table name prefix.

You probably forgot to install your module by overriding the setUp() method. Once your module is installed the query should work.

# Answer
> 0 votes
I got this error when I failed to call the superclass's `tearDown()` method. Once I put that back in place, the error went away.

---
Tags: testing
---


# Question
Title: Are updates applied across multiple sites?
When running updates for core and modules in a multisite configuration where modules are shared (`sites/all/modules`), are database updates applied across the multiple site's databases or do you need to run updatedb for each?

# Answer
> 6 votes
You need to run updatedb on each site individually. Note that as soon as you update the shared code, any site that has not had updatedb run could show errors or otherwise fail to function. You should therefore take all of the sites offline prior to updating the code, and bring each site back online again after updatedb completes.

# Answer
> 2 votes
I haven't experienced anything quite as disruptive as that... but it is definitely possible. I bashed a quick script that runs updates on all sites defined in the .drush/aliases.drushrc.php file. This will ensure all sites are updated separately even if they have shared contributes (the code will be updated by the first but each will run the updatedb.

```
---
#!/bin/bash

. ~/.bash_profile

base='/usr/local/apache/htdocs/drupal7'
cd $base

#take all sites offline before updating core/common contributes
for site in `drush sa|grep -v none|grep -v self|grep -v default`; do
  drush use $site
  drush vset maintenance_mode 1
done

#update all sites defined in /root/.drush/aliases.drushrc.php
for site in `drush sa|grep -v none|grep -v self|grep -v default`; do
  echo "Updating $site"
  drush use $site
  drush upc -y
  chown -R apache.apache *
  drush updb -y
  #restore current site from maintenance mode.
  drush vset maintenance_mode 0
done

---

```

## output follows so you can see it works for yourself.

```
# ./update.sh
Updating atlantra.com
Site set to atlantra.com
 Name                Installed Version  Proposed version  Message
 Display Suite (ds)  7.x-2.6            7.x-2.7           Update available
 Store (ubercart)    7.x-3.7            7.x-3.8           SECURITY UPDATE available

Update information last refreshed: Tue, 10/28/2014 - 12:43
Security and code updates will be made to the following projects: Display Suite [ds-7.x-2.7], Ubercart [ubercart-7.x-3.8]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project ds was updated successfully. Installed version is now 7.x-2.7.
Backups were saved into the directory /root/drush-backups/atlantra/20141028164424/modules/ds.                           [ok]
Project ubercart was updated successfully. Installed version is now 7.x-3.8.
Backups were saved into the directory /root/drush-backups/atlantra/20141028164424/modules/ubercart.                     [ok]
'all' cache was cleared in atlantra.com                                                                                [success]
You have pending database updates. Run `drush updatedb` or visit update.php in your browser.                            [warning]
 Ds  7202  Increase the label storage length to 128.
Do you wish to run all pending updates? (y/n): y
Performed update: ds_update_7202                                                                                [ok]
'all' cache was cleared in atlantra.com                                                                                [success]
Finished performing updates.                                                                                [ok]
Updating lawmatter.net
Site set to lawmatter.net

Update information last refreshed: 8 August 2014 - 9:30am
No code updates available.                                                                                [ok]
 Field_collection  7003  Update field_collection_field_schema columns for all tables.
 Field_collection  7004  Add index on {$field_collection_field}_revision_id column for all tables.
 Module_filter     7200  Rebuild the menu and theme registry.
 Module_filter     7201  Old update that use to remove the module_filter_dynamic_save_position variable.
 Services          7402  Update 7402 adds services_user table so that services can see users createdupdate by itself.
 Uuid              7103  Modify the labels of all example entities created by the now removed
                         uuid_default_entities_example.module to make it clear they're examples.  Also remove the administrator
                         role of any example user.
 Ds                7202  Increase the label storage length to 128.
Do you wish to run all pending updates? (y/n): y
Performed update: field_collection_update_7003                                                                          [ok]
Performed update: module_filter_update_7200                                                                             [ok]
Performed update: ds_update_7202                                                                                [ok]
Performed update: uuid_update_7103                                                                                [ok]
Performed update: module_filter_update_7201                                                                             [ok]
Performed update: field_collection_update_7004                                                                          [ok]
Performed update: services_update_7402                                                                                [ok]
'all' cache was cleared in lawmatter.net                                                                                [success]
Finished performing updates.                                                                                [ok]
Updating rexialo.com
Site set to rexialo.com

Update information last refreshed: Tue, 10/28/2014 - 9:47am
No code updates available.                                                                                [ok]
 Ds  7202  Increase the label storage length to 128.
Do you wish to run all pending updates? (y/n): y
Performed update: ds_update_7202                                                                                [ok]
'all' cache was cleared in rexialo.com                                                                                [success]
Finished performing updates.                                                                                [ok]

```

---
Tags: multi-sites, updating
---


# Question
Title: Move views global text field into code (attached fields and fields via relationships)
I have recently done away with using views php as it is unsafe. I have read a comment by @letharion whereby he mentions that adding a php directive `disable_functions = eval` is a good practice to tighten up security.

I have a problem with the views global text field:

* One cannot run php functions on fields
* It is a bit messy to have a lot of the html markup in the database
* It runs the markup through filter\_xss (which is good) without giving one the flexibility of expanding on the allowed tags.

I have read this question: Move php in views to module and would like to broaden it a bit.

I have implemented the accepted answer and it works with a slight modification:

custom.module:

```
function custom_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'custom') . '/views',
  );
}

function custom_print_my_link($nid, $type){
  return $nid . '-' . $type;
}

```

custom.views.inc:

```
function custom_views_data() {
  $data['node']['custom_stuff'] = array(
    'field' => array(
      'title' => t('Custom link'),
      'help' => t('Provide a custom content link.'),
      'handler' => 'views_handler_field_node_custom_stuff',
    ),
  );
  return $data;
}

```

views\_handler\_field\_node\_link\_custom\_stuff:

```
class views_handler_field_node_custom_stuff extends views_handler_field_node {
  function construct() {
    parent::construct();
    $this->additional_fields['type'] = 'type';
    $this->additional_fields['nid'] = 'nid'; // this had to be added !!!
  }
  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }
  function render($values) {
    $type = $this->get_value($values, 'type');
    $nid = $this->get_value($values, 'nid');
    return custom_print_my_link($nid, $type);
  }
};

```

I have set up the view with two hidden fields (nid and type) that appear before this custom field.

This works perfectly for fields attached to the node table.

**My question is:** How do I implement it for attached fields, and access the fields across relationships as well?

# Answer
So I figured out how to accomplish a small part of what I need done.

To add an attached field (a simple text field called 'test') I did this:

```
class views_handler_my_custom_field extends views_handler_field {
  function construct() {
    parent::construct();

    $this->additional_fields['test'] = array(
      'table' => 'field_data_field_test',
      'field' => 'field_test_value',
    );
  }

  /**
   * {@inheritdoc}
   *
   * Perform any database or cache data retrieval here. In this example there is
   * none.
   */
  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  /**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $test = $this->get_value($values, 'test');
    return $test;
  }
}

```
> 1 votes

---
Tags: views
---