# Question
Title: In Drupal 7, teaser view doesn't show the image filed because the image filed in the content type can have multiple images?
I've added an image field in a content type, and set the 'Field Settings' -\> 'number of values' to unlimited, which means users can upload unlimited images for this field.

then I build a view for this content type and expose the image filed to the view. what I 'd like is to expose only image in teaser view, and all images in the full view.

I use a template preprocess function

```
function MYTHEME_process_field(&$vars) {
  $element = $vars['element'];
  // Field type image
  if ($element['#field_type'] == 'image') {
    // Reduce number of images in teaser view mode to single image
    if ($element['#view_mode'] == 'teaser') {
      // something might be wrong here
      $item = reset($vars['items']);      // not working
      $vars['items'] = array($item);      // not working
    }
  }
}

```

In debugging this function, this 2 lines

```
  $item = reset($vars['items']);
  $vars['items'] = array($item);

```

doesn't seem to work. any suggestion?

# Answer
> 1 votes
The Display Suite Module offers you to choose the number of items to show on each viewmode.

# Answer
> 0 votes
I created a custom module with the following code. It works for me but you probably need to adjust the field names to your own.

```
function image_teaser_fix_entity_view($entity, $type, $view_mode, $langcode)
{
  if ($view_mode == 'teaser' && isset($entity->content['product:field_image'])) {
    $entity->content['product:field_image']['#items'] = array_slice($entity->content['product:field_image']['#items'], 0, 1);
  }

if ($view_mode == 'teaser' && isset($entity->content['field_field_image'])) {
$entity->content['field_field_image']['#items'] = array_slice($entity->content['field_field_image']['#items'], 0, 1);
  }

}

```

Could it be that in your code you need to replace 'items' with '#items' ? Just a guess.

# Answer
> 0 votes
The http://drupal.org/project/field\_multiple\_limit module allows you to set how many images display, per view mode. So you can set up your teaser to only show the first one but your full node to show all of them.

---
Tags: media, nodes
---


title: Drupal Views Inject Content

text:
# Question
Title: Drupal Views Inject Content
I have a View setup in Drupal that is a list of products. Each product has an associated location and all of the locations in a view are displayed in a map that is on the bottom of the page.

What I'd like to do is to bring the map "INTO" the view so that it works better with the flow of the page. Here's the layout:

Table

```
 col col map map
 col col map map
 col col col col
 col col col col

```

What would be the best way of integrating the map with the table?

# Answer
> 0 votes
You can use Gmap. There is also a great screen cast that shows how to use it. You can also take a look into the OpenLayers module to add maps into nodes.

# Answer
> 0 votes
My solution was to add a DIV class for each row using Grid format. This assigned a different value for each field. I then moved those pieces to a different region and replaced them with my map.

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


# Question
Title: Let Gmap center on the users geolocation, but still load all the node markers onto the map
For a website I am building I have a used a map to display all the nodes inside my country, by using a view. When the map is loaded, it shows the whole country (by standard settings in the Gmap module).

What I would like to do having this map centered on my location, but still show/load all these node markers that are spread across the map.

I manage to have the map centered on my location by using Filters and SmartIP in the view, but offcourse this limits the loaded nodes to only that location. I do not want to filter anything, just center the map. I am new to Drupal, and can't figure out how to make this work.

# Answer
I can clarify after my comment on your question is addressed but if I had to guess I would say you are using an nid contextual filter to center the map?

If so, that is why you aren't getting other nodes.

Alternatives are:

* Add the Global: Null contextual filter and pass the nid through that. The null contextual filter will not affect results at all.
* Keep using the nid contextual filter, but check the "Exclude" checkbox in the "More" fieldset of the filter. This will mean all nodes except the given nid will be displayed, but the given nid can still be used to center the map.

Use whichever method gives you the functionality you want.
> 1 votes

---
Tags: nodes, google-maps, location
---


# Question
Title: Filter node by custom_field in admin panel
I'm using Drupal 7, Views and Panels. Created a content type and custom field (field\_list) And showing contents by list on my site. Thanks Views :) But when i click find content in admin panel, many many contents in my area.

Can i add filter option by field\_list in my admin panel? Is it possible?

# Answer
> 1 votes
You need to install Admin views module. It will replace administrative overview/listing pages with actual views for superior usability. Now, you can override your views for admin panel for filter content by field\_list.

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


# Question
Title: Undefined variable error in node.tpl.php
I'm using the Basic theme, and I get the following error when I refresh my site.

> Notice: Undefined variable: unpublished in include() (line 18 of /Users/me/Projects/mysite/httdocs/sites/all/themes/mytheme/templates/node.tpl.php).

The line that is caused the notice is the following one.

```
    <?php if ($unpublished): ?>
      <p class="unpublished"><?php print t('Unpublished'); ?></p>
    <?php endif; ?>
  </header>
<?php endif; ?>

```

I don't understand this error. How can I fix it?

# Answer
Try `if ($node->status == 0)` instead of `if ($unpublished)`.

This may be happening because the variable is not set correctly in a `hook_preprocess_node()` implementation of the theme; you may also want to check the template.php file in your theme for these hooks.
> 5 votes

---
Tags: 7, theming
---


title: Cannot submit forms in Drupal 7

text:
# Question
Title: Cannot submit forms in Drupal 7
When I submit forms(all forms) in Drupal 7 it shows the *Your configuration settings have been saved* message, but the form values are still the same as the values before submission. I have cleared the cache but the problem still exists.

Any suggestion?

# Answer
I can suggest how you can test what's happening:

1. Create custom test form with submit function.
2. Install Xdebug on your LAMP, or WAMP or MAMP
3. Than watch callstack. look what functions have been called.

Looks you've done some specific changes in your instalation. Also try to download clear drupal instalation and check forms there.

(P.S. If you have opportunity switch to new instalation).
> 2 votes

# Answer
Your form returns not the elements of the form. But your return part of function is something like:

```
...
return system_settings_form($form);
}

```

if we look to this function:

```
function system_settings_form($form) {
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  if (!empty($_POST) && form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }

  $form['#submit'][] = 'system_settings_form_submit';
  // By default, render the form using theme_system_settings_form().
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}

```

Your problem is: $form\['#submit'\]\[\] = 'system\_settings\_form\_submit'; this adds another submit function to form. And this function saves variables through variable\_set() function:

```
function system_settings_form_submit($form, &$form_state) {
  // Exclude unnecessary elements.
  form_state_values_clean($form_state);

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

  drupal_set_message(t('The configuration options have been saved.'));
}

```

So you have to get your settings variables with function variable\_get();
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Place output of a custom module in a specific region
I am using the following code in a custom module to get the title of the node form in the node creation form, i.e, if i add a new content of type BLOG then on top of that node\_add\_blog form i get a heading/title "Create New BLOG". SO for this i got a custom module from this very forum (kudos). Now i want to know how can i place the output in a specific region, say as the right sidebar.

```
<?php
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */

function show_title_form_node_form_alter(&$form, &$form_state, $form_id) {
  // For the node add form.
  //<pre
  //<?php /** print_r($form);*/?>
  //</pre>
  //<?php
  if (!$form['nid']['#value']) {
    // Add "new" to the page title.
    $node_types = node_type_get_names();
    var_dump($node_types[$form['#node']->type]);
    drupal_set_title(t('Create new @type', array('@type' => $node_types[$form['#node']->type])));
   echo "Create"." ".$node_types[$form['#node']->type];
   ;
  }

```

Regards

# Answer
> 1 votes
If some variable you are looking for isn't available in the scope of your hook, there is a good chance that you are doing it wrong.

Title of the page can be accessed in your theme's `page.tpl.php` file (or its variants). You can use a `hook_preprocess_page()` in your `template.php` file and populate a new variable if the path matches (node add forms have `node/add` path) so you can put it in the appropriate sidebar in the `page.tpl.php`.

You cannot control stuff to be shown in the page with a `form_alter` hook. For Drupal 7, you could use `hook_page_alter()` or `hook_page_build()` to inspect and set sidebar contents.

For an example:

**template.php:**

```
function mytheme_preprocess_page (&$variables) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) && isset($vars['page']['content']['system_main']['nid'])) {
    $variables['sidebar_title'] = t('Create new @type', array('@type' => arg(2)))
  }
}

```

Now, print the sidebar title in your `page.tpl.php`'s appropriate div.

```
if (isset($sidebar_title)) {
  print $sidebar_title;
}

```

Drupa.org article: Setting up variables for use in a template (preprocess and process functions)

---
Tags: 7, blocks, users, nodes
---


# Question
Title: Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute()
I've created a view block with views3. When I attach the views block to a node, I want to know if the node is sticky and if the content type is "lodging". If the criteria are met, do not display view result.

In the views filter (php field) I've created the following code.

```
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid); // get node id
}
$sticky_status = $node->sticky;  //  get sticky status
$node_type = $node->type;  // get node type
if ($sticky_status == '1' && $node_type == 'lodging') // condition if sticky is 1 (active) and node type is "lodging"
{
  $view->result = null;  // do not display views
}

```

The code is working fine and I get the desired result, however I also get the following warning message:

```
Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute() (line 84 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_handler_filter.inc).
Warning: array_slice() expects parameter 1 to be array, null given in views_php_plugin_pager->post_execute() (line 46 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_plugin_pager.inc).
Warning: array_values() expects parameter 1 to be array, null given in view->execute() (line 1155 of /var/www/html/planetlodge/sites/all/modules/views/includes/view.inc).

```

Where is the error in the code ?

# Answer
The error is here:

```
$view->result = null;

```

Try changing it to:

```
$view->result = array();

```

Views is running over the `$view->result` var as an array without checking its type, but it's always expecting an array. As `NULL` isn't an array it complains, but it's just a Warning so the script continues. Because the results loop has failed you get the same effect as when the array is empty, and as you say everything works as expected.
> 5 votes

---
Tags: 7, views
---


# Question
Title: Check whether multiple images are uploaded to a field?
Is there a way to check whether or not more than one image is uploaded to a field? I'm working on a custom node template and want a conditional to do x if only one image and y if more than 1.

# Answer
> 2 votes
You can get it done in a few lines using the `field_get_items` function:

```
if ($items = field_get_items('node', $node, 'field_name')) {
  if (count($items) == 1) {
    // ...
  }
  elseif (count($items) > 1) {
    // ...
  }
}

```

It'd be best to keep this logic out of the template file itself and put it in a preprocess function though.

---
Tags: entities
---


# Question
Title: Why isn't my hook_theme being called or rendering output?
I am trying to use the hook\_theme function to utilize some template files. I have the following function defined in my theme:

## template.php

```
function my_name_theme($existing, $type, $theme, $path) {
    return array(
        'testy' => array(
            'variables' => array('title' => NULL),
            'template'  => 'testy',
        ),
    );
}

```

And I have the following template defined:

## testy.tpl.php

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

```

I have a content type called "Page" with a corresponding template:

## node--page.tpl.php

```
<?php
    print 'before theme call';
    $variables = array();
    $variables['title'] = 'my title';
    print theme('testy', $variables);
    print 'after theme call';
?>

```

When viewing one of my "Page" content types, the rendered page only shows the following, with no title:

before theme callafter theme call

I have cleared all caches. Why isn't this working?

# Answer
> 0 votes
I had to add a `path` to my function, then it worked.

## template.php

```
function my_name_theme($existing, $type, $theme, $path) {
    return array(
        'testy' => array(
            'variables' => array('title' => NULL),
            'template'  => 'testy',
            'path'      => drupal_get_path('theme', 'my_name') . '/templates',
        ),
    );
}

```

---
Tags: 7, theming
---


# Question
Title: Authorize.net - Multi-currency - disabling currency code when sending money
I have a issue processing multiple currencies in Drupal 7 Commerce with Authorize.net Gateways (version 1.0 stable).

I have Canadian store and have 2 currencies setup for my site: US and CDN funds.

Our processor is Bluepay and I have established separate US and CDN accounts.

I have noticed there are no problems processing US payments during check out. However when checking out in Canadian Currency using a Canadian Credit Card Authorize.net rejects my transaction.

Authorize.net is stating I must turn off 'currency code' in order for Canadian funds to be accepted with their gateways.

Is there a way to disable currency code in Drupal 7 Commerce? Is this even recommended if using more than 1 currency? How do most people go about processing multiple currencies in Drupal 7 Commerce via Gateways and Processors?

# Answer
> 0 votes
Are you sure the issue is that the currency code value is included or is it simply wrong? i.e. are you submitting a USD currency code to a CDN account? Note that in the 1.0 released earlier this month we fixed a couple of issues pertaining to multi-currency usage. Does updating to this version allow transactions to process as expected?

---
Tags: commerce, payment-gateways
---


# Question
Title: Upgrading Drupal from 6 to 7 results in double slash being present in image file paths
After upgrading from Drupal 6 to Drupal 7 I noticed that my image paths now have a double slash like this:

/files/sites/default//filename.jpg

I was thinking of running a simple find and replace in the database, but I'm sure how to resolve this.

# Answer
> 3 votes
I migrated my website from an old domain to a new one and this issue came up. Apparently, you should define new paths for website media (e.g. images) here:

`http://youwebsite.com/?q=admin/config/media/file-system`

There are two paths that must be specified. In my case,

Private: `sites/youwebsite.com/private`

Public: `sites/youwebsite.com/files`

---
Tags: media, uri
---


# Question
Title: User Registration to provide password on registration pg administrator approval and verification email
\[I tried looking for similar answers, I just got this: Administrator notification on user registration

For user registration I want: 1) Password and Confirm Password field on Registration page 2) Admin approval for account creation 3) Verification Email to be sent to the user

```
* For `Who can register accounts?` the setting says : `Visitors, but administrator approval is required`.
* I've installed the package "User registration password" to have password on registration page as well as getting a verification email sent

```

`Problem`: If I don't enable "Admin Approval" registration works fine. The user account is created immediately and it gets a verification email with a link which can be used to confirm the account.

If I enable `Visitors, but administrator approval is required`nothing works. User account is created, but it doesn't get a mail, admin doesn't get a mail and account is not activated.

Am I supposed to create a trigger?

# Answer
With the settings you are currently using, the user creating the account should receive an e-mail. On the `admin/config/people/accounts` page, near the bottom, look for the vertical tab labelled "Welcome (awaiting approval)". This is the e-mail the user should receive while waiting for the account to receive administrator approval. Check the Recent log messages page (`admin/reports/dblog`) to see if the e-mail is being sent by Drupal. If it is, check the spam filter on the e-mail account receiving the e-mail.

You will need to set up a trigger so that administrators receive e-mails when new accounts are created. I believe that the superuser account (the user created when installing Drupal) should automatically receive e-mails about new accounts. To notify additional e-mail addresses when accounts are created, see the directions listed at Administrator notification on user registration. You'll need to enable the Trigger module if it's not already enabled. If you want to e-mail all users having a certain role when an account is created (for example, e-mail all administrators), check out the Rules module.

I would also look into the LoginToboggan module. This module also allows the user to enter their password on account creation, but has several other great options. It allows you to set an additional role applied to users when they first create the account but before they verify the account. With this role, you can allow users to create an account and log in immediately, but not perform actions until they verify the account. The LoginToboggan module also allows users to log in using their e-mail address, and display two e-mail address fields on the registration page. I would recommend looking into this module as a replacement for the "User registration password" module you're currently using.
> 0 votes

---
Tags: users
---


# Question
Title: view to list already added referenced nodes to all content types by user
I have a content type of DELIVERY, and another content type of BOOK. Now each user has 3 DELIVERY content types that they are the author of. What i do is then edit a users DELIVERY content and add a BOOK to it (i have added a entity reference, referencing BOOK in DELIVERY).

All works fine, what i want to do is create a View, so that when i edit a users DELIVERY it lists the BOOKS i have already assigned to all the other DELIVERY's from that user. is this possible? been playing around with it but cant figure it out.

# Answer
OK i managed to do it, for anyone curious heres how i did it:

I created a new View I filtere it to show content of type DELIVERY i added 2 Relationships First relationship being the BOOK Reference field and the other being Author relationship I then added a Contexiual Filter of NID and set it to default value and NID From URL That was it, and i added the Book ref field to show the books
> 1 votes

---
Tags: views, nodes, entities
---


# Question
Title: Is it possible to add help text to addressfield module fields?
I would like to add some help info to address field fields from Address Field Module (http://drupal.org/project/addressfield). Is that possible, or do I have to use Javascript?

# Answer
When editing the field settings there should be a **Help text** field where you can enter "Instructions to present to the user below this field on the editing form".

If you want to provide additional instructions, use the Markup module to add a "field" containing the additional instructions. To keep the address field and the markup field in the same fieldset, use the Field group module to group the two fields into a single fieldset group.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I format a date value for a 3-column date drop-down widget?
I would like to pass a date in the format `2013-04-23 00:00:00` as a `#default_value` into a form builder function:

```
$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => $my-array['date'],
);

```

...but the form renders dates in a three column drop-down widget (which I want to keep). How do I reformat my date and/or form builder function so that my three drop-downs display 23 Apr 2013? At present, they display 02 Feb 1900.

Thanks

**Solution**

See @tostinni's answer for half of the soluion. This is the second half:

```
$timestamp = strtotime($my-array['date']);
$day = date('d', $timestamp);
$month = date('n', $timestamp);
$year =  date('Y', $timestamp);

```

# Answer
The Form API documentation will help you figure this out, you'll have to pass an array with the `year`, `month` and `day` keys like this:

```
$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => array('year' => 2013, 'month' => 4, 'day' => 23),
);

```
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: How do I replace function commerce_customer_options_list with my own?
How can I replace

```
/**
 * Implements hook_options_list().
 */
function commerce_customer_options_list($field) {

```

in commerce\_customer.module around line 949 with my own options\_list build routine?

the hook is just sent directly to the commerce\_customer module, and I don't see how I can hijack it.

Thanks

# Answer
Try using hook\_field\_widget\_form\_alter in your custom module for either `$context['field']['type'] == 'options_list'` or of type `options_select` ... it looks like the widget is set as `options_select` in `commerce_customer_field_widget_info_alter`. I'm pretty sure its 1 of the 2 values.

Then you can set a `#pre_render` attribute to a function that alters the default commerce\_customer supplied values. A derived example from the API comments is:

```
$element['#pre_render'][] = 'mymodule_pre_render_commerce_customer_options_field';

```

Then in your pre\_render function you can add/remove values from the list. I think i've done this once before myself for god knows what ... haha.

Alternatively, you could also probably set or unset values from any old FAPI `#options` array in a `$form` with `hook_form_alter`. Hopefully 1 of these 2 approaches gets you there.

Also, you'll probably want to be sure your module invokes after commerce\_customer.
> 0 votes

---
Tags: commerce
---


title: Reminder module recommendation

text:
# Question
Title: Reminder module recommendation
I am after a "reminder" module, which will enable the site users to subscribe to nodes/content types in order to receive reminders of closing dates and notifications of when the node has been updated/changed.

Any help would be greatly appreciated.

# Answer
> 1 votes
Checkout this module Subscriptions

> This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

# Answer
> 1 votes
There is also Notifications module

> This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.

Read Notifications Framework

---
Tags: 7
---


# Question
Title: How do I specify an image style in my preprocess function?
In my current project, whenever a node's image field is empty, I'm filling it with the image from an entity referenced in the node. To pull this off, I'm using this magical piece of code in template.php:

```
// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name);
        }
      }
    }

```

It works superbly - but with one small problem: it doesn't give the image its correct image style. In fact it just spits out the original image.

How can I force it to use the field's image style?

# Answer
> 1 votes
Have you tried `render`

```
// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = render($vars['content'][$field_name]);
        }
      }
    }

```

---
Tags: theming, media
---


# Question
Title: How to import date fields using CSV file?
I'm trying to import few nodes using feeds CSV file. I'm able to import some of the fields but I'm unable to import CCK **date** fields.

I have tried feeds module with `uc_feeds_product_importer`.

**How can I import date fields?**

# Answer
This was an issue with the feeds importer. I deleted the existing importer and created a new importer with new mappings, then all the date fields started working as normal.

The date format I use in the csv file is: `23-Apr-12`
> 0 votes

---
Tags: 7, datetime, importing-exporting
---


# Question
Title: Adjusting Apache Solr bias based on content length?
I have a site using the Apache Solr Search Integration module with a short-form content type that is getting weighted too highly in the Solr index. I've tried adding "Bias" to the other content types and leaving the short-form content type set to *Ignore*, but even with other bias settings maximized the short pieces still rise to the top. Looking at the particular items that appear at the top, it seems to be that multiple instances of the search terms in a short piece cause it to rank higher.

According to the help on the bias settings page, "Any value except *Ignore* will increase the score of the given type in search results." Is that a limitation of the Solr module or of Solr itself? Ideally, I'd like to **decrease** the relevance of the short type. What are my options for doing that?

# Answer
> 1 votes
Under bias setting you should be able to reduce the priority of the fields. So reduce the priority of the fields that is not much important, and increase the priority of the fields that you would prefer for solar to prioritize.

The settings can be found on: `admin/config/search/apachesolr/settings/solr/bias`

0.1 is the lowest and 21.0 is the highest rating.

---
Tags: 7, search
---


# Question
Title: How to show/hide login block on main page based on button in header?
I would like to ask the following:

My sections are lets say header, main page and footer.

I want to have a button in the header, and when it is pressed, another section comes up between header and main page showing the login form. (username and password fields must be displayed in parallel). In this section also I would like to have another button and when it is pressed, the section becomes bigger, showing the signup form.

For the show/hide functionality I will do it with HTML5, so no worries on this one.

But my question is a basic drupal architecture question that I do not know and I would need your help :)

What is the best approach to build the above? The steps below are correct?

1. Create a custom module to alter the standard login block it display it horizontally? Or this can be done with theming?
2. Create another block which will contain the 2 buttons and the login / sign up elements? If yes, in which section do I put this block? If I put it on header how then can I display the inbetween section?

Is there a drupal module that may help with the above?

Thank you!

# Answer
> 1 votes
Your first approach you can consider as best as we won't be actually touching the core Drupal functionality and creating our custom module to tweak the core. You can also have a look at logintoboggan module it may help you to get the drop down effect for login form and login block on click of link once you do the configurations for the loggintoboggan. you may need to additional theming and some jquery code to tweak it more for signup.

Hope it helps.

---
Tags: blocks, theming, users
---


# Question
Title: Huge amounts of locale queries clogging up drupal to 40 MB per request
I got an email today from my hosting company stating that they had to kill some processes of my site because it was using too much memory. Looking at the process table they provided, there were 10 processes of 40 MB, while my limit is 256 MB.

This poses me with two problems to solve.

1: Each page request drupal creates a process which uses 40MB of memory (which is of course killed again after the page is loaded). I've installed Devel and saw that each page makes around 900!! queries to the DB, most of which are from locale. All of them like this one:

```
   0.28270 locale P A E

   SELECT s.lid, t.translation, s.version
       FROM locales_source s
       LEFT JOIN locales_target t ON s.lid = t.lid AND t.language = :language
       WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'
   default

```

How can I reduce this?

2: Apparently some1 put in 10 page requests at the exact same time (elapsed time of each process was equal). Is there something I can do about this?

If you need any more information please ask. Thanks in advance.

# Answer
> 0 votes
900 queries looks far too much to me. By default, locale module caches all translations of strings that are less than 75 characters in 1 cache entry. This should prevent hundreds of separate translation string lookups.

The code involved (locale.module, function locale(), around line 668):

```
// Disabling the usage of string caching allows a module to watch for
// the exact list of strings used on a page. From a performance
// perspective that is a really bad idea, so we have no user
// interface for this. Be careful when turning this option off!
if (variable_get('locale_cache_strings', 1) == 1) {
  ...
  // Refresh database stored cache of translations for given language.
  // We only store short strings used in current version, to improve
  // performance and consume less memory.
  $result = db_query("SELECT s.source, s.context, t.translation, t.language FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.textgroup = 'default' AND s.version = :version AND LENGTH(s.source) < :length", array(':language' => $langcode, ':version' => VERSION, ':length' => variable_get('locale_cache_length', 75)));

```

I guess that somehow 1 of the variables involved got changed on your site. Looking at the comment (*watch for the exact list of strings used on a page*) this could be the l18n\_client module. Disable it on life sites.

# Answer
> 0 votes
Does your site use a caching system like Boost? Try installing the Drupal boost module and see if it helps. It is a static page caching system and needs to access the database only once.

---
Tags: database
---


title: How can filter a view by several NID's?

text:
# Question
Title: How can filter a view by several NID's?
I try to filter a node by the criteria of NID. Naturally I can filter by a single NID, but in this case I need to to filter by multiple NIDs.

I tried to wrote the following number values and non worked:

*1, 20, 31*

*1+20+31*

How should I write the number values so that it would work?

Thanks.

# Answer
You will need to add contextual filters in the view.

* Just go to advanced -\> contextual filter -\> add new 'content:nid' field.
* Check 'profile default value' option from list entitled 'WHEN THE FILTER VALUE IS NOT AVAILABLE' -\> Choose 'Fixed value' option and add multiple nids seperating them via '+' e.g. 1+2+3
* Then from 'more' fieldset check on 'allow multiple values' option.

This should do it. You can check also in sql query generated by view below it which should show something like this in where clause e.g. `WHERE (( (node.nid IN('1', '2', '3') ) )`
> 16 votes

---
Tags: 7, views
---


# Question
Title: Adding more values to Drupal user status
Are there any modules available for adding more values to the standard Drupal user status?

By default we have "Active/Blocked" values, but I would like to extend it with more values.

# Answer
> 2 votes
By default, I don't think there's any way of doing this. The user status is used by other parts of `user.module` (as well as x amount of contrib modules), so extending it *could* cause conflicts there.

What you *could* do however, is add a custom status field to your users and use that. You'll get most of the normal benefits of the Drupal user status, but it'll be as extensible as you need.

Combine it with Field Permissions to prevent users from being able to see or edit (or either one of those options) themselves should you need to.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you still want a user status that disabled the user account, then you could create a value on your custom status field (let's call it *Disabled* and then configure a Rule that says:

> **Event:**
>
> After saving a user account After updating a user account
>
> **Condition:**
>
> Use *data comparison* to se if \*field\_my\_user\_status\* is equal to *disabed*
>
> **Action:**
>
> Block user account

\*NB If you do this, don't forget to create an opposite rule that enables the user account based on your field value :)

# Answer
> 0 votes
You can add one more option to the status field using `hook_form_alter` and to keep a track for that extended status value.

You may need a database entry also, so you can add a CCK field to the user account, and when a user receives the extended value, simply update the CCK field value using a custom submit handler and finally calling `user_save()` inside it. This way you will always have a db entry for the extended option.

---
Tags: users
---


# Question
Title: Getting field value that attached to Commerce product field
From using commerce\_price\_savings\_formatter, I've created field `field_diskon` where it only contains number. `field_diskon` purpose is for discount rate.

So, I can assign different discount rate for different SKU.

For getting value in `field_specific_blabla` attached to node, I can use:

```
// Extract the first field item
$specific_items = field_get_items('node', $node, 'field_specific_blabla');
$specific_item = array_shift($specific_items);

// Get the field value
$itemvalue = $specific_item['value'];

```

But how to get value `field_diskon` attached to commerce product field?

I have no idea what entity hold commerce field. I've tried replacing `node` with keyword related to commerce, but still not works.

# Answer
You should be able to use `entity_metadata_wrapper` quite nicely for this. Note that it is part of the Entity API, but that is a dependency of Drupal Commerce so you'll be fine in this case.

Something like the following code should do it:

```
$wrapper = entity_metadata_wrapper('commerce_product', YOUR-REQUIRED-PRODUCT-ID);

$discount = $wrapper->field_diskon->value();

```

You can find out more about how to use `entity_metadata_wrapper()` here.
> 2 votes

# Answer
commerce\_price\_savings\_formatter only handles the display of the price with discount, it doesn't provide a method for creating the discounted price (AFAIK). If you want a field that allows a sale price to be set per-product then you can use Commerce Sale Price. If you want to have a rule that applies to all products check out this page on product pricing rules.
> 0 votes

---
Tags: 7, entities, commerce
---


# Question
Title: How can I allow users to create private pages?
I want a way to create a way to allow only specific users to see a specific page.

One page per user where one user can't see another's page.

# Answer
What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather course, and to control per-user access to view a page, you must use some sort of node access control module. There is a page at Drupal.org listing all node access modules, with a capsule review of each. I suggest you take a look at that page to see if you can find a suitable module.

One I suggest you take a closer look at, is Flexi Access. It let you control access to a *single node* (page) for an *individual user*. This, I believe, fits well with your requirements. Many other content access modules have *content types* and/or *roles* or *groups* as their smallest unit of resolution.

Disclosure: I am the maintainer of *Flexi Access*.
> 1 votes

---
Tags: users
---


# Question
Title: Drupal Users while developing: Methodology
I have recently been working on a Drupal project that due to time constraints had to be put up in a relatively infantile stage with the registration in place (using Profile2) and attempted log-ins blocked.

The problem that I have run into is that users have registered to the site in the interim time between my last update+commit and now.

I have exported the `authmap`, `profile`, `profile_type`, `users`, `users_roles`, `webform_emails`, `webform_roles`, `webform_submissions`, `webform_submitted_data`, & `zendesk_users` tables and imported them into my local environment. There doesn't appear to be any bugs .. \*knocks on wood\*.

Is this the only option for me? Does anyone have any insight as to how to best handle a situation of this nature?

# Answer
> 1 votes
I would suggest using Features to deploy your changes if you aren't already. That way there shouldn't really ever need to be any database changes going upstream, so this problem will be averted.

Any database changes that do ned to be made can go into `hook_update_N` functions in your Feature module's .install file

*EDIT*

In favour of other popular opinions, there is also the Configuration Management module which attempts to backport the CM functionality from D8 back to D7.

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

---
Tags: users
---


# Question
Title: What is the Correct UID path whilst using Ubercart Affiliate in Custom DB
I'm currently building a various user dashboard using my own custom hacked Workbench (WB) & cloned from one Master for end users (3 roles ex SU). WB chosen over Homebox as that was taking me too long and WB seems easier to integrate Views etc. FYI, I'm working on a D7.2x local Linux Ubuntu webdev box using the system localhost.

Things are going well and general path links to modules link well (Support tickets, Messages etc). However, one of the options I'm offering is the Ubercart Affiliate and whilst that module is working fine, I cannot for the life of me get a users Affiliate account path to show up correctly via a direct link from the Workbench. I require the path to be simply: site/user/affiliate linking direct the Affiliate dashboard (DB).

For my benefit, for now I created Custom Content Pane (as opposed to a Block) and simply created HTML links into it as one would do (using 'other' as the option URL settings. The other links work fine linking to the relevant modules, but the link to users main Affiliate DB overview won't work. I set "Affiliate Center" as the link to the UC Affiliate DB but am I either confused over the correct path structure or something is missing or both.

For example, user' joetest' can login and is redirected on login to his WB and all shows aok. joetest can access his UC DB via: \[http://localhost/sitename/user/12/affiliate\] but what I presumed was correct (...sitename/user/%/affiliate) or .../user/uid/affiliate) neither don't work and gives me an error message of what I expect, "affilate shop not found etc...".

I know it's a path issue (Redirect, Pathauto, URL-Alias) but I cannot figure it out. I checked all permissions and others.

I'm quite happy for the end result to be: in order for the user to access their said UC Affiliate main 'home' DB even maybe using the ME module? I'm not sure.

Presume this should be a five minute setup, but a few hours later, I'm getting stumped now but simply want to user to be able to view, edit, amend their Affilate details but via either a link on their WB. Not looking to use Menu tabs as I'm wanting a very light, minimal structure.

Any advice great appreciated.

Ok, I'm a learning 'novice', but probably missing a small point on the path structure knowledge. (: Thanks in advance.

# Answer
> 1 votes
I resolved this by using the ME Alias module which allow the insertion of the said UID into the path I required for all users.

---
Tags: ubercart, uri
---


# Question
Title: How does one theme a panel (or add a style)
I'm using drupal 7 and panels 3.

I'm looking for a good tutorial, or tutorial video that describes how to them panels. I understand generally hoe to theme nodes and them fields using the template files, but I don't really understand how to theme panels. I see that within the layout designer, it allows you to add a "style" to your panel panes. I understand this is probably theme based, but how would one add another style to this.

Any help would be great.

Thanks

P.S. I did do a search already for this info but was unable to find any really good info.

# Answer
When you add a CSS class using the "CSS Settings" for the pane, Panels will tag the panel html with the classes you have identified. You can then specifically change the css styling attributes by defining your class style using the local.css file found in the active theme directory (set in admin/appearance) to modify your targeted content.

IF you are not familiar with working with css , I suggest you get an intro level book on Drupal and theming, a basic primer on css coding, and upload firebug for Firefox browser to help you see which css styles are currently rendering any content you display on the site.

I have not found a good out-of-the-box solution for what you want to do. I hope this helps get you started on the 'custom route'.
> 4 votes

# Answer
First I will say that I'm *not* the themer in the team at work, so I don't know all the details, but I will explain what we do as well as I can. The way we do it in my team with nearly all theming, is by using the Pane "CSS Settings", and adding one, or maybe two classes onto a pane. On a frontpage we may have a "Views slideshow". When we add the Pane, we just add a "slideshow" class onto to it, and that's the only Panels specific action we take. Everything else is the done in the themes css files, and is no different from any other theming.

You mention "Styles", and these allowing you to autogenerate certain theming, encapsulating logic for the theming, and is one way of solving the problem. The best documentation for this right now is looking at one of the existing styles.
> 2 votes

# Answer
To add a css class, use the 'panel content' tab. It cant be done using 'customize this page' ...

The 'style' buttons there are not related to css - they are indeed theming; php code that hooks into theming bits. Read http://dustinbons.com/panels-styles-plugin-drupal-7 on how to create a new 'style' for panels.

I wish there was a style that allowed users to enter css classes under 'customize this page' ...
> 1 votes

---
Tags: 7, theming, panels
---


# Question
Title: Why are MailMime images not embedded when sending an eMail via Rules?
I'm sending an email using Mail Mime, based on a rule. I receive the email, and I can see in the HTML source that, the image has been translated,

E.g. `<img src="cid:8215e4a9ecb00ce2ead763b488ee529e@dev.intranet"`

But the image is not attached to the email. Do I need to explicitly allow Drupal to add attachments? I'm using Outlook if that makes any difference.

**Update:**

On further testing, I've noticed that when I use an embed image in the content, using HTML as a text type e.g

```
<img src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////
wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML
wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
alt="Base64 encoded image" width="150" height="150"/>

```

it produced the following in the Outlook email,

```
<img alt="Base64 encoded image" height="150" src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////
wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML
wWACH H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==" width="150">

```

Note the missing "+".

I've turned off all text filters.

When I use plain text as the format, I get the content as expect, but of course Outlook does not think the message is in HTML, so displays the saw markup.

Any ideas on what could be causing the "+" to turn into a space?

# Answer
Double check your setting on the mime mail configuration page.

In recent versions of the mime mail module there has been options added in relation to embedded images.

The option is called "Link images only". Generally I would turn that on as I don't see the need for embedding images in emails. You will generally have less issues with remote images.

There is also a permission for the mime mail module that relates to attached images, so check out the mime mail permissions too. **Edit** That permission is only a drupal 6 thing.

**Update**

In regards to your plus - space issue, what happens if you comment out the line

```
  $url = str_replace('+', '%2B', $url);

```

in the \_mimemail\_url function in the mimemail.inc file?
> 1 votes

---
Tags: rules, emails
---


# Question
Title: Block showing Parent Taxonomy Term of current Node
Ok my taxonomy is setup like this:

* Holiday Cards
* Trees
* Bears
* Religious

So the goal is to display a node belonging to 'Trees' but in that node I need to have a block that shows the Parent Item of 'Holiday Cards' (along with the description of 'Holiday Cards'.

I have attempted to use views to accomplish this but I keep hitting a wall. Can someone please walk me through, step-by-step, what I am missing in order to accomplish this seemingly simple task?

# Answer
> 0 votes
I think this is impossible with the Views module.

To achieve the goal, you can create a block with a relation to the "Holiday Cards" term. Under *Filter criteria* select *Taxonomy term: Name (= Holiday Cards)*.

To display the block only with the content related to another taxonomy term, you can consider to use the Context module.

1. Instal the module and turn it on.
2. Go to /admin/structure/context/add and create your new context
3. Under "Conditions" choose your taxonomy term "Trees"
4. Under "Reactions" choose "Blocks"
5. Select your block created in views and place it in appropriate region
6. Save the context

That's it! Your block with relation to "Holiday Cards" will be displayed only with content which is related to "Trees."

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


title: Drush Open_BaseDir Error

text:
# Question
Title: Drush Open_BaseDir Error
I keep getting the following error, although I've turned off SafeMode in my .ini file, and confirmed it's off with a PHP status page.

> The following restricted PHP modes have non-empty values: open\_basedir. This configuration is incompatible with drush. Please check your configuration settings in /usr/local/php-5.2.17/etc/php.ini or in your drush.ini file;

```
safe_mode            Off        Off
memory_limit        168M       168M
open_basedir    no value   no value

```

UPDATE: I think it's worth noting that this is on MediaTemple's Grid Service (gs). It looks like the PHP CLI is actually using a different .ini file with open\_basedir set. So I'm still trying to figure that part out.

# Answer
> 4 votes
My solution was to add this line to my .bash\_profile

```
alias drush='/usr/bin/php5 -c /home/000000/etc/drush.ini ~/bin/drush/drush.php'

```

It turns out the CLI on MediaTemples Grid Service uses a different PHP.ini file. So that line basically tells it to find your drush.ini file to override some settings. Make sure to replace the 000000 in with your server number. Thanks to kiamlaluno and MediaTemples support folks for the help.

# Answer
> 2 votes
The error you are seeing is reported by Drush, which verifies the "open\_basedir" directive contains an empty value, and returns an error if the value is not empty.

Drush can use the php.ini file used by PHP or its own INI file ("drush.ini"), which is looked for in the following directories:

1. Drush installation folder
2. User's .drush folder (i.e. "~/.drush/drush.ini")
3. System wide configuration folder (i.e. "/etc/drush/drush.ini")

The code I am referring to is contained in the `_drush_environment_check_php_ini()` function, and it is the following one:

```
  $ini_checks = array('safe_mode' => '', 'open_basedir' => '', 'disable_functions' => array('exec', 'system'), 'disable_classes' => '');

  // Test to insure that certain php ini restrictions have not been enabled
  $prohibited_list = array();
  foreach ($ini_checks as $prohibited_mode => $disallowed_value) {
    $ini_value = ini_get($prohibited_mode);
    $invalid_value = FALSE;
    if (empty($disallowed_value)) {
      $invalid_value = !empty($ini_value);
    }
    else {
      foreach ($disallowed_value as $test_value) {
        if (strstr($ini_value, $test_value) !== FALSE) {
          $invalid_value = TRUE;
        }
      }
    }
    if ($invalid_value) {
      $prohibited_list[] = $prohibited_mode;
    }
  }
  if (!empty($prohibited_list)) {
    drush_log(dt('The following restricted PHP modes have non-empty values: !prohibited_list. This configuration is incompatible with drush.  !php_ini_msg', array('!prohibited_list' => implode(' and ', $prohibited_list), '!php_ini_msg' => _drush_php_ini_loaded_file_message())), 'error');
  }

```

As you can see, the function returns an error if the "safe\_mode" directive, or the "open\_basedir" directive contains a non-empty value.

# Answer
> 2 votes
@Eric I.E. You're correct. That way solves the issue. But we do need to make a copy of drush.ini from http://drupalcode.org/project/drush.git/blob\_plain/refs/heads/master:/examples/example.drush.ini Also make sure "open\_basedir = " on an uncommented line.

# Answer
> 1 votes
For those who couldn't fill in the missing blanks here, your drush.ini file will need the line, in addition to being sourced from the alias in .bash\_profile:

```
open_basedir =

```

# Answer
> 1 votes
**install drush on CentOS with Plesk**

I tried to install drush 7.x-5.9 on on a CentOS system with the Plesk panel.

## I was still getting this error:

> drush
>
> sh: /tput: No such file or directory The following restricted PHP modes have non-empty values: safe\_mode. \[error\] This configuration is incompatible with drush. Please check your configuration settings in /etc/php.ini or in your drush.ini file; see examples/example.drush.ini for details. sh: /wget: No such file or directory Unable to create a temporary directory.
> \[error\] tempnam(): Unable to access filesystem.inc:461
> \[warning\] sh: /curl: No such file or directory

### This is how I fixed it

```
sudo -s
wget http://ftp.drupal.org/files/projects/drush-7.x-5.9.tar.gz
tar -zxf drush-7.x-5.9.tar.gz  -C /usr/local/share
ln -s /usr/local/share/drush/drush /usr/bin/drush
cd /usr/local/share/drush
cp ./examples/example.drush.ini drush.ini
vi drush.ini

```

Uncomment the following lines (at the bottom) by removing the ";" on the beginning of the line.

```
safe_mode =
open_basedir =

```

save the file

Tell dush to use this ini file `export DRUSH_INI='/usr/local/share/drush/drush.ini'` Add above line also to your ~/.bashrc file

# Answer
> 0 votes
Because (as @greg\_1\_anderson said) making an alias for `drush.php` is not covered in `drush-5.x` Readme file. A better solution is to copy the server's default configuration `php.ini` file to `$HOME/.drush` or to `/etc/drush`.

Then, edit it to set `open_basedir` to no value and add any other custom configuration for drush.

Also, check this answer for `php.ini` code sample.

---
Tags: drush
---


# Question
Title: Array Flip Error Message on All Node Pages
Hello i dont know where to begin. All of a sudden MY WEBSITE is displaying this error when i view a node-

> Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of /home/onlineba/public\_html/onlineplac.es/includes/entity.inc). Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>cacheGet() (line 355 of /home/onlineba/public\_html/onlineplac.es/includes/entity.inc).

I havent added anything or changed anything. I was hoping it was because OG groups upgraded to 7.2 but i seem to get it when viewing a node that is not in a group. Let me see my page content type as thats got no OG fields attached or postable in groups.... yes exactly the same thing. its only got a title, body and image field attached to it. Oh and a term referance. Lets remove that...yes still the same.

Panels node page is disabled. Im sorry i cant tell you anymore about my problem but if anyone could be a lifesaver and offer any advice it would be gratefully reveived. I get really depressed when things like this happen. :(

thanks

# Answer
> 4 votes
Something is calling entity load with an incorrect $ids parameter.

This could be from something like node\_load() or equivalent or node\_load\_multiple() or equivalent. If you pass in the wrong type of value into any of these you could end up with the error you mention.

If you want, add just above line 178 the line

```
print_r($ids);

```

Then reload the problem page and you will get a bunch of text print out. Post the text back here (if you can upload files and there is a lot of output you could paste it in a txt file and post it).

---
Tags: entities
---


# Question
Title: How do I display a sorting button in views?
I need to create functionality so that the user can switch between different sort/filter behaviors in a view. Hopefully, without loading a different page.

For example, I have a list of projects on my site and I want buttons that the user can click to hide projects that aren't of a specific type. ie: show only print, show only web, show only video, etc.

Is there any way to do this asynchronously with views, rather than custom scripting stuff with jquery or linking to totally different pages?

# Answer
You can set your filters and sorts to be exposed, which means the end user can interact with them choosing how to sort or filter the results,

There is also a setting in the "Advanced" column on the right of the views admin page called "Use AJAX". Set that to "Yes" and you will no longer have to have page loads when the user changes filters and sorts.

**Note:** If your view is a block view, you must turn on ajax for exposed filters to work.

Also, in the "Advanced" column if you click the "Settings" link for the "Exposed form style" option. In there you can check the "Autosubmit" checkbox, which will mean the view will be reloaded when the user selects a filter, without them having to click submit. This may or may not be desirable depending on your use case.

One last thing is the "Exposed form in block" setting. If you set that to "Yes" then a block will be available that will contain the filter and sort settings, so you can put them wherever you want, instead of them having to be in the top of the view.

**Note:** You cannot use exposed form in block with a block view. A potential workaround (I have not actually tried it) is here - https://drupal.stackexchange.com/a/38994/10729
> 2 votes

# Answer
I am assuming here that you want the user to switch between a number of different views. If that be the case you can try out the Quicktabs module. You can then create different views and have them presented as tabs. Quicktabs allows you to switch between the tabs using ajax.
> 1 votes

---
Tags: views
---


# Question
Title: Disable the toolbar module in install profile
How do I disable the toolbar module in my make file / profile info / install file?

# Answer
> 3 votes
From an install file perspective, you can use a combination of `module_exists` and `module_disable`, in an implementation of `hook_enable`.

*Example:*

```
function MYMODULE_enable() {
  if (module_exists('toolbar') {
    module_disable('toolbar');
  }
}

```

Module enabling/disabling isn't within the scope of a make file, so that won't work.

Lastly, as far as I'm aware, if a module is not declared as a dependency of a profile, the it won't be enabled. If I'm mistaken, you can still use the code shown above to disable the module (although I can't 100% confirm where to put it, as I've never made an install profile).

---
Tags: drush
---


# Question
Title: How can I show a flag link only for the "deepest" terms for a field with multiple values using hierarchical select?
On my site, users can add terms to their user profiles via a taxonomy field. They can add multiple terms with multiple depths using the hierarchical select widget, like this:

* Trees -\> Fruit trees -\> Apple trees
* CMS Software -\> Drupal

These terms are displayed on the user profile page using a view with the hierarchical select formatter.

I have a flag that allows users to flag taxonomy terms. **I want to print a flag link after the last term on each line, like this:**

* Trees -\> Fruit trees -\> Apple trees (flag me)
* CMS Software -\> Drupal (flag me)

The code for this is in `hierarchical_select/modules/hs_taxonomy.module`:

```
function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($item);
    $line  = '<span class="lineage-item lineage-item-level-' . $level . '">';
    $line .= drupal_render($item);
    //this adds a flag link to every term, not just the last term
    $line .= flag_create_link('hobbies_and_interests', $item['#options']['entity']->tid);

    $line .= '</span>';
    $items[] = $line;
  }
  $output .= implode($separator, $items);
  return $output;
}

```

As I commented in the code above, currently I am showing a flag link for every term, not the last term in each row. This output (**which I don't want**) looks like this:

* Trees (flag me) -\> Fruit trees (flag me) -\> Apple trees (flag me)
* CMS Software (flag me) -\> Drupal (flag me)

This is ugly; I just want the "flag me" link to appear at the end for the final term in each line. However, I don't know how to target only the last term in each row. I tried using end() but $output appears to be a string, not an array, so I'm lost at how to proceed (the answer may be obvious, but I'm a PHP novice).

# Answer
> 1 votes
Have you tried checking the $level variable? I have never used this module but the fact that there is a variable named $level suggests to me that this could be checked to only apply your flag link to the last 'level'.

edit in relation to comment:

Try this.

```
function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($item);
    $line  = '<span class="lineage-item lineage-item-level-' . $level . '">';
    $line .= drupal_render($item);
    //this adds a flag link to every term, not just the last term
    if(!count(taxonomy_get_children($item['#options']['entity']->tid))){
      $line .= flag_create_link('hobbies_and_interests', $item['#options']['entity']->tid);
    }

    $line .= '</span>';
    $items[] = $line;
  }
  $output .= implode($separator, $items);
  return $output;
}

```

# Answer
> 1 votes
You could check if it has no children, By using `taxonomy_get_children($tid, $vid)`:

```
$tid = $item['#options']['entity']->tid;
$vid = $item['#options']['entity']->vid;
$children = taxonomy_get_children($tid, $vid);
if (empty($children)) {
  // Print flag link here.
}

```

If there is no child it will be empty, It does also caching itself. Look at documentation here on drupal APIs.

---
Tags: taxonomy-terms
---


# Question
Title: Show block on term page if term has no children
Is there a way (probably with PHP block viability settings) to only show a view on term pages and only if the term has no child terms?

# Answer
> 0 votes
I've answered it over here, Check if taxonomy\_get\_children($tid) is empty, Then term has no children.

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


# Question
Title: How to programmatically add / remove a value for an unlimited multivalue field?
I was looking at http://php.net/manual/en/function.array-push.php but it seems one cannot use it as multi value fields are associate arrays. Any built in functions perhaps?

Here is an example array

> $myfield\["und"\]\[0\]\["value"\] = 23424;
>
> $myfield\["und"\]\[1\]\["value"\] = 76786;

# Answer
You can use the `entity_metadata_wrapper()` function with entities (you'll find good examples here); it makes things a bit cleaner, but not that much.

Other than that, no - you're stuck using vanilla PHP for this, Drupal doesn't have any built in functions to help.

There's no reason you can't use `array_push` as normal though:

```
array_push($myfield[LANGUAGE_NONE], array('value' => 23424));

```

Although that's actually more verbose and less readable than the original.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to make user profile page display extra fields in drupal 7?
I have added some extra fields to users under admin/people/ - when I click edit beside the user, I can see the extra fields I have added.

However, if I go to /user/ those fields are not displayed.

How do I display user profile fields when their profile is viewed at /user?

# Answer
You most likely added the fields through this admin page: admin/config/people/accounts/fields

To control which fields are actually displayed on the view page, go here: admin/config/people/accounts/display

Also if you have the Field Permissions module enabled, make sure all necessary roles have the permission to view the fields you've added.
> 3 votes

# Answer
A very belated reply that might help someone else.

I had a similar problem where I was going to populate the fields from another source and so the user wasn't to be allowed to edit them. I could see the fields as an administrator but not as the user.

The cause in this case was that the fields would only display if they had data in them. Adding data as an administrator made them visible (but read-only).
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to find out whether or not a page is cached?
I have some serious problems with the performance of my Drupal website and I think that the problem may caused by the fact, that the pages are not cached. How can I find out whether or not a page was cached and if not, how can I find out why the page is not cached?

I am using varnish for my page.

# Answer
**Whether a page is cached**

You can enable logging and use `varnishlog`, `varnishstat`, etc. See Debugging Varnish for a bit more information. There's also a lot of information on Pantheon's Working with Varnish, I'd highly recommend reading that.

**Why it is not cached**

That's a much bigger, harder question to answer. It's entirely down to your server/application logic. Your server's VCL files, in conjunction with response headers sent from your Drupal application, will determine whether or not a page is cached.

There may be other environmental factors affecting things, but again those would be specific to your server and your sysadmin (or whoever installed/set up the server) should be able to tell you about them.

There's a pretty decent tutorial available that walks through setting up Varnish with Drupal, I'd recommend reading through that and comparing your own set up to that known-to-be-working one.
> 1 votes

---
Tags: caching
---


# Question
Title: How to create a different second level block for every menu link?
I'm creating a small project and got stuck on the following:

Im using the module Menu\_block to create my navigation menu second level. What i need is a different background for each second level. (Not every link needs a different background, but the compleet block.) Menu\_block creates one block for all the second level items.

Now is there a way to make the one block into seven (i got seven menu links) blocks or is there an other way i could do this?

For a layout of the website see the following link: https://www.dropbox.com/s/p5nr0zm3r2eatbw/layout%20website.PNG The number 1 or 2 background is what I want to change according to the current active navigatie level 1 link.

# Answer
**Different colour second level menu items**

I would not use a block for each menu item even if you could.

The menu items should have classes with their mlid (menu link id), which is unique to the menu item.

You can add different colours with css based on those classes.

**Different colour second level menus based on active path**

Now that I understand your question you want the whole second level menu block to be coloured based on the currently active top level menu item.

In this scenario I think it is more acceptable to have a second level menu block for each parent menu item, so that is one solution, in which case you can easily style the blocks differently as they have different block IDs.

An alternative solution, is to add a single second level menu block for your main menu, and then add this code to your theme's template.php file:

```
/**
 * Override or insert variables into the menu block wrapper template.
 */
function THEME_NAME_preprocess_menu_block_wrapper(&$variables) {
  $active_trail = menu_get_active_trail();
  foreach ($active_trail as $item) {
    if ((!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) && !empty($item['mlid'])) {
      $variables['classes_array'][] = 'active-top-level-mlid-' . $item['mlid'];
      break;
    }
  }
}

```

That code will add a class to the block like active-top-level-mlid-405 - where 405 is the mlid of the active top level menu item.

You can then theme the block using this class.
> 1 votes

# Answer
The block should have a id which is unique for that specific block. You can use that as a css selector and change the block background.

For example: `<div id="block-nice-menus-1" class="block block-nice-menus contextual-links-region block-1 block-nice-menus-1 odd block-without-title">`

You could use #block-nice-menus-1 as your css selector to change the block background.

You could also then style children elements just for that block like this:

```
#block-nice-menus-1 li a {}

```

Hope this helps.
> 1 votes

---
Tags: 7, routes
---


# Question
Title: How can I make views show 10 items if there are actually less (and add placeholders)?
I have a view output that shows user-profiles. Each view is a group on it's own and has a maximum of ten members. How can i show always ten items, if there are currently -let's say- only 7 assigned? So it would show 3 empty slots with maybe a custom text.

I don't find any logic that's out-of-the-box views behaviour for this. Can someone please point me in the right direction?

Thanks!

EDIT: Adam Balsam pointed out the grid format, which has an autofill feature. Unfortunately it's just an empty table row that is created. It's also not useable for responsive layouts... bummer.

# Answer
You can add the empty rows to the view in the View's Style output template. Assuming you are using the unformatted style, the template name would be `views-view-unformatted--[view-name].tpl.php`.

Using the default `views-view-unformatted.tpl.php` as a starting point, add the following to the top of your custom template:

```
<?php
$num = count($rows);
$add = (10 - $num);
for ($i=0;$i<$add;$i++) {
  $rows[] = '<div>Empty Row</div>';
  $classes_array[] = 'views-row views-row-' . ($num + $i);
}
?>

```

If you're worried about the views-row-last classes, etc, the same sort of logic could be applied earlier in the view build process using something like `hook_view_pre_render()`, but depending on your scenario, the above should suffice.
> 2 votes

# Answer
You could use the Grid format and select the "Fill up single line" checkbox. Make sure you have entered either `5` in the "Number of columns" textfield and display 10 items in the pager settings.

That would fill each row with empty `<td>` elements.

*Note: If you have less than six results, it will only fill the first row; so this isn't a perfect solution.*
> 1 votes

---
Tags: 7, views
---


# Question
Title: drupal_match_path() for multiple wildcard patterns?
I want to add some CSS and JS to multiple matched wildcard URL patterns. According to Add javascript to multiple specific urls, I can use a wildcard using drupal\_match\_path() and that works well for one pattern. However, I am trying to use a few patterns to add the same JS and CSS. So far I've tried these:

```
  // By path matching wildcard patterns.
  $path = drupal_get_path_alias();
  $pattern = 'portfolio/* || photo-blog';

```

and

```
  $path = drupal_get_path_alias();
  $pattern = 'portfolio/*, photo-blog';

```

and

```
  $pattern = 'portfolio/*' 'photo-blog';
  $path = drupal_get_path_alias();

```

... but none of these work. I am guessing it may not be possible in the context of:

```
if (drupal_match_path($path, $pattern)) {
// add JS and CSS based on above
  }

```

# Answer
> 8 votes
The API page you've linked describes the format of the `$patterns` argument:

> $patterns: String containing a set of patterns separated by \n, \r or \r\n.

These are types of carriage returns, in different Operating Systems.

Sooo .... did you try:

```
 $pattern = "portfolio/*\nphoto-blog";
 // or
 $pattern = "portfolio/*\rphoto-blog";
 // or
 $pattern = "portfolio/*\r\nphoto-blog";

```

EDIT:

```
 // for platform portability heh
 $pattern = "portfolio/*" . PHP_EOL . "photo-blog";

```

# Answer
> 1 votes
This one got me *so* many times - `drupal_match_path()` is expecting a newline character to separate the paths. Add this function to your project and never look back:

```
function _get_path_pattern_string(array $items) {
  return implode(PHP_EOL, $items);
}

```

Example usage (overly verbose):

```
$patterns = array('portfolio/*', 'photo-blog', 'something-else');
$pattern_string = _get_path_pattern_string($patterns);
if (drupal_match_path($path, $pattern_string)) {
  // Do something...
}

```

---
Tags: 7, path-aliases, theming, javascript
---


title: hook_filter_info langcode is always und

text:
# Question
Title: hook_filter_info langcode is always und
I am trying to filter text and the result replace depends on the language of the node. The filter process callback function accepts $langcode argument but it always pass as "und". If I could access the Entity object to check it's langauge that would be perfect. I've tried to understand where the "und" value comes from and understand that it's from the field settings. Currently I'm getting the language code from the active $language object and in order to filter per language I set the filter cache to FALSE and I don't wanna do this.

How can I overcome this problem?

Thanks, Bnaya

# Answer
> 2 votes
The process callback is generally called from the check\_markup() function.

That function blindly passes the $langcode value through to the process function, so it is up to the caller of the check\_markup() function to send through the appropriate language.

You can see the list of functions that call check\_markup() here.

The main one that you will encounter would be the text module's \_text\_sanitize() function, which is what formats the text for text fields that user input filters.

As you can see, it also passes through the language of the field.

Going up another level we have hook\_field\_load(), which also passes through the langcode.

Back again we get field\_attach\_load(), which calls hook\_field\_load() via \_field\_invoke\_multiple().

All these are passing through langcode.

field\_attach\_load() is called by all these functions.

So basically you can scour the API site and see that is calling check\_markup() in your case and see why there is no langcode being passed in.

Alternatively, you can install the devel module and put

```
dpm(debug_backtrace());

```

in your format process function.

Then load the page where your text is printing out and you will get a backtrace on the screen.

The backtrace will give you all the functions that have been called to get to your code. It shows you all the parameters that have been passed into function along the way.

This way you can more quickly isolate the point where the language becomes LANGUAGE\_NONE (UND) - In theory :)

# Answer
> 2 votes
Modules implementing input filters should never make assumptions about for which entity they are called to change the content. An input filter can be called in different contexts: A function that calls `check_markup()` could use it for changing a node body, but also any text that is not associated with an entity, or associated to an entity that is different from the entity associated with the current page.

That is the reason why the implementations of the input filter callbacks should just depend from the parameters they get. There is no way for them to know for which entity (if an entity is involved) they are called.
For example, a field could need to render its content using `check_markup()`, but the language used for the field is different from the language used for the node. (It could happen that the node's language is French, but the field doesn't have any content in French, and the default language is used.)

---
Tags: entities, hooks, i18n-l10n
---


title: Form Parameters

text:
# Question
Title: Form Parameters
Some forms like the `user_login` form have `$form` and `&$form_state` for parameters. The Drupal 7 Module Development book also have the 2 parameters in their example. But in the Quickstart Guide, the example only have the `&$form_state` parameter. In what cases should there be 2 parameters and in what cases should there be only 1 parameter?

# Answer
The "Quickstart Guide" you linked to is for Drupal 6.

Drupal 6 form signature:

```
function MYMODULE_some_form(&$form_state) {
  // ...
}

```

Drupal 7 form signature:

```
function MYMODULE_some_form($form, &$form_state) {
  // ...
}

```

Nothing more to it :)
> 1 votes

---
Tags: forms
---


# Question
Title: Print something in a tlp file if a field isnt empty
I need to print some html in a node tpl file if a certain field is not empty. The follwing is giving me a white screen:

```
<?php if (!empty($content['field_hotel_sat_nav'])) {
                        print '<h1>The field is not empty</h1>'
            }
?>

```

# Answer
> 0 votes
Try this code:

```
<?php
  if ($content['field_hotel_sat_nav'] != '') {

    //Do something

  }
?>

```

---
Tags: 7, theming
---


# Question
Title: Drupal Views to Display Fields for Each Nodes of One Content Type
I have a *Content type* which has *Term reference* type of fields called *Tags* and *Categories* and a default field like *Body* (Long text and summary).

What I want to be able to do if possible is to have a *View* display these fields such that when this *Content type* is viewed, *Tags* and *Categories* are brought up by a *View* which will list the values in that field specific to that node, and any other field will be brought up the default way (through Manage Displays).

I figured that since that Tags and Categories are fields I didn't want to be visible, I set them to Hidden in Manage Display. So at least this part is done.

As for making Categories and Tags appear as a *View* in a Block, is it possible to do this by using Views Relationships and Contextual Filters? If so, how?

Here's a little graphic to help you visualize what I'm trying to do"

https://i.stack.imgur.com/PJ4Tm.png

Any help is appreciated. Thanks in advance!

# Answer
> 0 votes
There are a couple of ways to this using Views. Chances are that you will have to visit the display settings of the content type to hide its content so that it does not show duplicated.

**Solution 1.** Create a block for each section of the page you want to relocate using Views using the argument or contextual filter so that the block use the node ID to show the right content in the right page. Then enable the blocks and make them visible by content type and you can play with the position of the block using CSS and/or the module block class.

**Solution 2.** Use the module EVA that it will let you create an view attachment to the node content type entity and that you can re-arrange like any other field in the content type display settings screen. The rest of the setup is similar to the way you created the blocks in solution 1.

**Solution 3.** You don't need to use views at all, just CSS and you are good. Reposition the fields using the content type display manager make the tags field first, then the body and last the category. Since each field will have a wrap div then use a simple "float", "with" and "margin" css to accomodate the content.

**CSS Example (classes are not real)**

```
.div-wrap-for-tags {float:left;margin-right:20px;width:200px;}
.div-wrap-for-body {float:left;width:400px;}
.div-wrap-for-category {clear:both;}

```

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


# Question
Title: Two concatenated links throwing an error upon attempted logout
I've looked everywhere, and can't seem to find an answer to my problem. I've written some code to toggle between a log in block and, once the user has logged in, a line of text that includes both a link to the logged-in user's profile (I have the Profile 2 module installed) and a log out link.

Both the log in block and the line of text display nicely on my site when users log in and out. The problem comes when I click on the user profile link, which takes me to the user's profile page (which is correct). But then, when I click the "log out" link while on the profile page, it throws an error, rolling the two URLs into one.

Here is the code I included on the page.tpl.php:

```
  <?php
    global $user;
    $var1 = $user->name;
    $var2 = 'Welcome back' . " " . '<a href="/users/' .
    str_ireplace(' ', '-', $var1) .  '">' . ucwords($user->name) . '</a>' . " " . '|' . " " . '<a href="user/logout">Log Out</a>';
    if ($user->uid == false) {
      print render($page['code']);
    }
    else {
  ?>
</div>
<div id="style2">
  <?php print $var2; ?>
</div>

```

(Not that it matters, I'm sure, but a few lines of this code are wrapped in div wrappers that this post wouldn't allow me to include.) When a user logs out from the profile page, this is the URL that results:

www.site.com/users/user/logout

Which obviously doesn't do the job of logging the user out. I want to emphasize that on every other page I've tested, the user can hit the log out link and be logged out with no problem; the issue only exists when trying to log out from the profile page. I suspect that I've coded something wrong with respect to the link HTML, but can't seem to figure out what the issue is. Any help would be much appreciated, thank you.

# Answer
The issue is you have href="users/logout" not href="/users/logout", eg, it's a relative url, and thus building upon where you are in your site.
> 1 votes

---
Tags: navigation, users
---


title: Pick which fields to use for content

text:
# Question
Title: Pick which fields to use for content
I have content type = CD. As there are many fields to describe each detail (artist, publisher, performers, band, producer etc.) i want somehow to give user option which field to pick. Of course this works by default, but i would like some kind of checkboxes in block for example when adding node, so user picks only 3 of 15 if he wants, and then

If CD is compilation or you have many artist (Opera for example), user will proly use all fields, if CD is one man band he will use far less.

I hope i gave good explanation of what i want to acchive.

# Answer
> 1 votes
I'm not aware of a simple way to provide checkboxes of what fields you want to show for a node form.

You could probably use Conditional Fields to show 1 field type you create called `desired_fields` it simply has checkboxes for `artist, publisher, performers, band, producer`, as they check those boxes you could have a condition in Conditional Fields that `Shows` the field in the node form.

If you're comfortable coding you could probably have a custom form that gets the choices you want and then shows the form.

Both approaches will get complicated if you have `required` fields.

---
Tags: 7, entities
---


# Question
Title: Calendar module: Where is the pager markup? How can I translate it?
This is so driving me insane. I installed this: http://drupal.org/project/calendar

Now I'm trying to get the 'Next' and 'Prev' links in the monthly calendar to translate. Those strings don't show up in string translation, so I decided to look for their origins; where do they come from. Problem is, I can't even find the markup. The rendered final markup looks like

```
<ul class="pager">
    <li class="date-prev">
        <a href="http://pirkanmaa.fi/fi/etusivu/tapahtumakalenteri?mini=2013-02" title="Navigate to previous month" rel="nofollow">« Prev</a>
    </li>
    <li class="date-next">
        <a href="http://pirkanmaa.fi/fi/etusivu/tapahtumakalenteri?mini=2013-04" title="Navigate to next month" rel="nofollow">Next »</a>
    </li>
</ul>

```

It has to be somewhere, but where?

# Answer
> 5 votes
The pager markup is not directly related to calendar. It is part of date views, a submodule to the date module. Assuming your date module is installed in sites/all/modules, you can override the markup by copying the templates in sites/all/modules/date/date\_views/themes to your themes template directory. You can also see the template preprocess functions in sites/all/modules/date/date\_views/themes/theme.inc

# Answer
> 2 votes
The calendar module is a view so all the templates related to view is applicable here too. When you check the calendar view there is a theme information in the advanced section when you click on that you would get the list of all the themes used

The pagers are printed in the Display output the first one in the list. When you click on the you will get the code for displaying the view. Copy that and create a new file with the names suggested in the list. If you want this to be for all the views then you can select views-view.tpl.php the last one will be specific to the current view so it will effect only the current view.

Once you have copied the code there are two variables that out put the pager `$header` and `$pager` The $header is used if your pager is a the top of the calendar and $pager is used if it is at the bottom. Depending on your settings you can do a string replace on that variable some thing like

```
$header = str_replace("prev", "new prev", $header);

```

If you are using i18n module for translation then you should also look at Internationalization Views

Note: Drupal 7 version is still in development phase.

---
Tags: i18n-l10n, datetime, theming
---


title: Using Drush with ENVVARS

text:
# Question
Title: Using Drush with ENVVARS
I use EnvVars (vhost) to set my MySQL settings so I can have cross-server settings.php file without having to update it 3 different times.

I am wondering if there is a way to get drush to do one of the following.

1. Read the EnvVars from the VHOST (in which case where so I find the Drush database config gathering stuff).
2. Override the MySQL settings for pm-update

# Answer
This is an existing Drush feature request. See http://drupal.org/node/1848766 and http://drupal.org/node/1335626.

You could also make a bash alias (one per Drupal site) that set the appropriate environment variables, and then called Drush.
> 0 votes

---
Tags: 7, drush, database
---


# Question
Title: Add content type machine name to an attribute in the body tag?
I figured this would be easily done in the template\_preprocess\_html function, but I haven't found a way to do it... yet.

I need to add the content type machine name to a "data-init" attribute in the body tag. How can this be done exactly?

End result: `<body ... data-init="content_type">`

# Answer
> 4 votes
`template_preprocess_html` should be the right function to start with.

So your code should look like the following:

```
function mytheme_preprocess_html(&$variables) {
  if ($node = menu_get_object()) {
    $variables['attributes_array']['data-init'][] = drupal_html_class('node-type-' . $node->type);
  }
}

```

Make sure to replace `mytheme` with your custom theme and clear Drupal cache.

---
Tags: 7, hooks, theming
---


# Question
Title: Is it safe removing block-inner clearfix classes from block templates?
Is it safe to remove block-inner clearfix templates from block? I use mainly context module which works with blocks. Looking at html there is too much wrappers involved. Thank you.

# Answer
You can remove them, but they are there so that you can properly float elements within your content. That will depend on the modules you use (whether they include clearfix), and your own CSS.

Not sure about whether Admin requires it. In my case, I use an admin theme for all editing, precisely to avoid such complications.
> 0 votes

# Answer
You can override the template that includes that corresponding block. For example, I wanted to remove a clearfix in my branding region. I copied region-branding.tpl.php from the omega directory to my theme's templates directory. I then edited the file and removed the clearfix.
> 0 votes

# Answer
Instead of removing it is better to override them so that if you need to have them in case of any problem, you should have access to them. For exammple you can override .form-item, .form-text, .clearfix etc. etc. in your CSS.
> 0 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Images not displaying after transfer to temporary site ~username
I had my site running on my local machine w/ DAMP.

I transferred (FTP) to hostgator shared server under my temporary site url http:// Address/~username. Running drupal 6.28.

My images that are under sites/default/files are not displaying.

Here's what I've done

1. Full html was checked
2. Ran update.php
3. Ran Cron
4. File permissions checked and set
5. Cleared cache
6. Reviewed status report to check issues there
7. Added the base\_url to my settings.php file
8. updated my template so that it prints the base\_url file
9. Checked file system settings
10. Commented out, deleted .htaccess (under files)
11. cleared my cache
12. Site is not in maintenance mode

It seems that if there has been a solution thrown out there, I've tried it. Any solutions someone could provide would be greatly appreciated.

# Answer
Sorry, I just re-read the question and realised I misread it before.

Try setting your base path in the .htaccess file and also the base path in the settings.php file. (actually I think I'm confusing myself. I'll leave this here anyway.)

**Previous answer**

Are you talking just image style images or all images? Can you look in the source of your page and give an example of one of the file paths that is not loading properly?

I know you have stated you have already done some of these, but this is what I would try.

1. Check a few images by looking at their path in the source and checking on the server that they exist in that place.
2. Try going in your browser, directly to one of the files, for example yoursite.com/sites/default/files/yourfile.png or whatever it is.
3. Check permissions of files directory and also the temporary files directory, which must exist and be writable (the status page should alert you to these anyway).
4. Try saving your image styles to force them to regenerate your images, and clearing your caches again.
5. Check files .htaccess
6. Check your watchdog logs for any errors that might be related (any unrelated errors should be investigated too.
> 1 votes

---
Tags: media
---


# Question
Title: How to disable new user registered email to admin
When a new user registers, there's an email sent to the admin in the form:

Subject: Account details for \[name\] at \[site name\] (pending admin approval) Message: \[Name\] has applied for an account. \[profile URL\]

How can I remove this email alert? The reason being, that I've created a customised message triggered by the Apply for role module. Thanks.

# Answer
This email is not configurable via the UI.

You can use hook\_mail\_alter(), which will allow you to stop the sending of a message. So you would create a custom module that does this:

```
/**
 * Implements hook_mail_alter().
 */
function MODULE_NAME_mail_alter(&$message) {
  // Stop the default drupal email that goes out to admins when a user
  // registers on the site. An alternative email is sent out via other means.
  if ($message['key'] == 'register_pending_approval_admin') {
    $message['send'] = FALSE;
  }
}

```
> 4 votes

---
Tags: users
---


# Question
Title: Create path alias for hook_menu URLS based on node information
I'm looking for guidance on how to dynamically create a path alias for dynamic paths that I create in a module using hook menu. For example, I have a module that defines a path such as subsite/template2/% where % expects the nid of a node. For that specific node, however, I want to create the alias based on the title of the node.

So if the title at subsite/node/5 is "Community Gardens" I want the path alias of subsite/template2/% to become subsite/community-gardens. I'm pretty certain this is possible, I'm just not sure how to do it. It even gets more complicated because there are sub tabs that need to be aliased but I figure if I can figure out the first part I can puzzle out the rest. (Using version 7)

# Answer
For this I would use the pathauto module, which I am assuming you already have installed.

It provides a bunch of hooks to allow you to integrate with pathauto for your own needs.

For documentation, see the API.txt file in the pathauto module (from what I can tell though that file seems a little out of date).

You can look at working examples of its usage to give you an idea how to make your own. To see these look in the pathauto.pathauto.inc file in the pathauto module.

Here is an example of what you might do (I haven't tested it but it should be close to what you need if it isn't exactly):

This is for the install file:

```
/**
 * Implements hook_install().
 */
function MODULENAME_install() {
  // Set the default value of the pathauto pattern.
  variable_set('pathauto_subsite_pattern', 'subsite/[node:title]');
}

/**
 * Implements hook_uninstall().
 */
function MODULENAME_uninstall() {
  // Remove the pathauto pattern.
  variable_del('pathauto_subsite_pattern');
}

```

This is for the module file (note you can move some of this out into an include file if you prefer):

```
/**
 * The internal path pattern for subsites.
 */
define('MODULENAME_SUBSITE_INTERNAL_PATH', 'subsite/template2/');

/**
 * Implements hook_path_alias_types().
 */
function MODULENAME_path_alias_types() {
  $objects = array();
  $objects[MODULENAME_SUBSITE_INTERNAL_PATH] = t('Subsites');
  return $objects;
}

/**
 * Implements hook_pathauto().
 */
function MODULENAME_pathauto($op) {
  switch ($op) {
    case 'settings':
      $settings = array();
      $settings['module'] = 'MODULENAME';
      $settings['token_type'] = 'node';
      $settings['groupheader'] = t('Subsite paths');
      $settings['patterndescr'] = t('Pattern for subsite');
      $settings['patterndefault'] = 'subsite/[node:title]';
      $settings['batch_update_callback'] = 'MODULENAME_subsite_pathauto_bulk_update_batch_process';
      return (object) $settings;
    default:
      break;
  }
}

/**
 * Batch processing callback; Generate aliases for subsites.
 */
function MODULENAME_subsite_pathauto_bulk_update_batch_process(&$context) {
  if (!isset($context['sandbox']['current'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['current'] = 0;
  }

  $query = db_select('node', 'n');
  $query->leftJoin('url_alias', 'ua', "CONCAT(MODULENAME_SUBSITE_INTERNAL_PATH, n.nid) = ua.source");
  $query->addField('n', 'nid');
  $query->isNull('ua.source');
  $query->condition('n.nid', $context['sandbox']['current'], '>');
  $query->orderBy('n.nid');
  $query->addTag('pathauto_bulk_update');
  $query->addMetaData('entity', 'node');

  // Get the total amount of items to process.
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

    // If there are no nodes to update, the stop immediately.
    if (!$context['sandbox']['total']) {
      $context['finished'] = 1;
      return;
    }
  }

  $query->range(0, 25);
  $nids = $query->execute()->fetchCol();

  MODULENAME_subsite_update_alias_multiple($nids, 'bulkupdate');
  $context['sandbox']['count'] += count($nids);
  $context['sandbox']['current'] = max($nids);
  $context['message'] = t('Updated subsute alias for node @nid.', array('@nid' => end($nids)));

  if ($context['sandbox']['count'] != $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
  }
}

/**
 * Update the subsite URL aliases for multiple nodes.
 *
 * @param $nids
 *   An array of node IDs.
 * @param $op
 *   Operation being performed on the nodes ('insert', 'update' or
 *   'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias_multiple(array $nids, $op, array $options = array()) {
  $options += array('message' => FALSE);

  $nodes = node_load_multiple($nids);
  foreach ($nodes as $node) {
    MODULENAME_subsite_update_alias($node, $op, $options);
  }

  if (!empty($options['message'])) {
    drupal_set_message(format_plural(count($nids), 'Updated URL alias for 1 subsite.', 'Updated URL aliases for @count subsites.'));
  }
}

/**
 * Update the sibsite URL aliases for an individual node.
 *
 * @param $node
 *   A node object.
 * @param $op
 *   Operation being performed on the node ('insert', 'update' or 'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias(stdClass $node, $op, array $options = array()) {
  // Skip processing if the subsite has no pattern.
  if (!pathauto_pattern_load_by_entity('subsite')) {
    return;
  }

  module_load_include('inc', 'pathauto');
  pathauto_create_alias('test', $op, MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid, array('node' => $node));
}

/**
 * Implements hook_node_insert().
 */
function MODULENAME_node_insert($node) {
  // Insert subsite alias.
  MODULENAME_subsite_update_alias($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function MODULENAME_node_update($node) {
  // Update subsite alias.
  MODULENAME_subsite_update_alias($node, 'update');
}

/**
 * Implements hook_node_delete().
 */
function MODULENAME_node_delete($node) {
  // Delete subsite aliases.
  pathauto_path_delete_all(MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid);
}

/**
 * Implements hook_node_operations().
 */
function MODULENAME_node_operations() {
  // This will add an operation to update subsite aliases to the content
  // administration page.
  $operations['MODULENAME_subsite_update_alias'] = array(
    'label' => t('Update subsite URL alias'),
    'callback' => 'MODULENAME_subsite_update_alias_multiple',
    'callback arguments' => array('bulkupdate', array('message' => TRUE)),
  );
  return $operations;
}

```

This will use a default path alias pattern of subsite/\[node:title\] but allow you to configure it on the path auto settings page.

It will update the alias when a node is added, edited or deleted.

It will allow bulk updating of path aliases via the bulk update area of the path auto settings pages.

It will allow bulk updating of aliases via the options on the content administration page.

It would be trivial to add a views bulk operations action too.
> 3 votes

---
Tags: path-aliases
---