# Question
Title: user_load() and EntityFieldQuery not found when running script via Drush
I'm trying to run a php script from the command line via Drush. When I tried to use EntityFieldQuery...

```
$query = new EntityFieldQuery;

```

I got the error:

```
PHP Fatal error:  Class 'EntityFieldQuery' not found in /path/to/my/script.php on line 43

```

So, I tried to make it even simpler, and just used this script:

```
<?php

print "inside script\n\n";
$user = user_load(1);
print "name: ".$user->name;

?>

```

But I get the error:

```
PHP Fatal error:  Call to undefined function user_load() in /path/to/my/script.php on line 17

```

It doesn't appear that drush is bootstrapping properly. Am I missing something? What do I need to do for drush to be able to use the drupal apis?

I read through Drush php-script | Drupal functions such as node\_load() are not being found, but I've got mysql client libraries already installed so that isn't a solution for me.

# Answer
Ok, WOW, I found the error by running my script with the -d option:

```
drush -d scr /path/to/my/script.php

```

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I regranted the privs and my script ran just fine.

The error message about not being able to find a function was a total red herring.
> 0 votes

---
Tags: 7, drush, bootstrapping
---


# Question
Title: Functions like node_load() are not found
I successfully installed Drush on Ubuntu 12.04, and I created a script containing the following line.

```
print_r(node_load(10));

```

I am calling the script with `drush php-script --uri=http://localhost myscript.php` which returns the following error.

> PHP Fatal error: Call to undefined function node\_load()

I also tried with `drush --uri=http://localhost cache-get`, but I get the following error.

> Command cache-get needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
> The drush command 'cache-get' could not be executed.
> Drush was not able to start (bootstrap) the Drupal database.
> Hint: This may occur when Drush is trying to:
>
> * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
> * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details. Drush was attempting to connect to: Drupal version: 7.26
> Site URI: `http://localhost`
> Database driver: mysql
> Database hostname: 127.0.0.1
> Database username: **username** // This is shown correctly
> Database name: **database\_name** // This is shown correctly
> PHP executable: /usr/bin/php
> PHP configuration: /etc/php5/cli/php.ini PHP OS: Linux
> Drush version: 7.0-dev
> Drush temp directory: /tmp
> Drush configuration:
> Drush alias files:
> Drupal root: /opt/lampp/htdocs
> Site path: sites/default

# Answer
> 1 votes
I finally figured out what was missing.

In my case I had to install the mysql-client-core-5.5 package with `sudo apt-get install mysql-client-core-5.5`.

# Answer
> 0 votes
I ran into the same problem (user\_load() and other functions were not found), but had a different solution.

For me, it turned out that my sql privileges on the database were not correct.

I found the error by running my script with the -d option:

```
drush -d scr /path/to/my/script.php

```

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I sql `grant`ed the privs and my script ran just fine.

The error message about not being able to find a function was a total red herring.

---
Tags: drush
---


# Question
Title: Ubercart - how to get order information from order ID?
**How to get an object of `Order` *(or something similar - details of an order!)* by providing order id?** Perhaps, some kind of code like: `$order = order_load($orderId);`

I'm new to Ubercart (3.x)/Drupal (7.x) and searched the title but found no solutions.

I need to create a view/*page by custom module* which displays "My Purchases" or "My Sells"

I need to get complete Order details, by providing order-id. Also need the creator/seller and buyer info of the order.

Can someone give me some PHP example/other ways possibly using a View?

# Answer
Using the Ubercart API at api.ubercart.me, it is

```
$orders = uc_order_load($orderId);

```

`$orders` is an array, so `$order = $orders[0];`

See: http://api.ubercart.me/api/drupal/ubercart!uc\_order!uc\_order.module/function/uc\_order\_load/7
> 5 votes

# Answer
You can use this as well

```
$result = db_query("SELECT order_id FROM {uc_orders} WHERE order_status
IN ('abandoned', 'pending') ");
$deleted = 0;
 foreach($result as $row){
   uc_order_delete($row->order_id);
   $deleted++;
 }
drupal_set_message($deleted . ' Abandoned or Pending Orders deleted', 'status');

```
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: Error while altering js file Undefined index: scope in drupal_get_js() (line 4309
I need to change javascript code of jCarousel, and I want to create my own function and change it in `hook_js_alter()`, but it is not working properly, or I missing something.

```
function common_js_alter(&$javascript) {
  if ($node = menu_get_object()) {
    if ($node->type == 'home') {
      if (array_key_exists('sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js', $javascript)) {
        $file = drupal_get_path('module', 'common') . '/js/jcarousel.js';
        $javascript['sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js'] = drupal_js_defaults($file);
        dpm($javascript);
      }
    }
  }
}

```

I need to change `sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js` to `drupal_get_path('module', 'common') . '/js/jcarousel.js'`. The path is correct, but as I can see with `dpm()` no scope is enabled and type.

# Answer
> 3 votes
Just got into this function too to alter "folder/js\_file.js" and the issue causing the

> Notice: Undefined index: scope in drupal\_get\_js() (line 4309 of \[DRUPAL\_DIR\]\includes\common.inc).

error is that there are times when the hook is called but "folder/js\_file.js" is not yet in the array w/c just adds

```
[folder/js_file.js] => Array(
  [data] => [your_custom_js],
)

```

to the array but the scope, type, and other attributes are not there. So we first need to check if the array key exists like so:

```
if (isset($javascript['folder/js_file.js'])) {
  $file = drupal_get_path('module', 'mymodule') . '/your_custom_js.js';
  $javascript['folder/js_file.js']['data'] = $file;
}

```

That solves it. :)

---
Tags: hooks, javascript
---


# Question
Title: How to let selected role submit multiple data for 1 node?
I want to do a product price compare site. So a product is a node and product can have many different price at different store. I want to allow selected user's role able to submit new price or new store from time to time but I want them to submit data on the node page similar to submitting comments, NOT on node edit page.

I'm looking onto entityreference but i'm not sure where to start and what others module needed to accomplish my objective.

Thanks for helping.

# Answer
> 0 votes
The Field Collection module will let you do a couple of helpful things here:

* you can group a set of fields, ie store name, price so that this data is part of the same entity
* you can embed links to add/edit/delete field collections right on the node.

Embedding the form in the node is trickier, but doable, and Field Collection will get you off to a good start.

Once the Field Collection module is enabled, create a field of the type field collection on your content type. Set the widget to 'embedded'. Then go and add individual fields to your content type.

There is basic documentation at https://www.drupal.org/node/1353926 and a video tutorial at https://www.youtube.com/watch?v=1V1ofpgUw-Y.

---
Tags: entities
---


# Question
Title: Eliminate Views Entity Reference Duplicates. I have some titles the same on purpose
I have a view with an entity reference pulling in what I need from a content type. There are, on purpose, titles that are the same.

Is there a way to compare what is output and then only show one of the titles?

I am showing these in a select list.

This is not duplicates, as they are separate entries... so using the Query Settings \> Distinct isn't the correct solution in my case.

# Answer
You can use hook\_views\_pre\_render to get at the results array before it is output to the screen.

e.g.

```
function my_module_views_pre_render($view) {
  if ($view->name == 'the machine name of the view') {
    foreach ($view->result as $result) {
      // do some kind of comparison and de-duplification
    }
  }
}

```
> 1 votes

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


title: Search bar in main menu

text:
# Question
Title: Search bar in main menu
I would like to place the search bar in the main menu on the right. I have seen several people on the net asking for this but never encountered some information I could actually use. I use Drupal 7 and the "Responsive Blog" by Devsaran.

As far as I understand the way to go is inserting some php into the main menu code in the main-menu part in page.tpl. This is what it looks like but I am struggeling with the exact to dos now...

```
<nav id="navigation" role="navigation">
  <div id="main-menu">
    <?php
      if (module_exists('i18n_menu')) {
        $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
      } else {
        $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
      }
      print drupal_render($main_menu_tree);
    ?>
  </div>
</nav>

```

# Answer
Here is one approach:

1. Start by adding a new region to the theme's .info file:

regions\[navigation\] = Navigation
2. Next, *render* the region. Put the code below in page.tpl.php either just before or just after the \</div\> in your code above. You may need to experiment a little.

\<?php print render($page\['navigation'\]); ?\>
3. Clear your cache so your site knows that the new region exists.
4. Next, in Admin -\> Structure -\> Blocks, place the Search block in the Navigation region.
5. Finally, style the search form so it looks the way you want.
> 4 votes

---
Tags: 7, theming, routes, search
---


# Question
Title: How to attache multiple nodes of a node type to another node of another node type?
Currently I am making a advertisement website for restaurants. Now I am putting the restaurant basic information (name, address,etc) in a node.

What I want to do is making a menu list for the restaurant, Say each menu item is a node (with the type of 'item') while the restaurant is another node type 'restaurant'.

In database level, the relationship between node (restaurant) and menu item node type is one-to-many.

So how can I do this?

Thanks for any help!

Cheers!

# Answer
> 2 votes
Install the references module, once you done that, you can enable the `node_reference` submodule and attach a "Node Reference" field to your "restaurant" content type.

Next, set the "item" content-type as reference for the field and the "Number of values" setting as "Unlimited".

When creating or editing a restaurant, you should now be able to link multiple menus to the node.

---
Tags: nodes
---


# Question
Title: need to have image dragging option to position images in Gallery
I have created a image content type and upload few images. And then I created another content type for Gallery and using node reference field, I added several images under a gallery. I followed the tutorial in youtube https://www.youtube.com/watch?v=MUSpTSTVL0Q

Now I wish I could have dragable like feature, so that I can adjust the serial order of each image in a gallery. Image in 1st order should be cover of the gallery. Please suggest.

# Answer
This is solved by module called "Draggable Views"
> 0 votes

---
Tags: media
---


# Question
Title: Pulling CiviCRM data into a custom Drupal module based on checksum/hash link
I have a CiviCRM contribution page that allows an individual to renew a membership on behalf of an organization. When we email them from CiviMail with a checksum link to the page, it will prefill their information in the form automatically and have the membership renewal associate correctly to the organization.

How can I pull the organizational information into a custom Drupal module (e.g. a block that displays in the sidebar, for example)? I would like to have a text block that displays some information about the org and potentially names of people who are related to the org by relationships in CiviCRM. I won't have a problem doing that with Views and/or the CiviCRM API in a custom Drupal module, but I'm not sure how to get the org's ID in this scenario, to know which info to display.

# Answer
> 2 votes
I am assuming you want to show the organization information of logged in contact. So I would do following:

1. Get the contact id of logged in contact *(or anonymous user who used a checksum link, via the `cid` field in the URL, as @petednz noted)*.
2. Get the current employer id
3. then retrieve address of current employer

---
Tags: civicrm
---


title: How to configure node variations?

text:
# Question
Title: How to configure node variations?
I have a content type with a lot of different fields. Now this content can have (but not always) variations, which have the same fields, but different content.

I don't know how it would be best to organize this on the admin side. I could use child nodes, but if I have children, I'll have an empty parent. Basically what I need is to have multiple sets of the same fields for a content item.

I don't know if this is understandable, you might think of the as product variations or subproducts, here's an example:

```
Macbook (this only has title + description)
 -- Macbook Air (title + one set of characteristics)
 -- Macbook Pro (title + 2nd set of characteristics)
Mac Mini (title, description, characteristics)
iMac (title, description, characteristics)

```

# Answer
> 3 votes
As @W.M. said, i will use Conditional Fields module Conditional Fields along with Field Collection Module.

Essentially you will first define collections of fields (this is a kind of grouping of fields that are related. ie retina screen details), and then you can make this fields collections to appear if another field value is set using Field Collection.

# Answer
> 1 votes
I'm not sure what you are describing but according to your example I think Field group is what you need

# Answer
> 1 votes
You need the **Conditional Fields module**. It can show and hide fields upon values of other fields etc. The module can be found here: Conditional fields

# Answer
> 0 votes
If I understand the 'question' correctly, take a look at taxonomy - In your example case, Macbook would be the Vocabulary, and Macbook Air and Pro would be the 'Terms' with the fields you want.

---
Tags: nodes
---


# Question
Title: Why would taxonomy_term_save be slow when called from hook_install_tasks?
As part of making a site more easily deployable from scratch, I have generated two PHP scripts to pre-populate taxonomy vocabularies with a list of terms. The scripts are straightforward, creating `stdClass` objects with the appropriate fields and calling`taxonomy_term_save` on each one. Example:

```
$term = (object) array (
  'name' => 'Art & Architecture',
  'description' => '',
  'format' => 'plain_text',
  'weight' => '0',
  'vocabulary_machine_name' => 'categories',
  'field_cc_numeric_code' =>
  array (
    'und' =>
    array (
      0 =>
      array (
        'value' => '102',
      ),
    ),
  ),
);
$term->vid = $vocabulary->vid;
taxonomy_term_save($term);

```

The variable `$vocabulary` already contains the appropriate taxonomy vocabulary structure at the time this is called. One vocabulary has about 150 terms to create, the other about 2,000.

On a fresh installation of the site made using `drush site-install`, these scripts run almost instantly when called via `drush php-script`. However, if they are incorporated into the installation profile and called by a task in the implementation of `hook_install_tasks`, they are much slower. In the latter case, saving each term takes about a second, which is unacceptably slow.

There is discussion of a similar issue at https://www.drupal.org/node/1887924, but no solution offered either there or in the linked bug report.

Why would `taxonomy_term_save` be so much slower when performed from an installation task? Is there anything that can be done about it?

# Answer
In this case, the problem resulted from having the Pathauto module enabled during installation. When a new taxonomy term is saved, Drupal calls `pathauto_taxonomy_term_insert()`, which calls `pathauto_taxonomy_term_update_alias()`, which in turn calls `pathauto_create_alias()`. This last function calls an internal function, `_pathauto_path_is_callback()`, to determine whether an alias can be created for a given path, and this in turn calls the core function `menu_get_item()`, which contains the following lines:

```
if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  menu_rebuild();
}

```

`menu_rebuild` contains the following lines:

```
if (defined('MAINTENANCE_MODE')) {
  variable_set('menu_rebuild_needed', TRUE);
}
else {
  variable_del('menu_rebuild_needed');
}

```

The cumulative effect seems to be that the `menu_rebuild_needed` variable is continually reset to `TRUE`, meaning that a complete menu rebuild is triggered each time a new taxonomy term is saved, slowing things down immensely (from ~100 terms saved per second to ~1 per second).

This seems like a bug, though it's not clear which component, if any, is at fault. For now, I am working around the problem by disabling `pathauto`, creating the terms, and then re-enabling `pathauto`:

```
module_disable(array('pathauto'));
…
module_enable(array('pathauto'));

```
> 1 votes

---
Tags: taxonomy-terms, deployment, installation-profiles
---


# Question
Title: Reverting blocks and other pseudo-exportables in an install hook
We have a medium-sized Drupal 7 site whose configuration is almost entirely stored in code, in a single Features module. In order to permit automated testing and a cleaner development workflow, I'd like to make it possible to install a new instance of the site from scratch without cloning the database. To that end, I've created a simple install profile (based on the `standard` profile) which enables our themes and configuration module. This mostly seems to work, but I've found that some feature components are not immediately reverted on the newly-installed site: specifically, blocks exported with `fe_block_settings`, user permissions, and variables. All these are applied if I run `drush fra -y` from the command line after installing the new site, but I would like to do everything programmatically to make writing tests easier.

There is some discussion of the problem with blocks at https://www.drupal.org/node/1901116, but I've tried the fix given there (calling `module_install` in the `hook_install` implementation instead of listing a dependency in the `.info` file), without successs so far. That page also doesn't address the issues I'm seeing with variables and user permissions.

Is it possible to successfully apply all of these exported feature components from an install hook, or do I need some other mechanism?

# Answer
In short: the workaround is to call `drupal_flush_all_caches()` and `drupal_static_reset()` before reverting the module containing exported features again from an install task.

In detail: The main symptom observed was that blocks (exported as `fe_block_settings` components), were not correctly applied on the new site when they depended on a Views block display defined in the same features module. This remained true even after adding an additional call to `features_revert_module()` in an installation task. (There were also problems at one point with variables and permissions, but these were cleared up more easily by the addition of the call to `features_revert_module()`).

The problem with settings for views blocks is that Views caches all views loaded from the database in a static variable, making any views loaded or enabled for the first time during a single request or `drush` command invisible to later calls to `views_block_info()`. One possible (tested) workaround is the following:

```
views_get_all_views(TRUE);
drupal_flush_all_caches();
features_revert_module('xyz');

```

Supplying `TRUE` for the `$reset` parameter to `views_get_all_views()` forces the module to discard its static cache and re-compute the list of blocks from scratch. This allows the revert of block settings to go through correctly.

Because I suspect this will not be the only problem caused by invalid static variable caches, I am trying the more drastic approach of resetting *all* static variables and clearing all caches before reverting the module:

```
drupal_static_reset();
drupal_flush_all_caches();
features_revert_module('xyz');

```

(Resetting all static variables does produce a few extra PHP warnings, which hopefully are spurious.)

The above lines are run as an installation task, and are combined with the approach described in https://www.drupal.org/node/1901116: i.e., remove the module with exported blocks from the `dependencies[]` list, and enable it manually in `hook_install()` after enabling themes for the site. The complete implementation in the profile `.install` file then looks more like this, where the installation profile is named `foo`, the features module is named `xyz` and the site theme `quux`:

```
/**
 * Implements hook_install().
 */
function foo_install() {

  // ... other setup code here ...

  // Enable themes
  theme_enable(array('seven', 'quux'));
  variable_set('admin_theme', 'seven');
  variable_set('node_admin_theme', '1');
  variable_set('theme_default', 'quux');

  // Enable module containing features-exported block settings
  module_enable(array('xyz'));
}

/**
 * Implements hook_install_tasks().
 */
function foo_install_tasks(&$install_state) {
  $tasks = array(
    'foo_revert_xyz' => array(
      'display_name' => st('Apply all settings in "xyz" module'),
      'type' => 'normal',
    ),
  );
  return $tasks;
}

function foo_revert_xyz() {
  drupal_flush_all_caches();
  drupal_static_reset();
  features_revert_module('xyz');
}

```

Tracking this down was a real headache, so I hope the solution is useful to someone else.
> 1 votes

# Answer
Here is approach that I am using to automate creation of the Drupal site from scratch:

1. Create new installation profile and add all required modules and features as dependencies to the profile .info file
2. Run `drush site-install {{ profile }} -y` to install site
3. Run `drush features-revert-all -y` to revert all features
4. Run `drush cache-clear all` to clear all caches

I've noticed that if simply install feature as a module, then not all feature components are reverted, that is why step #3 is required.

If you install feature by running `module_install` then you should run `features_revert` afterwards http://drupalcontrib.org/api/drupal/contributions%21features%21features.module/function/features\_revert/7
> 0 votes

---
Tags: features, installation-profiles, installation
---


# Question
Title: How to add a CSS attribute to Image generated with image style
Pretty much all in the title. I would like to add a CSS classes to images generated via a image style theme function, so that the output looks like :

```
<img class="MYCLASS" alt="" src="site.com/sites/default/files/styles/profile_picture/public/pictures/picture-1-1318455022.jpg" typeof="foaf:Image">

```

Is there anyway to do so ?

# Answer
> 4 votes
If you are comfortable overriding theme functions in your theme's template.php you can just create a YOURTHEME\_image\_style() function:

http://api.drupal.org/api/drupal/modules--image--image.module/function/theme\_image\_style/7

# Answer
> 4 votes
Here's some code based on Ryan's answer.

1. Copy and paste the code from theme\_image\_style to your theme's template.php.
2. replace `theme` in `theme_image_style` with your theme's name.
3. add the following lines to the function

```
  $variables['attributes'] = array(
      'class' => 'my-class',
  );

```

Instead of `'my-class'` I wanted to use the actual style's name, so I used `$variables['style_name']` instead. Image style names are always valid css class names, so there should be no problem with this approach. The function should look like this:

```
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  $variables['attributes'] = array(
    'class' => $variables['style_name'],
  );

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  return theme('image', $variables);
}

```

# Answer
> 4 votes
**Use preprocess function**

You want that class on the actual image, adding through JS/jQuery is messy and breaks if content is ajax loaded.

```
function THEMENAME_preprocess_field(&$variables) {

    if($variables['element']['#field_name'] == 'field_photo'){

        foreach($variables['items'] as $key => $item){

            $variables['items'][ $key ]['#item']['attributes']['class'][] = 'img-circle';

        }

    }

}

```

---

**Why I don't use theme\_image\_style() for this**

The issue with doing this through theme\_image\_style() is that it overrides the output function for just one field, what if you have multiple fields in different places... too many `THEME_field__field_photo__team($variables)` achieving the same as the above using theme\_image\_style() would look like this:

```
// Override the field 'field_photo' on the content type 'team'
function THEMENAME_field__field_photo__team($variables) {

    // Determine the dimensions of the styled image.
    $dimensions = array(
        'width' => $variables['width'],
        'height' => $variables['height'],
    );

    image_style_transform_dimensions($variables['style_name'], $dimensions);

    $variables['width'] = $dimensions['width'];
    $variables['height'] = $dimensions['height'];

    $variables['attributes'] = array(
        'class' => $variables['img-circle'],
    );

    // Determine the URL for the styled image.
    $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
    return theme('image', $variables);

}

```

# Answer
> 1 votes
If the reason you want to add the class is to provide some extra css for the images, then you can circumvent this by going to an upper level in the dom tree. Your images should be included in a field div that has a class like `.field-type-image`. With this in mind, you can write a selector that picks the images, something like:
`div.field-type-image img {border: 1px solid #ccc }`

or a more specific one like:

`div.field-type-image div.field-items div.field-item img {border: 1px solid #ccc }`

# Answer
> 1 votes
I think you want to use this for captions. After much hunting around, use Jquery. This stuff is for Drupal 7.

create your js file. Call it caption.js. You can call it something else. Store it inside your theme somewhere.

Make sure the script gets called by editing your theme.info file and adding scripts\[\] = pathtoyourfile/caption.js

caption.js should contain the following code

```
(function ($) {
Drupal.behaviors.caption = {
attach: function(context, settings) {
$('.views-field-field-useimage img').addClass('caption');
  }}})
(jQuery);

```

Substitute .views-field-field-useimage img for your own selector.

Hit the empty cache button and give it a go.

# Answer
> 0 votes
A suggestion for this answer.

Change the

```
$variables['attributes'] = array(
  'class' => $variables['style_name'],
);

```

to

```
$variables['attributes']['class'][] = $variables['style_name'];

```

so the image style name is appended to the class array and nothing is inadvertently squashed.

Full snippet:

```
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  $variables['attributes']['class'][] = $variables['style_name'];

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  return theme('image', $variables);
}

```

---
Tags: 7, theming, media
---


# Question
Title: Get Template Variables in my Custom Module
I am new in drupal. I am trying to get a variable from a template file e.g. maintenance-page.tpl.php and want to get $title variable in a form e.g. admin/config/development/maintenance form. This form will contain a field/textbox to set a custom title and I want to print that custom title on maintenance-page.tpl.php page. How could it be implemented with custom module. I am using Drupal 7. Thanks in Advance.

# Answer
> 3 votes
In Drupal 7 getting global module specific settings or module-site configuration settings is done via:

1. variable\_set

> Sets a persistent variable.

2. variable\_get

> Returns a persistent variable.

3. variable\_del

> Unsets a persistent variable.

This is to be used for global settings which means it is used site-wide. In your use-case it seems appropriate to use.

For your custom form you will get the variable when you build the form, and set the variable in the form's submit handler. If you are using system\_settings\_form, then the process is even easier as all you have to do is to make sure that your form element for the title is named exactly the same as your persistent variable. For an example please refer to: How to add a custom admin settings form to accept variable values in Drupal

To print the variable in your template you can either get the variable using variable\_get in a preprocess function and set a preprocess variable for it which you then use, or you can just get the variable directly within the template. How do you know which method to use? If the template file is rendered because of a theme function, then there will be a preprocess function for it. But don't break your head to much over this one. Because getting a variable using variable\_get is such a small operation, you might as well just do it directly in the template file.

---
Tags: forms
---


# Question
Title: Other (related) nodes with the same taxonomy block grouping problem
Quick view: I want to create a views block that lists all other nodes that have the same taxonomy term(s) and I want to group the related nodes by term.

---

I have trouble while doing this:

The content type has some taxonomy terms fields and one of them is `my_taxonomy_field`. I can enter multiple values to this field.

What I basically want is to show all other nodes tagged with the term(s) on this node and group them by terms. I could do this by contextual filters (content: has taxonomy term ID + ) as explained here or here.

**Let me explain:**

This is my node list:

* **NODE 1** taxonomy term field: term 1, term 2, term 3
* **NODE 2** taxonomy term field: term 3, term 4
* **NODE 3** taxonomy term field: term 5, term 6, term 7
* **NODE 4** taxonomy term field: term 6, term 7
* **NODE 5** taxonomy term field: term 1, term 3
* **NODE 6** taxonomy term field: term 1
* **NODE 7** taxonomy term field: term 8
* **NODE 8** taxonomy term field: term 2, term 9

Let's look at **NODE 1**, it has these terms: term 1, term 2, term 3

And the terms are tagged on that nodes:

term 1: node 1, node 5, node 6

term 2: node 1, node 8

term 3: node 1, node 2, node 5

This is the related nodes block based on the taxonomy term field:

* node 1 (excluded)
* node 2
* node 5
* node 6
* node 8

I want to group them by terms as that (note that current node (node 1) excluded):

### BLOCK

* **TERM 1**
    + node 5
    + node 6
* **TERM 2**
    + node 8
* **TERM 3**
    + node 2
    + node 5

I tried to this with that way: views -\> style -\> settings (grouping field) and I selected the taxonomy term field. It does what I want, not what I want actually, more than what I want because it creates a views block as that:

### BLOCK

* **TERM 1**
    + node 5
    + node 6
* **TERM 2**
    + node 8
* **TERM 3**
    + node 2
    + node 5
* **TERM 4**
    + node 2
* **TERM 9**
    + node 8

This views doesn't add any (irrelevant) nodes to the list, the nodes are the same with the un-grouped one but because node 2 and node 8 are tagged with other terms, other terms listed here.

**How I could list related nodes as grouped but without this 'unwanted' terms, with only the terms in the current node?**

(Note: I'm working on both two ways mentioned above, these are the screenshots of them):

Method 1:

Method 2

# Answer
> 6 votes
I've used tags as the term field, so adjust for that.

Create the block view as follows:

A view of content (nodes).

**Relationships:**

1. Content: Tags (field\_tags), require relationship // you will use your term field here
2. Taxonomy term: Content using Tags (Relate each Content with a Tags set to the term.) and set the relationship to the first relationship added, and tick require this relationship // yours will be named differently

**Contextual filters:**

1. Content: Nid (node id). Set the relationship to the second relationship added. Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -\> your content type -\> Node ID -\> Hide view
2. Content: Nid (node ID). **DO NOT USE A RELATIONSHIP.** Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -\> your content type -\> Node ID -\> Hide view. Click on more and **tick Exclude**.

**Fields:**

1. Content Title (NO relationship)
2. Taxonomy term: Name, use relationship 1, and hide from display

**Sort Criteria**

1. Taxonomy term: Name, use relationship 1, ascending
2. Content Title, ascending

**Filter Criteria**

Add a filter of Content (node) type to filter on your content type.

**Format:**

Unformatted list, with settings: Grouping field Nr.1 set to the term field (field 2)

# Answer
> 1 votes
One possible solution would be to pass in taxonomy term ids from node 1, before you even start building the view.

This might involve creating a custom block (preferably by making very simple block module). The block would simply node\_load(1), get the taxonomy terms from the node object.

The block could now embed the view in the block content using views\_embed\_view, passing the term ids into the view as multiple arguments (eg 7+6+46), and possibly the node id (to exclude). Now the view only needs to list nodes associated with these term ids, excluding the nid, and grouping by term. You could try excluding the nid using 'id from url', but I am not sure whether this works with views\_embed\_views, and if you do, watch out for block caching.

Given that node and taxonomy tables should be relatively stable (being in core) you might actually find this relatively easy to do with a simple db query in your block, though then you lose the extended configurability of views.

There may well be a way of doing this all within views, but I can't think of it presently, as the logic suggests a subquery (views relationships?).

# Answer
> 0 votes
As per this blog, you need to follow steps to display related content.

1. Create view (block)
2. Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
3. “Arguments” is from now on called “Contextual filters”, so go there.
4. Add the filters: “Content: Has taxonomy term ID *(with depth)” and “Content: Has taxonomy term ID depth modifier”*
5. Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
6. Now you need to add the second filter in order to exclude the current node from the list. Click \[+\] button of the contextual filters section.
7. Select Content: Nid
8. Set the ‘when argument is not present’ to ‘Provide default argument’
9. Set the ‘Default argument type’ to ‘Content ID from URL’
10. Go to “MORE” , and check the “Exclude” box.
11. *Move the filter “Content: Nid” to the top position.*
12. Add a block to your view and embed the block on your node pages
13. Save your view

**Grouping :**

After following the steps you need to Grouping your Fields using Taxonomy Term. You can group the items in view's `Style Settings`.

---
Tags: views
---


# Question
Title: How to use view to display a list of nodes?
My site have a restaurant node type and each restaurant node has multiple menu items. Each menu item has food name, price , discount, etc.

What I want to do is creating a view that shows a list of all menu item node list which belong to a specific restaurant node.

Can anyone tell me how can I do that?

Thanks!

# Answer
Install

Menu Node API

> Manages relationships between node ids and menu items.

and Menu Node Views

> The Menu Node Views module provides Views integration for nodes assigned to the menu system.

Create a view something like this:

View of Content (nodes)

**Contextual filter:**

1. Add a contextual filter of Content: Nid

**Fields:**

1. Content: Title, and exclude from display.
2. Menu: Link title (The link text used for the menu item.)

**Format:** Unformatted list, with settings of Grouping field Nr.1 -\> Content:title

That should do it.

This is not the only module solution available so research others as well.
> 0 votes

# Answer
You need to a function called *views\_embed\_view*.

1) Create an *embed*-type view display to display menu items. Assign a *contextual filter* for this view to be the referenced node (i.e. the id of the restaurant node).

2) Using a custom block that is shown only on restaurants' nodes, put these lines of PHP code (using PHP filter):

```
<?php
if ($node = menu_get_object()) {
 $nid = $node->nid;
}

print views_embed_view('view-name', 'views-display-name', $nid);
?>

```

That's it.
> 0 votes

---
Tags: views
---


# Question
Title: How can I use a drupal variable to dynamically change a Views field?
I'm trying to change a View field output depending upon a user's IP.

There's a double conditional I need to accommodate: If the user is outside of an IP range, and if the selected content is restricted, display Restricted Text.

My IP detect works fine, and the Restricted Text works manually, but I can't connect the two.

I have tried using tokens, drupal variables, and Header Global Text fields, but I can't access them within the View.

I looked at Filters, Behaviours without success, and D7 won't let me use php to rewrite the field results.

Creating a custom view lets me add \['content'\] to a header, but not a field, and passing in a variable to the \['field'\] returns an error (expecting an object maybe?).

The last day has been spent trying to make a handler for that field (modifying a recipe from Views Cookbook) but it isn't commented well enough for me to figure out what I'm trying to do with it.

I feel like I've run out of climbing pegs and can't make it up the Drupal Cliff. I'm ready to hard code it and call it a day.

What am I missing??

# Answer
From what I can see you can simply use Views PHP module and access and modify the data before it's rendered in the view. What this does is add a custom field in the view through which you can do operations on the fields rendered. However this is not optimal as the code is stored in the database and this will be hard to maintain and extend.

If it's a simple operation, you can go ahead and use it (like in your case, a simple condition), but if you want it to be easily maintained and extended use custom templates for the view itself.
> 1 votes

# Answer
You need to hook into the view before it's rendered. There are a list of hooks that could be used to do this - https://api.drupal.org/api/views/views.api.php/group/views\_hooks/7

You'll need to create a custom module to place your hook into first.

If you output the contents of hook\_views\_pre\_render and hook\_views\_post\_render you should be able to see where to add in your additional logic.
> 0 votes

---
Tags: views
---


title: Moderate user uploaded images

text:
# Question
Title: Moderate user uploaded images
I want offer a solution that a registered user can upload Images through File entity but like Copyright, Privacy and laws i want to check the image before the Image will be public.

The best solution would be if the not checked image would be temporary in a folder. If the Image is ok then i want to select it and change it to other other folder which has public access. (i can play here with CHMOD permissions on Linux). If the image isn't ok it should be deleted and not reachable via public access.

The background is, if a image including copyright infringement or other criminal materials then it should't be public reachable. It means if i hidden or don't make it with Views public in Frontend available a visitor can with right URL open the image.

I use the modules:

* File Entity (last dev)
* Views 3
* Panels 3
* VBO Views Bulk operations

Has anyone an idea? Maybe with Rules module?

# Answer
> 0 votes
You should consider using File admin module.

> File admin extends the File entity module to add administrative options to files, including published, promoted, and sticky status.

If you decide to use the module please also look at the issue queue. Although the module is stable a few extras can be had by applying a few select patches, especially Create tie in for views\_bulk\_operations as you are using that module.

---
Tags: media, files
---


title: Calling a procedure from drupal

text:
# Question
Title: Calling a procedure from drupal
I have a procedure structure like this in an Oracle database:

```
procedure overlapping_course (
  v_id  number,
  v_program varchar2,
  v_message_type  varchar2,
  v_user_type varchar2,
  v_language  varchar2,
  v_channel varchar2,
  v_country varchar2,
  v_start_date  date,
  v_end_date  date,
 v_return_val  out varchar2
 )

```

I am trying to call this procedure from Drupal 7 and I am following this link. My code looks like this:

```
 $conn = Database::getConnection();
 $saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
 $conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));
 $statement = $conn->prepare('call overlapping_course(?,?,?,?,?,?,?,?,?,?)');

$statement->bindParam(1, $id,PDO::PARAM_INT);

$id=1;

$statement->bindParam(1, $program,PDO::PARAM_STRING);

$program='c++';
 -------
 --------

```

but I am always getting the following error

```
Fatal error: Call to undefined method DatabaseStatementPrefetch::bindParam()   in C:\Apache24\htdocs\drupal\includes\database\oracle\database.inc on line 655.

```

# Answer
> 1 votes
I don't know the problem, but after adding the following piece of code in my database.ini of oracle directory and changing my calling method prepare('-----') to oraclePrepare('-------') I am able to access the stored procedure with parameters. I got the reference from here

Check for the oraclePrepare('-------') method in database.ini. If it is not there then add following lines in the DatabaseConnection\_oracle class.

code Added in DatabaseConnection\_oracle class of oracle's database.ini:

```
 public function oraclePrepare($query)
 {
     return parent::prepare($query);
  }

```

---
Tags: database
---


# Question
Title: Combine Webforms to export multiple form results in a single CSV
I need to be able to select multiple webforms and then be able to export all of their results in a single CSV download.

I am considering using this module (Views data export) but I'm not yet sure it will fit the task.

Any suggestions on the approach you would take would be appreciated.

**UPDATE:** I approached this using the 'Webform Mysql Views' module but the process is incredibly time consuming as each Webform needs to have a view created for its submissions. These fields then need to be associated in the Webform Submissions view and duplicate fields need to be merged.

# Answer
Webform 4.x is integrated out of the box with views on drupal 7.

1. Upgrade to last webform 7.x-4.x release.
2. Create a view: webform submissions
3. Select each field: webform submission data:Value and your webform node to extract the fields

To download all results the best option is Views data export, you should configure it to use batch for better performance.
> 1 votes

---
Tags: views, webforms, importing-exporting, files
---


# Question
Title: Add tid or name as a class to each item of a taxonomy term
I'd like to add the term ID or the name of the term as a class to each one of my taxonomy terms on a node page.

note that I'm not using views, so I wonder how can I achieve this via template.php or any customized tpl.php, I couldn't find any module as well to add class to each term separately.

thanks.

# Answer
> 2 votes
You can modify the output of any field with:

Possible override templates are:

* field.tpl.php
* field--content-type.tpl.php
* field--field-name--content-type.tpl.php
* field--field-type.tpl.php
* field--field-name.tpl.php

So according to your specification in comment `"product_display" and the reference term field is "field_product_specs"` your custom `tpl` file name should be **field--field-product-specs--product-display.tpl.php**

OR

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

---
Tags: entities, theming, taxonomy-terms
---


# Question
Title: Cannot apply custom CSS via theme settings
With Drupal 7.x and the Whitejazz theme, I want to apply custom CSS styles to some elements. This theme has the option to include custom CSS styles by specifying the path to the CSS file (in Appearance \> Settings).

>

I created the folder and uploaded my file, specified path, but this doesn't work for me, even after clearing the cache. I can apply my styles using the *CSS injector* module without a problem, but I want to find out why I can not set this using the theme settings.

# Answer
The correct method is below. The theme maintainer replied me, there is a wrong path entry in template.php file, line 15

```
  if (theme_get_setting('whitejazz_uselocalcontent')) {
    $local_content = path_to_theme() . '/' . theme_get_setting('whitejazz_localcontentfile');
    if (file_exists($local_content)) {
      drupal_add_css($local_content);
    }
  }

```

At the moment whitejazz (template.php) search for the CSS file in its own themefolder Whitejazz. So CSS should be placed anywhere **inside** the themefolder Whitejazz, i.e. 'css/headers.css' But if I want move the css file to an another place in the drupal rootfolder, then I have to remove in template.php on line 15 this path\_to\_theme() . '/' ., that is:

```
if (theme_get_setting('whitejazz_uselocalcontent')) {
//   $local_content = path_to_theme() . '/' . theme_get_setting('whitejazz_localcontentfile');
   $local_content = theme_get_setting('whitejazz_localcontentfile');
   if (file_exists($local_content)) {
      drupal_add_css($local_content);
   }
}

```

So any of these two methods works.
> 0 votes

# Answer
I think the problem is that you forget to add a reference statement in your theme's info file. like this:

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

```

After that, need to clean the cache.
> 0 votes

# Answer
Looking at the theme, the template assumes that the custom css is within the theme folder:

```
path_to_theme() . '/' . theme_get_setting('whitejazz_localcontentfile');

```

If you want to provide custom CSS in this manner the you need to provide a relative path from the theme folder, eg `test.css`, rather than `sites/all/theme/whitejazz/headers.css`. I have tested this and it works fine.

The description provided by the theme is therefore misleading, but this theme is minimally maintained in any case.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to setup a development server on Linux?
I am developing a new web site for a client who is already on the web with an old site.

I need to develop the site under a different name (dns) and when it's ready, move it safely to a right name.

I am developing and hosting on AWS under Ubuntu using multi-site setup.

When I am ready I will pointing the DNS to my development server and by doing so I will be on air with the real site. My question is: While developing I will be directing another domain to the development server say something like deveopment.com by the time I am ready to go live, I will be pointing the real domain to it, say real.com Other than the dns' what else will I have to change on the server? Will I have to change anything in the DB? Remember it’s on the same server and I can use the same DB.

Am I likely to run into any trouble?

# Answer
> 2 votes
It should work with no or limited changes. However, some modules include fully qualified paths in database tables or variables, so it is worth checking.

Some areas to look at are:

* `settings.php`, particularly the database array, `$cookie_domain`, and `$base_url`
* The sites directory: are you using the `default` directory or one tied to your development environment? If your material is in `sites/my.dev.com` then you'll have `my.dev.com` in the files table
* URL related modules like `securepages`, `xmlsitemap`, and so on

When I am moving from dev to production, I also use `drush` to double-check that I missed nothing. Running `drush vget` dumps the content of the variables table, so I can grep that for URLs. For example to see all the variables that have `www.indiemade.com` hardcoded:

```
$ drush vget | grep indiemade
securepages_basepath: 'http://www.indiemade.com'
securepages_basepath_ssl: 'https://www.indiemade.com'
seotools_base_url: 'https://www.indiemade.com'
xmlsitemap_base_url: 'http://www.indiemade.com'
...

```

One other tool you might want to look into is drush migrate, well explained here.

# Answer
> 1 votes
Normally not. If you are not using any special, domain related, modules (Mike domain access for example) you should be fine. Of course it is always a good idea to test it first(for example with a subdomain) to see how the site behaves on a new domain.

---
Tags: 7
---


title: Views 3 filter on academic year

text:
# Question
Title: Views 3 filter on academic year
Using Drupal 6, Views 3. I am trying to build a view that will include events for the current school year. So this year the view would include everything from September 2014 through June 2015. Once we got to July 1st 2015 the view would show the next year (Sept 2015 - June 2016).

I'm thinking this might be accomplished with arguments but I'm not sure.

Any kick in the right direction would be greatly appreciated.

Les Z

# Answer
> 0 votes
There is a Date filter inside views that can be set and customized easily to satisfy your needs. You need to enable the *Date module* first. Here:

https://www.drupal.org/project/date

If you find implementation using Date module difficult, you can achieve the same result using the straight forward *Views between dates filter module*:

https://www.drupal.org/project/views\_between\_dates\_filter

---
Tags: views
---


# Question
Title: Negative number of stock after order many products
I have a website made using Drupal 7 and Ubercart 3.6, and with the `uc_stock` module.

If client is adding to cart product qty more, then set in stock level that is doesn't generate any errors or notices. And stock level is decrementing to negative number, see screenshot:

Is it possible to disable Negative number of stock level?

# Answer
> 0 votes
Solution of this problem is Ubercart Out of stock Notification module.

---
Tags: ubercart
---


# Question
Title: View display content by value based on user profile field values
I need to create a view that displays saved content with defined field values to users with specific attributes. I.E.

content form with a field boolean of regulated: \[0\] unregulated \[1\] regulated \[2\] both

the view needs to display this content depending upon the user profile value for whether that user is licensed or not. field value of both needs to display regardless of profile value for licensed.

profile field licensed is a boolean. 0 non-licensed, 1 licensed.

There will be content marked as regulated that needs only to be displayed to licensed users, content that is not regulated that needs only to be displayed to non licensed users, and content that is marked for both that needs to be displayed to both licensed and non-licensed users.

Can this be done in views or do I need to write custom php to accomplish this?

# Answer
You may use the flag module to flag users (*it could be an automatic flagging in conjunction with Rules*)as regulated, unregulated or both and then filter via views all flagged users. For anonymous users needs some special handling.
> 0 votes

---
Tags: views
---


title: Prevent caching of a node

text:
# Question
Title: Prevent caching of a node
I'm working on facebook like button for drupal 8. It's about to be done, but I've faced a trouble. Whenever I change the configuration of my module, I still need to clear all caches manually for the changes to take effect.

I'm adding the like button like this:

```
function fblikebutton_node_view(&$build, $node, $display, $type, $lang) {
  $build['fblikebutton'] = [
    '#theme' => 'fblikebutton',
    '#weight' => 100,
  ];
}

```

Are there any ways to prevent all nodes from caching or to clear cache programmatically after configuration is updated? Or I should just change the way I add the button to the page?

# Answer
> 2 votes
It is not clear what exactly you are asking.

@Cottser's answer is correct for disabling the render cache during development but that is not something you want to do on a production site as the render caching critical for performance. Also, when disabling the render cache locally, make sure to always test changes on the same configuration as production to catch problems with it.

If the markup you are outputting is dynamic on something, then you can add that context to the cache key, see my answer in https://drupal.stackexchange.com/a/140777/31.

If it is about clearing the cache after the user changes settings, you can clear the node\_view cache tag with `Drupal::entityManager()->getViewBuilder('node')->resetCache()`. If you want to clear the cache of a specific tag, you can pass the node ID to that method or you can use `\Drupal\Core\Cache\Cache::invalidateTags($node->getCacheTags())`.

Each thing that is rendered has one or multiple cache tags (inspect the X-Drupal-Cache-Tags header of a page response, I'm sure there will be development tools to better understand them in the future), by invalidating them, you can automatically clear all caches that contain them.

# Answer
> 1 votes
The node entity rendering is cached.

To disable the render cache, uncomment the following lines from the bottom of settings.php, copy `sites/example.settings.local.php` to `sites/default/settings.local.php`, and clear the Drupal caches:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

Please see https://www.drupal.org/node/1903374#drupal-render-cache for more information.

# Answer
> -1 votes
You need the *CacheExclude*, you can find it here:

https://www.drupal.org/project/cacheexclude

You may also get inspirations for a customized application.

---
Tags: caching, 8, theming
---


title: Drush does not support Drupal?

text:
# Question
Title: Drush does not support Drupal?
My Drush 5.x was working normally and then suddenly threw this message.

I upgraded to Drush 6 using the Windows installer but I am getting the same message.

This is a Windows 7 machined and I stress that I had been using Drush for hours and as far as I can recall, nothing unusual happened between the last successful use and the sudden error message.

I will be grateful for any tips to resolved this.

# Answer
What version of Drupal are you using? Drupal 8 is only supported by the 'master' branch of Drush on github. Older versions of Drush say "Drush does not support Drupal 8." There was a bug in some versions of Drush where the version number of Drupal is not reported correctly. Perhaps this is what you are encountering.
> 4 votes

---
Tags: drush
---


# Question
Title: Is there a module provides UI to create field index?
My views are quite slow in some cases, needs create indexes on field tables. Is there a module for that?

# Answer
> 0 votes
Field module does not always add indexes for its columns (value column of text field for example), this leads to poor performance in views when we would like sort or filter views using the unindexed columns.

We can check the query executed by views and add custom indexes manually, but it's not deployable. With field\_index.module, we can create and export custom indexes for fields.

# Answer
> 0 votes
Because views does not create tables but rather builds queries, you cannot add indexes to views but what you can do is insert Mysql Index hints via the Views Index Hint module.

If this module is not flexible enough for you, you can manually add the index hint after the sql query is constructed by using the hook\_views\_query\_alter hook.

---
Tags: entities, performance
---


# Question
Title: Where is place $content in node--product--type.tpl.php be generated and manipulated in drupal commerce?
I am a beginner of drupal commerce, I know Drupal Commerce display product with `node--product--type.tpl.php`, "`render($content)`" does this work.

I need to add a property "*monthly sales*" to each node(product display) so that I can display it in node page.

With drupal core, I can use `hook_load` and `hook_view` to display custom properties, but it seems Drupal Commerce doesn't work by this way.

Where is place the array `$content` be generated and manipulated in Drupal Commerce? Which hook can I use?

Appreciate for any help or comments.

# Answer
I got it, It's hook\_entity\_view. We can read profiles\commerce\_kickstart\modules\contrib\commerce\modules\product\_reference\commerce\_product\_reference.module for reference.
> 0 votes

---
Tags: commerce
---


# Question
Title: how to display sales volume for a product or a product variation in drupal commerce?
I need to display number of sales for a product or a product variation in product list. But I cannot find a decent way to go. Can I count order numbers for a product or a product variation with their relation? How should I do? I looked this thread Drupal Commerce: Number of a sales per product, what he want is a view, but I need to display number of sales in product list. I appreciate for any help or comments.

# Answer
I got it, We can use hook\_entity\_view. and we can read profiles\commerce\_kickstart\modules\contrib\commerce\modules\product\_reference\commerce\_product\_reference.module for reference.
> 0 votes

# Answer
Look at https://drupal.org/project/commerce\_reports and edit your product list View to do what it does in its product sales report.
> 0 votes

---
Tags: commerce
---


# Question
Title: Commerce module: Why this commerce_order_ui_form_commerce_order_ui_order_form_alter won't work?
I have this commerce order, and I want to hook into it when an administrator review the order (edit it to set it as complete, canceled, or whatever state).

I want at that moment to use a specific field to check using ajax if the name I'm typing in a specific field, already exists as a username.

So I checked out how it works the username\_check module, and found that it does add that automatic checking using ajax. It does that check when the user types her desired username at the register form.

**How may I adapt it in order to use that functionality for other fields?**

The field machine name is `field_commerce_username`

I've looked into commerce\_order.api, at hook\_form\_alter api, commerce\_order\_ui and specially commerce\_order\_ui\_form\_commerce\_order\_ui\_order\_form\_alter in order to know what to do.

**The username\_check module uses hook\_form\_alter:**

```
function username_check_form_user_profile_form_alter(&$form) {
  $mode     = variable_get('username_check_mode', 'auto');
  if($mode != 'off'){
    _username_check_profile_load_resources($mode);
    $form['account']['name']['#field_suffix'] = '<span id="profile-check-informer"> </span>';
    $form['account']['name']['#suffix'] = '<div id="profile-check-message"></div>';
  }

```

**So, I thought in doing something like this:**

```
function commerce_order_ui_form_commerce_order_ui_order_form_alter(&$form, &$form_state) {
  $mode     = variable_get('username_check_mode', 'auto');
  if($mode != 'off'){
    _username_check_profile_load_resources($mode);
    $form['element']['#field_name'] = 'commerce_customer_profile';
    }
}

```

Now, if I try to add that example code to the username\_check.module (just for testing purposes), I get this error:

```
Fatal error: Cannot redeclare commerce_order_ui_form_commerce_order_ui_order_form_alter() in /home/sitio/public_html/sites/all/modules/username_check/username_check.module on line 75

```

(75 line if where I declare my function).

***I just need to be pointed to the right direction here, why is this error?***

commerce\_order\_ui\_form\_commerce\_order\_ui\_order\_form\_alter() wasn't declared before in the file... and it won't work even if I comment all \_form\_alter functions in the module.

# Answer
I'm guessing by your rep that you already know most of the following but it pays to check:

1. Hooks can only exist once per module
2. Hooks must begin with the module name

So this means `commerce_order_ui_form_commerce_order_ui_order_form_alter(&$form, &$form_state)` won't work inside username\_check.module

If you really want to put the code inside the username\_check module call it:

`username_check_form_commerce_order_ui_order_form_alter(&$form, &$form_state)`

---

\[edit:\]

Of course, you shouldn't put test code inside an existing module. The best way to test code is to make your own custom module, which is pretty easy once you get the hang of it.
> 1 votes

---
Tags: forms, commerce
---


# Question
Title: How to retrieve specified fields using services?
Using services we can retrieve list of all nodes with different filters and we can get a specific node as well. But is there any way we can specify the fields we would like to retrieve ?

Eg: `api/node/[nid]?fields=field3`,`field6` =\> It should return only the mentioned fields of the given nid

And when we specify *fields=all* it should return all fields of the node.

What is the best way to achieve this ?

# Answer
> 0 votes
There is no built in option in Services 3.x that i am aware of, try any of these;

1. Views Datasource
2. Services Views

**Views Datasource**

> Views Datasource can be thought of as a userland complement to the work going on in the Services and RDF APIs as a site operator only needs to know Views to be able to create datasources in the different formats.

**Services Views**

> It has currently two features: \- Create view based resource creating Services display in a view \- Execute any view of the system via views resource call

Views Datasource

---
Tags: 8, services
---


# Question
Title: Possible to set user privileges on part of the text?
In my node I have embeded a view using php snippet in body field. When regular user edits it I don't want him to accidently delete the snippet, is there a way to hide or lock that part of the text from that user so no matter what he does the snippet will remain there? Should I add a custom field just for it or are there a better options? Also note, that the snipped could be placed in the middle of the body field content.

Thanks!

# Answer
> 3 votes
No, there are no ways to do this. And there shouldn't be. First of all, read PHP in database: bad practice but \- this addresses exactly the situation you have here. Long story short: don't do it. Turn off PHP module if you don't need it.

And why you don't need it? Because there is Viewfield module.

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Exactly what you want to do, but without any snippets in user editable texts.

---
Tags: nodes, users
---


title: Change a node page with views module

text:
# Question
Title: Change a node page with views module
If you have for example http://www.example.com/node/5 and you go to that node page you get the page created by Drupal. My node is about an organization and I want on the bottom of that page a list with all the employees. Is there a way that I can do this with the views module?

Because I don't want to use PHP or HTML in the file for that. I know how to create a new view but if I create a new one I cannot use the same page link.

I think that this is a common problem but can't find a solution.

# Answer
Whatever your employees are, if you can create a view of them *(and you say you can)*, you can use Viewfield module.

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Exactly what you want to do, without any snippets of PHP.

Specifically, you need to use this capability:

> * Administrators may supply a common value that will be used for all entities in a content type.

Just set viewvield to display "employees" view for all organization nodes, and filter views by whatever association between employees and organizations you created, using contextual filters.

Viewfield has built-in passing mechanism, token-based on node / content type configuration side. It can pass node id, author, creation date and any field value you have. On the Views side, these will be contextual arguments as usual.

Benefit over blocks: it will work no matter how and where node is displayed - display configurable just as any other field. You don't need do care to alter block configuration if you want, for example, change path from `/node/50` to `/organization/drupalangels`. Blocks may get left behind. Viewfield will simply continue to work. Also, you can place it directly between other fields without any problem, should the need arise.

Of course for each his own, Viewfield is not flawless either. Blocks was always faster for me to configure, for example. And bit easier to theme. I just found the bit of extra time at first configuration worth it in the *long* run. For short and fast project, for a client that does not pay well and don't want you to manage site after it's done, it might be not worth to bother.
> 4 votes

# Answer
You can create a *block* display for your view and display it in the content region of that page (below main content). Specify the path of the page in the block configuration to have it appear just on that page.

If your node is one of many organisation nodes, you will want to pass information about which organisation is being displayed to the block so that it shows only employees related to that organisation. If this is the case, add a *Contextual Filter* to the view which takes a default argument from the url (the node id).
> 3 votes

---
Tags: views, nodes
---


# Question
Title: Views Bulk Operations with Field Collection Item tokens
I am trying to modify the values of one field in all instances of a field collection type. I have a view listing all field collection items, that I want and an operation field with modify entity. Setting value in the field works fine, but I can't use any tokens from the current item, only site tokens are available.

Can this be done with VBO? Are there any other easy ways to do it?

# Answer
You can create a view of nodes, rather than field collections, then add the collection as a **Relationship**.

Your node tokens should now be available for application to the field collection fields.
> 0 votes

---
Tags: views
---


# Question
Title: RESTws POST List (text) field type Error
I'm using RESTws and POSTing a JSON object to "/node". Everything works fine until I include a List text field (checkbox type). The field in question is:

```
...
"field_days_closed_v": ["Monday", "Tuesday"],
...

```

When I post I get this error:

> Recoverable fatal error: Argument 2 passed to RestWSBaseFormat::getResourceReferenceValue() must be of the type array, string given, called in .../restws/restws.formats.inc on line 278 and defined in RestWSBaseFormat-\>getResourceReferenceValue() line 311

My JSON is:

```
{
  "body": {
    "format": "filtered_html",
    "summary": "",
    "value": "test"
  },
  "field_opening_times_t": {
    "format": "filtered_html",
    "value": "Daily"
  },
  "field_price_category": "",
  "field_price_text_t": {
    "format": "filtered_html",
    "value": "<p>Free entry</p>"
  },
  "title": "Mark test test test",
  "type": "primary_article"
}

```

The field is a List(text) and the widget type is Check boxes/radio buttons. Values are:

```
Monday|Monday
Tuesday|Tuesday
Wednesday|Wednesday
Thursday|Thursday
Friday|Friday
Saturday|Saturday
Sunday|Sunday

```

Am I right in thinking it is just an array that should be POSTed?

Any ideas?

# Answer
> 1 votes
The JSON format for list (text) for checkbox type would looks like follows

```
{"title":"My Day","type":"page","field_days_closed_v":{"und":["sunday", "monday"]}}

```

I've tested this, and working fine.

Here `field_days_closed_v` is the machine name of the List text field (checkbox type). similarly `sunday`, `monday` are the values of checkbox type so change them accordingly.

Hope this helps. :)

---
Tags: 8
---


title: Clean url disabling not working

text:
# Question
Title: Clean url disabling not working
For some reason Drupal is parsing my landing pages address with both alias and clean url. Meaning that the landing page for new users becomes /dashboard&destination=node/30 instead of ?q=dashboard or ?q=node/30.

I have tried disabling clean url by unchecking use clean urls (?q=admin/config/search/clean-urls) and clearing the cache, but it still uses them (e.g problem continues). So I was hoping somebody might enlighten me how to force Drupal not to use clean url:s?

Thanks

# Answer
Try to run drush command : ***`drush vset clean_url 0 --yes`***

or

Include a line in settings.php : ***`$conf['clean_url'] = 0;`***

**Updated :**

Check this LINK. There are many ways to disable the clean url.
> 0 votes

---
Tags: caching, uri
---


# Question
Title: Safety of letting user define javascript paths in fields
I have a module that uses the Fields API to insert a HTML5 canvas element and allows users to define paths to user scripts to be loaded with the page:

The scripts are relative to a hard-coded path `base_path() . 'sites/all/libraries' . $field_value . '.js'` so users will have to put all their scripts in the libraries folder.

Is this a safe way to implement this? Does it have and security vulnerabilities?

# Answer
I'm not sure you'll get a much different answer here than you did in your previous question...

But anyhow, assuming your module properly sanitizes the input of the script paths field, it's still potentially dangerous to the extent that:

* your users could be untrustworthy, *and*
* your users could add arbitrary scripts to the file system

I can't tell from this question or the original if you mean that users will be adding a *unique* javascript file for each bit of content, or only that they get to choose one among several scripts to add. If they're adding *new* javascript files, add to the risk above:

* your users may not be able to write safe scripts

So for the most part, this boils down to an issue of trust, so long as the architecture is as described.

To deal with the first item first, it's possible to deny roles upload privileges, so you can prevent them uploading anything or everything if you prefer.

For the second point, the key word is "arbitrary". Drupal has a hook, hook\_library that allows you to define js libraries that can be added and referred to from code. You could use this hook to define a preset collection of libraries that your users could add to individual pages (if, as I mentioned, you only need to offer a choice of libraries, and not *unique* libraries per page).

---

But I'd suggest rethinking the architecture. For example, if users need to add a *unique* script to each node, I'd wonder if it would be possible to abstract out what is common to each script, load that script on every relevant page automatically, and let the users pass configuration options through the form fields instead (or e.g. even upload a json or other structured data file which could be sanitized/sanity-checked in PHP before being output to the page).

Alternatively, if you just need to offer your users the option of one among several libraries, *and* you already use the Context module, you could use a module like e.g. RE Context Libraries to add js files to individual nodes (disclaimer: I wrote the module).

This would allow you to restrict the insertion of libraries to those you've pre-approved, as well as allowing you to piggy-back on the Context module's permissions (though I'd note that the Context module's permissions may not be fine-grained enough if you have many users).
> 3 votes

# Answer
# It's only as safe as your users wants it to be

You allowed your users to put files on your server, in a folder where Drupal keeps files meant to be executed. It means that:

## If you allow PHP in libraries

any of them can do anything with your site whenever he wants.

## If PHP files placed in libraries are blocked

it still does not really matter what paths you allow in fields. Their JS files will be able to do pretty much anything they want anyway. This includes ability to **unknowingly introduce XSS options** for third-parties even if they didn't mean it.

# Safer way

would be to do what Stack Exchange is doing. You can read about it in Introducing Runnable JavaScript, CSS, and HTML Code Snippets. Main points are:

> * We use HTML5 sandboxed iframes in order to prevent many forms of malicious attack.
> * We render the Snippets on an external domain (stacksnippets.net) in order to ensure that the same-origin policy is not in effect and to keep the snippets from accessing your logged-in session or cookies.

And of course they will not allow anyone to write to the folder that keeps site's own files.
> 2 votes

---
Tags: 7, entities, security
---


# Question
Title: Finding variables available in preprocess node or node.tpl.php from cck fields
Would really appreciate help resolving this. I am using D7 and the devel module is not an option, for some reason it causes some problems with my site. I have looked into the contemplate module but see it isn't supported in D7, otherwise it would be great. Is there any quick way for me to see all my variables so I can utilize them in a preprocess function?

# Answer
Yes, you can do something like this in a custom module:

```
function YOURMODULE_preprocess_node(&$vars) {
  drupal_set_message('<pre>' . print_r($vars, true) . '</pre>');
}

```

or this in your theme's template.php file:

```
function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('<pre>' . print_r($vars, true) . '</pre>');
}

```

If that's too much information, you can get just the variable names with:

```
 foreach ($vars as $name => $value) {
   drupal_set_message($name);
 }

```

instead of print\_r()ing the entire array.
> 3 votes

# Answer
I use Drupal for Firebug module and respective extension for firefox. With these modules yo can call firep() function:

```
function YOURTHEME_preprocess_node(&$vars) {
  firep($vars);
}

```

to see result in firebug console (in a special 'drupal' tab).
> 2 votes

---
Tags: theming
---


# Question
Title: How to load login, register and other forms and nodes in modal window?
I am seeking a module or technique to show forms (for example login form, register form etc.) and nodes in a modal window/pop up.

I found some modules that promise to do that, but none of them seems good for my use case:

What is the best way to have this feature. I would prefer a solution that is easily extendible to load nodes or other entities as well within a modal window.

What is the Drupal 7 way to do that?

# Answer
> 4 votes
No need to write single line of code.

To open node add/edit form in modal window, try below modules

https://www.drupal.org/project/ctools\_automodal https://www.drupal.org/project/ctools\_automodal\_admin

I tried & it works properly for me.

To open node add form in modal admin/config/system/ctools\_automodal\_admin -\> **Modal content types** and select content types.

To open node edit form in modal add **node/%node/edit** in **Extra modal links** textarea.

# Answer
> 3 votes
The core module **Overlay** in combination with the Overlay Paths module might be a good choice (i'm using it at one of my sites).

Another solution which seems to fit better your question should be the Ctools Automodal and/or CTools Auto-modal Admin Interface modules. With a little theming you can have nice popup windows for any form.

# Answer
> 0 votes
If you are using Twitter Bootstrap or Zurb Foundation I think it's not hard to do. Just copy the modules that you want to change to the custom folder (you have to create that folder in sites/all/modules) and then change some codes to fit the requirement of foundation or bootstrap. It's not that hard i think.

On the other hand, if you are not using those css/js frameworks. You can always use Jquery UI or other js. But make the changes always in the custom folder

I hope that help. Thank you

# Answer
> 0 votes
Popup module allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content. Even you can mention the block to appear in popup window. And it have the option to popup the login form, register form etc.

> • Popup that provides the basic popup framework as well as a few basic popup styles.
>
> • Popup block that provides block configuration options to allow any block to be displayed as a popup.
>
> • Popup descriptions that replaces form item descriptions with popups.
>
> • Popup filter that privides an input filter that replaces popup tags with popups in filterable content. (The popup suite grew from the Popup filter module).
>
> • Popup menu that provides blocks of popup menus for each defined menu within the system.
>
> • Popup nodereference that displays node references as popups.
>
> • Popup UI that provides a means of managing popup display formats, as well as cck and views integration of node-reference fields

---
Tags: javascript
---


# Question
Title: How to ensure CiviCRM checksum / cid are valid in custom Drupal module
Follow up to an earlier question:

I am writing a simple custom Drupal module to display information about a contact's related organizations (see above for more background if interested).

One use case is that a logged in user sees this info, in which case determining whether to show the info is easy (I just use the Drupal contact ID to pull information from CiviCRM).

However, if someone visits the page from a checksum link sent via CiviMail, Drupal considers the user to be anonymous. I can pull the `cid` (CiviCRM contact ID) from the URL easily enough, but I need to be able to also verify the checksum in order to display information without a possibility of an information leak. How do I do that?

I found this function: `CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId)` but this generates the checksum. I just need to verify an existing checksum (from the URL), not create a new one.

# Answer
> 3 votes
A little grepping around and I found this:

`CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])`

which takes a CiviCRM contact id (`$cid`) and compares it to the checksum in the URL and did the trick for me as follows:

```
  $cid = check_plain($_GET['cid']);
  if ($cid != "" && CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])) {
        //Contact ID and Checksum match up, embed a view
        //with $cid as an argument (or other custom functionality)
  } else {
        //Not a match, decide what you want to do in this case
        //(e.g. check if user is logged in, or display error...)
  }

```

**UPDATE:**

It looks like the usage has changed slightly in core since I pulled the above out of there (although the above was still working for me). Try this (taken from here):

```
    //check if this is a checksum authentication
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
if ($userChecksum) {
  //check for anonymous user.
  $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
  if ($validUser) {
    return $tempID;
  }
}

```

---
Tags: civicrm
---


# Question
Title: xml sitemap module : XML declaration allowed only at the start of the document
I installed the xml sitemap module, when I go to my sitemap.xml page, it give me an error:

> This page contains the following errors: error on line 1 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error.

How can I find spaces that shouldn't be there? How to find spaces before `<?php` tag, but omit files where they are legitimate, like theme files?

# Answer
> 1 votes
I fixed the problem by deleting a white space before the php tag in the settings.php file.

---
Tags: xml-sitemap
---


# Question
Title: How to get a list of all javascript files in a directory
Is it possible to get a list of all the javascript files in the libraries directory? So far I have tried using files\_scan directory but it's not returning anything:

```
$dir = base_path() . 'sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");
dpm($files);

```

many thanks.

EDIT

I changed to using `DRUPAL_ROOT`. This gives the correct path and returns an array of js files but there is a double slash `//` in the uri just before the file names: `/var/www/html/droop/sites/all/libraries//d3/d3.min.js`

```
$dir = DRUPAL_ROOT . '/sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");
dpm($files);

```

# Answer
libraries\_get\_libraries should return an array of library directories, with the library name as the key and the directory as the value.

libraries\_get\_path will get you the path to a specific library (js).

Follwing your approach, this works fine for me:

```
  $dir = "sites/all/libraries";
  $files = file_scan_directory($dir, '/.*\.js$/');

```

I think it might be base\_path that is breaking it in your example, as it adds a `/` in front of the (relative) path from the site root.

Combining libraries\_get\_libraries with file\_scan\_directory will also get you libraries from profile and site specific directories:

```
$libraries_array = libraries_get_libraries();
foreach($libraries_array as $library => $directory) {
  $files = file_scan_directory($directory, '/.*\.js$/');
  $js_paths[$library] = $files;
}
dpm($js_paths);

```

It may be worth noting that these libraries may contain many javascript files that are not actually used by modules.
> 2 votes

# Answer
I am looking into it a little more but for starters does dpm() show the correct value for `$dir`? Also, according to the documentation the trailing slash on `$dir` is not supposed to be there.

code that is working for me:

```
$dir = DRUPAL_ROOT . '/sites/all/libraries';
$files = file_scan_directory($dir, '/.*\.js/');
dpm($files);

```
> 1 votes

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


# Question
Title: Possibility to apply a patch to a target directory with Drush make?
Is there any way to declare target directory for a patch in a Drush make file?

I need to apply a patch to a subfolder of a module. The reason is that CiviCRM's project is composed from multiple repositories (the patch is from the civicrm-drupal repository, which corresponds to `civicrm/drupal` in the packaged module).

There was a proposal along these lines in #745224, but ultimately only support for `-p0` and `-p1`-type patches was committed.

(I'm now using a work-around by declaring a library in that location and applying a patch to it, but a cleaner way would be nice).

# Answer
> 2 votes
After clarifying that the goal of the original question was to be able to use patches generated by pull requests on GitHub directly, I'm suggesting an alternative answer. My original answer is correct if the goal is to package this on Drupal.org. Because a drupal-org.make requires patches to be found on Drupal.org, the path can be updated in the patch to to target directories within the CiviCRM project. drupal-org.make also requires all external projects to be whitelisted. Only the sk (starterkit) build of CiviCRM is whitelisted (https://www.drupal.org/node/1588192) because of the size and licensing limits.

When using drush make locally, you can use both patches and code from any source.

> IIRC it was a bit more complicated than just combining the repos?

It really isn't more complicated than just combining the repos. There is some additional logic in https://github.com/civicrm/civicrm-core/blob/master/tools/scripts/releaser/releaser and https://github.com/civicrm/civicrm-core/blob/master/distmaker/distmaker.sh, but you can really focus on what happens in...

https://github.com/civicrm/civicrm-core/blob/master/distmaker/dists/drupal\_php5.sh

```
dm_install_core "$SRC" "$TRG"
dm_install_packages "$SRC/packages" "$TRG/packages"
dm_install_drupal "$SRC/drupal" "$TRG/drupal"

```

That combines https://github.com/civicrm/civicrm-core with https://github.com/civicrm/civicrm-drupal and https://github.com/civicrm/civicrm-packages.

Other than the versioning, that's really all that happens when a new release of CiviCRM is packaged. There isn't any code for a D7 release that doesn't come from those 3 repos. By adding each of these projects directly, the relative path of the code will match what the patch expects allowing the patch to be applied in the .make.

So to get something like https://github.com/civicrm/civicrm-drupal/pull/144.patch to work before it is merged into a release, your .make would look something like...

```
libraries[civicrm][download][type] = get
libraries[civicrm][download][url] = "https://github.com/civicrm/civicrm-core/archive/4.4.10.zip"
libraries[civicrm][destination] = "modules/"
libraries[civicrm][directory_name] = civicrm

libraries[civicrm-drupal][download][type] = get
libraries[civicrm-drupal][download][url] = "https://github.com/civicrm/civicrm-drupal/archive/7.x-4.5.4.zip"
libraries[civicrm-drupal][destination] = "modules/civicrm/"
libraries[civicrm-drupal][directory_name] = drupal
libraries[civicrm-drupal][patch][144] = https://github.com/civicrm/civicrm-drupal/pull/144.patch

libraries[civicrm-drupal][download][type] = get
libraries[civicrm-drupal][download][url] = "https://github.com/civicrm/civicrm-packages/archive/4.5.3.zip"
libraries[civicrm-drupal][destination] = "modules/civicrm/"
libraries[civicrm-drupal][directory_name] = packages

```

# Answer
> 0 votes
You can find dozens of patches to all levels of CiviCRM (the Drupal modules, CiviCRM core, and additional libraries this project includes) in the .make for https://www.drupal.org/project/civicrm\_starterkit

http://cgit.drupalcode.org/civicrm\_starterkit/tree/drupal-org.make

---
Tags: drush, version-control
---


title: Javascript closures in modules

text:
# Question
Title: Javascript closures in modules
I am trying to adapt some code I have written in javascript outside Drupal to a Drupal module:

```
(function($) {
  Drupal.behaviors.myModule = {
    $(config.targetElement).html(config.template).promise().done(function(){
      initialize($(config.targetElement).attr('data-region'));
    });

    var initialize = function (region) {
      if (region in config.regions) {
        //Calls the API
        $.ajax({
          url: config.apiUrl + config.regions[region]
        }).then(function(data) {
          //Build a regional weather object and render it to the UI
          renderUI(buildRegionalWeather(data));
        });
      }
    };
  }
})(jQuery);

```

This code was working before I wrapped it in the Drupal behavior, but now it is broken. initialize() can't be referenced from within the promise callback.

I assume it has something to do with the intricacies of closures which to be honest I'm not that familiar with.

I had a similar problem with some other code where I ended up Doing like this:

```
(function($) {
  Drupal.behavior.myModule = {
    //Document ready code here...
  }
  Drupal.myModule = {
    doStuff: function() {
      //Some public function here...
    },
    doMoreStuff: function() {
      //Yet another public function...
    }
  }
})(jQuery);

```

Which works, but exposes every single function I write. In the above case it is not so much of a problem, but there are many other functions in the javascript-file I am trying to adapt which should not be exposed like that.

How should I be implementing this?

# Answer
Try this for Drupal 7 documentation:

```
(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      // code here
      // example function call
      Drupal.behaviors.myModule.exampleFunction();
    },
    exampleFunction: function () {
      // code
    }
   }
 })(jQuery);

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Views related nodes with contextual filters multiple-value handling problem
I created a related nodes block with views.

Everything seems good but there is one problem that I couldn't find a solution for days.

The views has **Content: Has taxonomy term ID (with depth)** as contextual filter.

If a node has only one taxonomy term there is no problem and the related views block shows the related nodes tagged with the same taxonomy term.

But if a node has multiple taxonomy terms, the related nodes block shows all the nodes that are tagged with **any** of the taxonomy terms although I selected the **Filter to items that share all terms** option.

**Is there any way to solve this problem?**

# Answer
The answer was very simple but I missed it, you don't miss it if you are in the same situation:

Tick the **Allow multiple values** below the **MORE** part in contextual filter.
> 9 votes

---
Tags: 7, views
---


title: Cannot move a site to the local server

text:
# Question
Title: Cannot move a site to the local server
I am a complete newbie to Drupal, although I have many years of PHP development and even more years as a system administrator. My task is to move a few Drupal sites from CentOS 5.x/Drupal 6.x to Centos 6.x and Drupal 7.x

My plan is to move all sites to Centos 6.x and then upgrade to 7.x (if possible).

I downloaded the first drupal site using rsync and then I exported the relevant database with mysqldump.

I imported the database and created the appropriate mysql user with the same permissions as in the production server.

Important: In my local server I use the domain **"testsite.local"** The production domain is "testsite.com".

Now, the problem: When I enter testsite.local in my browser, all I see is the Drupal page saying that I have not created a first page!

I am almost sure that this is a configuration problem, but I cannot pin-point it. Can you help me?

# Answer
You need to configure Drupal to connect to your new database. Also, make sure you have copied all the dot-files (.htaccess) as well. You will realize using a version control system is faster than rsync (although rsync is much faster than copying all files again and again).

Site migration instructions are nicely said in this drupal.org article. It's a lengthy one, so I'm quoting the part that you probably need to fix your site from current state.

> Make changes to the “Database settings” section of the settings.php file, to ensure that they are pointing to the new database, with the right user (which may be different that the one you used on the old computer) and the right password. You may also have to adjust the “base URL” if you are moving between a sub-domain and a domain level. If you are moving the site to a new domain, or to localhost, also check that "$cookie\_domain" is not set to your old domain.
> 2 votes

---
Tags: migrations
---


title: How to check author role in Views PHP

text:
# Question
Title: How to check author role in Views PHP
I need to check author role using views php. I've already added a relationship and added a field(excluded from view) User: role. How can I check if author role is equal to 'administrator'?

# Answer
I've added in Value Code:

```
$user_load = user_load($row->uid);
$var = $user_load->roles;
return $var;

```

then I've used in Output code:

```
print_r($value[3])

```

to get the string
> 0 votes

---
Tags: users, views
---


# Question
Title: How to override limit of only 10 items showing in Create an Order page in Drupal Commerce?
On the Create an Order page (/admin/commerce/orders/add), my client is not able to see more than 10 items in the dropdown when using the 'Add Line Item' for a Product. I can see that in the commerce\_product.module that the function function commerce\_product\_autocomplete() is limiting with the following line:

```
// Get an array of matching products.
$products = commerce_product_match_products($field, $instance, $tag_last, $match, array(), 10);

```

..but how can this be overridden? Trying to implement a change in a custom module does not seem to be read by the system. Can anyone explain why this is, and how it can be changed?

Any help is greatly appreciated. Thanks!

# Answer
> 3 votes
This should be the screen you are referring to yes?

The field here is an auto complete field that is widely used in Drupal Commerce. And yes the hints are limited because if they were not limited then the AJAX call could take a very long time to run. You have to keep typing to narrow down your options in the provided guesses.

Short answer: No you cannot change this without hacking Commerce.

Long answer: To change this would require a lot of work because the create order form (/admin/commerce/orders/add) is built by attaching fields from the entity. Specifically here is the code that creates the form in the image above. So in order to change this you would have to alter the field types of the order entity. Specifically the Product SKU field would have to be altered and it's call back replaced with one that would load more than 10 items. Doing so would of course alter Commerce and any upgrade you did to Commerce would erase your alterations.

```
// Add the field related form elements.
$form_state['commerce_order'] = $order;
field_attach_form('commerce_order', $order, $form, $form_state);

```

This uses field\_attach\_form to attach elements to the existing form based off the entity, in this case the entity 'commerce\_order'.

---
Tags: commerce
---


title: Views sorting a custom field

text:
# Question
Title: Views sorting a custom field
I've added a custom field to my view using hook\_views\_data:

```
/**
 * Implements hook_views_data().
 */
function homepage_views_data() {
  $data['homepage']['table']['group'] = t('Recency field');
  $data['homepage']['table']['join'] = array(
    // Exist in all views.
    '#global' => array(),
  );

  $data['homepage']['recency_field'] = array(
    'title' => t('Recency'),
    'help' => t('Display a calculated recency date'),
    'field' => array(
      'handler' => 'views_handler_recency_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
  );

  return $data;
}

```

Right now, my field is simply returning the value of node\_created. In my field handler:

```
/**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $output = $values->node_created;
    return $output;
  }

```

I can add my custom field to a View no problem. But after adding it as a sort field, I get:

> SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'recency\_field' in 'field list'

The query looks like this:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, recency_field AS recency_field
FROM
{node} node
WHERE (( (node.status = '1') ))
ORDER BY recency_field ASC

```

Does views\_handler\_sort\_date need to work with a real database value?

# Answer
> 0 votes
I believe views lets the database do the sorting, so unless your field exists inside the database, the database controller won't recognise it which is what your error message basically says.

---
Tags: 7, views
---


# Question
Title: Users are unable to approve a one way relationship
I've set up a one way relationship with the User Relationships module When one user requests a relationship to another user, the table that should allow the other user to approve/deny the request has no operations automatically populated.

To be more specific lets say this is a Manager relationship to an employee. Where User A is the manager and User B is the employee. User A requests to be User B's Manager. User B receives the request and follows the link to the page where he/she would normally approve the relationship.(example.com/user/\[uid\]/relationships/received) When User B arrives on the page there is a table showing the request, but under the Operations column there is nothing in the cells.

I initially thought this was a permissions issue, but when I looked it appears that both users have the permissions they should need to accomplish this.

For reference I'm using version 7.x-1.0-alpha5 of the User Relationships module.

# Answer
> 0 votes
It looks like this actually was a permissions issue. In order for someone to be able to accept a relationship request, they also need permission to make the request.

In order to accomplish what I needed I also had to enable the "User Relationship Implications" module.

---
Tags: users
---