# Question
Title: Add class to Bootstrap login form button
I want to add a class to a button in my login form. I have searched through all the template files and I cannot find where to do this. I found the following code that best matches the form in modules/user/user.module

```
function user_login_block($form) {
$form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
$form['#id'] = 'user-login-form';
$form['#validate'] = user_login_default_validators();
$form['#submit'][] = 'user_login_submit';

```

The HTML for the button is below. My aim is to change btn-default to btn-primary

```
<button class="btn btn-default form-submit" id="edit-submit" name="op" value="Log in" type="submit">Log in</button>

```

Please help!

# Answer
You should refrain from hacking core.

Rather add this code to your sub theme's template.php file:

```
function MYTHEME_button(&$variables) {
  dpm($variables);
  $element = $variables['element'];
  $label = $element['#value'];
  element_set_attributes($element, array('id', 'name', 'value', 'type'));

  // If a button type class isn't present then add in default.
  $button_classes = array(
    'btn-default',
    'btn-primary',
    'btn-success',
    'btn-info',
    'btn-warning',
    'btn-danger',
    'btn-link',
  );
  $class_intersection = array_intersect($button_classes, $element['#attributes']['class']);
  if ($variables['element']['#type'] == 'submit' && $variables['element']['#value'] == 'Log in') {
    $element['#attributes']['class'][] = 'btn-primary';
  }
  else if (empty($class_intersection)) {
    $element['#attributes']['class'][] = 'btn-default';
  }

  // Add in the button type class.
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];

  // This line break adds inherent margin between multiple buttons.
  // dpm($variables);
  return '<button' . drupal_attributes($element['#attributes']) . '>' . $label . "</button>\n";
}

```

Bootstrap theme overrides the theme\_button, and this is where I copied this code (minus the alteration of adding the class). We then override Bootstrap's implementation with our own.

The code that adds the class is this part:

```
if ($variables['element']['#type'] == 'submit' && $variables['element']['#value'] == 'Log in') {
    $element['#attributes']['class'][] = 'btn-primary';
}

```

It's perhaps no the best way to detect that specific button (going on type and text), but it works.
> 0 votes

# Answer
Checkout `hook_form_alter`. You can add and change (I would suggest only adding unless you are sure it will only affect the forms you want it to) classes with `#attributes`
> 0 votes

---
Tags: theming
---


# Question
Title: how to change max upload size of media file
I am using media module to add files to server and have given same access to others. Now I want to keep the upload size limit to 1 MB. Please let me know if any option to change this.

# Answer
> 1 votes
What have you tried, what are your limitations? You should be able to change your php.ini if you have access per this.

# Answer
> 1 votes
From your admin menu follow path as `Structure` \>\> `Content types`

You will see list of content types, click on `manage fields` for the one you have your media field to limit download size. Now you will see list of all your fields, click on edit link for the field you want to edit download size. Scroll down to find `Maximum upload size` textfield and set its value as 1 MB. By default it is set to a value allowed by your php.ini

---
Tags: media
---


title: What is :source in the Token module?

text:
# Question
Title: What is :source in the Token module?
I look at the List of tokens and I see a lot of tokens with the same name and description, but some `node` have `:source` appended to it. Some of these, such as `[node:title]`, I can understand, since `title` is a field of the node. But what is `[node:source:title]`, or `[node:source:source:title]`? There's even an `[node:source:source:source:source]`, which has the description 'The source node for this current node's translation set.'

What is :source in the Token module?

# Answer
> 5 votes
`:source` you can understand as parent of that node when you get in touch with drupal translation you can easily understand what hierarchy this `:source` is referring to.

as per above link:

Translations are managed in sets of posts, which represent the same information in different languages. Only content types for which the administrator has explicitly enabled translations could have translations associated. **Translations are managed in sets with exactly one source post per set. The source post is used to translate to different languages**, so if the source post is significantly updated, the editor can decide to mark all translations outdated.

so `:source` here is referring to the parent node from which it gets translated (if there are translation enabled if not then you need not to worry about `:source`)

---
Tags: nodes, tokens
---


# Question
Title: How to use the Rate module to rate things inside the content?
I'm quite new to Drupal so I haven't figured out how to use the Rate module for rating things inside the content of, for example, a basic page. I'm using Drupal 7.

Here is what I want to do, but I don't know how:

I have a basic page with links inside the content. I want visitors to be able to vote with thumbs up or down if the link is good. Also I want stars for voting for the contents of the other page. My problem is how to display the thumbs up and stars on my page. Do I create a widget? A view? How do I make them show on my page? A step-by-step explanation would be great!

I've spent so many hours on figuring this out, but I'm sure you can do it in just a few minutes.

# Answer
> 1 votes
I was also looking how to use the Rate module until I found how. Just:

1. Go to Structure \> Rate Widgets.
2. Select the type of rate you want to create and click on Next
3. Enter the information. It allows you to select what type of content will have the new type of rate.

Hope it helps anybody else.

# Answer
> 0 votes
1. Go to content \> Add content.
2. In that create content for the Article page.
3. Go to Structure \> Rate Widgets.
4. Select the type of rate you want to create and click on Next.
5. Enter the information. It allows you to select what type of content will have the new type of rate.

finally, when you view the content in article page the there appars the rating widgets what you choose

---
Tags: nodes, rating
---


title: find all core patches

text:
# Question
Title: find all core patches
I work on site that is drupal `7.20`, I am sure previous team that worked on this project patch core in some places,I want to find all of patched they did, is there any way to find all patched they did? one of my idea is find a clean drupal `7.20` core and compare it but I am not sure this is good solution

# Answer
The **Hacked!** module will analyze the code base of the core and all contributed modules, compare each to a freshly downloaded version, and if the **diff** module is installed it will also generate a easy to read report showing all "hacks" to the code base.

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the **diff** module is installed then **Hacked!** will allow you to see the exact lines that have changed.
>
> **Hacked!** also provides drush integration so that you can see what files have changed from the command line.
> 1 votes

# Answer
You can use the Hacked! module

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.
>
> Hacked! also provides drush integration so that you can see what files have changed from the command line.
> 2 votes

---
Tags: version-control
---


# Question
Title: How to convert the Title field on Image type to multi-line text box
I have a Basic Page content type with a Gallery field that lets the user upload images to that page.

* when I active the Title field for the user to input a title, it shows as a single text box.

But is there a way to convert this to a multi-line text box?

# Answer
> 0 votes
* Using the Media module, you can add fields to images, such as description or caption.

**OR**
* Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.

---
Tags: 7
---


# Question
Title: Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\drupal-8\core\vendor\react\promise\src\functions.php on line 62
I have just installed Drupal 8 development version (drupal-8.0.x-dev) but while running it on my web server I am getting this error:

```
Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\drupal-8\core\vendor\react\promise\src\functions.php on line 62

```

Line 62 has code:

```
59   return resolve($promisesOrValues)
60          ->then(function ($array) use ($howMany) {
61              if (!is_array($array) || !$array || $howMany < 1) {
62                  return resolve([]);
63              }

```

My PHP version is 5.3.8

Is there anybody else who has faced same issue?

# Answer
Drupal 8 requires PHP 5.5.9 or higher (for short array syntax among other things).

You'll need to upgrade your version of PHP.

Source: System Requirements
> 10 votes

---
Tags: 8, installation
---


title: View: Recent posts all users

text:
# Question
Title: View: Recent posts all users
I'm working on drupal 7 with Views 3.8. I'm trying to make a view with one post(most recent one) of all users of my site. I found out via this forum I can make a view based on all users. I then add a relationship called User: Representative node. And I choose to sort on \[post date\].

Now this should work right? But the view doesn't show the most recent post but it shows the oldest post. I tried change descending to ascending or change the sorting to \[NID\] or \[post updated\] but nothing seems to work. What can I do?

If it's usefull here's my view:

```
$view = new view();
$view->name = 'recent';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Recent';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Recent';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Representative node */
$handler->display->display_options['relationships']['uid_representative']['id'] = 'uid_representative';
$handler->display->display_options['relationships']['uid_representative']['table'] = 'users';
$handler->display->display_options['relationships']['uid_representative']['field'] = 'uid_representative';
$handler->display->display_options['relationships']['uid_representative']['subquery_sort'] = 'node.created';
$handler->display->display_options['relationships']['uid_representative']['subquery_view'] = '';
$handler->display->display_options['relationships']['uid_representative']['subquery_namespace'] = '';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'uid_representative';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'recent';
$translatables['recent'] = array(
  t('Master'),
  t('Recent'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Representative node'),
  t('Page'),
);

```

# Answer
> 0 votes
In your view,

* To sort based on Posted Date of content, then You should adding a **Sort Criteria:** `Content: Post date` as *Descending*
* To sort based on Updated Date of content, then You should adding a **Sort Criteria:** `Content: Update date` as *Descending*

---
Tags: views
---


title: Query on custom drupal 7 field

text:
# Question
Title: Query on custom drupal 7 field
I'm facing problem in Drupal query for order by custom field Here is my query

```
$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype', array(':ntype' => 'portfolio'));

```

this work fine but when I change that to this

```
$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype order by n.field_weight DESC', array(':ntype' => 'portfolio'));

```

That query not working. It saying field not found?

# Answer
Try something like (supposing "weight" module is used and weights are stored in the "weight\_weights" table - to be adapted for another module ) :

```
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'type'));
$query->join('weight_weights', 'w', 'n.nid = w.entity_id');//join can not be chained
$query->condition('n.type', 'portfolio', '=');
$query ->orderBy('w.weight', 'ASC');

```
> 1 votes

# Answer
```
$result = db_select('node', 'n')
                ->fields('n', array('nid','type','field_weight'))
                ->condition('n.type', 'portfolio', '=')
                ->orderBy('n.field_weight','DESC')
                ->execute();

```

You can use this code.
> -1 votes

---
Tags: 7, database
---


title: node load multiple order by

text:
# Question
Title: node load multiple order by
How can I order by weight using node\_lode\_multiple and the weight module ?

```
   <div id="photos_inner">
         <?php
           $type = "staff";
           $nodes = node_load_multiple(array(), array('type' => $type));
           foreach($nodes as $staff):
         ?>

```

# Answer
No, results of `node_load_multiple()` are in the order in which the node IDs were passed to it in the first place. There are no other sorting options through that function.

The weight module doesn't appear to have an API for this, so you'll need to create a query that joins the `node` and `weight_weights` tables to get the nids in the right order, *then* pass them to `node_load_multiple()`.
> 2 votes

# Answer
In addition to Clive's answer, you can do it this way:

```
$type = 'your_content_type';
$query = db_select('node', 'n');
$query->join('weight_weights', 'w', 'n.nid = w.entity_id');
$query->fields('n', array('nid'))
  ->condition('type', $type)
  ->orderBy('w.weight', 'ASC');
$nids = $query->execute()->fetchCol();
$nodes = node_load_multiple($nids);

```
> 2 votes

---
Tags: nodes
---


# Question
Title: How can I save all taxonomy terms automatically?
I'am using hook\_taxonomy\_term\_presave to redirect file urls to another link.

In order to see the changes I need to go to : Mysite/taxonomy/term/10/edit and save the page.

I need to do this operation for all taxonmy terms of my website, is there a way to do this automatically whithout editing every page and save it ?

Thanks.

# Answer
> 0 votes
I used this to get all my taxonomy terms :

```
function Mymodule_update_7100() {
 $terms = array();
 $v = taxonomy_vocabulary_machine_name_load('vocab_name');
 $query = new EntityFieldQuery();
 $result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $v->vid)
  ->execute();

if (!empty($result['taxonomy_term'])) {
  $terms = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
}
    foreach($terms as $term){
        taxonomy_term_save($term);
    }
}

```

I hope this will help someone else. Thank's again @Елин Й.

# Answer
> 0 votes
The best I know from your question is to use the Views Global Filter module.

Using this module you can save you taxonomy term into cookie and get any where in the page and can also redirect and filter the results.

# Answer
> 0 votes
You can do this in your modules `.install` file, using `hook_update_N`. The script you need:

```
/**
 * Updates all terms in 'vocabulary_name' vocabulary.
 *
 * Change the update number accordingly if you have previous updates already.
 */
function YOURMODULE_update_7100 {
  $vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name');
  $terms = taxonomy_get_tree($vocabulary->vid, 0, NULL, TRUE);
  foreach ($terms as $term) {
    taxonomy_term_save($term);
  }
}

```

After that simply run your update script by calling `update.php` or using drush:

> drush updatedb

### Method 2

If you don't want to use an update script, you can do it using `drush php-eval`, as well. This is a one-line version of the above script:

> drush php-eval '$v = taxonomy\_vocabulary\_machine\_name\_load("vocabulary\_name"); $ts = taxonomy\_get\_tree($v-\>vid, 0, NULL, TRUE); foreach ($ts as $t) {taxonomy\_term\_save($t);}'

---
Tags: taxonomy-terms
---


# Question
Title: Drupal 7, creation of new node, how redirect to the edit page of the new node
When I create a new node in my website, I want to be redirect to the edit page of the new node. I see several hook, but according to this post its not possible use drupal\_goto..

Is there a way for me ? I prefer a programming approach Thanks =)

# Answer
> 2 votes
In a custom module, use this code, and don't forget to replace MYMODULE\_ with your module machine name :

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_content_type_node_form': // Replace my_content_type with yours
      $form['#submit'] = array_merge(array('MYMODULE_my_content_type_node_form_submit'), $form['#submit']);
    break;
}

function MYMODULE_my_content_type_node_form_submit(&$form, &$form_state) {
  $initial_values = $form_state['build_info']['args'][0];
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = array('destination' => 'node/' . $initial_values->nid . '/edit');

  unset($_GET['destination']);
  $_GET['destination'] = 'node/' . $initial_values->nid . '/edit';
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}

```

---
Tags: nodes
---


# Question
Title: Translate simple code snippet - Get taxonomy term id
im following this great podcast which is drupal 5 (i guess).

I want to add a View into my page--taxonomy.tpl.php and get the id of the taxonomy term im currently looking at. Could maybe anybody translate this code snippet for drupal 7?

```
<?php
$view = views_get_view('taxonomypages');
$display = $view->execute_display('block_1', 2);
print $display['content'];
?>

```

I figured out that this shows me the view:

```
$view = views_get_view('taxonomypages');
print $view->preview('block_1',$tids);

```

but $tids is undefined. i need to have the current taxonomy term id that im looking at e.g when im at `taxonomy/term/12` the id is 12 but $tids is undefined.

# Answer
I never used "page--taxonomy.tpl.php", but based upon what you want to do, I guess your looking for taxonomy-term.tpl.php.

In Drupal 7, you have a $term variable, from which you can get the tid. Below is some D7 code I've used for a similar purpose, that I adapted a bit to yours. Note that the argument to Views *must* be in an array.

```
$view = views_get_view('taxonomypages');
$view->execute_display('panel_pane_1', array($term->tid));
$output = $view->render();

```

But I do *not* recommend you proceed down this path. Instead use Panels, and pass the argument to a View that way. Yes, it will require a bit more configuration, but it will also be much more sustainable, easier to maintain, and keep less logic in the template files.

Relevant panels tutorials here.
> 1 votes

# Answer
When you already are on the term page it is possible to use the URL argument to determine the term id. The term id should be in `arg(2)`.

```
$tid = arg(2);

```
> 0 votes

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


# Question
Title: Using taxonomy terms alias in views contextual filters
I hope you can help me out with this. I have created a simple view with an argument. I use that argument to filter (contextual filter) the content of the view. I already know I can use that argument as a taxonomy term ID and as a taxonomy term name, which means I can get my view loaded as:

www.myhost.com/myview/12

or

www.myhost.com/myview/termname

Both ways are ok and work fine but the problem I have is that I'd like to use an alias for the term, instead of the termname. Term names I already have on the site have some characters which are not really SEO friendly.

Is there a way to use the taxonomy term alias or any other workaround to get this?

Thanks in advance for your help.

# Answer
> 2 votes
Finally my work around this was as it follows:

1. I created a custom taxonomy vocabulary which has an extra field "human friendly tag".
2. I changed the name of all the taxonomy terms for being seo-friendly (not spanish accents, nor brackets and so forth).
3. I use term name for the internal stuff in my view (term names are part of the url). You can see how to get this here as @RobW pointed out.
4. I use the first field (the "human friendly tag") when content is rendered (in the view). I need to use "rewrite results" options when creating the view.

I hope it is clear enough. :-)

# Answer
> 0 votes
install the path auto module and configure the alias patterns for the taxonomy terms as you wish

# Answer
> 0 votes
You can use views, pathauto and taxonomy\_display modules together. The taxonomy\_display module lets override the term's page by your custom view and make it accessible by drupal native pathauto alias.

Usually I use this modules for building the catalog for Commerce shops.

PS: make sure read decumentation for taxonomy\_display carefully ;). It has settings on /admin/structure/taxonomy/\[vocabulery-name\]/display page.

# Answer
> 0 votes
You mention above that you are using panels. In that case you can create another display of your view with a display type of "Content Pane". Make the contextual filter look for the tid (not name or name converted), and open up the "Argument input" options and select "From context" for TID.

Now add the new display to the term page in Page manager and in it's panel settings set tid value to the tid context from the term being viewed. That way it should work regardless of the path the term page is being viewed upon.

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


# Question
Title: Call multiple node forms using multiform_get_form()
I am trying to call multiple node forms using multiform\_get\_form() a utility function by multiform module.Here is the code I am trying with

```
function custom_multiform_menu() {
  $items = array();
  $items['add/multiform'] = array(
    'title' => 'Add Spread',
    'page callback' => 'multiform_get_form',
    'page arguments' => array(array('article_node_form'), array('page_node_form')),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

I am not seeing any node fields on page add/multiform

# Answer
Use your own 'page callback', and in this callback call `module_load_include('inc', 'node', 'node.pages');` which is required for node forms
> 0 votes

---
Tags: nodes
---


# Question
Title: Hide title in Inline Entity Form with Automatic Nodetitles module?
Is there a way to suppress a node's Title and Status fields when used in the Inline Entity Form module's editing form? I keep having use cases for a very clean and slim "add one or more" subform to create lists of related entities.

# Answer
> 2 votes
You can use hook form alter in your custom module. For example

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_form') {
    $form['title']['#access'] = FALSE;
   }
 }

```

Or better use `hook_form_FORM_ID_alter`. For example

```
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
    $form['title']['#access'] = FALSE;

 }

```

# Answer
> 2 votes
It seems that `hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)` is not being called by inline\_entity\_form. I can use the hook to hide the node title on the node edit page, but not when the form is included into the parent node's edit page.

The hook `hook_inline_entity_form_entity_form_alter(&$form, &$form_state)` is made available by the inline\_entity\_form module instead. There is no $form\_id as this is run on just part of the final form, but you can use the $form array to obtain useful information about the inline entity type. For example `$form['#bundle']` gives you the node type for an inline node reference.

Example, to hide the 'title' field for an inline entity:

```
/**
 * Implements hook_inline_entity_form_entity_form_alter().
 */
function mymodule_inline_entity_form_entity_form_alter(&$form, &$form_state) {
    $form['title']['#access'] = FALSE;
}

```

I just set the title field for all inline entity forms to be hidden, as all my inline nodes had automatic node titles being generated. It should be possible to write some code to see whether automatic node titles was in action, and to hide the title field accordingly.

# Answer
> 1 votes
In Drupal 7 you cal alter every form using

```
hook_form_alter(&$form, &$form_state, $form_id)

```

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7

which you have to implement in a custom module. Through this hook you cann access the labels, etc. of the form elements in $form and you can change them,

# Answer
> 0 votes
It should be $form\['title'\]\['#access'\] = FALSE; in Drupal 7.

---
Tags: entities
---


# Question
Title: EntityFieldQuery get total of paged results
I have added a pager to my query with `$query->pager(6);` but I also want to display a total number of results. For example, if there are 8 results I want to display `Search results (8)` with 6 per page but I don't know how to get the total number of results, the query only ever returns an array of up to 6 elements so I can't add them all up.

# Answer
I know its quite a while since this answer, but global $pager\_total\_items as given in another answer gives the totals of all the different pagers on the page.

After executing your query that has a pager, you access the total in $query-\>pager\['total'\].
> 0 votes

# Answer
As usual, I find an answer soon after asking :P

If anyone's wondering, there is a global $pager\_total\_items https://api.drupal.org/api/drupal/developer!globals.php/global/pager\_total\_items/7
> 0 votes

---
Tags: paging, database
---


# Question
Title: how to make $page['content'] stop replacing HTML
In my page (basic page content type) I have the following code in the body field

```
<h3 class="blue-txt">Heading</h3>

```

In my custom themes page.tpl.php I have

```
<?php print render($page['content']); ?>

```

However the rendered content replaces the h3 with a p and stripes my class for some reason and I need it to render the code that I saved.

```
<p>header</p>

```

However, if I use the following then it will print correctly:

```
<?php print field_get_items('node', $node, 'body')[0]['value']; ?>

```

If I use that then when I navigate to any of the default pages, mainly the admin login I get an error as $node is not defined. I added a conditional to check that $node was defined to prevent the error. After that the error wasn't displayed but since $node was supposed to contain the content, no content is displayed.

What am I doing wrong here? I just need my page to print out the body without deciding it should edit my code for me and I don't understand why $page\['content'\] is butchering my code.

# Answer
> 1 votes
Try going to `admin/config/content/formats/html` where 'html' is your WYSIWYG profile and check your **filter processing** order.

Mine:

Insert view filter
Convert Media tags to markup
CKEditor Link Filter
Convert URLs into links
Correct faulty and chopped off HTML
Limit allowed HTML tags

If I put 'Limit allowed HTML tags' at the top I get similar issues to what you are describing.

**EDIT:** The order did not actually cause the issue for me. I had just forgotten to add `<h3>` to the allowed list.

# Answer
> 0 votes
Did you check the options under `Structure` \> `Content Types` \> `Basic page` \> `Manage Display` \> `Body` field (format column).

---
Tags: theming
---


title: Problem with temporary URL in new host

text:
# Question
Title: Problem with temporary URL in new host
I'm migrating my Drupal website to a new host.

Here's what I've done:

1 - Create an DB.mysql.gz using backup and migrate module (in old host)

2 - Create a new database and user in new host and restore this DB.mysql (step 1) directly using mysql -u USER -pPASS MYBD \< /home/DIR/DB.mysql

3 - Install in new host the drupal using QuickInstall (installed v7.32)

4 - Transfer all data by directory www (old host) to a new host (hostgator - public\_html) overhidding all files of Drupal 7.32 (installed by QuickInstall) to my current install v7.34.

5 - Change settings.php database content

I need check if all site is running OK before change DNS, for it, i need login using www.URL\_TEMP/~MYUSERHOST/user/login, but this URL return 404 - Page not found.

Home page is load disfigured and browser log say 404 not found in css/js files, eg: www.URL\_TEMP/~MYUSERHOST/sites/default/files/css/css\_xE-rWrJf-fncB6ztZfd2huxqgxu4WO-qwma6Xer30m4.css and others. This file exists in public\_html/sites/default/files...

I try change hosts file in my local machine (http://support.hostgator.com/articles/general-help/technical/how-do-i-change-my-hosts-file) but not solved.

This problem does not allow that I access with admin and change file temporary path in /admin/config/media/file-system, clean cache and test website.

Am I missing something, or do something wrong?

Ps: In old host the website is running OK!

# Answer
I add `RewriteBase /~MYUSERHOST` in .htaccess and solved problem!

I can now logging using `URL_TEMP/~MYUSERHOST/user/login`. I'm testing website, but initially everything is ok.
> 0 votes

# Answer
If you are sure that settings.php and ftp files are all set right, my guess is you miss some package in php or in appache. Please compare php and appache settings between old host and new host. For example, rewrite\_module in apache
> 0 votes

---
Tags: migrations
---


# Question
Title: Error when using the Domain Access module
I installed the Domain Access module and get the following error:

> Domain access failed to load during phase: bootstrap include. Please check your settings.php file and site configuration.

How can I solve this?

# Answer
> 4 votes
You can access the readme file here.

There is also a quickstart version here.

The main bit you will need is the following (taken from the quickstart version - line 24):

> Add the following four lines of code to your settings.php file:
>
> > /\**
> > * Add the domain module setup routine.
> > \*/
> > include DRUPAL\_ROOT . '/sites/all/modules/domain/settings.inc';
>
> NOTE: You may need to alter the file path above based on your site configuration. See INSTALL.txt for further help.
>
> IMPORTANT: You must add these lines to settings.php after the $databases. Normally, you should add these lines to the end of the settings.php file.
>
> NOTE: If you perform a Drupal core version upgrade, you must remove these lines from settings.php. See UPGRADE.txt for details.

# Answer
> 0 votes
"Domain access failed to load during phase: bootstrap include. Please check your settings.php file and site configuration."

Solution was the following: you need to add the 4 line to the settings.php file, right? But, to do it, you need to set the 'default' folder permission to '777' After this, you can delete the settings.php... upload the new one, which includes this: /\** * Add the domain module setup routine. \*/ include DRUPAL\_ROOT . '/sites/all/modules/domain/settings.inc

at the bottom of the file. Changed the permission back to '555' and thats it... Enjoy!

---
Tags: domain-access
---


# Question
Title: Rules - anonymous users redirected to user/login prevents request new password link from working
I'm using the rules module with drupal 7 in order to redirect anonymous users to the login page.

Events: Drupal is initializing Conditions: User has role(s) - Parameter: User: \[site:current-user\], Roles: anonymous user NOT Text comparison - Parameter: Text: \[site:current-page:url\], Matching text: user/login Actions: Page redirect - Parameter: URL: user/login

My problem is I need the "request new password" to work. How do I tell Rules to ignore clicks to user/password?

This is the current setup for the Actions but it doesnt work.
When a user gets to the login page I want them to be able to click Request New Password and not be redirected back to user/login.

# Answer
Try adding a condition to your redirection rule like this :

1. **Path has url alias**
2. **Value** : user/password
3. **Negate** : True

Edit :

It must be something like this :
> 0 votes

---
Tags: rules, users
---


# Question
Title: Drupal Form Button + "Are you sure"-Button
I am trying to add an own JS function to a Drupal Core Form - think Config, Development, Clean Cache. This function basically just asks if the user is sure. Here is what I have so far:

```
Drupal.behaviors.confirm_delete = {

    attach: function (context, settings) {

         jQuery("#field-module-subsections-values input[id$='-remove-button']", context).bind('mousedown', function (ev) {

            ev.stopImmediatePropagation();
            ev.preventDefault();

            var followLink = window.confirm(question);

            if (followLink) {
                jQuery(this).click();
            }

            return false;

        });
    }
}

```

The problem I have is, that the function gets called before the click-event (thanks to mousedown), but the Ajax action on the button still fires. Maybe someone has a hint as to why?

# Answer
Using hook\_form\_alter you can implement simple popups like this using `#attributes`.

```
 $form['submit']['#attributes'] => array(
  'onclick' => 'if(!confirm("Are you sure?")){return false;}',
 );

```

or

```
$form['submit']['#attributes']['onclick'] = 'if(!confirm("Are you sure?")){return false;}';

```
> -1 votes

---
Tags: javascript, forms, ajax
---


# Question
Title: Drupal core patches with Commerce Kickstart 2.0
In the installation instructions for Commerce Kickstart 2.0, it alludes to the fact that Kickstart has two patches to the core. See instructions at https://drupalcommerce.org/commerce-kickstart-2/install.

Did these patches make it into Drupal 7.34? I am asking because I don't want an install of Drupal core with Commerce Kickstart; I just want the Commerce Kickstart code without the core. I don't want to use the installer.

# Answer
Basing on the content of the drupal-org-core.make file that comes with the distribution, I can say the patches are not part of Drupal 7.34. In fact the make files requires Drupal 7.34, and then lists the patches to apply.

```
projects[drupal][version] = 7.34

; Patches for Core
projects[drupal][patch][] = "http://drupal.org/files/issues/install-redirect-on-empty-database-728702-36.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-1470656-14.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-865536-204.patch"
projects[drupal][patch][] = "http://drupal.org/files/issues/drupal-7.x-allow_profile_change_sys_req-1772316-28.patch"
projects[drupal][patch][] = "http://drupal.org/files/1275902-15-entity_uri_callback-D7.patch"

```

You could apply those patch manually, but you would still be missing all the patches the distribution is applying to third-party modules. See all the lines containing `[patch][]` in the drupal-org.make file. The following lines are the ones for the Features module, but you can find more lines for other modules.

```
projects[features][version] = 1.0
projects[features][patch][] = "http://drupal.org/files/1572578-part-one.patch"
projects[features][patch][] = "http://drupal.org/files/1597186-1-features-do-not-cache-includes.patch"
projects[features][patch][] = "http://drupal.org/files/927566-multiple-link_path.patch"
projects[features][patch][] = "http://drupal.org/files/1669720-fix-features-flush-cache.patch"

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Are there any other settings besides php.ini to allow file upload?
I have a problem with drupal upload file (core module) bigger than 1 MB. For images smaller than this, the upload run smoothly, the progress bar correctly shows the progress and when completed it display the uploaded images as expected.

However, when I tried to upload image bigger than 900 kb, the problem start to arise. The throbber progress indicator show progress until about 98% and then restart again from 0% and never completed and stuck.

In Firebugs it shows that the request was aborted when the progress reach 94%-98% depending on the size images I uploaded. And it only happend when the file \> about 900 kB and never for smaller images.

I already changed the php.ini as suggested here and I verified through phpinfo() it is correct setting. I also change the max\_input\_time and max\_execution\_time in httpd.conf

In fact, when uploading images, I monitor temporary folder /tmp and it shows temporary file progressing from 0 to the size of the file and restarting from 0 again. Thus, it indeed receive the file, no issue on the size of the file.

I also check the permission, 777 on /tmp and 755 on default/files and it is no problem as I can easily upload 500kb images.

Can anyone help? is there any other settings in the server I have to look into?

Thanks

# Answer
Please read through this documentation: https://www.drupal.org/node/97193

Depending on your HTML form and server configuration if you have a 1MB filesize limit; uploaded files *close to your maximum filesize* may not successfully upload to a webserver because a file is sent as apart of a *multi-part* HTTP transmission.

You want to assure post\_max\_size is typicaly 2x or 3x larger than your upload\_max\_filesize. Brief discussion on this can be found here: https://stackoverflow.com/a/15077229/1491507

Googling PHP maximum post size and file sizes should lead to similar documentation on php.net and other resources.
> 0 votes

# Answer
After some experiments, I conclude that the problem is not on the server side, but rather on my client and LAN. Apparently using proxy server (I use ClearOS) as gateway server, to access server that is the cause the problem.

By turning off proxy (squid), accessing directly internet, the problem immediately dissapear. But the problem remains if we are behind proxy server.
> 0 votes

---
Tags: media
---


# Question
Title: Problem with Google Analytics module: "undefined index"
I use "Google Analytics" module (version 7.x-2.1 = up to date) and I get the following error message:

> Notice : Undefined index: value in googleanalytics\_page\_alter() (ligne 217 in .../www/sites/all/modules/google\_analytics/googleanalytics.module)

Any idea how can I solve it? Perhaps some manual modifications in the googleanalytics.module file?

# Answer
> 1 votes
This is a support request on Drupal.org for this here.

Since it is not really a bug or feature request though it is technically on topic here so the summary of that issue is:

1. Make sure that you have run update.php.
2. If that didn't fix the problem then try re-saving your google analytics settings (it would be a good idea to confirm that they are what they should be before saving).

Also I would recommend that if you get error messages like that to search google and the drupal.org issue queue for the module(s) in question.

---
Tags: google-analytics
---


title: How to Style in Drupal

text:
# Question
Title: How to Style in Drupal
Please, I need help.

I have a site design that has a totally different home page than the rest of the pages. The interior pages might present problems too, I don't know...everything in Drupal seems like a mighty struggle that takes days or weeks to understand.

At any rate, i'm using a zen sub-theme. I created all my blocks from scratch in the admin interface and then styled them in \_custom.scss (imported to styles.scss) such that they all had styles to set them up exactly as I intended...It took awhile but I finally made it look like I wanted it to look.

Then I thought I should try using zen grids to do the layout since it was included in zen package and thought I would be able to utilize all the benefits of that system by doing so. So I re-did the entire home page by editing the responsive.scss in /layouts folder specifically for my home page layout with the blocks all over the place. But now I realize this won't work because I need to have a different layout on the other pages...possibly many different layouts...so maybe zen grids won't work for me, but I don't know that for a fact...I just don't know.

So I looked into creating a template.php function to call a different css file for the home page but after reading a bunch of articles on this site and other sites I couldn't get that to work either. I tried calling a different stylesheet if it's the front page from my .info file but couldn't get that to work either...maybe I don't know how to call the 'home page' correctly.

Does anyone have any tips for moving forward with what should be a fairly simple design using the zen sub-theme and about 6-7 other sites pages (including one custom module which is almost done and some views pages)?

# Answer
> 1 votes
The problem you are facing is that Drupal is so versatile that you may feel swamped by the many ways to accomplish this goal.

The things you need to do:

1. provide the correct body class
2. override the correct theme template at the appropriate context
3. inject the correct style sheet at the appropriate context (optional)

This is how you do it:

You must make sure that you have a body class that identifies the page you want to CSS style. Front page already has 'front' class. You can inject body class via template\_preprocess\_html (example here). Your CSS can then target the body class in the same style sheet (no need for separate style sheet).

To provide separate style sheets you need to inject different style sheet for different contexts. When using the info file the style sheet is always loaded. To do it conditionally, you will need to use drupal\_add\_css, and as you wish to do it at a page level you need to add that function probably in template\_preprocess\_html. You will need to detect the page that you are on by inspecting the url, then load the CSS file that you need. Example here: Adding style sheets

Style sheets can also be removed/altered via hook\_css\_alter

To target different layouts for different pages, look at Drupal 7 Template (Theme Hook) Suggestions. You can use the available theme suggestions, and you can also add your own (by ading to the theme\_hook\_suggestions key in an appropriate preprocess\_function.)

If some of this sounds too complicated, just go with the Context module. That module has a slew of plugins that can do everything I described above. There are many tutorials, as in Drupal 7 Context module - Daily Dose of Drupal episode 72.

There are also many video tutorials available on theming with Drupal Zen and Zen Grids

---
Tags: theming
---


title: Send attachments with drupal_mail

text:
# Question
Title: Send attachments with drupal_mail
I'm trying to send attachments with my email from Drupal. In my custom module i have added:

```
class SponsorprogramMailSystem implements MailSystemInterface {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }
  /**
   * Send an e-mail message, using Drupal variables and default settings.
   *
   * @see http://php.net/manual/en/function.mail.php
   * @see drupal_mail()
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   * @return
   *   TRUE if the mail was successfully accepted, otherwise FALSE.
   */
  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}

```

and i can send mails with html, that part is working.

But when i try to attach a file it does not arrive in my inbox. I attach my test file like this:

```
$attachment = array(
        'filecontent' => file_get_contents(DRUPAL_ROOT . '/README.txt'),
        'filename' => 'test.txt',
        'filemime' => 'text/plain',
      );

```

But nothing arrives.

Anyone know how i can fix it?

# Answer
There might be other ways, but I have found that mailsystem and mimemail modules have to be installed to send email with attachment. So install these two modules first.

Then implement hook\_mail to pass attachment to $message

```
/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];

  // Add attachment when available.
  if (isset($params['attachment'])) {
    $message['params']['attachments'][] = $params['attachment'];
  }
}

```

There are two ways to add attachment, you can either pass filecontent or filepath when adding an unmanaged file as attachment (not recorded in DB) or pass file object when adding an managed file.

When adding unmanaged file:

```
$attachment = array(
  'filepath' => $filepath, // or $uri
);

```

or

```
$attachment = array(
  'filecontent' => file_get_contents($uri),
  'filename' => $filename,
  'filemime' => 'application/pdf'
);

```

By using filecontent way, you probably will get two php errors by Jan 08, 2015 including

When adding managed file:

```
$attachment = file_load($fid);

```

Then send email by:

```
$params = array(
  'key' => 'my_email_template',
  'to' => 'test@example.com',
  'from' => 'test@example.com',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail('mymodule', $key, $to, $language, $params, $from);

```
> 20 votes

# Answer
I remember I want did it before, I tried this and worked for me

```
function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
    $system = drupal_mail_system($module, $key);
    // Format the message body.
    $message = $system->format($message);
    // Send e-mail.
    $message['result'] = $system->mail($message);

    if($message['result'] == TRUE) {
        drupal_set_message(t('Your message has been sent.'));
    }
    else{
        drupal_set_message(t('There was a problem sending your message and it was not     sent.'), 'error');
    }
      break;
  }
}

```
> 3 votes

# Answer
```
$attachment = array(
      'filecontent' => $filepathname,
      'filename' => $namefile,
      'filemime' => 'application/pdf'
      );
//where $filepathname should contain the path to the file and $filename should contain the name of the file.
$to = 'test@example.com'; // emails
$from = 'test@example.com';

$params = array(
  'headers' => array('Content-Type' => 'text/html'),
  'key' => 'test',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail($module, $key, $to, $language, $params, $from, $send = TRUE);

```

This worked for me.
> 3 votes

---
Tags: 7, emails
---


title: How to call CCK as block?

text:
# Question
Title: How to call CCK as block?
Actually I created user's request mail form as CCK.This CCK displayed page name as node/add/laptoprepair.I want to display this CCK page as Block for the purpose of calling multiple page.How to create this CCK as block?

In user's page it is displayed as,

# Answer
Please refer these modules, would be helpful

nodesinblock and nodeblock
> 1 votes

---
Tags: blocks, entities
---


# Question
Title: CronJobs - I have two cron jobs but only one works
I have created 2 cron jobs on my server(ubuntu), but only one works.

```
*/5 * * * * curl -s http://www.example.com/cron.php?cron_key=TzVesnZuNqR4mkjv_LgBemUV-oYvsfYalyHOfDtL4cc

*/5 * * * * curl -s http://www.example.gr/cron.php?cron_key=OrrbXhtfSEZ2NI7BlHjAPRtMT_ENAKaz68iH86Kl5wI

```

In my log file at /var/log/syslog there is an error stating "Cron could not run because an invalid key was used." but my key is correct. When I launch manually, it runs the cron successfully.

I can't understand why this is happening. Is there any solution?

# Answer
> 0 votes
The URL of the cron.php page requires a "cron key" to protect against unauthorized access. Your site's cron key is automatically generated during installation and is specific to your site. The full URL of the page, with the cron key, is available in the "Cron maintenance tasks" section of the Status report page at Administration \> Reports \> Status report.

As an example for how to set up this automated process, you can use the crontab utility on Unix/Linux systems. The following crontab line uses the wget command to visit the cron.php page, and runs each hour, on the hour:

0 * * * * wget -O - -q -t 1 http://example.com/cron.php?cron\_key=YOURKEY

Replace the text "http://example.com/cron.php?cron\_key=YOURKEY" in the example with the full URL displayed under "Cron maintenance tasks" on the "Status report" page.

---
Tags: cron
---


# Question
Title: How to pre-populate the username field on the login page when clicking an e-mail link?
I am using the Private Message module on my site; users receive a notification by e-mail when they receive a new message.

In this e-mail, there is a link to the login page. Many users access the page via their mobile phones, so typing in their username can be a pain (they might also forget what their username is).

**Is there some way to prepopulate the username via the link in the e-mail, perhaps using tokens?**

# Answer
You can do it using Prepopulate module. You haven't mentioned the version you are working with. It's in dev version for D7.

When you configure the email, use token in the same format given in the example to pass value of their username, which will be prepopulated when they click on your sent link.
> 2 votes

# Answer
```
function YOURMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
    $form['name']['#default_value'] = $_GET['email'];
}

```

That'll grab the email from a URL query string and pre-fill the login form e.g.:

```
http://yoursite.com/?email=test@test.com

```
> 2 votes

---
Tags: emails, users
---


# Question
Title: Download count of file in table of files
So I wanted to add date alongside the size of the file in filefield table of files so I added this snippet to templates.php

```
function mytheme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'),t('Upload Date and Time'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    if ($item['timestamp'] == 0) {
      $item['timestamp'] = 1234567890;
    }
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
      format_date($item['timestamp'],'custom','Y/m/d - g:i'),
    );
  }
  asort($rows);
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

```

It works just fine but I also need to show the download count of the file, and I have no clue on how to do this. Thanks

# Answer
There's many ways to get this working depending on the type of file access you want.

File Download Count - counts download when it's really been downloaded and not just clicked, new so I can't post more than 2 links. Google this.

Public Download Count \- track public files

Download Count \- track private files
> 1 votes

# Answer
You can also try the Track da files module. It does work for tracking access to both private or public files.
> 0 votes

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


title: Get all fields connected to an entity

text:
# Question
Title: Get all fields connected to an entity
I am trying to figure out the structure of a fieldable entity. I can see the main table in to install file, however it has various fields attached to it. How can I get an grand overview of the structure programmatically?

# Answer
You can get an entity type or bundle's field structure with `field_info_instances()`. e.g.

```
// Get metadata for all fields attached to the article content type.
$instances = field_info_instances('node', 'article');

```
> 1 votes

---
Tags: entities
---


title: links__system doesn't use URL aliases?

text:
# Question
Title: links__system doesn't use URL aliases?
I'm trying to use the `links__system` preprocess function to output a menu as a select element, unfortunately though `$link['href']` appears to output the URL in a format like:

`node/2`

Even though the URL alias is set to something like:

`nice-url`

The code I'm using in my `template.php` file is as follows:

```
function THEME_links__system_MENU_NAME($variables) {
  $html = '<select name="" id="dropdown-menu">';
  $html .= '<option class="" value="home">Select Item</option>';
  foreach ($variables['links'] as $link) {
    $html .= '<option class="" value="' .$link['href'].'">'. $link['title'] .'</option>';
  }
  $html .= '</select>';

  return $html;
}

```

I've had a look at the `$variables` variable passed to this function, just to make sure I'm not referencing the wrong thing - but it doesn't appear to contain any other items in the array that contain the correct URL alias.

When using the default menu code output by Drupal it picks up the URL aliases and uses them.

What am I doing wrong here?

# Answer
> 0 votes
I managed to get around this by using the `drupal_get_path_alias` function in the end, so my resulting code was:

```
function THEME_links__system_MENU_NAME($variables) {
  $html = '<select name="" id="dropdown-menu">';
  $html .= '<option class="" value="home">Select Item</option>';
  foreach ($variables['links'] as $link) {
    $html .= '<option class="" value="'. drupal_get_path_alias($link['href']) .'">'. $link['title'] .'</option>';
  }
  $html .= '</select>';

  return $html;
}

```

Dissapointed I didn't think to search for such a function in the first place!

---
Tags: 7, routes, hooks
---


# Question
Title: Importing existing users into a new Drupal site
We have an existing Drupal site that has a requirement to inherit about 10k users into, and we've been able to gather most of this data through CSV exports on the Database, and Views Export/VBO. What we have is two CSVs, one with usernames, password hashes, UIDs; the other with user field data and a UID to join/union the data during import. There are differences between the Field structure between the site data we inherited and the new site, so new data relationships will need to be established during the import, ruling out a direct port of the existing Database records.

I have no issues writing a Drush script that will import all the users with a joined CSV. What I am wondering is if its possible to import the user records, complete with the password strings within the Drupal User space. Looking at the user\_save() method its not clear as if I can define the User ID, or password hash. And we have a lot of logic implemented that depends upon this

So the approach I have in my head is this:

* Use SQL IN FILE to import the baseline minimum data to establish users in Drupal's users table: Username, Password Hash, created date, changed date, etc...
* Use a second drush script to iterate through the field data, and update the user records with user\_save() off UID.

Is there another approach I can use that's strictly Drush based? This assumes that the data I import will be with a Unioned CSV file. Not being able to adjust the UID probably means this isn't possible, but its worth asking.

# Answer
It sounds like you're after the Feeds module! It supports mapping fields sources to destinations, and will auto-create entities in some cases.

After installing & enabling the module, you'll want to create a Feeds Importer (under Structure) and go from there. Navigate to /import to upload a CSV file to a feeds importer for processing.

There's a sandbox module *Drush Feeds Import* that should allow you to run some of this from the command line if necessary.

Check out:

> The site builder's guide to Feeds:
>
> https://www.drupal.org/node/622698

If the stock Feeds modules don't quite solve your problem, you could use the Feeds API to define your own processing class that manipulates and inserts the data into the new site.
> 2 votes

---
Tags: 7, users, drush
---


# Question
Title: How to update the page breadcrumb when using theme page
I have an entity form(theme page to display it) . I have used `hook_node_view()` to handle breadcrumbs for nodes. But I don't find any place to handle this `$breadcrumb` when I have a form and a theme page for it.

This is how I got the `$breadcrumb` for my news.

```
/**
 * Implements hook_node_view().
 */
function news_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'news' && $view_mode == 'full') {
    //BREADCRUMB ////
    $breadcrumb = array();
    $breadcrumb[] = l('Home', '<front>');
    $breadcrumb[] = l('News', 'news');
    drupal_set_title('News');
    drupal_set_breadcrumb($breadcrumb);
  }
}

```

I have hook functions like:

```
hook_init()
hook_menu()
hook_form()
hook_form_validate()
hook_form_submit()
hook_theme()
hook_preprocess_form()

```

But I don't find a place to work on `$breadcrumb`, or somehow manage it.

# Answer
> 0 votes
If you are looking for GUI to handle breadcrumbs, take a look at Custom breadcrumbs module. Otherwise, you can manage your breadcrumbs programatically in lot of hooks. The code you've printed is correct, so you can create for example a function with a switch case like this one :

```
function manager_breadcrumbs($form_id) {
  $breadcrumb = array();
  $breadcrumb[] = l('Home', '<front>');
  switch ($form_id) {
    case 'my_first_form' :
      $breadcrumb[] = l('Category', 'taxonomy/term/1');
      break;
  }
  drupal_set_breadcrumb($breadcrumb);
}

```

And then, call this function in a **hook\_form\_alter()** like this.

```
function MY_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  manager_breadcrumbs($form_id);
}

```

---
Tags: 7, forms, breadcrumbs, entities
---


# Question
Title: How do i install drush for a drupal site which is on shared hosting?
I have a shared hosting account on which i have created sites using joomla 2.5 and drupal 7.

I want to use drush to apply patches to existing modules for my drupal 7 site.

Can any one guide me as to how can i install this drush and use it for these drupal 7 sites on my shared hosting ?

Step by Step Guide would be highly appreciated (New here)

Thanks

# Answer
When I google "install drush on shared hosting", the two top hits are exactly what you are looking for.

1. Learning How to Install Drush on a Non-Admin Rights Server
2. Installing Drush on Shared Hosting Accounts
> 5 votes

# Answer
Update: There is a complete github project now https://github.com/theodorosploumis/drush-installer.

Assuming that you have **ssh access** to the server and no sudo permissions.

Also, there must be `curl` and `zip` installed. Otherwise you have to change the related commands according to your tools.

Drush now is installed through Composer so we need to install Composer before Drush.

```
# 1. Login to the server from your local machine with ssh
$ ssh USER@SERVER
$ cd ~

# 2. Use Bash as command line (if you like you can use your own CL too!)
$ chsh -s $(which bash) $USER

# 3. Install Composer
$ mkdir ~/bin
$ curl -sS https://getcomposer.org/installer | php -- --install-dir=bin

# 4. Download Drush files (we are in our home folder)

# 4.1 Git method (recommended). After this go to step 5
$ cd ~
$ git clone git@github.com/drush-ops/drush.git
$ cd drush
$ git checkout 6.x

# 4.2 Alternatively, if you don't have git,
# download the files with wget. Currently stable version is 6.x
# Notice that you need Drush 7.x to be able to work with Drupal 8.x
$ wget https://github.com/drush-ops/drush/archive/6.x.zip

# Unzip it and rename the folder to /drush
$ unzip 6.x.zip
$ rm 6.x.zip
$ mv ~/drush-6.x ~/drush

# 5. Make the drush folder executable by current USER
$ chmod u+x ~/drush/drush

# 6. Install Drush from Composer
$ cd ~/drush
$ php ~/bin/composer.phar install

# 7. Add alias drush to .bash_profile
$ echo "alias drush='~/drush/drush'" > ~/.bash_profile

# 8. Source the changed .bash_profile or restart ssh session
$ source ~/.bash_profile

```

I have created 2 simple bash scripts for this task.
> 2 votes

---
Tags: drush
---


# Question
Title: Add pagination to the results in custom module after split the row to many sub rows
I try to build new module `(Drupal 7)`, in some page I show the results to the user as a table like the following:

```
<?php
    $header = 'bla bla bla'; //header come here
    $query = db_select('myTable', 't')
        ->fields('t', array('field_1', 'start_date', 'end_date', 'due_date'))
        ->extend('TableSort')
        ->extend('PagerDefault');

    $result = $query
        ->limit(10)
        ->orderBy('t.startdate')
        ->execute();

    foreach ($result as $row) {
        $rows[] = array('data' => (array) $row);
    }

    $form['tablesort_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('Sorry, there is no results to show'),
    );
?>

```

and this of course works perfectly (`each page has 10 rows`), but for some reasons I have to split each row to multi sub row according to the `start date` and `end date` like the followin

```
foreach ($result as $row) {
    $timeInLoop = $row->start_date;
    while($timeInLoop < $row->end_date){
        //split the row to multi row (one week for each row)
        $timeInLoop = strtotime(date("Y-m-d", $timeInLoop) . " +1 week");
        $row->due_date = date("Y-m-d", $timeInLoop);
        $rows[] = array('data' => (array) $row);
    }
}

```

and here is my problem: if some row has 10 weeks and other row has 2 weeks the total rows in the page will be more than 10 rows how can I make them `10 rows in each page` ??? thank you for your help

# Answer
I find the solution here

```
$limit = 10;
$rows = pager_array_splice($rows, $limit);
$form['tablesort_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Sorry, there is no results to show'),
);

function pager_array_splice($data, $limit = 10, $element = 0) {
    global $pager_page_array, $pager_total, $pager_total_items;
    $page = isset($_GET['page']) ? $_GET['page'] : '';
    // Convert comma-separated $page to an array, used by other functions.
    $pager_page_array = explode(',', $page);
    // We calculate the total of pages as ceil(items / limit).
    $pager_total_items[$element] = count($data);
    $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
    $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
    return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```
> 0 votes

---
Tags: paging
---


title: The "Remove" button is not working

text:
# Question
Title: The "Remove" button is not working
I'm using a "managed file" to upload an image, which works fine, but if you want to remove the image by clicking on the "Remove" button, nothing happens.

```
 $form['logo'] = array(
    '#type' => 'managed_file',
    '#title' => 'Logo',
    '#default_value' => variable_get('logo', ''),
    '#theme' => 'mymodule_thumb_upload',
    '#upload_location' => 'public://my-files/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(0.3*1024*1024),
      'file_validate_image_resolution'=>array('100x100'),
    ),
);

```

I'm using a custom theme, and I just realized when I switch back to 'Seven' the button works. But what could be the problem?

# Answer
> 0 votes
```
function name_module_form() {
  $form['logo'] = array(
    '#type' => 'managed_file',
    '#title' => 'Logo',
    '#default_value' => variable_get('logo', ''),
    '#description' => t('Upload File'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(100 * 1024 * 1024),
    ),
    '#theme' => 'abc_thumb_upload',
    '#upload_location' => 'public://abc/',
    '#attributes' => array(
    'multiple' => 'multiple'
  ));
}

function name_module_theme() {
  return array(
    'abc_thumb_upload' => array(
    'render element' => 'element',
    'file' => 'name_module.module',
  ));
}

function theme_abc_thumb_upload($variables) {
  $element = $variables['element'];
  if (isset($element['#file']->uri)) {
    $output = '<div id="edit-logo-ajax-wrapper"><div class="form-item form-type-managed-file form-item-logo"><span class="file">';
    $output .= '<img height="100px" src="' . file_create_url($element['#file']->uri) . '" />';
    $output .= '</span><input type="submit" id="edit-' . isset($element['remove_button']['#name ']) . '-remove-button" name="' . isset($element['remove_button']['#name ']) . '_remove_button" value="Remove" class="btn btn-default form-submit ajax-processed">';
    $output .= '<input type="hidden" name="' . isset($element['remove_button']['#name ']) . '[fid]" value="' . $element['#file']->fid . '">';

    return $output;
  }
}

```

---
Tags: 7, forms, files
---


# Question
Title: hook_node_view OR template_preprocess_page
I have some data to be extracted from external sources. I want to display those data in a custom template tpl page ( **page--zzz.tpl.php** ) . I had implemented **hook\_node\_view** in my module, and with the **node-\>nid**, output the data to be displayed on a **node.tpl.php** page.

However, the designer wanted to use the full width of the page, so I had to display the collected data in the **page-zzz.tpl** page, instead of just in the **node.tpl.php**, so I have moved my function for collecting the data from my module to the **template.tpl.php**, and inside the function **template\_preprocess\_page**, with the node-\>nid, I collect the same data.

Is that correct? Everything would have been much easier if I had been able to access to the **$page** variable inside of the *hook\_node\_view* function. I tried but I did not succeed!!!

Please advice me. Now it is working but I am hesitating whether there was need to move the collecting data function from my module to the template tpl page.

# Answer
> 1 votes
`hook_node_view()` is *not* really suitable for loading anymore data. There is a `hook_node_load()` hook, which you'll receive an array of all nodes that site is about to load. Note that this is only for loading, and that doesn't mean the user is on a `node/XYZ` page. You will probably need to add a URL argument match to make sure you load only the data related to the given node. Otherwise, pull all the information at once, and store them in each `$node` variable, which is passed by reference (all PHP 5 objects are).

The reason to use `node_load` hook over `node_view` hooks is that all modules implementing preprocess and view hooks now have access to this new piece of node. Otherwise, a hook\_node\_view is OK.

Secondly, you do not need to load them again in `hook_preprocess_page` at all. For Drupal 7 and later, `hook_page_alter()` is recommended. Since you store the data in `hook_node_view/load` hook, simply place the content in the regions you need. If this is theme specific, `hook_preprocess_page()` is better, but most of the contribs that take over entire page contents tend to use `hook_preprocess_page()`. Besides, you will have access to the renderable array because other preprocess functions are not executed at that moment.

You can get the current node like below (make sure you add `arg()` conditions to check the page router is `node/%node`)

```
$node = menu_get_object();

```

This `$node` object will contain the data you stored in the load/view hook. Make sure you pass the first argument to `hook_page_alter(&$build)` by reference, and place the content anywhere you want like god.

---
Tags: nodes
---


# Question
Title: Bulk move content from one category to another - Drupal 7
I have a lot of content that I've imported into Drupal 7. Unfortunately it imported to the wrong category. Is there a way in Drupal or drush to bulk move that content from one taxonomy term to another? Or is it a simple matter of assigning the new taxonomy term to the content?

# Answer
> 1 votes
Have you checked out Views Bulk Operations? How to batch assign taxonomy terms to nodes using Views Bulk Operations is a good blog post about how to accomplish this. Basically, make a view that displays the nodes you want to edit. Add a VBO field to this view (using the instructions in the above blog post) and then go to the page you created with the View to do bulk operations on the desired nodes.

---
Tags: 7, taxonomy-terms, importing-exporting
---


# Question
Title: What MySQL privileges would a read-only drupal db user need
I am in the process of configuring a server that will be on the front end and will be the read-only installation. Can anyone give me some guidance on what to look for for in regards to what tables the mysql user will need write access for... such as like access log, etc.

I am just looking for a starting point. It doesn't need to be specific.

# Answer
> 3 votes
Looking through the core tables of a fairly lean install, these will probably need to be writeable:

* access
* batch
* cache and cache\_\*
* flood
* history
* node\_access
* queue
* sessions
* semaphore
* users (for last login date)
* watchdog

These I'm not too sure about, worth testing:

* registry
* registry\_file
* file\_usage
* blocked\_ips

Contrib modules are different matter, you'll need to look at those one-by-one as it will depend on which ones you use (e.g. ctools has ctools\_css\_cache and ctools\_object\_cache)

---
Tags: database
---


# Question
Title: How to trigger Drupal.attachBehaviors after successful Ajax
I have a module that updates a node via ajax when a link is clicked.

The link is a toggle, it should update the node with value 1 on first click, then with value 0 on a subsequent click, etc. Like turning something on/off.

The code below works on the first click after page load, but not on subsequent clicks. I believe Drupal.attachBehaviors has to be called/triggered after each clicks, but I can't figure out how to do this.

1. The Module

```
function mymodule_menu() {
  $items['mypath/%/%/ajax'] = array(
  'title' => 'My title',
  'page callback' => 'mymodule_ajax_callback',
  'page arguments' => array(1,2),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );

  ...
}

function mymodule_ajax_callback($id, $status) {
  //Validation[...]

  //Node Update using $id as the nid and $status as the field value[...]

  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #div.
  $replacedivid = '#status'.$id;
  $replacestring = '<div id="status'.$id.'"><a data-url="'.base_path().'mypath/'.$id.'/'.$new_status.'/ajax" title="This item is marked as '.$status_text.'" id="statuslink'.$id.'" class="midui">'.$status_text.'</a></div>';

  $ajax_commands[] = ajax_command_replace($replacedivid, $replacestring);

  return drupal_json_output($ajax_commands);
}

```
2. Javascript

```
(function ($) {
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
      var $uilink = $('.midui'); //find all links

      for (var i=0;i<$uilink.length;i++) { //Loop
        var $link = $('#' + $uilink[i].id);
        if (!$link.hasClass("middone")) {

          new Drupal.ajax('#' + $uilink[i].id, $link, {
            url: $link.attr('data-url'),
            effect: 'fade',
            settings: {},
            progress: {
              type: 'throbber'
            },
            event: 'click tap'
          });

          $link.addClass("middone"); //add class when we're done

        }
      }
    }
  }
})(jQuery);

```
3. What I have tried so far:

(a)Add an `ajax_command_invoke(NULL, 'mymodule');` to the $ajax\_commands array coupled with a `$.fn.mymodule` function

(b)Add `$('body').ajaxSuccess(Drupal.attachBehaviors);` to my javascript. ajaxComplete tried as well. Tried it on the document as well.

(c)Create a custom command as detailed here http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7

Note : I know that it's just a matter of triggering attachBehaviors after each click to 'ajaxify' the new html being inserted/modified. If I click the link and then type Drupal.attachBehaviors() in the console, the link will be processed again by my javascript, as evidenced by the addition of the 'middone' class, and can be clicked again.

Note: Also of interest, if I leave the `$ajax_commands` empty and return it (empty array) at the end of the callback function, the link will remain clickable on the first and subsequent clicks. It will have the functionality that I am looking for (a toggle). However, since no change is made to the html after each click, there is no way for the user to know if the toggle is on or off.

Any pointers would be greatly appreciated.

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

A partial Answer :

Drupal ajax.js success function only re-attaches behaviors for forms (I think ?)

```
    if (this.form) {
      var settings = this.settings || Drupal.settings;
      Drupal.attachBehaviors(this.form, settings);
    }

```

so I decided to hack all my ajax objects' success function.

The Javascript now becomes

```
    (function ($) {
      Drupal.behaviors.mymodule = {
        attach: function(context, settings) {
          var $uilink = $('.midui'); //find all links

          for (var i=0;i<$uilink.length;i++) { //Loop
            var $link = $('#' + $uilink[i].id);
            if (!$link.hasClass("middone")) {

              myAjax = new Drupal.ajax('#' + $uilink[i].id, $link, {
                url: $link.attr('data-url'),
                effect: 'fade',
                settings: {},
                progress: {
                  type: 'throbber'
                },
                event: 'click tap'
              });

              myAjax.options.success = function (response, status) {
                //Trigger Attach Behaviors
                setTimeout(function(){Drupal.attachBehaviors($(myAjax.selector))}, 0);
                // Sanity check for browser support (object expected).
                // When using iFrame uploads, responses must be returned as a string.
                if (typeof response == 'string') {
                  response = $.parseJSON(response);
                }

                return myAjax.success(response, status);
              }

              $link.addClass("middone"); //add class when we're done

            }
          }
        }
      }
    })(jQuery);

```

The success function is a copy paste of the default from ajax.js with an added line for reattaching behaviors. For some reason, `Drupal.attachBehaviors` has to be within a timer. I can't just have it on its own for a reason that I ignore.

I'll leave this question open for few in case someone can either find a more elegant solution and/or explain the timer oddity.

Many thanks

# Answer
After some debugging, I realized the issue was not with my code.

The problem was with another module, in my case the colorbox module, which was the source of a js error in its own behaviors function. I believe the error caused the attach behaviors process to halt, and as such, my own behaviors function was not re-attaching. The error could be seen in the console.

The colorbox error : in 7.24

```
Uncaught TypeError: Cannot read property 'transition' of undefined colorbox_inline.js?

```

and in 7.25

```
Uncaught TypeError: Cannot read property 'mobiledetect' of undefined

```

My solution was to disable the colorbox module.

Many thanks to everyone who helped.
> 2 votes

# Answer
It can be tricky attaching ajax behaviours to content that is returned from an ajax request itself. However, it is possible.

Although your hook\_menu code snippet looks incomplete, assuming it's correct (returns $items and function is closed) - In your case, you may just need to adjust the delivery callback to 'ajax\_deliver'

i.e:

```
/**
 * Implements hook_menu
 */
function mymodule_menu() {

  $items['mypath/%/%/ajax'] = array(
    'title' => 'My title',
    'page callback' => 'mymodule_ajax_callback',
    'page arguments' => array(1,2),
    'access arguments' => array('access content'),
    'delivery callback' => 'ajax_deliver',
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  return $items;

}

```
> 3 votes

# Answer
I can't comment first answer, but you can set property for colorbox in settings. For example:

```
myAjax = new Drupal.ajax('#' + $uilink[i].id, $link, {
  url: $link.attr('data-url'),
  effect: 'fade',
  settings: {
    colorbox: {
      mobiledetect: false
    }
  },
  progress: {
    type: 'throbber'
  },
  event: 'click tap'
});

```
> 2 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: Advantages of running cron via drush rather than via curl?
Are there any major advantages of triggering Drupal's cron tasks via Drush rather than via a curl call to the site? The main thing I can think of is that no web server process would be needed, when using drush. Are there other benefits?

Thanks!

# Answer
> 3 votes
Advantages is a loaded term, but I'll describe the differences.

If you compare https://github.com/drush-ops/drush/blob/master/commands/core/core.drush.inc#L647 with http://cgit.drupalcode.org/drupal/tree/cron.php?h=7.x, you'll notice that they both ultimately execute drupal\_cron\_run(). The only difference at the code level is what happens before that.

cron.php checks that a cron\_key is passed in the query string and that maintenance\_mode is not on. It also logs to watchdog.

Drush doesn't check either of those things and uses drush\_log which is very different than watchdog (see Where are logs created by drush\_log() stored?).

Finally, wget uses the service configured to handle http requests (most likely Apache or Nginx) even when configured to request cron.php through localhost. Drush is PHP running in Bash which executes the Drupal functions like drupal\_cron\_run() directly.

There are several reason you may or may not want to trigger cron through an http service, but here is one use case that might help illustrate a big difference. Let say you have a Drupal site that is moving to a new server and domain and you configure a redirect at the .htaccess level to send all http requests for olddomain.com to the new site at newdomain.com. Requests to execute cron using wget in a crontab would also be redirected, but calls to drush would continue to run cron. If the wget requests being redirected to the new site used the old cron\_key, you would begin seeing errors about that in your logs.

Someone could make the case that the memory and CPU footprint of the Drush request is smaller, but that should be very trivial compared to what happens in drupal\_cron\_run().

I don't think one is necessarily better than the other, but they are different.

---
Tags: drush, cron
---


# Question
Title: Conditions for using mail.css with drupal_mail()
**Problem**

I'm trying to style an email sent with drupal\_mail. Sometimes it works, other times it doesn't and I can't work out why.

I'm running mail system, SMTP and mimemail:

Mail system sets up: SMTP for sending and mimemail for styling.

In the mimemail options include stylesheets is disabled because it's found mail.css in my theme. Mime mail CSS compressor is enabled because people use hotmail and gmail.

**Condition 1**

User uses form to send email, this works as expected I receive a styled email in gmail.

```
$message = drupal_mail('module_1', 'notify', $email, language_default(), $params);

function module_1_mail($key, &$message, $params) {
    $title = check_plain($_SESSION['title']);
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';
    $message['subject'] = t('Email subject plus ').$title;

    $message['body'][] = "Body text goes here";
    $message['params']['attachments'] = $params;
  }

```

**Condition 2**

The user uses another form which schedules a rule action which sends an email some time later. This doesn't receive any styling despite seeming identical for all intents and purposes.

```
$message = drupal_mail('rules_module', 'notify', $user->mail, language_default(), $params);

function rules_module_mail($key, &$message, $params) {
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';

    $message['subject'] = t('Here is a (@location)', array('@location' => $params['location']));
    $message['body'][] = 'This is some body text';
  }

```

Could rules somehow affect the calling of a stylesheet? Am I missing something obvious?

# Answer
The problem in my case was that the email being sent wasn't using the drupal\_mail function but php send mail.

I run msmtp on my server to route mail and so rather than passing through drupal, the email was being sent directly through my server with none of the styling.
> 0 votes

---
Tags: 7, theming, rules, mimemail
---


# Question
Title: Unable to set field collection field value on form validation
The question might look similar to How to form\_alter fields attached to an unlimited field collection? but I am more concerned about "values not saved after custom validation"

I have a field collection "field\_assignments" consists of:

* field\_check\_user: A user reference field
* field\_assigned\_booklets: An integer field
* field\_total\_cost: A hidden field (used in validation handler for calculation)

I have content type "marking" having this field collection (unlimited values) along with a field\_rate. I have alter node editing form and defined a custom validation which is working fine. The problem is that I cannot update the field collection item "field\_total\_cost" value in custom validation function. The validation function is

```
function _additional_validate($form, &$form_state) {
   // If rate is set to 100 and assigned booklets are 5; this should result 500
   $tc = $form_state['values']['field_assignments']['und'][0]
         ['field_assigned_booklets']['und'][0]['value'] * $form_state['values']['field_rate']['und'][0]['value'];

   $form_state['values']['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'] = $tc;
}

```

If I dpm $form\_state, I can see that the \['field\_total\_cost'\]\['und'\]\[0\]\['value'\] is updated (see image below) but when the node is submitted, it does not show that value in node view and does not save that value in the database. How can I save a value in field collection field?

I tried form\_set\_value() but couldn't understand how to set value for compounded fields (field collection in this case, I'll be thankful if someone can show how can I construct that "#parent" stuff with these fields). The code with form\_set\_value() I tried:

```
 // testing on a single field - works perfectly
 form_set_value($form['field_rate']['und'][0]['value'], $tc, $form_state);

 // does not update the value
 form_set_value($form['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'], $tc, $form_state);

```

P.S: I have written 'und' instead LANGUAGE\_NONE for ease

# Answer
Use Computed field instead of doing it yourself! Don't use `_validate`, just use `_compute`.

* Change field\_total\_cost to a computed field, saving as decimal.
* Create a custom module and add the following (much clearer than using Computed Fields settings inputs - yuk)

Do something like the following :

```
/**
 * Computed field for - field_total_cost
 */
function computed_field_field_total_cost_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $tot   = 0;
  $books = 0;
  $rate  = 0;
  if (isset($entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'])) {
    $books = $entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'];
  }
  if (isset($entity->field_rate[LANGUAGE_NONE][0]['value'])) {
    $rate = $entity->field_rate[LANGUAGE_NONE][0]['value'];
  }
  $tot = $books * $rate;
  $entity_field[0]['value'] = number_format((float) $tot, 2, '.', '');
}

/**
 * Display for - field_total_cost
 */
function computed_field_field_total_cost_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return '£' . number_format($entity_field_item['value'], 2);
}

```

I obviously don't know what your calculations are like but you get the idea. This will calculate and populate the Total Cost field per field collection.

**OR**

If you still want to do it on validate you (afaict) can't do it on node\_validate but you can on a field validate. So you need to add a custom validate function to your Field Collection field, then it should work as you think.

Add a custom validate callback on `hook_field_widget_form_alter`

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add custom validation hooks for Field Collections.
  if ($context['field']['field_name'] == 'field_assignments') {
    array_unshift($element['#element_validate'], 'MYMODULE_field_assignments_validate');
  }
}

```

Create the custom validate function and set the value similar to how you suggested

```
/**
 * Custom validate function for field_assignments.
 *
 *  @see MYMODULE_field_widget_form_alter()
 */
function MYMODULE_field_assignments_validate($element, &$form_state, $form) {
  form_set_value($form["field_assignments"][LANGUAGE_NONE][0]['field_total_cost'], array(LANGUAGE_NONE => array(0 => array('value' => 123.456))), $form_state);
}

```

I obliviously left out any logic in this example, but you get the idea :)
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How do I pull a field value from a form field in to my inline entity form?
I'm trying to do something which I would think is fairly simple, but I'm just stumped right now, hoping somebody can help.

I have an entity called 'page', and in that entity I have inline entities called 'subpages'. Both of these entities have a field called 'group\_reference' which tells the entity what 'group' the entities belong to.

Basically what I want to do is automatically change the group\_reference form field value in my inline entity form to match the group reference in my page form. So far, I'm using inline\_entity\_form\_entity\_form\_alter to access the inline entity forms values. I'm able to adjust the value to an arbitrary value like this:

```
function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $entity_form['field_group_reference']['und']['0']['#default_value']=X;
  }
}

```

X being the group id.

So the next step I want is to pull in the group id from the page group\_reference field which is already set. That way, they will always match (the user is not able to change this value, it all should be done behind the scenes).

I've tried to include in my module a function that pulls out the value from the field, but I just can't seem to make it work:

```
function MYMODULE_grab_group_reference(&$form, &$form_state) {
    return $form['field_group_reference']['und']['#value'];
}

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $groupid=MYMODULE_grab_group_reference();
    $entity_form['field_group_reference']['und']['0']['#default_value']=$groupid;
  }
}

```

I've tried a bunch of different variations. Am I not targeting my values correctly? Is this just an improper way to do it? I'm flummoxed. Any help would be greatly appreciated! Thanks!

# Answer
Just want to share my solution to this problem. Turns out I didn't need another function, I had all the variables available in my MYMODULE\_inline\_entity\_form\_entity\_form\_alter function in the $form\_state array.

I targeted: $form\_state\['input'\]\['field\_group\_reference'\]\[und\]

And that got me the value of the field in my parent entity.
> 2 votes

---
Tags: 7, forms, entities
---


# Question
Title: Managed file validation on first upload only
In D7,I have new\_form with a managed\_file field to allow my user to upload documents to public://. I'm trying to prevent my user from uploading a document if the file name they are trying to upload already exists in the system. So far I've been successful using this:

```
function mymodule_file_validate($file) {
  $filename = $file->filename;
  $errors = array();
  if (file_exists('public://' . $filename)) {
    $errors[] = t("File exists already!.");
  }
  return $errors;
}

```

This displays an error if the user browses for the file and presses upload, even before the file submission, which is exactly what I need.

However, I also have another form modify\_form in this module that allows users to modify the document and in that case it's okay to upload the document with the same name even though the file name exists already. BUT... the function above blocks my modify\_form too.

Any suggestions how to make the function apply only to my new\_form? Or another way to prevent upload if file exists already only on new\_form? Thanks!

# Answer
I ended up adding a custom validator only to the new\_form file upload field:

```
'#type' => 'managed_file',
'#upload_validators' => array(
      'file_validate_unique' => array($file),
)

```

and then added a function:

```
function file_validate_unique($file) {
   $errors = array();
   $filename = $file->filename;
   if (file_exists('public://' . $filename)) {
         $errors[] = t('The file could not be uploaded because a file by that name already exists in the destination directory.');
   }
   return $errors;
}

```

now it only validates the new\_form and outputs an error right when the user tries to upload the managed\_file, before the form is even submitted.
> 2 votes

# Answer
In my hook\_form\_alter(), I only wanted this limit on new uploads, so I have this:

```
// Set the upload field to disallow duplicate filenames.
$lang = $form['field_upload']['#language'];
$last = $form['field_upload'][$lang]['#file_upload_delta'];
$form['field_upload'][$lang][$last]['#upload_validators']['tta_custom_materials_upload_validation']
  = array(TRUE);

```

And my function looks like this:

```
function tta_custom_materials_upload_validation($file) {
  // Fetch filename from $form.
  $filename = $file->filename;

  $errors = array();

  if (file_exists(file_build_uri('materials/' . $filename))) {
    $errors[] = t("The new material file already exists. Please use a different name.");
  }

  return $errors;
}

```

This works exactly as you would want.
> 0 votes

# Answer
* Instead of putting it into hook\_file\_validate try attaching a form validation handler through hook\_form\_alter or hook\_FORMID\_form\_alter. Add your validation handler with $form\['#validate'\]\[\] = 'my\_module\_my\_form\_validation\_function'
* And then just write the code in the condition:

```
function my_module_my_form_validation_function(&$form) {
 if(form_id == 'your_form_id') {
 $filename = $file->filename;    // fetch filename through $form
 $errors = array();
 if (file_exists('public://' . $filename)) {
   $errors[] = t("File exists already!.");
  }
  return $errors;
 }
}

```
> -1 votes

---
Tags: 7, forms, files
---


# Question
Title: Configure Panels That Uses View With Entity Reference For User Profile
I am having a hard time setting up my Panels page for the user profile page ie: /user/%user

I am using the "Reference" module, and have my content type "News" reference users. I created a view for this called "User News Reference" to make sure it is working correctly. The view has a "page" and a "block". The "page" display for the view correctly returns the referenced data when you manually put the user's id in the path.

I then went to panels and used the Panel's page for the User Profile Page, ie: /user/%user I created a variant and my user's profile to the top of the content and then I added the view "User News Reference" to the center content. I then loaded the user page with a valid user that has referenced "news" content, but the referenced material never shows up.

I created images of every step along the way to help you help me diagnose the problem:

1) First here is my view that I created that returns "news" content that references the user.

2) Here is the view in page display showing the "news" content that references the user with id = 1 (added to show that the references are configured correctly)

3) here is the panel page. In the context section I first have the User Profile, and then the "User News reference" view. I followed it up with some custom content to show that the panel page is actually loading correctly and the page shown is the User Profile Panel page.

4)After setting all of that up here is the page for user 1. This is the Panel's version of the user profile. Note that you can see the profile and the custom content, but not the "news" referenced content from the view.

5)To be sure that the view was loading properly, I went to the view and changed the contextual filter from "display no results if the filter value is not in the url" to "display all results for the specified field" and reloaded the user profile for user 1. then all of the "news" content is returned on the user profile page for user 1, proving that the "User News Reference" view is loading properly for the user profile panel.

Can someone help me understand what I need to do correctly to get the user:Uid to show up in the url for the view used in the panel? I believe the view used in the panel is using the "block" display of the "User News Reference" view, but not sure how it is misconfigured.

I thought it might have something to do with the "context" section in for the Panels User Profile.

I thought I had to add another context, and tried under "user", but the only option was the currently logged in user, or a user by name.

# Answer
The %user portion of your URL is called an *argument*. Your final screenshot shows that argument and that you can use %user\_uid in your page. So that's the context handled.

Instead of a page or block, make a content pane for your view, you will need to enable the `Views content panes` if you haven't already.

In that content pane, set your *argument* to `From context` and choose **User**-\>User ID from the dropdown. This tells the view where to get the information for your contextual filter (which looks ok I think).

Once you have saved that, go back to your page in page manager and insert the view pane as content, it will ask you where to get its argument from, choose `Argument 1` because that will refer it to the %user portion of your URL.
> 1 votes

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