# Question
Title: Migrate callbacks() with addFieldMapping for destination_dir
i want to switch the **destination\_dir** in a custom file migration class derived from DrupalFile6Migration. The DrupalFile6Migration class is provided by the migrate\_d2d module.

For this purpose i think it's necessary to use **callbacks** for field mappings like it's described here: https://www.drupal.org/node/1133448

I use successful a callback with the field mapping for destination\_file in the file migration:

```
class FileMigration extends DrupalFile6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);
    $this->addFieldMapping('destination_file', 'filepath')
      ->callbacks(array($this, 'myPath'));
  ...
  protected function myPath($uri) {
    // do stuff
  }
...

```

But when i try do do this with the **destination\_dir** i can't get success. XDebug shows, that myDestination() is never called:

```
  this->addFieldMapping('destination_dir')
    ->callbacks('myDestination');
  ...
  protected function myDestination() {
    if(...) {
       return 'private://';
    }
    else {
      return 'public://';
    }
  }

```

But i can change the destination\_dir with defaultValue, e.g.:

```
  this->addFieldMapping('destination_dir')
    ->defaultValue('private://');

```

Any suggestions, knowings if callbacks() in combination with **destination\_dir** is perhaps not possible?

# Answer
Maybe you can use file\_class like this

```
$this->addFieldMapping('field_yourimage_field', 'fidsarray');
$this->addFieldMapping('field_yourimage_field:file_class')
->defaultValue('MigrateFileFid');

```

The you have to implement prepare row to get the managed file fids you want to import like this

```
public function prepareRow($current_row) {
 if (parent::prepareRow($current_row) === FALSE) {
  return FALSE;
 }
 //sample code to get the file ids. it may be different in your case
 $fidsarray= array();
 $fidsarray = explode(",", $current_row->columnwith_file_ids_comma separated);
 $current_row->fidsarray=$fidsarray;
}

```

if you dont have managed files and therefore fids available other options can be used too. See https://www.drupal.org/node/1540106
> 1 votes

# Answer
OMG, it is possible with addFieldMapping(param1, param2), witha destination and **source**. The callback function can just override the **source** value and when there is no **source value** the callback is useless/never called.

So i change my code like this and everything is fine:

```
this->addFieldMapping('destination_dir', 'filepath', FALSE)
  ->callbacks(array($this, 'myDestination'));
...
protected function myDestination($uri) {
  if (preg_match('/^myfiles\/\w{2}\/thumbs\/\S+$')) {
    return 'public://';
  }
  else {
    return 'private://';
  }
}

```

Third parameter FALSE avoids warn\_on\_override :)
> 1 votes

---
Tags: migrations
---


# Question
Title: Is it possible to add a wildcard in template.php to apply function to multiple items
I have a webform with 20 different select options under different fieldsets and they all need to have a custom drop down select field title. To achieve that you use this:

```
function theme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_653') {
    $form['submitted']['products']['product_1']['quantity']['#empty_option'] = t('Qty');
  }
}

```

Now each form is identical except the `['product_1']`, so to make that custom title work on every field is that you have to copy paste 20 lines of same code and just rename the `['product_1']` to `['product_2']`, `['product_3']` and the etc.

I was thinking is there some method like in CSS where you can use wildcards, e.g. (to get the idea): https://stackoverflow.com/questions/5110249/wildcard-in-css-for-classes

So you could achieve all that with just one line of code and apply it to all quantity fields in the webform.

So instead of spamming:

```
$form['submitted']['products']['product_1']['quantity']['#empty_option'] = t('Qty');
$form['submitted']['products']['product_2']['quantity']['#empty_option'] = t('Qty');
$form['submitted']['products']['product_3']['quantity']['#empty_option'] = t('Qty');
And so on...

```

You could do something like

```
$form['submitted']['products']['*']['quantity']['#empty_option'] = t('Qty');

```

But it doesn't work.

# Answer
This seems more like a general PHP question, but I'll answer it anyway with some Drupal context.

You usually loop through the array in these instances. You'll find looping as you code in Drupal more and more common.

Consider the following structure:

```
$form['submitted']['products']['product_1']['quantity']['#empty_option']

```

Assuming that you're editing the `['quantity']['#empty_option']` of each \[product\_x\], you loop through your array like so:

```
foreach(element_children($form['submitted']['products']) as $key) {
  $form['submitted']['products'][$key]['quantity']['#empty_option'] = t('Qty');
}

```

`element_children` gives you the keys for the array which don't start with a hash `#`. Whether or not it's suitable for your particular array is a different matter. You can inspect your variable using `var_dump($variable)` or through Devel module's `dpm($variable, 'label');` function.

You may find that you may need to run some if statements to test if `$key` starts with `product_` if you have more than `product_x` keys under `$form['submitted']['products']`

```
foreach(element_children($form['submitted']['products']) as $key) {
  // Only proceed if array key starts with product_
  if (substr($key, 0, 8) == 'product_') {
    $form['submitted']['products'][$key]['quantity']['#empty_option'] = t('Qty');
  }
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: hook_page_alter and trying to change the '#theme_wrappers' property
I'm going a bit Drupal crazy trying to change the '#theme\_wrappers' property of certain blocks in my sidebar region. I am able to set it using hook\_page\_alter and can dpm() it and confirm it is being set, but it never calls the function I point it to:

```
 $element = $vars['page']['sidebar_first'];

  foreach($element as &$elements){
    if (array_key_exists('#block', $elements)){
      $menuBlock = (array) $elements['#block'];
      if ($menuBlock['delta'] == "navigation" || $menuBlock['module'] == "menu"){
        $elements['#theme_wrappers'] = array('wet4_menu_tree__menu_sidebar');
      }
    }
  }

=====================

function wet4_menu_tree__menu_sidebar(&$variables) {
  dpm($variables);
    return '<ul class="list-group menu list-unstyled">' . $variables['tree'] . '</ul>';
}

```

Any ideas?

# Answer
> 1 votes
As I commented above, the issue was that I was missing the & before $vars in this line:

```
$element = $vars['page']['sidebar_first'];

```

It was not creating a reference so it wasn't actually setting my '#theme\_wrappers' property.

# Answer
> 0 votes
The theme function is menu\_tree and menu\_tree\__menu\_sidebar is a more specific version.

So the theme name you need to use is menu\_tree\__menu\_sidebar. Like this:

```
$elements['#theme_wrappers'] = array('menu_tree__menu_sidebar');

```

Then the theme system will search form implementations of that and find your wet4\_menu\_tree\__menu\_sidebar function.

---
Tags: routes, theming
---


# Question
Title: Sheetnode Multisite Javascript error message: 'Unknow line type '' '
I'm using sheetnode in a multisite configuration and I'm trying to refer data from an other sheetnode into the current sheetnode.

My issue is very similar to this one https://www.drupal.org/node/1386114 except that clean url are working correctly:

Formula: '=mapping!A1' Javascript error message: 'Unknow line type '' '

I've been looking at the network tab in chrome and I realize that the difference between a working version and my multisite are few white line at the top of the load/sheetnode call.

I believe that this is part of my problem but I don't know how to resolve it.

Any idea of what's going on ?

Thanks.

# Answer
> 0 votes
**SOLUTION:**

It seems obvious now but... if you have the same problem with any other module, just look at the source code.

If you see a lot of white space at the beginning, it's a clue.

Someone might have inadvertently left a closing php tag ('?\>') somewhere in his code.

Someone doing copy/paste from online example/sources....

Anyway..I pulled my hair but learned some knowledge. No hard feeling to my colleagues ! ;)

---
Tags: 7, nodes, entities
---


# Question
Title: How to return a DatabaseStatementBase object
I have a method that extends the execute() method used in the Drupal 7 database abstraction layer.

When used with db\_query, such as:

```
$result = my_extended_db_query("SELECT * FROM {node} WHERE nid<100")->execute();

```

$result holds a DatabaseStatementBase object, whether there are resulting rows or not. However, following:

```
return $result;

```

the calling function receives an empty array if there had been no query results, instead of a DatabaseStatementBase object. Because of this, -\>fetchAll() fails because it is attempting to operate on a non-object.

How do I get my return to arrive as the same object is started as?

The method:

```
public function execute() {
$sql = $this->sql;
switch ($this->function) {
  case 'db_query':
    if ($this->args) {
      $args = $this->args;
      uksort($args,"si_stats_sort_by_length");
      foreach($args as $name => $value) {
        $sql = str_replace("{" . $name . "}",$value,$sql);
        if (is_array($value)) {
          $sql = str_replace($name,"('" . implode("', '",$value) . "')",$sql);
        } else {
          $sql = str_replace($name,"'" . str_replace("'","''",$value) . "'",$sql);
        }
      }
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e->getMessage() . "\n";
        $msg .= $e->getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    } else {
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e->getMessage() . "\n";
        $msg .= $e->getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    }

```

# Answer
> 0 votes
Bandaid fix, instead of `return $query;` test to see if the class of `$query` is of `DatabaseStatementBase` or else create a new empty instance of that class and return that ... Eg:

```
if (is_a($query, 'DatabaseStatementBase')) {
   return $query;
} else {
  return $empty = new DatabaseStatementBase(Database::getConnection());
}

```

---
Tags: database
---


# Question
Title: Javascript variable value in page source for seo from Drupal.settings
Declared a variable in settings.php

```
$conf['my-variable'] ="my-variable-value";

```

Added inline javascript

```
drupal_add_js("array('my-variable'=>variable_get('my-variable'))");

```

Need to print variable values from Drupal.setttings in inline js

```
drupal_add_js("jQuery(document).ready(function(){
  window.my-val = Drupal.settings.my-variable;

})",'inline');

```

So the output on page is comming up like

```
<script type="text/javascript">
window.my-val =Drupal.settings.my-variable;
</script>

```

But I need it should be like below for seo requirement

```
<script type="text/javascript">
window.my-val = "my-variable-value";
</script>

```

# Answer
> 1 votes
I think you're over-estimating the potential SEO value of making such a change, but if you don't want to use Drupal settings you can just interpolate the value into a static string and use that:

```
$var = variable_get('my-variable');
$js = <<<EOF
function() {
  window['my-val'] = '{$var}';
}
EOF;
drupal_add_js($js, 'inline');

```

I'll leave data-sanitising up to you, how far you need to go will depend on the source of the variable.

---
Tags: javascript
---


# Question
Title: 2015: What am I missing to get a simple hit counter block by page?
I've tried every recommendation I can find; I've enabled statistics and advanced statistics and can see that hits are being counted. I can display lists by what nodes are the most hit, etc; but I just want to display the results for the given node I'm on. How can I do this? I suspect the solution is in using contextual filters for a view, but I can't get this working, either. Help appreciated.

Drupal 7.

# Answer
> 1 votes
I couldn't figure out how to do it with contextual filters, so I guess I still don't understand things on that front. However, a custom block with just a couple lines of PHP did the trick. All directions from:

How to get visitors count of a page created using views

As per that post, custom code was:

```
<?php
$path = $_GET['q'];
drupal_set_message($path);
$visits = db_query("SELECT count(*) FROM {accesslog} where path = :path", array(':path' => $path))->fetchField();
echo "Views: " . $visits;
?>

```

---
Tags: blocks, views
---


# Question
Title: Add "email" to /admin/people overlay view
I have been browsing around trying to find the answer to this but I am not having any luck. I want to add the users email to the table so that we can identify them easier. I have tried to create a new page and use "/admin/people" as the path but I get the error that it can not be overridden. I am relatively new to Drupal so if it sounds like a noob question that is why.

# Answer
> 1 votes
Have you tried using Views for this? This will work well if you want to make a new page that lists all of the users. It won't work out of the box if you want to add the email information to the existing admin/people overlay.

* To use Views, enable the module and go to admin/structure/views/add
* Give the View a name, and then for the 'Show:' option from the dropdown select 'Users'
* To create a new page, leave the 'create a new page' item checked, give the new page a title and path, and under Display Format select 'Fields' Hit Continue and Edit
* On the next screen under Fields hit the Add button, and select User:email

There are tons of options to configure with Views - check out the Views Documentation for more information if you're new to Views.

# Answer
> 0 votes
Similiar to @kbrinner answers, I recommend installing the Admin Views module.

This module:

> Replaces administrative overview/listing pages with actual views for superior usability.

By doing this you can then edit the People view and add the email column for all users.

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


title: Contextual Filter tied to 2 relations?

text:
# Question
Title: Contextual Filter tied to 2 relations?
I've currently got a view on a Node type (Prospects) where part of the filtering is a Contextual filter filtering a 'Sales Region' taxonomy field against a Sales Regions taxonomy field in the User. The idea is that, given a path of, e.g., /user/4/prospects, the view should only show Prospects whose (single) Sales Region term matches one of those in the Sales Regions terms for user 4. This is actually currently working quite nicely.

The problem comes in that we have just added another pair of taxonomy fields to the Prospect and User - a Company field in each. The User has one Company term, and the Prospect can have multiple. The idea is to additionally limit the Prospects shown to those who have a Company Term that matches the selected user's Company Term. The issue (which I realized when I tried to modify the view to handle this) is that I essentially need to tie the one Contextual Field (a UID) to two different Relations - one for the user's Sales Region field, and one for the Company field, but the Contextual Field UI only appears to allow tying it to one Relation. Is there actually a way to do this, or am I going to have to do something like write a custom filter to handle the additional Company filter?

# Answer
> 0 votes
A colleague and I got this figured out after I posted the question.

To clarify the original question: the situation is, you've got a view with a path with one argument (e.g. user/%/prospects, where the argument is expected to be a uid), but you need to use that argument in two different contextual filters - in my case, two different taxonomy comparisons between the selected user and the content I've viewing. The problem is, a contextual filter only lets you reference one relation.

The solution is to enter both contextual filters, but in the second one, in the "WHEN THE FILTER VALUE IS NOT IN THE URL" section, choose 'Provide default value', and in the type, choose (in this particular case) "User ID from URL". Other 'from URL' types are available. This allows you to 'share' one argument with two different contextual filters.

---
Tags: views
---


title: User suddenly logged in as another user

text:
# Question
Title: User suddenly logged in as another user
I face new problem in my site, we have reports from users that when they are surfing our site with their account, suddenly logged in as another user and continue surfing site as it.

I searched all modules for below patterns to find where global $user changed by mistake but found nothing.

```
$user->uid =
$user =
->uid =

```

Is there any suggestion about this issue?

# Answer
I am sure that there is developer mistake here, we have something like you guested,a global `$user` information overwrite by developer code,I suggest you found when this happened,when a comment submit?when a specified form submit and .... ? I think in custom module your developer first write `global $user;` and in continue define $user variable,I suggest you search for `global $user` then look at afterwards codes.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How can I add the full HTML format, and attach CKEditor to it?
I have 2 Drupal sites running on Drupal 7. How can I add the full HTML format, and attach CKEditor to it?

# Answer
> 7 votes
Installation / Configuration

1. Unzip the module files to the "sites/all/modules" directory. It should now contain a "ckeditor" directory.
2. Download standalone CKEditor from http://ckeditor.com/download. Unzip the contents of the "ckeditor" directory from the installation package to the "sites/all/modules/ckeditor/ckeditor" (or "sites/all/libraries/ckeditor") directory. Note: you can skip uploading the "\_samples" and "\_source" folders.
3. Enable the module in the "Administration panel \> Modules \> User Interface" section.
4. Grant permissions for using CKEditor in the "Administration panel \> People \> Permissions" section. Note: In order to enable the file browser, refer to the "Installing CKFinder" section.
5. Adjust CKEditor profiles in the "Administration panel \> Configuration \> Content Authoring \> CKEditor" section. Profiles determine which options are available to users based on the input format system.
6. For the Rich Text Editing to work you also need to configure your filters for the users that may access Rich Text Editing. Either grant those users Full HTML access or use the following tags: `

  <map> <area>

     <quote>

 <address>
  <embed> <object> <param>

` To make copying the list easier, below all tags were placed in one line: `

  <map> <area>

           <quote>

 <address>   <embed> <object> <param>

` If you are going to use CKEditor with the Filtered HTML input format, please refer to the "HTML Filters and Inline Styling" section.
7. To have better control over line breaks, you may disable the line break converter for a given text format in the "Administration panel \> Configuration \> Content authoring \> Text formats" section (recommended).
8. Modify the ckeditor.config.js file to adjust it to your needs (optional). Configuration options are described here: http://docs.cksource.com/ckeditor\_api/symbols/CKEDITOR.config.html Developer's documentation for CKEditor: http://docs.cksource.com/CKEditor\_3.x/Developers\_Guide WARNING: Remember to clear the browser cache after you have modified any of the JavaScript files. If you skip this step, you may notice that the browser is ignoring your changes.

# Answer
> 3 votes
CKEditor version 4 presents the error "version of CKEditor could not be detected" when installed in Drupal 7. This is due to a change of quote marks in CKEditor V4. It can be solved by editing the modules/wysiwyg/editors/ckeditor.inc about line 81:

> if (preg\_match('@version:\\'(?:CKEditor)?(\[\d.\]+)(?:.+revision:\\'(\[\d\]+))?@', $line, $version)) {
>
> to
>
> if (preg\_match('@version:\\"(?:CKEditor)?(\[\d.\]+)(?:.+revision:\\"(\[\d\]+))?@', $line, $version)) {

After I did this, I was getting the following error: "PDOException SQLSTATE 42S02". I also had to uninstall and reenable WYSIWYG to get it working.

# Answer
> 1 votes
It may be helpful to know that this error can be quickly fixed by using an older stable version of the ckeditor library (i.e. 3.6.6.1). Just look for "CKEditor 3.6.6.1 (20 Feb 2013)" under "Older Versions" on the CKEditor download page and download this to sites/all/libraries instead. This worked for me with Drupal 7.22 and Wysiwyg 7.x-2.2.

# Answer
> 1 votes
CKEditor version 4 presents the error "version of CKEditor could not be detected" The dev version https://drupal.org/project/WYSIWYG 7.x-2.x-dev solved this issue without hacking or dublicating the "ckeditor" folder in the "Libraries" folder

# Answer
> 0 votes
I think the simple solution would be to get the "7.x-2.x-dev" from https://www.drupal.org/project/wysiwyg

This a developer version but work fine and I have not witnesses any problems yet.

CKeditor has changed a lot in past years. And older solution like editing CKeditor.inc file does not work anymore.

---
Tags: 7, wysiwyg, input-formats
---


# Question
Title: Using multiple sort criteria on a view, can't get them to play nicely
So, I have a view (D7, Views 3) that provides a list of staff with a thumbnail image based on a location "contextual filter". Some staff members are set as "sticky" and need to appear above all the others. All staff members also need to be sorted by last name, which i'm doing with a custom php sort.

So, first, stickied staff members should be shown sorted by last name. Next, unstickied staff should be shown also sorted by last name.

Last name sort works great, but I can't get the view to group them by sticky.

Here's a screenshot of the view: http://grab.by/h2Gg Here's a screenshot of the first part of the output: http://grab.by/h2GA (Jeremy Irwin is stickied, so should display at the top)

Here's the php code i'm using for the last name sort:

```
list($fname1, $lname1) = explode(' ', $row1->title , 2);
list($fname2, $lname2) = explode(' ', $row2->title , 2);
return(strcasecmp($lname1,$lname2));

```

Any suggestions why this isn't playing nicely with sorting by sticky?

# Answer
> So, first, stickied staff members should be shown sorted by last name. Next, unstickied staff should be shown also sorted by last name.

So you want 2 views (1 being an `Attachment`) and not 1 View. and you can do all this.

* 1 View is of all the people fields with only `stickied` people as a `filter`. Sorted by last name.
* The Attachment is all non-stickied people sorted by last name. You then "attach" this View after the 1st view. Get the page to look how you want using CSS in your theme.

As a final thought I tend to make 2 fields in my content types: `first_name` and `last_name` and then join them as a pseudo-field in Views using `substitutions` or use the Node Automatic Title to hide the title field by using the fname and lname as the title field upon save.

You could change your name column into 2 fields using Views Bulk Operations after creating the "last name" field in your content type ... just saying.

**EDIT**

The benefits to this approach is that you get rid of the odd custom sorting you've hand made and rely on Core Views utilities on your site. This makes moving your site or upgrading drupal versions easier in the long run ...
> 1 votes

# Answer
So, I ended up combining the two sorts into one php field, which works great. Here is the code I used:

```
list($fname1, $lname1) = explode(' ', $row1->title , 2);
list($fname2, $lname2) = explode(' ', $row2->title , 2);
$sticky1 = $row1->sticky;
$sticky2 = $row2->sticky;

// $row1 = sticky so favor it
if ($sticky1 == 1 && $sticky2 == 0) { return -1; }

// $row2 = sticky so favor it
else if ($sticky1 == 0 && $sticky2 == 1) { return 1; }

// Neither are so do normal sort
else { return(strcasecmp($lname1,$lname2)); }

```
> 0 votes

---
Tags: views
---


# Question
Title: Multiple Image Upload and Rename - avoiding multiupload image field
I'm looking to provide the following functionality on my Drupal site:

I'd like to make an easy to use content type that allows users to upload multiple photos easily. The uploader needs to allow them to dump in files, rename them and upload them. I'm currently using the multiupload image field which I've found to do the job of uploading well but, I don't like the thought of increasing my php upload limit to allow users to upload a whole load of photos at once. I wondered whether there was an uploader that allows users to drop in their photos and, providing an individual photo isn't over the upload limit, will handle the upload of all of the photos?

An added bonus would be the ability to rename photos, once they've been uploaded.

Thanks in advance for your help!

# Answer
Plupload has a variety of upload widgets that should allow you to upload without increasing the php limit. You can view examples of the widgets here. You can pick one of the \[modules that integrate pulpload on its project page at https://www.drupal.org/project/plupload.
> 0 votes

---
Tags: nodes, media
---


# Question
Title: Drush to get and print single node data in terminal?
I want to do a raw dump of a single node's data with Drush, for testing purposes and just to inspect a node fast. Similar to getting a variable with "drush vget". Here is a PHP equivalient:

```
drush php-eval "print print_r(node_load(243271), 1)";

```

Only, I'd like it to be simplified to be like:

```
drush nget 243271;

```

Is there a command like that already?

# Answer
> 4 votes
Install this set of Drush tools to either your $HOME/.drush directory or within your project.

Drush Entity

Brief examples from the project page are:

```
drush entity-read node 3  |  less

#read in json format
drush entity-read node 3 --format=json

drush entity-type-read user

drush entity-type-read node --fields=label

drush entity-type-read user node --fields=label,bundles/*/label,drush/count

```

**EDIT**

For legacy Drupal6 support of viewing what a Node contains consider using Node Export via the command line and drush, possibly using the `--pipe` command to Linux `Less` command.

---
Tags: 6, drush
---


# Question
Title: How can I improve as a site builder for dealing with errors I don't know how to handle?
As a relatively new Site Builder, I understand some of what is going on under the hood. But when things go wrong .…

Without an intimate knowledge of module code and inner workings, the error messages often simply tell me *something* went wrong.

Furthermore, I don’t know if a particular message occurred from the action I **just** executed, or if I have simply not been to a specific page in a while (or never before), in which case any number of actions could have broken it.

In any case, I have no idea what messages like this one mean:

```
'Notice: Undefined index: var_name in _some_method_some_where() (line 35 .…'

```

This are the steps I typically perform (my workflow) to resolve an error:

1. Check the module's issue queue for known bugs – Occasionally I find a known problem.
2. Google the error – Normally this doesn’t help as the same error could happen for so many reasons, but occasionally it leads me to a fix.
3. Ask a developer if possible – They often have no idea about my problems …
4. Ignore the error and keep working.
5. If my site is really broken, I try to reset (ugh) or give up on the module altogether and do something else (sigh).

As a site builder, I really don't want to dive into the code every time.

How can I improve my workflow? Like what other steps, resources, approaches, etc would you recommend to a site builder when such kind of things go wrong?

# Answer
> 1 votes
I'm not really aware of a way to improve your workflow. In general I would recommend limiting your usage to modules that have hundreds or thousands of Downloads by site builders, but that is not a silver bullet. And, sometimes you need to use that -dev module that has only 5 downloads because it will save you tons of time in development work on your project.

Everyone typically builds up a listing modules they are familiar with, comfortable with and trust -- build that list for yourself.

Something you didnt mention and I think is a larger problem than what you've outlined is testing module updates to an existing site that is using tried/tested modules previously. I'm more scared of things breaking during a large update (even amongst stable modules) -- then of experimenting with modules earlier in my site building process.

# Answer
> 1 votes
I think the key is in bullet number one:

> Check module issue queue for known bug

You need to get to know the quirks of the module. **Study** the issue queue of the module the error is occurring in (as well as the module description and documentation, obviously). If your problem isn't there at all, file a bug report and help out the community.

---
Tags: 7, debugging
---


# Question
Title: Correct SQL Statement for Joining Taxonomy Terms
I have 2 different taxonomy vocabularies setup.

1. Courses (First Aid, H2S Alive, Air Monitoring, Gas Detection, etc...)
2. Locations (Vancouver, Calgary, Toronto, Montreal)

I have a content type called **Landing Page** for each of the courses that has a taxonomy reference field so you can assign a course or multiple courses to that node.

I have a second content type for **Courses** which also has the 2 taxonomy vocabularies set as taxonomy reference fields on its nodes. These course nodes get displayed in a calendar format and is setup with the entity registration module.

**WHAT I NEED HELP WITH:**

Im looking for a way to output a set of buttons on the **Landing Page** nodes that will give me a the list of locations that have been assigned to any node that is based on the given Courses taxonomy term.

For example;

3 Different **Courses** nodes all have **First Aid** assigned to them. However, they have 3 different locations set to them.

I've created a landing page for the **First Aid** Course assigned it the First Aid taxonomy term. I need to display a set of locations that this course has courses offered at.

# Answer
> 0 votes
If you want to show Locations a Course is offered. Or Courses at a Location I would recommend using the Views Field module, or perhaps Context to show a View on the content type page.

Views field allows you send parameters to the embedded field view from the source Node. So you should be able to get the related content(s) you want to show by passing the necessary filter parameter criteria you want to the View -- usually as a `contextual filter`.

For example for a Landing Page Content Type (eg, First Aid) you add a field that is a View. Call the view like `locations for course`. Then make a View that outputs Location taxonomy term names based on a contextual filters. The contextual filter will be:

* the taxonomy term name of the course(s) in your taxonomy of Courses.

Then output the taxonomy Location term names for results of the set course name contextual filter. Overwrite the linkpath as needed.

# Answer
> 0 votes
In views you can add a relationship to emulate an sql join. In the relationship you define the field that you want to use for this join. The cool thing is that a relatioship has a name. So when you add a field to display you can use this relatioship. Eg if you add field\_sometag it displays the fields of your base entity. But when select to use the relationship then the field displays info about the joined entity

# Answer
> 0 votes
Alright I finally figured it out with the help of @tenken. I didn't end up needing any extra modules except the Views Distinct module to reduce my duplicates as the regular aggregation and DISTINCT items weren't working (assuming it was due to the fact that I had the relationship in there). I was able to relate it through the relationships and the default views.

Heres how I did it;

And the field settings. Its imperative you use Content: All Taxonomy Terms with the "node" relationship applied to it.

And Finally the Views Distinct Module settings.

---
Tags: nodes, taxonomy-terms, database
---


# Question
Title: How can I print messages in a Panel layout template?
Printing the drupal messages in page.tpl.php is easy:

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

```

How can I go about doing a similar thing in my Panel layouts?

Notes:

1. I realise there is 'status messages' pane you can use - I wish to avoid this since admin staff will forget to include it on new pages
2. I definitely wish to do it in the Panel template because there is a section above where the messages should display that is set by the admin staff
3. I have tried simply putting that code into `mylayout.tpl.php`, it didn't work

Here's an example of what I am trying to do:

Is there something I can do in a pre-process function to get this to work?

EDIT:

Thanks to @Beebee I rediscovered the template\_preprocess\_LAYOUT function in my layout's .inc file and added

```
$variables['messages'] = drupal_get_messages();

```

now both `$variables['messages']` and `$messages` exist when the template is called but they contain an array of messages rather than the usual rendered output in a string.

# Answer
> 1 votes
For anyone else who comes across this requirement, messages weren't printing in the Panel template because they were already being called by the page preprocess function in core.

As per this answer about a similar requirement with nodes, the thing to do is to edit your page preprocess function to include this:

```
function YOURTHEME_preprocess_page(&$variables) {
  // This disables message-printing on ALL page displays
  $variables['show_messages'] = FALSE;
}

```

And put this in your preprocess function in your `layout.inc` file:

```
function YOURTHEME_preprocess_PANEL_LAYOUT(&$variables) {
  $variables['messages'] = theme('status_messages');
}

```

# Answer
> 1 votes
What do you think about using Panels Everywhere? You could then add a message pane to your Default site template and avoid 1.

Also you can disable Block from now on, because all parts of your site, are now panels.

# Answer
> 1 votes
I have used Panels sparingly but I've made custom regions in themes and used `#prefix` and `#suffix` wrappers in the Form API to rearrange HTML on my sites.

Offhand I think you should look for a API hook similar to `hook_preprocess_page` or `hook_process_page`, but for Panels to override when viewing content to insert or re-arrange the render array used for the `$content`. Since Panels isn't exactly straight Drupal API, I'm kinda venturing out into unknown territory but here's the best research I can provide now.

After abit of googling I recommend looking at:

The jist of what I'm trying to help you with is to permanently rearrange the output of a Node page such that you can control where `$messages` is placed.

At the theme layer you might want to try to set `Help (Messages)` to a `Region` within the Panel template -- but if that's not possible, hence my attempt at the above magic.

# Answer
> 0 votes
the best integration I could use was having it placed in my `html.tpl.php` file.

---
Tags: panels, theming, chaos-tool-suite
---


# Question
Title: Remove output of author username and blog link of news snippets from search results
I currently have this in *template.php* to remove the *'username's blog'* link from blog entries.

```
function phptemplate_links($links, $attributes = array()) {
    unset($links['blog_usernames_blog']);
    return theme_links($links, $attributes);
}

```

How would I go about using unset to remove the *'username's blog'* link from the search results page?

# Answer
Consider using Display Suite module.

To make changes to search results for article content type, Goto `admin/structure/types/manage/article/display` and enable the search result custom display.

Then visit `admin/structure/types/manage/article/display/search_result` and add or remove the fields as per your requirement.
> 2 votes

# Answer
one simple way without any change in template files.. Just add following code in your css.

```
.search-info {
display: none;
}

```

It done all the tricks..

Hope this will help you.
> 1 votes

# Answer
You can implement using ThemeName\_preprocess\_search\_result() function. Just Refer this link from Drupal.org: http://drupal.org/node/1101554#comment-5345554

```
/**
    * Process variables for search-result.tpl.php.
    *
    * @see search-result.tpl.php
    */
    function YOUR_THEME_NAME_preprocess_search_result(&$variables) {
      // Remove user name and modification date from search results
      $variables['info'] = '';
    }

```

Another solution is that you can override the search-result.tpl.php file in your theme folder. Just remove following snippet from the file:

```
<?php if ($info): ?>
      <p class="search-info"><?php print $info; ?></p>
    <?php endif; ?>

```
> 0 votes

# Answer
You can find `search-result.tpl.php` file in your drupal instance folder `modules/search`. You need to edit that file to hide the author and date details.

Place this part of code in HTML comments tag.

```
<?php if ($info): ?>
      <p class="search-info"><?php print $info; ?></p>
      <?php endif; ?>

```

Now, reload the page. In that way you can remove author details.
> 0 votes

---
Tags: 7, search, nodes
---


# Question
Title: Drupal 7 Bartik Menu tabs changed to vertical list - how to reset back to tabs?
I have been working on a Drupal 7 install with the Bartik theme. Today, the main menu tabs changed to a vertical list on the left side of the page. I do not know how to reset this. I checked the theme folder and none of the css files have been changed, so I suspect it is either a module I installed today or something I did when I was working on editing some pages. Any suggestions would be aprpeciated.

# Answer
Try turning off "Aggregate and compress CSS files" on /admin/config/development/performance and then use right-click inspect element (firefox or chrome) to identify the css responsible for the override. You should see the bartik css files overridden by something else causing this behavior.

A clear cache never hurts either.
> 0 votes

---
Tags: routes, theming
---


# Question
Title: Customise main-menu link - adding a '/' between <li> items
I am using the Omega HTML5 base theme and am attempting to add a '/' delimiter between main\_menu items on my site.

I have searched high and low and the closest I've come is the following:

```
function MYTHEME_menu_link(array $variables) {
$delimiter = '';
  // Only add delimiter to the main menu
  if (strpos($variables['element']['#theme'], 'main_menu') !== FALSE ) {
    // Only add delimiter if item is not the last one
    if (!in_array('last', $variables['element']['#attributes']['class'])) {
      $delimiter = '<span class="delimiter">/</span>';
    }
  }
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  // Add delimiter just before the closing </li> tag
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . $delimiter. "</li>\n";
}

```

This actually works on any another template (just not OMEGA). Irrespective does anyone have an approach to adding this forward slash on main-menu items?

Thanks!

# Answer
> 1 votes
I would suggest a purely CSS approach to this. There is really no need to go through the trouble of adding a function to your theme for this change.

The following CSS code would get you (at least close to) the results you desire:

```
  ul.main-menu li:after {
    content: "/";
  }
  ul.main-menu li.last:after {
    content:"";
  }

```

The `:after` pseudo-class's support includes all browsers except IE 7 & below and Firefox 3.0 and lower.

# Answer
> 0 votes
For those using Sass, I have written a mixin for this purpose:

```
@mixin addSeparator($element, $separator, $padding) {
    #{$element+'+'+$element}:before {
        content: $separator;
        padding: 0 $padding;
    }
}

```

Example:

```
@include addSeparator('li', '|', 1em);

```

Which will give you this:

```
li+li:before {
  content: "|";
  padding: 0 1em;
}

```

---
Tags: theming, routes
---


title: Nested Dropdown Menu of Bootstrap

text:
# Question
Title: Nested Dropdown Menu of Bootstrap
I would like to add Nested bootstrap menu in my project. (I'm using the Bootstrap Business Theme.) I already tried with the Superfish module.. But I don't like that much because the appearance of menu is not good looking and have to overwrite many CSS files. I also tested with TB Mega Menu. It doesn't work. I put TBMenu Block in Navigation block. But the whole menu was totally disappear. I don't know why it happen like that.

Anyone knows other flexible dropdown menu for bootstrap theme?

# Answer
Responsive Menus module is suitable for bootstrap theme. https://www.drupal.org/project/responsive\_menus
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: Search API Views - How to display facets on a views block?
I am using Search Api Views and Facet API to achieve that.

I am trying to enable facets to a views block, or when calling a view programmatically, but unfortunately they are not displayed as expected.

However facets are correctly displayed on the page created under views interface:

I tried to create a block via views interface, and then adding it through blocks, but the facets block doesn't appear.

Either if a try to print the view programmatically this way:

```
$view = views_get_view('news_search_api_');
$view->set_display('page');
$preview = $view->preview('page');
print $preview;

```

The facets are not loaded at all.

# Answer
The answer depends on your theme; but this is an example of how to do it with 'Commons'

in \> admin \> Structure \> Blocks

> Search for your facets and select the block you want them to go in . ie 'Sidebar First'
>
> SAVE
>
> open your View \> Page .
>
> under FORMAT change Show to 'Panel Fields'
>
> In Settings choose your Panel Layout from the list. ie 'AT One Column' should display the above block example.

> And then still in the VIEW - making sure you are in the 'Page' display; otherwise you won't see this option. Under 'Advanced' - you should now see under 'Exposed Form' the text 'Exposed form in block:' - Change this to Yes.
>
> once you've added this to the view you'll now be able to go back to \> structure \> blocks.
> And see the exposed form here to move to the block you wish.

This information should be enough to point you in the right direction.
> 0 votes

---
Tags: blocks, search
---


# Question
Title: Allow subusers to access parent's content
I have 2 drupal roles. Let's say a teacher and student.

**A teacher should be able to:**

1. Create student account.
2. Create new nodes.

**Student should be able to:**

1. Edit and view ALL nodes created by the teacher who has created his account.

Since it involves mapping of users, I've used the subuser module

I have checked the content access and node access modules as well but they doesn't let me map teacher's content to his student (sub-user). These modules require me to grant permission for individual nodes created by teacher and does not apply permissions automatically to all content created by the teacher.

How do I make all sub-users automatically get edit permission to all content created by parent user?

PS: My actual problem is much more complicated with multiple seller roles and integrating with payment methods. However a solution to this simple case will guide me to go about the problem.

# Answer
I think you already solved this yourself but searching the same issue I ended up on this post. Since I found a solution I will post it here for all other people running in to this problem.

The solution is in combining the modules subuser and user relationships and **rules**.

* **Subuser** gives other users the right to add new users. These users are related to each other with the relationship module but there is no link between their nodes.
* To get the link between content of the users I used the **user relationship** module. This module let's you set up relationships as *friend*, *coworker* or *co-editor* or whatever name you want to give it. These relationships can give one way or two way permissions to update, view or delete each others nodes.
* Normally you would have to go to a users page and request the relationship with the user but with **rules** it's possible to set a relationship when a new user is created.

So what steps to take. First enable all modules. For the **user relationship** you have to enable the main module but also the **User Relationship UI** and the **User Relationship Rules** module. Now go to the relationship module admin/config/people/relationships and create a relationship with the name "friends" (or whatever name you want). At the share content tab make sure that the content type you want to share is selected.

Now go to **roles** admin/people/permissions/roles and create a new role with the name "friends" (so the same as your relationship, just because it's the most clear).

Now go to permissions admin/people/permissions and set the **User Relationship** permissions as you want. Make sure that Grant view permission to related users and Grant update permission to related users is set in the right way to the roles you use. So if you want the subuser(friend) to be able to see and edit the parents content make sure the permissions are on for him. Also make sure he has the right to get the *friends* relationship. Also make sure the parent has all these rights as well.

Now go to the parents user page and go to the **share content** part, set it up so that the **friend** is able to update and view content.

When all this is done it's time to go to **Rules** in rules it's possible to create a rule that says: \- If User Created \- And Role is Friend \- Request Relationship (Friend) - Auto Approve Relationship

Now when the parent creates a subuser the subuser will be able to edit and view its parents nodes. For the parent it is still possible to give his Friends a per node based access to it's nodes. So on default all nodes are shared but the parent can edit this per node.

I hope this is clear enough I did my best, but please let me know if there are any unclear parts.
> 3 votes

---
Tags: 7, users
---


title: Redirect users function of role

text:
# Question
Title: Redirect users function of role
I need to redirect users function of his role using external authenticate.

In my form\_alter() I have:

```
$form['#validate'] = array(
  'user_login_name_validate',
  'beneficiaire_authenticate',
  'user_login_final_validate'
);
$form['#submit'][] = 'beneficiaire_user_login_dispatch';

```

My function to authenticate:

```
function beneficiaire_authenticate($form, &$form_state){
  module_load_include('inc', 'beneficiaire', 'ws');

    if('admin' == $form_state['values']['name']){
        user_login_authenticate_validate($form, $form_state);
    }else{
    $authResponse = beneficiaire_ws_authenticate($form_state['values']['name'], $form_state['values']['pass']);
        if($authResponse)   {
            user_external_login_register($form_state['values']['name'], 'beneficiaire');
            $account = user_external_load($form_state['values']['name']);
            //var_dump($account);exit();
            $form_state['uid'] = $account->uid;
            $account->roles[4]= 'beneficiaire';
            user_save($account);
      $_SESSION['account'] = $authResponse;
        }
    }
}

```

And finally my dispatch function where the aim is to redirect users function of their account status / type:

```
function beneficiaire_user_login_dispatch($form, &$form_state){
  if($_SESSION['account']->temporaire){
    drupal_goto('update-password');
  }else{
    drupal_goto('order');
  }
}

```

My point is, each user is always redirected to /node. How can I redirect them function of account status ?

Thanks

# Answer
> 1 votes
I've found a solution:

```
function beneficiaire_user_login($form, &$form_state){
  if($_SESSION['account']->temporaire){
    $_GET['destination'] = 'update-password';
  }else{
    $_GET['destination'] = 'order';
  }
}

```

# Answer
> 0 votes
You should check a few things:

1. Use `$form_state['redirect']` instead of `drupal_goto`
2. Check other submit functions attached in `$form['#submit']` array. Probably one has redirect to /node
3. Follow Drupal coding standards :)

---
Tags: redirection, users
---


# Question
Title: Problem with image file names containing utf-8 characters
I have a problem **image file names containing utf-8** characters in my drupal website. When drupal has to display a thumbnail (image style) that contains utf-8 characters on it's image file, it fails. **All other images/image file names, work ok.**

For example there's this image:

http://example.com/sites/default/files/styles/thumbnail/public/%CE%B8%CF%81%CE%B7%CF%83%CE%BA%CE%B5%CF%85%CF%84%CE%B9%CE%BA%CF%8C%CF%82%20\_%CE%B3%CE%AC%CE%BC%CE%BF%CF%82.jpg

The actual image file really **exists** in default/files/styles/thumbnail/public/ directory, but it cannot be displayed in website.

Visiting the above image url, I can see the following message:

**Error generating image.**

but I should be able to see the actual image, because it exists on server directory, I can download it using FTP, and it's a **normal thumbnail image file**.

Why is this happening and what can I do to fix it?

UPDATE-----

htaccess.txt

sample image

# Answer
> 4 votes
Use https://www.drupal.org/project/transliteration to automatically rename the files and avoiding problems like this. No need to train your editors. :-)

---
Tags: media
---


title: Hide main page content block

text:
# Question
Title: Hide main page content block
I've configured the **Main page content** block to show on all pages except those listed. The paths I have listed are:

* commodity-selection
* commodity-selection/\*
* value-chain-studies
* value-chain-studies/\*

When visiting one those pages however, the main page content is still present. Even after all caches are cleared.

Is there a trick to hiding the Main page content block?

What I'm trying to achieve is a page that that presents its content within a tab. Other tabs are populated with content from other nodes.

My approach so far has been to use Quicktabs to create a block with the node content I want (ie. node 1, 3, 5). I place that block in the content region and configure it to show on the page I want (node 1). I planned to then hide the Main page content block to hide the node 1 content, without success.

Appreciate your suggestions.

# Answer
Main content is required. To hide it you can do this (I'm using bartik and hiding only for article) in theme's template.php:

```
function bartik_preprocess_page(&$vars) {
  if($node = menu_get_object()){
    if ($node->type == 'article') {
      $vars['page']['content']['system_main']['#access'] = FALSE;
    }
  }
}

```

However, I think you need to rethink your approach and either use Views, Display Suite, or Panels to take over the rendering.
> 3 votes

---
Tags: blocks
---


# Question
Title: How to develop a page which displays data from more than one content type/table
how do I develop a view/page which displays the data like below.

I have the Image, blogger name ( this is my join field) , profile photo and details as one content type(table) and Blogs are in different content type (table). Blogs content type has also blogger name.

I'm newbie to drupal and we are using Drupal 7.

Bloggers are not going thru user registration process and as admin's we enter the blogger details as bloggers content type (for those who enter more blogs).

Any help/hints on how to accomplish this

# Answer
> 0 votes
As mentioned by the commenters to your question, use the Views module. Here's some documentation to get you started.

In general, it is an enhanced query/list/menu builder, with which you can build most of your site's general pages, blocks and lists.

You can join multiple tables (or content types) in any way Drupal's structure lets you, and output the results as

* a table of columns and rows (one record per row),
* a grid with multi records per row,
* short lists used to make menus,
* and so much more.

Views should be in any newb tool chest of modules (opinion). It's invaluable for examining your site content, and in learning Drupal's content relationships (after you get beyond it's learning curve). It's now even in Drupal 8 core.

---
Tags: views
---


# Question
Title: Create a Modal to Add new fields dynamically
I have to develop a contest page. Every participant may have one or more codes that can use to participate in the event. After that the user must fill a form with their personal data so they can be contacted in case they win the contest.

How could I add a `[+]` button that opens a modal window asking me how many code field would I need? If I write 5 for example, we create dynamically 5 code fields to the input.

I managed to create an add more button that add just one more button, but for clients requirements, we need to use a popup that ask how many fields we need.

# Answer
> 0 votes
I am not sure how this can be done entirely with Webforms. One option is to include in this webform all necessary fields, including the ones that would appear as a modal dialog. Even better, group these as a fieldset.

Then in a custom module or theme include some jQuery logic with which would be very easy to create a modal dialog in the same page. There is a dialog widget in jQuery UI and this is a relevant question in SO.

---
Tags: webforms
---


# Question
Title: How do I use hook_views_pre_render in template.php in Drupal 7?
I have some auto generated data from my articles stored in a view(my\_amazing\_view). I also have a custom field in articles where user can enter similar data. If user has entered the data, i want to show that data. Otherwise I want to show auto generated data.

To do this, I want to implement hook\_views\_pre\_render in my template.php file and target that specific view. I tried naming the function as my\_amazing\_view\_views\_pre\_render as well as mytheme\_views\_pre\_render and targeting that view but I am unable to do so.

How do I use the pre\_render hook in my theme?

# Answer
The hook is run for every view, therefore you need to inspect the $view object (the parameter passed to the function).

Place the function in your theme's template.php.

Name it YOURTHEMENAME\_views\_pre\_render (ie replace 'hook' with your theme name). Then use $view object to target specific view name and display\_id, as in $view-\>name and $view-\>display\_id (from memory, I might be wrong, but you get the gist).

```
function MYTHEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->display_id == 'DISPLAY_ID') {
    // do what you want
  }
}

```

If you want to do this for many views, best do it like this to separate the views into their own functions:

```
function MYTHEME_views_pre_render(&$view){ {
  // will run for all views
  $function = __FUNCTION__ . '_' . $view->name;
  if (function_exists($function)) {
    $function($view);
  }
}

function MYTHEME_views_pre_render_VIEWNAME(&$view){
  // will only run for specific view, but for all of its displays.
}

```
> 2 votes

---
Tags: views, theming, hooks
---


# Question
Title: drupal_add_css does now work when in cache mode
I am trying to add a jquery plugin to a page through drupal\_add\_css and drupal\_add\_js as follows:

```
drupal_add_css($path = 'sites/all/libraries/gips/css/gips.css', $type = 'file', $media = 'all', $preprocess = true);
drupal_add_js('sites/all/libraries/gips/js/gips.js', array('type' => 'file', 'scope' => 'header', 'weight' => 3));
drupal_add_js("jQuery(document).ready(function(){...dosomething...});"), array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

```

When I'm not aggregating/caching the CSS files, it works fine. When I try to aggregate the CSS files, it doesn't. The behavior is as if some css rules get lost in the process. The same happens even if I change the `$preprocess` to `false`.

From Chrome's code inspector, I cannot see any overriding rules getting in the way either.

I am at a loss on how to debug this. Any suggestions?

# Answer
While you are using the version 7 drupal\_add\_js, the snippet you posted appears to be using the Drupal 6 arguments for drupal\_add\_css. You might also need to set the `every_page` option to true so that it is aggregated. Maybe try:

```
drupal_add_css('sites/all/libraries/gips/css/gips.css', array('type' => 'file', 'media' => 'all', 'preprocess' => true, 'every_page' => true));

```

You could also have a look at the group and weight settings on the api page linked above to see if they will help.
> 7 votes

# Answer
For d7 with enabled aggregation needed `'preprocess' => FALSE` for css and js: https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_css/7
> 0 votes

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


title: Using user_access() on Custom Node Type

text:
# Question
Title: Using user_access() on Custom Node Type
How can I check if a user has access to create a new node of a custom node type?

In 'admin/people/permissions' I have an item named "Custom Type: Create new content" and it is enabled for authenticated users.

How can I use `user_access()` to verify against "Custom Type: Create new content"?

# Answer
```
user_access($string, $account = NULL)

```

if a custom module you can say

```
 if (user_access('Custom Type: Create new content') {
    // do X
 }

```

this will check the current logged in user. To check someone else

```
 $uid = //get if from somewhere;
 if (user_access('Custom Type: Create new content', $uid) {
    // do X
 }

```

When you create a node, Drupal checks this by default....so I assume that you are trying to check it somewhere else. What function you would like to check it in, I cannot predict, but any function, template file, preprocess, etc will do
> 6 votes

# Answer
Perhaps I'm missing something, but noting that using exactly the text 'Custom Type: Create new content' does not work with `user_access`, at least not for me.

Instead, use the machine value of the permission. One way to get that is to look at the user permission page, and view the checkbox value for the permission.

For example, instead of this:

```
if (user_access('Basic page: Edit any content'))

```

use this

```
if (user_access('edit any page content'))

```

To find the definition of the machine name, look in the .module file of the module that defines the permission.
> 7 votes

# Answer
user\_access() function did not worked for me. I used node\_access()

like this: node\_access('create', 'custom\_content\_type', $user) and it worked.
> 0 votes

# Answer
Thought I'd share this. (Druapl 6.x)

```
global $user;
$types = node_get_types();
foreach ($types as $type)
{
    print '<pre>' . $type->name . '</pre>';
    if (node_access('create',$type->type,$user)) {
        $output = l(t('Add new '.$type->name), '/node/add/'.str_replace('_','-',$type->type));
        print $output;
    }
}

```
> 0 votes

---
Tags: users
---


title: Commerce account pane email change

text:
# Question
Title: Commerce account pane email change
I am using Drupal 7 with commerce module. In the commerce shipping pane I have created a new email filed through `admin -> store -> Customer profiles -> Shipping Information` and it is displaying in the shipping section that’s all fine.

Now what I have to do here is use this email while creating the account for anonymous users instead of using email from the account pane and also I need to hide the email filed in account pane. Can anyone guide me how to implement this? Thanks in advance.

Ratheesh

# Answer
I have resolved the issue like adding a submit handler function when click on continue button click. Code is provided below

```
your-module_form_alter(&$form, $form_state, $form_id) {
   global $user;
   if(!$user->name){
      $form['account']['login']['mail']['#required'] = 0;
      $form['account']['login']['mail']['#prefix'] = '<div style="display: none;">';
      $form['account']['login']['mail']['#suffix'] = '</div>';
      array_unshift($form['buttons']['continue']['#validate'], 'your-module_submit_handler');
    }
}

your-module_submit_handler(&$form, &$form_state){
    $form_state['values']['account']['login']['mail'] = $form['customer_profile_shipping']['field_email']['und'][0]['value']['#value'];
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Rule to remove two specific items from commerce cart
I am using Drupal commerce and I try to make a rule to remove two specific line items from the cart. However, the most I can achieve is to empty the whole cart.

Can this be done with rules?

# Answer
* You remove a product from the cart by deleting the line-item entity for that product.
* But first you must expose the line-item data to your Rule so you can check whether it should be deleted. **Line-item data including sku is not available to Rules Actions unless you do this.**
* Note that you can access some properties about the line-item, such as `commerce-line-item:type`, in your Rule Condition, but this is for the line-item referenced in the event, **not for the other line-items in the cart**. You cannot access other line-items' data, such as sku, in your Rule Action.
* You force the other line items' sku and other data to become available to your Rule Actions by checking a property of each line item **in the Action**, even if you don't otherwise need to do the check. In this example I check the type of each line-item to be evaluated for deletion.
* Much of the documentation available as of today is a couple of years old and calls for use of Rules components ... nowadays Rules Conditional is the way to go as it allows you to bring conditional logic right into your Action (so you can choose which line items to delete, for example). You may choose to put this Rule in a component if you have many varied situations in which you want to call it. If you only have one or two situations, using conditional logic within the Rule Action, via Rules Conditional, is much simpler.

In the example below, the Rule is evaluated on the event "After removing a product from the cart" because I have an add-on product that should be removed after the "mother" product is removed by the customer. But you can use any Commerce event.

The Condition here is to check whether the product removed from the cart by the customer was a "mother" product ... you may not need any conditions for your Rule.

The Action first does the aforementioned check of the line-item type to bring the line-item properties into scope for the Action data selector, then loops through the list of line-items, and tests each one for the skus you want to delete. Then deletes the line-item if there is a match. You could of course delete based on price, quantity, or anything else in the line-item data.

Note that once you start to loop through a list, the data you are after will be accessed through the variable `list-item:` which represents whatever you are looping through; in this case, the line-items. Note that `list-item` and `line-item` are syntactically very close, watch for typos!

```
{ "rules_delete_products_from_cart_by_sku" : {
    "LABEL" : "Delete Products from Cart by SKU",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart" ],
    "ON" : { "commerce_cart_product_remove" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-line-item:type" ],
          "value" : "my_product_type"
          }
       }
     ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "list-item:type" ], "value" : "product" } },
                  "DO" : [
                    { "CONDITIONAL" : [
                        {
                          "IF" : { "data_is" : {
                              "data" : [ "list-item:commerce-product:sku" ],
                              "op" : "IN",
                              "value" : { "value" : [ "SKU-01", "SKU-03" ] }
                            }
                          },
                          "DO" : [ { "entity_delete" : { "data" : [ "list-item" ] } } ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

Hope this helps someone on the same journey I am!
> 3 votes

---
Tags: commerce, rules
---


# Question
Title: Is it possible to determine what attachments (JS libraries, CSS, etc.) are required by a node form?
I'm developing a solution which allows users to create content through a custom AJAX-driven UI. The first step in the process requires users to pick a content type from a dropdown list, which will then trigger the relevant node form to be loaded in to the page via AJAX. The HTML for the node form is being built correctly, but the issue I'm experiencing is that required JavaScript libraries are not included in the page, e.g. system libraries such as drupal.ajax and jquery.form, and libraries provided by contributed modules such as CKEditor and the media browser provided by the Media module.

Is there an elegant way of determining what libraries are required by node forms for a range of content types before the form is loaded? My intention would be to include all of the libraries using `drupal_add_library`, `drupal_add_js` and `drupal_add_css` in the page callback function for the UI.

Thanks in advance to anyone who has any ideas!

# Answer
> 0 votes
The most elegant way to do that is define attachments in hook\_form\_FORM\_ID\_alter. You can specify css files, js files or libraries:

```
$form['#attached']['library'][] = array('system', 'jquery.cookie');
$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';
$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';

```

---
Tags: 7, ajax, nodes
---


# Question
Title: How do I turn off the add to cart message from Commerce site using Rules
I finally got a duplicate cart rule to work in my Drupal Commerce site. My "**After item is added to cart**" rule determines if there are duplicate sku's, if so, resets the quantity of that item to one.

When that rule is run, it posts a system message to the user saying the duplicate has been removed from the cart, but the original "*Item has been added*" message still appears, so the green, "item added to cart" msg appears and just under it, my "duplicate item has been removed" msg appears.

I want to turn **off/not display** that first "*item has been add*" message, **when a duplicate has been detected**. Obviously the message would appear as normal when no duplication is found.

What is the simplest means of accomplishing this? Nothing I've tried thus far has worked.

**default add to cart message:**

```
{ "commerce_cart_add_to_cart_message" : {
    "LABEL" : "Display an Add to Cart message",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [
      { "commerce_cart_add_to_cart_message" : { "commerce_product" : [ "commerce-product" ] } }
    ]
  }
}

```

**my stop duplicate rule**

```
{ "rules_restrict_quantity_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-line-item:quantity" ],
          "op" : "\u003E",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },
      { "entity_save" : { "data" : [ "commerce-line-item:order" ] } },
      { "drupal_message" : {
          "message" : "Duplicates items are not allow.  This item has been removed from \u003Ca href=\u0022\/cart\u0022\u003Eyour cart?\u003E",
          "type" : "warning"
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
You can't remove a message from the queue once it's been added via Rules, so you just need to reproduce the conditions in inverse from one rule to the next. In other words, you already configured the conditions in your custom rule to prevent the duplicate, so now put the opposite conditions on the rule that shows the normal Add to Cart message.

# Answer
> 0 votes
Whether or not you choose to follow Ryan's advice to disable the message, be aware that your Action:

`{ "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },`

will only change the line-item quantity, not its total.

Unless you also add a second Action such as:

`{ "data_set" : {
 "data" : [ "commerce-line-item:commerce-total" ],
 "value" : [ "commerce-line-item:commerce-unit-price" ]
 }`

then the total amount for the line-item will increment each time the customer tries (and fails, because of your rule) to add more than one of the product. Your Cart will show a quantity of 1 but a total of *n* x unit price.

---
Tags: commerce, rules
---


# Question
Title: Tpl for page having url like product/checkout/%/%
I have created a page with hook menu with url product/checkout/%/% where % will be userid and product id. How can I add a page tpl for this url ?

# Answer
In your page callback, you would have to set `'#theme'` on a renderable array.

You can use an existing theme function, or create your own using hook\_theme.

If creating your own and you prefer to use a `tpl`, you can set the `template` option in `hook_theme` and bypass having to create a theme callback function.
> 2 votes

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


# Question
Title: Using "Rabbit Hole nodes" and "Facebook Like Button"
I am busy developing a Drupal 7 website. All nodes of content type "X" are displayed on my front page as well as on (possibly) multiple taxonomy term pages. But that is it, users are not allowed to access the single node page directly.

* I have restricted the user's access to `example.com/node/*` pages using the plugin "Rabbit Hole nodes", redirecting them to `example.com/#node-[node.nid]` using the "Token" module.
* I have also implemented the "Facebook Like Button" module to provide a Like button for each node.

Each of these Like buttons are placed inside a generated iframe with following iframe Src.:

`//www.facebook.com/plugins/like.php?href=http%3A%2F%example.com%2Fnode%2F1&layout=button_count&show_faces=true&width=450&font=arial&height=80&action=like&colorscheme=dark&locale=de_DE&send=false`

Note: Look at the "href" value that is passed along. It uses the exact URL pattern (../node/\*) that I am restricting access to.

**I asked myself these questions:**

1. Does the Facebook crawler (user agent: `facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php`) actually have access to this?
2. Will "Rabbit hole nodes" not break this like functionality?
3. Where will users from Facebook land when clicking on the Facebook "like" notification of their friend? I mean, it's restricted..

**\[Update\] How it should actually work:**

When accessing the URL `example.com/node/1` the following should happen:

* Normal User (everyone except Facebook's crawler): Should be redirected to `example.com/#node-1`.
* Facebook's crawler: Should not be redirected, instead it should just stay on the single node page `example.com/node/1`.

**Possible solution:**

1. One solution that I considered implementing is altering "Rabbit Hole nodes" module code and checking for the Facebook crawler user agent like this:

```
if (in_array($_SERVER['HTTP_USER_AGENT'], array(
  'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)',
  'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
))) {
  // Don't execute Rabbit hole functionality
}
else {
  // Execute Rabbit hole functionality
}

```

What are your opinions, ideas and solution approaches?

# Answer
Perhaps consider using Page Manager (part of Chaos Tools) to redirect users instead of the Rabbit Hole nodes module.

1. On the Page Manager admin page (Structure -\> Pages) edit the `node/%node` page
2. Make a an HTTP response variant that redirects the user to `site/#node-NUMBER` when they are trying to reach `site/node/NUMBER`.
3. Set the selection criteria for that variant depending on the user agent (i.e. don't use this variant when facebook is looking). This will require a custom php rule.

There is an excellent Page Manager tutorial here.
> 1 votes

# Answer
1. Facebook will not have access if anonymous users do not.
2. Depends what you mean by 'break'.
3. Depends on how your Rabbit Hole module is set up. If you set rabbit hole to display a 404 page, this is what people will see.

Hard to offer alternative solutions as you do not explain how you want it to actually function. But altering the Rabbit Hole module is probably not the best way.
> 0 votes

---
Tags: 7, redirection, users, social-network
---


# Question
Title: How to set the ordering of a taxonomy term's listing page
When you click on a tag term (or any other taxonomy term), a page is displayed listing the nodes tagged with that term. How can the nodes be displayed alphabetically?

The only module that looks like it could yield results is this one: http://drupal.org/project/taxonomy\_display

But as of yet, can't get this to work as expected.

# Answer
Using the Views module, enable the Taxonomy view. You can customise the content of the tag results page by adding/ordering fields, just as you would any other view.
> 7 votes

# Answer
Another possibility is to use the Node Order module:

> The nodeorder module gives users an easy way to order nodes within their taxonomy terms.

A PHP way is also described in the question: alphabetize the taxonomy term page without views
> 4 votes

---
Tags: 7, taxonomy-terms
---


title: Unpublish content automatically

text:
# Question
Title: Unpublish content automatically
Hi I want to know if there's a way to unpublish content(nodes) automatically based on a field date previously created.

I want that task to be automatically based on the current date.

Example:

The user already has a content with that field called "Deadline" filled with 20/01/2015 so, for now that content should be passed to unpublished.

If I can do it through some hook let me know to insert in my costume module, thx so much

Edit: I can't use the **Rules module** because whenever I try to add some condition to one Rule one error just pop up, and I can't continue, and I'm not gonna do a CLEAN installation .....

# Answer
Well I managed by myself, as I always do in this forum:

```
$query_get = db_query("SELECT n.nid, p.your_field_value FROM node as n INNER JOIN your_field_table as p ON p.entity_id = n.nid WHERE n.status = 1");

foreach($query_get as $row){
  $date1 = date('Y-m-d');
  $date2 = explode($row->your_field__value);
  if(strtotime($date1) < strtotime($date2[0])){
  }else{
    $query_update = db_query("UPDATE {node} SET status = 0 WHERE nid =".$row->nid);
  }
}

```

You can place this inside your custom module.
> 0 votes

# Answer
you cane do it by Rules module

please check this article it will help if you are new in rules module
> 0 votes

---
Tags: nodes
---


# Question
Title: No option to validate for email in drupal webforms validation
I've installed both the Clientside Validation module, and Webform Validation, but there is no option to validate for **"valid email"** in the **"Form Validation"** tab of the webforms edit panel. Clientside Validation claims to validate for email - what's going on?

How should I go about adding email validation?

# Answer
> 1 votes
Currently it seems there is no such functionality, as it still sits in issue queue as a feature request. You can either:

# Answer
> 1 votes
try with this code inside your form alter:

```
// Add a callback function to your email field.
$form['mail']['#ajax'] = array(
  'callback' => 'email_validation',
  'wrapper' => 'email_validation_message',
);

// Field-wrapper to display result message
$form['email_presence_message'] = array(
  '#type' => 'markup',
  '#prefix' => '<div id="email_presence_message">',
  '#suffix' => '</div>',
  '#weight' => -1,
);

```

The ajax callback:

```
/**
 * Ajax callback.
 */
function email_validation($form, $form_state) {

  if (!valid_email_address($form_state['values']['email'])) {
    form_set_error('email', t('That e-mail address is not valid.'));
    $form['email_presence_message']['#markup'] = t('email not valid');
    return $form['account']['email_presence_message'];

  }

```

}

# Answer
> 0 votes
I have been experinced the same problem since, the first version of my website was a real issues and bad design... i found this, hopefully helps you... https://drupal.org/project/clientside\_validation

# Answer
> 0 votes
You can use valid\_email\_address() function to validate your email.

```
function MyModule_form_validate($form, &$form_state) {
    if (!valid_email_address($form_state['values']['email'])) {
        form_set_error('email', t('That e-mail address is not valid.'));
    }
}

```

# Answer
> 0 votes
Use the Webform Validation module and **use Regular expression, case-insensitive**.

Eg:

1. For name validation: `\b[A-Z]{3,30}\b`
2. For mobile number: `\b[0-9]{10,15}\b`

Now you can use any regular expression to validate your web form.

# Answer
> 0 votes
Get Email Verification module. Though it is still in development for durpal 7.0 it works fine.

# Answer
> -1 votes
Webform Validation with this module you can set validation rules for each fields see the below image.

> This module adds an extra tab to each webform node, allowing you to specify validation rules for your webform components. You can create one or more of the predefined validation rules, and select which webform component(s) should be validated against those.

---
Tags: webforms, forms
---


title: Don't show blocks on some pages

text:
# Question
Title: Don't show blocks on some pages
I don't want to show blocks inside some pages, and I can't touch the theme files.

Is there any way to do this programmatically inside a module?

# Answer
You can use hook\_block\_list\_alter() to hide the blocks in your module code. See docs for more information on how to achieve this. This is the the alter for the function Drupal used to hide/show blocks.
> 2 votes

# Answer
1. You should not hide all blocks because `system_block` contains your page markup.
2. You can use hook\_page\_build to hide unwanted blocks.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How might I have Webforms save files to private file system or as a database blob?
In Drupal 7, I have the file system configured as

In the code for the Webforms' file component located at `sites/all/modules/webform/components/file.inc`, it appears that one could easily change it so that Webform file uploads are moved to the private file system by `changing 'scheme' => 'public'` to `'scheme' => 'private'`. But I also know the pitfalls of hacking (changing) anything that could easily be overwritten with `drush upc`.

```
 /**
 * Implements _webform_defaults_component().
 */
function _webform_defaults_file() {
  return array(
    'name' => '',
    'form_key' => NULL,
    'required' => 0,
    'pid' => 0,
    'weight' => 0,
    'extra' => array(
      'filtering' => array(
        'types' => array('gif', 'jpg', 'png'),
        'addextensions' => '',
        'size' => '2 MB',
      ),
      'scheme' => 'public',
      'directory' => '',
      'progress_indicator' => 'throbber',
      'title_display' => 0,
      'description' => '',
      'attributes' => array(),
      'private' => FALSE,
      'analysis' => FALSE,
    ),
  );
}

```

Given that all file uploads are stored referenced in the file\_managed table

```
mysql> describe file_managed;
+-----------+---------------------+------+-----+---------+----------------+
| Field     | Type                | Null | Key | Default | Extra          |
+-----------+---------------------+------+-----+---------+----------------+
| fid       | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
| uid       | int(10) unsigned    | NO   | MUL | 0       |                |
| filename  | varchar(255)        | NO   |     |         |                |
| uri       | varchar(255)        | NO   | UNI |         |                |
| filemime  | varchar(255)        | NO   |     |         |                |
| filesize  | bigint(20) unsigned | NO   |     | 0       |                |
| status    | tinyint(4)          | NO   | MUL | 0       |                |
| timestamp | int(10) unsigned    | NO   | MUL | 0       |                |
+-----------+---------------------+------+-----+---------+----------------+

```

**Is it feasible to do a post operation to a file upload that manually moves a file from public:// to private:// *and* updates the database entry? Would hook\_file\_presave or hook\_file\_insert be good tools to accomplish this?**

## Update

Based on the suggestion of using hook\_webform\_component\_info\_alter(), I implemented the following

```
/**
 * Implements hook_webform_component_info_alter().
 */
function  MYMOD_webform_component_info_alter(&$components) {
   $components['file']['extra']['scheme'] = 'private';
   dsm($components['file']);
}

/**
 * Implements hook_file_insert().
 */
function MYMOD_file_insert($file) {
  dsm($file);
}

```

After the output of the DSM() shows the component array seems to be altered but the DSM from hook\_file\_insert() still shows that the file was deposited into the public area:

# Answer
Did a little digging into Webform. There is a setting for this in webform I believe. There was an issue posted in the webform issues but it has been resolved. Saving file submission to private directory

OP already solved but for future onlookers: There are instructions I believe on how to accomplish this in the comments of the issue referenced above, also make sure Webform is up-to-date.
> 2 votes

# Answer
Webform itself has an API. You could change the `scheme` from `public` to `private` without hacking the module by implementing hook\_webform\_component\_info\_alter().

In a custom module this would look like:

```
function MYMODULE_webform_component_info_alter(&$components) {
  $components['file']['extra']['scheme'] = 'private';
}

```
> 1 votes

---
Tags: 7, hooks, webforms, files
---


title: Cannot connect to Amazon S3

text:
# Question
Title: Cannot connect to Amazon S3
Whenever I try to save the bucket name I get these errors:

```
Notice: Use of undefined constant CURLOPT_CLOSEPOLICY - assumed 'CURLOPT_CLOSEPOLICY' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLCLOSEPOLICY_LEAST_RECENTLY_USED - assumed 'CURLCLOSEPOLICY_LEAST_RECENTLY_USED' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Warning: curl_setopt() expects parameter 2 to be long, string given in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLOPT_CLOSEPOLICY - assumed 'CURLOPT_CLOSEPOLICY' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLCLOSEPOLICY_LEAST_RECENTLY_USED - assumed 'CURLCLOSEPOLICY_LEAST_RECENTLY_USED' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Warning: curl_setopt() expects parameter 2 to be long, string given in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).

```

And the configuration is not saved. The bucket name contains "-", would this be a problem?

# Answer
Just got the answer. After PHP 5.5, these constants were removed!

https://bugs.php.net/bug.php?id=68147
> 1 votes

---
Tags: 7
---


# Question
Title: Geofield From another field showing only after saving from form
I am programmatically creating nodes with a Field Collection that contain a geocoded field, the field where i take the data from for the geocoding is a computed field (i have already applied this patch: https://www.drupal.org/node/1679926 ). The problem is that the map from the field appears only after i open the node and save it from the interface, the nodes i have created through node\_save() in my code won't show the map until i save them again from drupal interface. I have tried the geocoder patch in the first comment of this discussion How to programmatically iterate over nodes, load into form, and save the form? but it didn't work (the geofield patch doesn't work because it's for 7.x-1.x version), i have also tried saving them all with bulk operations but it doesn't work

Is there any way to solve this? I was thinking about saving nodes as it was done through form submission in my code but i don't know if it's possible, also i don't want to go as far as having to use selenium or something similar to do a bulk form submission

# Answer
> 1 votes
Geofield runs geofield\_field\_presave() before saving the data, and calculates various values for the field. Use the devel tab, and check whether the 'geom' array of the geofield is populated and the others are empty. That was my case, and I am using geofield\_compute\_values() to calculate these data, but afterwards I repopulate the 'geom' array again, because I think it converts it into WKB. You can take a look at my code. There might be other, better solutions too.

---
Tags: nodes, location
---


# Question
Title: How to scp one file to remote using drush?
I'd like to send one file to remote host which is defined as alias in drush.

The file is actually private ssh key, so it needs to be placed in `~/.ssh`.

I've tried the following command:

```
drush -v rsync conf/my_rsa @remote:~/.ssh/

```

but then it's saying:

```
You will destroy data from drush@remote:'/var/www/~/.ssh/'

```

I don't want to destroy any existing data in my `~/.ssh`.

Any workaround to that?

# Answer
I've found the following workaround useful:

```
cat my_rsa | drush @remote ssh "cat > ~/.ssh/my_rsa"

```

It'll send content of the file directly via ssh into the file.
> 2 votes

---
Tags: drush, deployment
---


# Question
Title: Views PHP: how to get the `end-date` value within `Global(PHP)`?
I am rewriting the output a view block with a `Global(PHP)` field from the module Views PHP, and one of the fields I am rewriting is a Date field.

The value for the field is : `2015 - 08:30 to 09:30`

I am looping through the fields and simply printing them to see the output:

`foreach ($data->field_field_item_timespot as $timeEntry) {
 $time = $timeEntry['raw']['value'];
 print $time;
}`

This is the output: `2015-01-01 08:30:00`

The issue that I am having is that it is only printing the `start-date` of the field, when I need both `start-date` & `end-date`. I am specifying the `Date field` to display start and end date values, and it does in the view, but not inside the `Global(PHP)`.

Any ideas how to get the `end-date` value within `Global(PHP)`?

# Answer
`$time = $timeEntry['raw']['value']` == Start Date

`$time = $timeEntry['raw']['value2']`== End Date
> 2 votes

---
Tags: views
---


# Question
Title: Previewable email templates token replacement
From my form\_alter code, I would like to redirect to email template (Previewable email templates)

```
$form_state['redirect'] = url('pet/email_template', $options )
The params are set as
$options = array(
      'absolute' => TRUE,
      'query' => array('nid' => '1','uid' => '3')
  );

```

In the email template, there are tokens \[webform:sid\] and \[webform:data\]. How do I replace those data \[webform:??\] by using the url call to template? Thank you.

# Answer
Put the token \[webform:sid\] in template

Use function mymodule\_pet\_substitutions\_alter(&$substitutions, $params) { $substitutions\['webform'\] = array('sid'=\> {value}); }
> 0 votes

---
Tags: tokens
---


# Question
Title: Hierarchical Select Doesn't allow multiple vocabularies in drupal7
Hierarchical Select I have taxonomy vocabularies:

For example

Products, systems and Support

Each vocabulary has 2 terms:

Products -\> product1, product2

systems -\> systems 1, systems 2

Support -\> support1, support2

I am using Hierarchical Select as a field to select this vocabularies.

But with Hierarchical Select ,it is defaulting to only one vocabulary.

Please let me know how to select terms from multiple vocabularies while creating nodes and alternate to Hierarchical Select.

# Answer
> 1 votes
You can't I'm afraid; it's actually a limitation of the taxonomy term field type, not of Hierarchical Select.

You can only ever choose one vocabulary per term reference field, regardless of the widget you're using. For example, this is what the field settings page looks like when adding a bog standard term ref field on a Drupal install that doesn't even have HS installed:

As you can see you only have the option to choose one vocabulary.

# Answer
> 1 votes
Try using entity reference instead of term reference as your field type. Here's how I got it to work for my needs. In Field Settings I chose Target Type: Taxonomy Term; Entity Selection: Mode: Simple (with optional filter by bundle). This will show a list of all vocabularies with check boxes next to each (Target Bundles). Select the vocabularies you would like to be able to reference.

That's it.

# Answer
> 0 votes
The drupal core taxonomy module is actually coded in a way that allows for multiple vocabs on a term reference field, however it is not exposed to the user via the field UI.

There is a module Combined Termref that exposes this ability.

The drawback it currently has is it is hard coded to allow up to 3 vocabs, not unlimited, although I plan to write a patch for unlimited as I will need that ability soon.

There is also a related drupal core issue at https://drupal.org/node/1623054 that has been closed in favour of https://drupal.org/node/1801304, which has removed term reference fields in favour of entity reference fields, so you should be able to reference multiple vocabs in drupal 8 core.

# Answer
> 0 votes
Hierarchical Select DOES allow multiple vocabularies in drupal7. 1) Go to the given "HR Field" on your content type, 2) then select the "Widget Type" tab, 3) scroll down and configure the "Drop Box" settings. You'll see it. Also you might take a peek at this guys overview to see the skinny: http://eureka.ykyuen.info/2012/05/29/drupal-7-mutiliple-selection-list-for-taxonomy-using-hierarchical-select/

---
Tags: entities
---


# Question
Title: How can I lock out non-authenticated users from a whole taxonomy
I have a taxonomy hooking together different content types, everything is working as expected. However, I never want non-Admins to see the taxonomy pages, just names or other related fields in views on other pages. **How can hide all of this taxonomies pages from non-authenticated users?**

Specific example:

* Sales Contact (Node Type) - Sales contact name, address, phone, etc.
* Products (Node Type) - All sorts of assorted Product Details
* Sales Classifications (Taxonomy) - Types of contracts we have with Sales Contacts, and what products they cover.

Product pages and Sales Contact pages are public, but a Sales Classification page makes no sense to show end users. That said, on Product detail pages I'd like to show some of the Sales Classification fields to end users.

**Taxonomy Access Control** looked promising, but you can ether lock down the whole term (including related nodes) OR set it to do node permissions separately.

Any recommendations would be appreciated.

thanks

# Answer
> 1 votes
I ended up using Rabbit Hole, it seams to do everything I was looking for. More details from the module's project page:

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

# Answer
> 0 votes
Enable the drupal taxonomy views and set as one of the filters the admin role.

# Answer
> 0 votes
You can use Panels to override the taxonomy path, then make one variant for authenticated users and another variant for anonymous users. (control access using selection rules)

Panels adds some setup overhead but will give you complete control over the information shown on the page.

---
Tags: taxonomy-terms
---


title: Remove filter formats help text

text:
# Question
Title: Remove filter formats help text
In D6 and D7, with a simple form\_alter you could unset $element\['format'\], but now the format help and the format tips are added in a #process method.

How can I remove them?

# Answer
Apparently you can't hook into the #process phase, but you can still do a `#pre_render`, from `/Drupal/Core/Render/Renderer.php`

```
// If the default values for this element have not been loaded yet, populate
// them.
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  $elements += $this->elementInfo->getInfo($elements['#type']);
}

// Make any final changes to the element before it is rendered. This means
// that the $element or the children can be altered or corrected before the
// element is rendered into the final text.
if (isset($elements['#pre_render'])) {
  foreach ($elements['#pre_render'] as $callable) {
    if (is_string($callable) && strpos($callable, '::') === FALSE) {
      $callable = $this->controllerResolver->getControllerFromDefinition($callable);
    }
    $elements = call_user_func($callable, $elements);
  }
}

```

For example, to hide the element format of the body field of an article:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymodule_form_pre_render_body';
}

function mymodule_form_pre_render_body(array $element) {
  foreach (Element::children($element) as $key) {
    if ($key == 'body') {
      foreach (Element::children($element[$key]['widget']) as $widget) {
        $element[$key]['widget'][$widget]['format']['#access'] = FALSE;
      }
    }
  }

  return $element;
}

```
> 4 votes

---
Tags: forms, 8
---


# Question
Title: Why is Rules reacting on Commerce Events multiple times and out of order?
I am having lots of problems with my site because Rules is evaluating Events multiple times, and out of order.

For example, the debug log shows that when I add a product to cart, Rules reacts as follows:

`Calculating the sell price of a product` \<- for internal processing, ok.
`Calculating the sell price of a product` \<- why twice?
`Before saving a commerce line item`
`Apply a fee to a given order` \<- why now?
`After updating an existing commerce order` \<- but it didn't update; no fee added?
`After adding a product to the cart`
`Calculating the sell price of a product` \<- for display, ok.
`Apply a fee to a given order` \<- why now? and why again?
`Select available payment methods for an order` \<- why now?

Would like to know if there is a way to debug deeper than the log; i.e. find out exactly when each rule evaluation was called ...

Somebody please help, this is making it impossible to work!

thank you.

# Answer
> 0 votes
Solved!

I had upgraded to PayPal WPP, but also left PayPal Express Checkout enabled.

This caused EC to not display where it normally does, i.e. on every page starting with the cart, but to only display on the Review page where other payment methods can be selected. However, the Rules events for EC were evaluated in their normal place in the process.

Thus the Events were being evaluated even though they had apparently not occurred.

The multiple evaluations of the Event "Calculating the price of a product" is normal.

---
Tags: commerce, rules
---


# Question
Title: How can I assign a View Page on a Domain?
On my Drupal 7, I assign Views Block by using **Domain Access** and **Domain Context** on a node(a node that already assigned to a domain). How can I assign a Views Page with Domain Access? The Views Page "**Path**" does not have the domain option, which I only can assign to the default domain. Anyone know how?

# Answer
Domain Views

This module should provide that integration. It is supposed to link the domain access module and views together.
> 0 votes

---
Tags: views, 7, domain-access
---


# Question
Title: how can i re-direct a user of a particular role, if that user tries to access a page containing certain content type?
i have set a up a role called subscriber. If a non-subscriber (authenticated or anonymous user) tries to access a page with content type of ‘video class’ i’d like to have them redirected to a page that suggestions they subscribe. so far, the content access modules i’ve looked at don’t handle page re-directs.

is there a module that would handle that?

the Context module doesn’t seem to handle content types. I could use it to set up a block with a javascript re-direct based on user role that seems kind of flimsy

# Answer
> 1 votes
You can consider Rules for this requirement.

You can add new rules for event such as "viewing a page" & put conditions to match user type & content type. In action you can add page redirect.

---
Tags: users, 7
---