# Question
Title: How can I let anonymous users view user profiles by role?
I have 2 different roles like A and B.

I want anonymous users (everyone) can view user profiles from A role but can't view user profiles from B role.

In summary, A role profiles is open for everyone but B is not.

Access user profiles permission or View profiles permissions module is not enough for that.

Thanks in advance.

# Answer
You can also use hook\_user\_view($account, $view\_mode, $langcode) function to handle the permission. At first you need to copy the original function as below in the template.php

```
function hook_user_view($account, $view_mode, $langcode) {
    if (user_access('create blog content', $account)) {
        $account->content['summary']['blog'] = array(
        '#type' => 'user_profile_item',
        '#title' => t('Blog'),
        '#markup' => l(t('View recent blog entries'), "blog/$account->uid",  array('attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($account)))))),
        '#attributes' => array('class' => array('blog')),
);
      }
 }

```

Then check the current user role and the role of the user that is being visited. current user role is get by this:

```
global $user;
$role = $user->role;

```

the role of the profile is saved in the `$account` variable. Check to see what exactly its syntax is using `devel` module (I forgot the code syntax), If it was not there, you can get the owner of the profile `id`, use `user_load(id)` function to load the user then get its role. After getting the roles, you should perform the condition at the first line of the hook function.
> 0 votes

# Answer
You can use Views to achieve this. Under **Page Settings** change Access to Role & select **Anonymous users** from the list. Check exported view shown below:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User Profiles';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  1 => '1',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['label'] = '';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
$handler->display->display_options['fields']['uid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['uid']['link_to_user'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['path'] = 'user-profile/[uid]';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_user'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Roles */
$handler->display->display_options['filters']['rid']['id'] = 'rid';
$handler->display->display_options['filters']['rid']['table'] = 'users_roles';
$handler->display->display_options['filters']['rid']['field'] = 'rid';
$handler->display->display_options['filters']['rid']['value'] = array(
  5 => '5',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user-profiles';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: User: Rendered User */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_user';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'full';
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 1;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['path'] = 'user-profile/%';

```

In my case, I wanted to list user of role **field executive**.
> 0 votes

---
Tags: users
---


# Question
Title: db_update after a submit button is clicked
I want to update a field. This the code I am using to write values in the database.

```
$enrollment = array(
  'database' => 'enrollment',
  'username' => 'postgres',
  'password' => '',
  'host' => 'localhost',
  'driver' => 'pgsql',
);

Database::addConnectionInfo('myid', 'default', $enrollment);

db_set_active('enrollment');

db_update('student')
  ->fields(array('picture' => 'Yucks'))
  ->condition('studid', '101-03043', '=')
  ->execute();

db_set_active();

```

The code doesn't work. Instead of saving values in the database, it throws an error.

>

What do I need to change in the code to make it work?

# Answer
Although `db_update()` would work with `db_set_active()`, `db_set_active()` is completely unnecessary in Drupal 7.

Instead, you can just use the following code.

```
Database::getConnection('default', 'enrollment')
  ->update($table, $options);

```

It's a bit more verbose, but it doesn't require to change the active connection, which is used from every Drupal core and contributed modules.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Entity filed query for sorting by title and weight both?
"i need to display data in alphabetical oredr if weights are in same number(1,1,1)condition ,if weights like(1,2,3) condition need to display data weight based ASC order" i'm using below code alphabetical sorting working good in same weights condition, but weight based condition not working please help me

```
               $query = new EntityFieldQuery();

               $query->entityCondition('entity_type', 'node')

              ->entityCondition('bundle', 'closing_team')
              ->fieldCondition('field_homebranch', 'tid',   $node->field_closing_team_categories['und']['0']['tid'])
              ->fieldCondition('field_featured','value','No','=')
              ->propertyOrderBy('title', 'ASC');

              $result = $query->execute();
              $nids = array_keys($result['node']);
              $news_items2 = node_load_multiple($nids);
                /*echo "<pre>";
                print_r($news_items2);
                echo "</pre>";exit;*/

             function element_sort1($a, $b) {
             $a_weight = (is_array($a) && isset($a ['#weight'])) ? $a ['#weight'] : 0;
             $b_weight = (is_array($b) && isset($b ['#weight'])) ? $b ['#weight'] : 0;
             if ($a_weight == $b_weight) {
              return 0;
                }
            return ($a_weight > $b_weight);
                }

```

?\>

# Answer
```
> Below code working good regarding sort by weight and title both
> condition,by default taken sort by weight ,if all weights are same
> then it  display alphabetical order .

         $query = new EntityFieldQuery();
         $query->entityCondition('entity_type', 'node')
         ->entityCondition('bundle', 'closing_team')
         ->propertyCondition('status', NODE_PUBLISHED)
         ->fieldCondition('field_homebranch', 'tid', $node->field_closing_team_categories['und']['0']['tid'])
         ->fieldCondition('field_featured','value','No','=')
         ->propertyOrderBy('title', 'DESC');
         $result2 = $query->execute();
          if (isset($result2['node']))
          {
             $news_items_nids2 = array_keys($result2['node']);
             $news_items2 = entity_load('node', $news_items_nids2);
             echo "<pre>";
              print_r($news_items2);
             echo "</pre>";
          }
         function sortByTitle($a, $b)
          {
            return strcmp($a->weight_weight, $b->weight_weight);
          }
          usort($news_items, 'sortByTitle');
          function sortByTitle2($a, $b)
          {
           return strcmp($a->weight_weight, $b->weight_weight);
          }
          usort($news_items2, 'sortByTitle2');

```
> 0 votes

# Answer
This is more of a straight PHP question than a Drupal question, but it looks as if you have a bug in your value comparing function. It should return 1 if you want $a to sort greater than $b, it should return -1 for $b to sort greater than $a, and it should return 0 if the items should sort equally. But your function will only ever return 0 or 1. Try replacing your last return statement with `return ($a_weight > $b_weight) ? 1 : -1;`
> 0 votes

---
Tags: views
---


# Question
Title: Printing fields in theme: Undefined index: safe_value
I want to print my fields in tpl.php files as cleanly as possible. To do this, I have used the following code in my template.php file:

```
function print_field($field_name, $format = 'safe_value') {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);

if ($format == 'url') {
    print file_create_url($field[0]['uri']);
} else {
print $field[0]["$format"];
}
}

```

Now, I can print my fields in my tpl.php file in a clean manner, without any unnecessary mark-up or labels:

`<?php print_field('field_section') ?>` -- Prints the field with safe formating

`<?php print_field('field_title', 'value') ?>` -- Prints the field in Raw

`<?php print_field('field_intro_image', 'url') ?>` -- Prints the image url of a field

It all works fine, but I get this error message:

> ```
> Notice: Undefined index: safe_value in print_field() (line 19 of template.php).
>
> ```

How I can resolve this?

Also, is it possible to just enter *value* or *url* in my tpl.php file without wrapping them in quote marks?

# Answer
The problem is with your function, not the template.

Ideally you should check if the index exists, e.g.

```
print array_key_exists($format, $field[0]) ? $field[0]["$format"] : '';

```

or:

```
print !empty($field[0]["$format"]) ? $field[0]["$format"] : '';

```

or:

```
print @$field[0]["$format"] ? $field[0]["$format"] : '';

```

Alternatively you can ignore the notices in PHP config (php.ini) or in Drupal admin.

Or you can just prefix the field with `@` to silence/suppress any errors (usually not recommended), e.g.

```
print @$field[0]["$format"];

```
> 1 votes

# Answer
Have you seen `field_view_value()` which already does what you're attempting, i.e. getting the value of a field without additional markup.

e.g.

```
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

```

(For reference taken from: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way which is well worth a read.)
> 1 votes

---
Tags: theming
---


# Question
Title: How to redefine a message type for drupal_set_message?
By default, there are 3 (status / warning and error). I will wish to add the info type, with a blue background for example. What to do?

# Answer
The status is arbitrary, so:

```
drupal_set_message('A message', 'custom_status');

```

Will produce

```
<div class="messages custom_status">A message</div>

```

Notice the "custom\_status" class, which you can target with CSS.
> 4 votes

---
Tags: status-messages
---


# Question
Title: How can I remove 0 & negative values(-1 to -100) in weight module section?
I want to remove 0 and negative values (-1 to -100),so need to display only 1 to 100 items only in drop down list .

How can I achieve this?

# Answer
> 1 votes
> Display weights 1 to 100 only case below code working good. path:sites/all/modules/weight/weight.module file 751 line

```
/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;

  $options = array();

  for ($i =1; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;
}

Before code:

/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;
  $min = $max * -1;
  $options = array();

  for ($i =0; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;

```

---
Tags: 7
---


title: Get node ID in a form submit

text:
# Question
Title: Get node ID in a form submit
I am struggling with how to get node id in my user\_register\_form\_submit. I need to get the node id of the node where my form is, let me explain :

I have created a tpl for my user register form in order to print it in nodes of a special content type, those nodes prepopulate my form and helps to create users, I need this node id to delete the node after submiting the form wich means delete the node after a user is created.

here is my hook :

```
    function hook_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'user_register_form'){
            $form['#submit'][] = 'user_register_form_submit';
        }
    }

    function user_register_form_submit($form, &$form_state) {
    // print the node id
    }

```

Last thing, I'm working with Drupal 7. Thanks !

# Answer
Add one more line below your *user register form* embed code,

```
$form = drupal_get_form('user_register_form');
print drupal_render($form);

echo "<script>
  jQuery(document).ready(function() {
    jQuery('#user-register-form').append('<input type=\"hidden\" name=\"nid\" value=".arg(1).">');
  });
</script>";

```

Then you will get the `nid` of node inside user register submit function like this:

```
function user_register_form_submit($form, &$form_state) {
  // print the node id
  echo $form_state['input']['nid'];
}

```

Also you can do it with `hook_form_alter`. Add one hidden field and assign `nid` as value for it.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#submit'][] = 'user_register_form_submit';
    $form['nid'] = array(
      '#value' => arg(1),
      '#type' => 'hidden',
    );
  }
}

```
> 1 votes

# Answer
For Drupal 8 Add your custom submit handler in form alter:

```
$form['actions']['submit']['#submit'][] = '_custom_node_form_submit';

```

And add custom submit handler:

```
function _custom_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  echo $form_state->getValue('nid');
}

```
> 11 votes

# Answer
To expand on Niks answer.

```
function custom_module_form_validate(&$form, &$form_state) {
  // This will print the node id.
  var_dump(arg(1));
}

```

I didn't actually know this until I tried it just now. Credit should go to Niks.

Note; From the Drupal docs arg(), "Returns a component of the current Drupal path." In this case the second. That means that this **will not** work on all forms because not all forms will use the node path.

**Edit: Incorporating info from MPD's comment below** Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu\_get\_object() instead.
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: One time change field + personal comments
I'm not very familiar with all the modules for Drupal. Therefore, let me try to explain what I'm looking for.

1) The users shall be able to create nodes with some specific fields. Some of those fields shall be writable only one-time.

2) To this node only the author and users allowed by the author shall have access.

3) Additionally the users who have access to nodes of another user shall be able to make comments (including attachments). Something like a discussion forum to each node, but only the author of the node and the creator of the comment shall see their nodes.

Hope it's somehow understandable.

Are there any kind of modules for any of the above requests?

# Answer
> 1 votes
If I understand the problem. You can write hook\_form\_alter() in custom module and disable needed fields when user edit node. And configure permissions on this page admin/people/permissions

---
Tags: entities, comments
---


title: Drupal 7 img src path issue

text:
# Question
Title: Drupal 7 img src path issue
I created a block, in which an img with src="sites/mysite/files/imagename". It works every node, but failed loading in search page.

Is this an issue of Search module? Drupal 7, I hope, has a uniform url management, for example:

* exapmle.com/files, exapmle.com/modules/Module\_name, or
* exapmle.com/modules/core(Symbolic Link points to sites/all/modules) /Module\_name
* exapmle.com/themes/Theme\_name, or
* exapmle.com/themes/core(Symbolic Link points to sites/all/themes) /Theme\_name ...
* ...

# Answer
For any source or path of any thing in drupal site use src like this. It will work everywhere.`$src = base_path() .'sites/files/logo.png';`
> 4 votes

# Answer
I had the same problem with a site where there were a lot of nodes with user-written links with relative paths. Something that I found noteworthy: It turns out that using *clean urls* can mess up references to relative paths, see this question. When you have clean urls enabled, you shoud better use absolute paths in your links.
> 0 votes

---
Tags: media, search, uri
---


# Question
Title: Rules - Check if coupon has been added to an order
I need to check in Rules if a coupon has been added to an order as a condition.

I have tried using the ENTITY HAS FIELD option in Rules and then a data selector of

Commerce-order

and to then look for the field commerce\_coupon\_code

But this fires a negative, I have also tried to look for commerce\_coupon\_fixed\_amount

But this also fires a negative.

# Answer
> 0 votes
Add A Condition Also In Rules That Will Help You In These You Can Also Create Manual Option

---
Tags: commerce, rules
---


# Question
Title: create url with destination parameter and additional query string to views page with exposed filters
I have a views page with several exposed filters. I have created a link using a view php field as per below:

```
$url = '/admin/dashboard/applications/create/' . $row->nid . '?destination=' . current_path() . '&' . $_SERVER['QUERY_STRING'];
$link = '<a class="create-app" href="' . $url . '" title="Create application">App+</a>';

```

This leads to a form page with a confirmation 'Submit' or 'Cancel' button. The resulting URL on that page being something like this:

```
http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries&nid=&field_enquiry_fname_value=&field_enquiry_email_value=&field_enquiry_country_tid=&field_enquiry_campaign_id_value=&field_enquiry_emailed_value=0&field_enquiry_stage_1_tid=All&field_enquiry_enabled_value=1

```

When the redirect is done, the querystring after ?destination=admin/dashboard/enquiries is removed. I think this happens because it is not URL encoded.

I then tried url encoding the link as per below:

```
$query_string = array('destination' => current_path() . '&' . $_SERVER['QUERY_STRING']);
$url = url('admin/dashboard/applications/create/' . $row->nid, array('query' => $query_string));
$link = '<a class="create-app" href="' . $url . '" title="Create application">App+</a>';

```

This creates the following url:

```
http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%26nid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

```

The issue now is that when the redirect is done back to the views page, views does not recognize the URL query and does not load the view, and falls back to the parent menu callback.

# Answer
Instead of Trying to generate destination manually, can use drupal\_get\_destination(). So your above code would be like this:

```
$url = url('admin/dashboard/applications/create/' . $row->nid, array('query' => drupal_get_destination()));
$link = '<a class="create-app" href="' . $url . '" title="Create application">App+</a>';

```

drupal\_get\_destination() gets the current path + encode the query strings and make them as destination. this will generate below URL:

```
http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%3Fnid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

```

instead of your URL.

```
http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%26nid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

```

The difference is the encode of '?'. I have tested it in local D7 installation.
> 2 votes

# Answer
What you could do is this:

Either alter the Submit/Cancel form directly or call hook\_form\_alter to add a hidden item

```
$destination = drupal_get_destination()
$form['destination'] = array(
  '#type' => 'hidden',
  '#value' => $destination['destination']
);

```

Then, you have two scenarios. If you control the form submission handler, you can simply do

```
function MY_MODULE_blah_blah_form_submit($form, &$form_state)
{
   ...
   $destination = urldecode($form_state['values']['destination']);
   $path_parts = explode('&', $destination);
   // The first path_part is your URL, the rest will make up the query_string.

   $url = array_shift($path_parts);
   $query = array();
   foreach($path_parts as $path_part)
   {
      list($key,$value) = explode('=', $path_part);
      $query[$key] = $value;
   }
   $form_state['redirect'] = array(
      $url,
      array(
          'query' => $query,
      ),
   );
}

```

Or create a second submission handler for the form, which will fire after this one, and implement the above yourself.

Some useful (and more detailed information): https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal\_redirect\_form/7
> 1 votes

# Answer
From personal experience: when debugging destinations, make sure you look at any use of the 'Rules' module that might be overriding your edits.
> 0 votes

---
Tags: views, uri
---


# Question
Title: Ternary operator not evaluating checkbox values
I am using Drupal 7. I have created a form using the Form API, in which I defined several checkboxes. The form sends its contents in an email and this works fine at the moment as long as I simply output the values of the fields, with the checkboxes outputting the value if checked (e.g. Elderly) and 0 if not. In making up the body of the email I want the zeros to be omitted and only the values of the checked boxes to appear. I have tried to achieve this by using a shorthand ternary operator to include some html if the box is checked and not if not. I can't get this to work. Here's how I've defined the checkboxes in the form itself:

```
$hometypes = array(
            'Elderly' => t('Elderly'),
            'Disabled' => t('Disabled'),
            'Council tenant' => t('Council tenant'),
            'Home owner' => t('Home owner')
            );

        $form['personaldetails']['survey']=array(
            '#type'=>'checkboxes',
            '#title'=>t('Please indicate your situation by ticking the appropriate boxes'),
            '#description'=>t('You can tick a box by clicking on it once'),
            '#options'=>$hometypes
            );

```

Here's where I set up the variable $elderly:

```
$elderly = $form_state['values']['survey']['Elderly'];

```

And here's the section of the submit function that is not working:

```
  .($elderly == 'Elderly' ? '<td>Elderly</td> </tr> <tr> <td></td> <td>' : '<td>').

```

This returns the 'True' value regardless of whether the box is checked or not. If I change it to be:

```
  .($elderly <> 0 ? '<td>Elderly</td> </tr> <tr> <td></td> <td>' : '<td>').

```

it returns the 'False' value regardless of whether the box is checked or not.

This may be a bit of a newbie question, but that's because I'm a bit of a newbie! Any help gratefully received.

# Answer
Solved it!

I redefined the keys for my checkboxes as values rather than strings. Like so:

```
$hometypes = array(
        1 => t('Elderly'),
        2 => t('Disabled'),
        3 => t('Council tenant'),
        4 => t('Home owner')
        );

```

remembering to change this:

```
$elderly = $form_state['values']['survey'][1];

```

which means that this:

```
($elderly == 1 ? '<td>Elderly</td> </tr> <tr> <td></td> <td>' : '<td>')

```

works perfectly.
> 0 votes

---
Tags: forms
---


# Question
Title: How to fetch image from database in drupal
Let me know how to fetch image from database. actually i am trying to fetch image from database using this question. I am try to fetch image from database using following code. $fid is my $row\['column\_name'\]

```
 $fid=$r['field_upload_photo_fid'];
 $image = theme('image_style', array(
'style_name'=> 'small',
'path' => $file->uri,
'alt' => 'user picture'
 ));
 print $image;

```

Actual file url is http://example.com/sites/default/files/styles/Style\_name/public/Chrysanthemum.jpg

but now it shows http://example.com/sites/default/files/styles/small/public/styles/Style\_name/public/Chrysanthemum.jpg. thats why image not fetching from database.

Also what is a style in $variable.

# Answer
You have to replace 'Style\_name' with an actual image style, then it should work. That's because the function you are using does not only fetch the url of the image, it actually tries to fetch the image for a particular style, not the original.

Per default drupal ships with the image styles 'thumbnail', 'medium' and 'large'. You get these names when going to 'admin/config/media/image-styles', open the style you want to use for your image and look at the machine name - that's the 'style\_name' you need.

So in your above example use for example:

```
$variables = array(
 'path' => $file->uri,
 'style_name'=>'medium'
);

```

You can use a custom image style as well of course.

---

**Edit:**

From the comments I guess you do not actually want to retrieve the url for a styled image, but the original url of the image. Here is the code which should retrieve the file url:

```
$fid=$r['field_upload_photo_fid'];
$file = file_load($fid);
$url_to_your_file = file_create_url($file->uri);

```
> 0 votes

# Answer
The style is an image style which is described a bit in Working with images in Drupal 7 and 8. I believe that you need to use Style\_name as the `'style'` in your code instead of `'public'`:

```
 $fid=$r['field_upload_photo_fid'];
 $file = file_load($fid);
 $variables = array(
 'path' => $file->uri,
 'style'=>'Style_name'
 );
 print theme('image_style', $variables);

```

But also, what is the data in `$file->uri`? If you start with bad data then the result is also going to be bad.
> 0 votes

---
Tags: media
---


# Question
Title: Delayed error messages for webform blocks in template
I am printing a webform block in my node.tpl.php:

```
  <?php
      $block = module_invoke('webform', 'block_view', 'client-block-72');
      print render($block['content']);
  ?>

```

And when I submit the webform with nothing, no error messages are shown. They are shown on the next reload.

If insert the block in admin -\> structure -\> block, it works fine.

Is there any way to make it work with inserted block in template file?

# Answer
I've created a new region and inserted the webform block there.
> 0 votes

# Answer
The first time around, your `module_invoke` will generate a webform block for you. After submitting, assuming you return to the same code, it will do this again, but notice that there is a submission, validate that and if there is anything wrong with it, generate drupal messages internally.

However, since you're probably already deep in the page, the place where drupal messages are displayed is already passed at this point. Try this:

```
<?php
     $block = module_invoke('webform', 'block_view', 'client-block-72');
     // found errors ? dump m here !
     print theme('status_messages');
     print render($block['content']);
?>

```
> 0 votes

---
Tags: 7, blocks, webforms, status-messages
---


# Question
Title: Drush only partially working in both VM (Ubuntu) and host OS (Mac OS X 10.10)
I am currently running on a MacBook Pro with OS X 10.10 (Yosemite). That is the host machine and OS. I am using a synced folder between the host and my VM, which is running Laravel's Homestead VM (Ubuntu instance).

The project is a Drupal 7 project and I am running the latest version of Drush installed both on Mac OS X (via homebrew) and within the VM (I can't remember how I ended up installing it there). Very new setup, had the machine for a week and a half. Setup this way for maybe a week.

I am able to access and load the site just fine from the VM in my browser. It works great there. But, when I go to use drush against it (both in the VM and in Mac OS) it doesn't seem to give me most of the options.

Within the VM (ssh'ed in) I run "drush pml". Below is the message I get.

```
Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                     [error]
The drush command 'pml' could not be executed.

```

I get the same message in Mac OS X. I am running the command from the docroot folder where drupal is installed. Not sure why this is. I could see it happening in the host OS. But it SHOULD be working within the VM that is running it and has the DB installed.

I haven't used Drush or Drupal for 2 years. So I probably forgot an obvious config or something. Please help me out here.

Thanks!

# Answer
If you are in docroot then the most likely cause is multiple site definitions which mean drush can't tell which is active. You may need to supply the -l or --url parameter to disambiguate if that is the case.

In your drushrc file you can set up parameters so as to avoid having to keep supplying the parameter explicitly.
> 2 votes

---
Tags: 7, features, drush
---


# Question
Title: How can I make special non-Drupal URLs without file extensions?
As I understand it, Drupal is supposed to check the web root for any URLs it doesn't recognize, to see if it's a non-Drupal file on disk. Also, Apache is supposed to assume that anything without a file extension is a request for *whatever.html*, correct?

Here's what I'm trying to achieve: a user requests *mysite.com/FOO*, Drupal doesn't find any path/alias for *FOO*, and thus turns it over to Apache. Apache doesn't see a file extension, and thus looks for a file called *FOO.html* (which exists) and serves up that file.

If I request *mysite.com/FOO.html*, the file is returned just fine. I'm just trying to make it so that people can access *FOO.html* by simply requesting */FOO*, since you can't trust the user to type in the full URL. (And because it looks nicer in a print ad.)

I'm guessing that there's some .htaccess magic that needs to happen, but I haven't been able to come up with the right trick. I think that Drupal passes to Apache, which doesn't find */FOO*, then the .htaccess file punts the request to Drupal's index.php, which returns the Drupal 404 page.

# Answer
This is what finally worked for me:

In *httpd.conf* :

```
<IfModule mod_rewrite.c>
RewriteMap lc int:tolower
RewriteMap uc int:toupper
</IfModule>

```

In *.htaccess* :

```
#-- is it a code with letters only?

# lower-case only
RewriteCond %{REQUEST_URI} ^/[a-z]+$ [OR]
# upper-case only
RewriteCond %{REQUEST_URI} ^/[A-Z]+$
# convert to upper-case and redirect to corresponding file
RewriteRule (.*) ${uc:$1}\.html [L]

```

This allows the little PHP snippet inside the appropriate file to make a tally mark in the tracking database, before redirecting the user to the desired landing page within the actual website. I know, Drupal can track hits on a specific URL, but I'm dealing with a legacy system from our pre-Drupal days. :)
> 0 votes

# Answer
If the file exists serve it.

```
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.html -s
  RewriteRule .* %{REQUEST_URI}\.html [L,T=text/html]

```

You'll need to put it above this inside your .htaccess file.

```
  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

```

You can't pass the request back to apache once you've passed it to Drupal. The code above will hit the .html file first if it exists.

To do exactly what you want, you can set the 404 handler inside of drupal to a custom page; that page could then check to see if the file exists and use that. Config page for 404: `admin/config/system/site-information`. The handler would use something like this

```
<?php
$path = substr(request_uri(), strlen($GLOBALS['base_path'])) . '.html';
if (file_exists($path)) {
  echo file_get_contents($path);
  exit;
}
return MENU_NOT_FOUND;
// OR this, not sure.
return drupal_not_found();
?>

```
> 2 votes

# Answer
You can use the Redirect Module (https://www.drupal.org/project/redirect) to create custom URL redirections.
> 0 votes

---
Tags: .htaccess
---


# Question
Title: Bootstrap subtheme - theme_menu_link(array $variables) not reacting
I'm using the Bootstrap theme and I've successfuly created a bootstrap subtheme that I named **bootstrapdreve**

I've already overidded successfully two templates, but now I'm facing a problem I'm stuck for hours on.

I wanted to overide the **bootstrap\_menu\_link** theming function located in **bootstrap/theme/menu/**. So I copied it into my

```
bootstrapdreve/template.php

```

and renamed it

```
function bootstrapdreve_menu_link(array $variables)

```

Before bringing my adaptations I set a *dsm('test');* on first line:

```
function bootstrapdreve_menu_link(array $variables) {
  dsm('test');
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = drupal_render($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '<ul class="dropdown-menu">' . drupal_render($element['#below']) . '</ul>';
      // Generate as standard dropdown.
      $element['#title'] .= ' <span class="caret"></span>';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == $_GET['q'] || ($element['#href'] == '<front>' && drupal_is_front_page())) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

... and nothing's displayed

I've followed the idea given by this subtheme preprocess functions inheritance post by creating this structure:

```
bootstrapdreve/theme/menu/menu-link.func.php

```

and by setting also a *dsm('test');* at first line of code...

Still no message... and thus as I interpret it no execution of this function...

I don't understand why. Could you please help me find why this theming function overiding doesn't work ?

*Rem.:* There's no problem with the dsm(), I've tried to put one at top of bootstrapdreve/template.php and it works fine...

*Rem. 2:* I've offcourse cleared the cache at every modification I made

# Answer
> 1 votes
I maintain a Bootstrap subtheme that I use for most of my projects and I override `theme_menu_link()` in my subtheme using the same method with no problem:

```
/**
 * Overrides bootstrap_menu_link().
 *
 * Resets theme_menu_link() to the default that ships with Drupal. Bootstrap
 * attempts to make every menu with children into a dropdown menu. Remove this
 * function if you want drop down links.
 */
function bootstrap_ignitor_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

You must have a problem somewhere else.

# Answer
> 1 votes
try using

option 1: function THEMENAME\_menu\_link(**&$variables**) {}

option 2:

```
 /**
* theme_menu_link()
*/
function THEMENAME_menu_link(array $variables) {
//add class for li
   $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//add class for a
   $variables['element']['#localized_options']['attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//dvm($variables['element']);
  return theme_menu_link($variables);
}

```

option 3 :

```
function bootstrapdreve_preprocess_menu_link(&$variables) {
        $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
        $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#title'])));
        // Another option $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#original_link']['link_title'])));
        $variables['element']['#attributes']['class'][] = 'menu-' . $menu_title_class;

        if ($variables['element']['#original_link']['menu_name'] == 'user-menu') {
            $variables['element']['#localized_options']['html']= true;
            $variables['element']['#title'] = '<span>'.$variables['element']['#title'].'</span>';
        }
    }

```

# Answer
> 0 votes
You need to add `function bootstrapdreve_menu_link(array $variables) {` in your template.php and not in a .func.php file. If you add it in a func.php file then you need to include this file in the template.php file somehow.

Just copy the code inside template.php and it should work.

---
Tags: theming
---


# Question
Title: Views: creating a hierarchy of content - am I doing it right?
This is a little complicated, but here goes:

* I have a taxonomy vocabulary in a tree-structure.
* I have a content type with a field of the vocabulary.
* I am using the Views Tree module to display a tree of the vocabulary, and want the content to display within the tree. (Please see the illustration below).
* In my view I use a relationship to add the links to the content type to the view.
* animal
* vegetable
    + flowering plant

This would seem to me to be a fairly common thing to do. Am I doing it right? (i.e. is creating a taxonomy vocabulary and using Views Tree the best way to do this?)

# Answer
> 1 votes
A taxonomy tree is often the first that comes to mind thinking of a hierarchical directory of content items – but similar structures can also be built in many different ways. Here's just two examples that I personally find often easier to handle, than a taxonomy tree:

* Entity reference – rather than having 'lists' of content items 'attached' to taxonomy terms, to me this approach has a more 'real' feel concerning the item-to-item relations. You actually have nodes (items) that can either be partens, children or siblings of nodes (or content types) with all the advatages that come with nodes like commenting etc. And the free tagging reference field let's you even generate new elements 'remotely'.
* Book module – probably one of the most underrated core modules – let's you genrate complex tree structures out of the box. While I consider it ideal for a quick start, it might become a bit low-fi in the long run.

For me reading this article "RIP Taxonomy Module in Drupal 7" was appeared to be quite helpful when I (again) had to decide how to build a tree of related nodes.

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


title: Search for drupal site using taxonomy

text:
# Question
Title: Search for drupal site using taxonomy
We are due to move our website (a rather large charity site) and we would really like to make sure search is working as well as possible. We are currently working on tagging all our content using a controlled vocabulary taxonomy which we hope to be able to use in Drupal.

What I would like to know if there are any search modules for drupal, where search result would be displayed with visible taxonomy tags. So as for example if someone would search for "drugs" and "depression" a list of result would be displayed where you by the article also could see the taxonomy tags related to that article. So Search result one would have the tags "Drugs""Depression" and any other tags used so perhaps "stress", search result two "Drugs""Depression" and "Pain". I hope this makes sense? Does anybody know if this is possible and if so are there any website that uses something like this already?

# Answer
I'm not very clear what you're asking, so I might be on the wrong track. However a basic search returns a set of nodes that match in a particular order; the normal culprits are Apache Solr and Elastic Search, but there are others. For a large site definitely don't use the builtin search, and do investigate using 'search api' if you're not already.

Once you have a set of nodes, it's up to you how to display them. Including the taxonomy terms associated with each node is part of the display logic, rather than the search itself, and should be relatively easy. Have a look at Display Suite for better control of search views if you need it, though it may well be more appropriate to write a custom node render hook.

If you are more interested in something like a tag cloud of terms that the currently matched nodes reference, that is more difficult but I would look at the tag cloud module, with some custom glue logic to link them.

Hope this helps...
> 0 votes

---
Tags: taxonomy-terms, search
---


# Question
Title: View will not display taxonomy location information
I have a taxonomy that contains information about event venues. I am using the location module to add locative information to these taxonomy terms.

I've created a view so that I can see all my venues and their location information, but the location information is not appearing in the view.

Here's a screenshot of the view I have built, but the location information does not appear!

Each term has its location info filled in:

# Answer
> 0 votes
It's not a great answer, but I do have an answer.

For some reason, Views isn't pulling this data. I've been unable to get a clean install of Drupal 7, views, location to pull this info when entered in the Location fieldgroup on a taxonomy term.

I HAVE been able to create a custom field for the location via 'manage fields', and THAT will appear in Views.

I hope that helps you (and anyone else looking at this!)

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


# Question
Title: Can I track embedded pdf's in statistics module
Client has pdf's embedded in pages. They want to track pdf clicks. Statistics tracks nodes and there are add-on modules that track file field clicks, but I haven't seen anything within Drupal to track the embedded files. Any suggestions?

# Answer
The gist of most Drupal performance-tuning essays is don't use the statistics module, because it causes a lot more Drupal DB traffic.

I can't help with configuring the statistics module itself and I suspect the reason the links aren't being monitored is that those files are being delivered from the sites/.../files folder by Apache|Nginx directly, and Drupal isn't seeing them. As such, you might be able to monitor the webserver logs to get the info you need.

Alternatively I would start off by looking at google analytics or some similar client-side tool for this. If that isn't suitable (and it's not guaranteed it is), then next step could be to create a handler for your files, e.g. a ctools module, which parses the path to get the file to deliver, logs whatever info is appropriate and then sends the file onward. There are some issues re: caching and headers, but not very hard.

If you could do that, but are stymied because the file links are entered by the user within nodes, perhaps you could add a text content filter (such as those that break paragraphs at newlines) that read in the original URL and converted those matching the right pattern to the monitored form. That isn't hard either.
> 0 votes

---
Tags: files, nodes
---


# Question
Title: programmatically create one bean block to the default theme
I am trying to programmatically create beans in a custom module using entity\_metadata\_wrapper. This is creating a bean for each installed theme. (In Drupal 7)

**Is there a way I can create only one instance of the bean block?**

for example in my database it creates a bean block for

* my subtheme
* omega
* seven

I would like to only create one block/bean for my subtheme. I am then using mymodule\_beans\_block\_info\_alter(&$blocks, $theme, $code\_blocks) {} to then change region location and other block parameters.

```
function bean_ctas_enable(){
    foreach(bean_ctas_info() as $bean_content){
        $bean_ids = array();
        $bean = bean_create(array('type' => 'block_cta'));
        $bean_wrap = entity_metadata_wrapper('bean', $bean);
        $bean_wrap->label->set($bean_content['label']);
        $bean_wrap->title->set($bean_content['title']);
        $bean_wrap->field_text->set(array(
            'value' => ($bean_content['field_text']),
            'format' => ('full_html'),
            ));
        $bean_wrap->field_link->set(array(
            'url' => ($bean_content['link_url']),
            'title' => 'Read More',
        ));
        $bean_wrap->save();
        $bean_ids[] = $bean_wrap->bid->value();
        //set variable to store bean ids
        variable_set('bean_ctas_bean_ids', $bean_ids);
    }
}

```

# Answer
> 0 votes
I used `hook_block_info_alter(&$blocks, $theme, $code_blocks)` to alter the blocks in my custom modules .module file

inside of my hook\_block\_info\_alter i wrote an if statment

```
if($blocks['bean'][$key]['theme'] == variable_get('theme_default', '0')){}

```

to make sure I was only altering regions only for my default theme

---
Tags: theming, database, blocks
---


# Question
Title: search and facet api tables dropped during module updates
We recently added search-api and facet-api functionality to work with a new Drupal 7 view, and now whenever certain module updates are performed using Drush, one or more of the following tables are found to be corrupt or missing:

> search\_api\_db\_00\_facet, search\_api\_db\_00\_facet\_field\_facetname, search\_api\_db\_00\_facet\_text, search\_api\_db\_00\_search, search\_api\_db\_00\_search\_text, search\_api\_db\_00\_facet, search\_api\_db\_00\_facet\_field\_facetname, search\_api\_db\_00\_facet\_text, search\_api\_db\_00\_facet\_text\_1, search\_api\_db\_00\_search, search\_api\_index.sql, search\_api\_server.sql

After these tables are restored from backup all is well again. We are using MyISAM table format in the database. No error message displays in the Drupal log until after this has occured. Search module is being used for whole site, while search-api is used for one application. Website is medium sized. The application created by content type and view contains 44,000 nodes. Is this a MySQL problem, such as a need to convert to INNODB, a search-api issue, or a facet-api issue? This doesn't seem to be a common occurrence.

# Answer
> 1 votes
This issue is resolved, thanks to an insight rocketeerbkw provided about the `drush up` process. I changed my user umask setting to 022 in .bashrc to be more permissive for files that my account creates on the server. This completely resolved the database table dropping issue. Before I changed the umask, I had been running drush using my normal user account with a private umask setting, and when drush downloaded new files for updates, the resulting strict permissions broke any cache rebuilds that might have been involved and also on occasion broke the database connectivity. This was neither a MySQL nor drush issue.

---
Tags: 7, drush, search
---


# Question
Title: drush sql-sync structure tables in alias dont work
It seems that the structure tables dont work on a sql sync from my live site to my dev. Using the following comman:

drush sql-sync @example.live @example.dev

The search\_api\_server is every time overritten, so it gets synced. So i think also my cache tables get synced. Whats wrong with my aliases?

```
/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-key' => 'common',
    ),
  ),
  // No need to modify the following settings
  'command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
      'structure-tables' => array(
       // You can add more tables which contain data to be ignored by the database dump
        'common' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog','search_api_server'),
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
);

```

# Answer
There are three places you can reference aliases when using sql-sync:

drush @site sql-sync @prod @dev

@site - Where the sql-sync will execute. If this is a remote site, then the other two aliases must be defined in files that reside on the remote machine. Options from 'command-specific' will be applied to the command.

@prod - The source for the sync. Options from 'source-command-specific' will be applied to the command.

@dev - The target for the sync. Options from 'target-command-specific' will be applied to the command.

The alias @site is not usually used with sql-sync; most people just run `drush sql-sync @prod @dev`.

Drush is going to look for *different* 'command-specific' records depending on the position of the alias appears on the commandline.

@site - The alias that appears before the command name will have options from the 'command-specific' -\> 'sql-sync' record added to the evaluated options list.

@prod - The alias that appears in the first position after the command name will have options from the 'source-command-specific' -\> 'sql-sync' record used.

@dev - The alias that appears in the second position after the command name will have options from the 'target-command-specific' -\> 'sql-sync' record used.

In the typical case (`drush sql-sync @prod @dev`), the 'command-specific' record is not used at all, the 'source-command-specific' record from @prod is used, and the 'target-command-specific' record from @dev is used.

Try using alias records more like the following set:

```
/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'target-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-list' => 'cache,cache_admin_menu,cache_block,cache_bootstrap',
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
    ),
  ),
);

```
> 0 votes

---
Tags: drush
---


# Question
Title: Performances with many fields per content type
Drupal creates a new table for every new field in a content type.

How much this affects the performance in fetching data when the fields of an entity are 15 or more?

Is possible to store all fields in a table (with a new entity?) without drawbacks? Is worthwhile?

# Answer
> 3 votes
MySQL limits you to 61 table joins but Drupal doesn't care about this limit. Each field gets loaded individually, so every field will slow down Drupal a little bit but there is no practical limit. The impact depends on how long a round trip to the database takes. If you have Apache & MySQL on the same box and you're using sockets for communication then the impact will be minimal (read slides 60-68 from my presentation for more info). If Apache & MySQL are on different servers then the number of fields will have more of an effect. All of this can be mitigated by using something like the https://www.drupal.org/project/entitycache module.

---
Tags: 7, entities, performance
---


# Question
Title: Updating Commerce Kickstart’s Contrib Modules
What is the recommended way to update outdated Drupal contrib modules? The Commerce Guys doing a great job to keep Commerce secure and updated. However there’s always a Contrib Module update around. For the most part this isn’t an issue. Most of the Contrib Module updates are maintenance fixes. However what about security fixes for Contrib Modules? Usually I don’t touch the /profiles/commerce\_kickstart/modules/crontrib folder and I am waiting until a new Commerce Kickstart release is published.

Does Commerce Kickstart uses special Contrib modules? Can I update ctools, Webform myself?

# Answer
First, you need to understand that Commerce Kickstart is a Distribution. So your goal is to learn how to update a Drupal distribution before their official release.

For the most part you would need to understand how Drupal Make works. Where is a great article ( Maintaining your installed Drupal distro.) that would explain you how to maintain Drupal distributions.

If you successfully was able to update your Drupal distribution (commerce\_kickstart) using Drupal Make. You should created a patch and provide that patch to the commerce\_kickstart issue queue.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to hide the configure slider in MD Slider?
I've installed the MD Slider, but I would like to remove the **Edit Slider** and **Configure Slider** links in the **administrator** role. What function should I use to remove that?

# Answer
You probably would need to uncheck the permissions of the MD Slider to administrator. You can do this by going to the `admin/people/permissions`.
> 0 votes

---
Tags: blocks
---


# Question
Title: How can I add a view to the front page news feed?
I have created a view and I would like to promote the link to this view on the front page. How can I do this?

Thanks

**UPDATE 1**

I would like the view to show up in the front page news feed like in line along with other content that is "promoted to front page"

# Answer
> 1 votes
You can create a View block and display this block in any region like other blocks. Then make this block to show only listed pages, which is `<front>`.

# Answer
> 0 votes
You can use the empty front page to remove the promoted to the front page behavior. After that can created a block view and display it on the front page.

Another option would be to created a page view and setup this page to be in the front page at this page `admin/config/system/site-information`

---
Tags: views, feeds
---


# Question
Title: Choosing which comments field to display when published
I'm using the basic comment module to allow users to leave comments (name, phone, email, comment, and rating) on each resource for that specific comment type. One of the fields is an option to allow users to choose to share their personal information to others if they want. All comments are unpublished by default and have to be moderated to be published.

So, my question is this: how can I selectively choose to publish a users email or not depending on if they selected to share that information with others?

Either a manual or automatic way would work fine. Thanks!

# Answer
You could use the template\_preprocess\_comment function. First you need to check the value of the "share my personal information" field or whatever you called it and act on that to display the user's email.
> 1 votes

---
Tags: comments
---


# Question
Title: Is there a hook after user confirmation?
I want to add a content type after a user registers to the site.

I tried `hook_user_save()` but it saves the content type before the user confirms his e-mail.

Is there a hook after e-mail confirmation?

# Answer
> 11 votes
Although this approach uses modules, I add nodes after users confirm their e-mails using Logintoboggan and Rules. The Logintoboggan rules integration adds a new event, `When the user account is validated`, which will allow you to perform actions upon e-mail confirmation.

# Answer
> 8 votes
This does the job for me:

```
/**
 * Implements @see hook_user_presave
 */
function hook_user_presave(&$edit, $account, $category) {
  if ($account->uid // user is not new
      && $account->status === "0" && $edit['status']==1) { // user is being activated
  }
}

```

# Answer
> 2 votes
If you're using the LoginToboggan module for e-mail validation and you don't wish to use the rules module you can simply mimic the module's validation response (exploiting a temporary `logintoboggan_email_validated = TRUE` account property that's pushed to hook\_user\_update) yourself in code:

```
 /**
 * Implement hook_user_update()
 *
 */
function yourcustommodule_user_update(&$edit, $account) {
  if (!empty($account->logintoboggan_email_validated) && !isset($account->your_custom_action)) {
        $account->your_custom_action = TRUE;

        // Do what you want here

  }
}

```

Since core and other modules will also invoke hook\_user\_update you'd want to implement something to avoid repeated actions. In this example I set another property on the $account once the action is initiated but you can impose finer control if necessary.

Note that if using LoginToboggan for automatic e-mail validation IOco's method won't work (among the many reasons - during a hook\_user\_presave, the $account-\>status == 1 (it's just the role is in your elected "pre-authorised" state).

---
Tags: users
---


# Question
Title: Perform action when new user verifies email link
I am looking to catch the event when new user updates password after clicking on link in the email, right after one time login.

I actually want to perform an action right after user sets password after validating/clicking on one time login link in welcome email.

I have gone through this: Is there a hook after user confirmation?

However, it does not solve my problem as explained below:

I used this condition to check if user is just created:

```
if ($account->uid // user is not new && $account->status === "0" && $edit['status']==1)

```

The issue with this is it holds usable for me in case if admin approves pending creation. In my case I don't want admin to approve, i want drupal to send email to user for confirmation. According to my workout, when admin approves, then above condition works, because status is changed from 0 to 1 so i can do some work at this change. But without admin, when user creates account, it is automatically activtaed, so I can't grab with this condition to perform my work at this event.

# Answer
I also updated the link your posted to.

If you're using the LoginToboggan module for e-mail validation and you don't wish to use the rules module you can simply mimic the module's validation response (exploiting a temporary `logintoboggan_email_validated = TRUE` account property that's pushed to hook\_user\_update) yourself in code:

```
 /**
 * Implement hook_user_update()
 *
 */
function yourcustommodule_user_update(&$edit, $account) {
  if (!empty($account->logintoboggan_email_validated) && !isset($account->your_custom_action)) {
        $account->your_custom_action = TRUE;

        // Do what you want here

  }
}

```

Since core and other modules will also invoke hook\_user\_update you'd want to implement something to avoid repeated actions. In this example I set another property on the $account once the action is initiated but you can impose finer control if necessary.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: Image captcha module not showing in admin after updating Drupal to 7.35
I have a site with Captcha module installed and Image captcha submodule working perfectly before upgrading.

I followed the recommended steps, and even did it in a nearly identical test site. Everything worked perfectly in the test site. But when I applied the changes (updating from previous core version) in production, I realized that Image captcha is not only not working anymore: it even doesn't appear as submodule in Admin.

The folder is there but is no longer detected. I am thinking of reinstalling the complete Captcha module, but I am very worried about the rest of modules.

Going back to my backup of my database is not an option as I realized the problem after 2 days and that means losing a lot of data (if I would restore my backup).

Any tip on what could be causing this?

# Answer
> 1 votes
I discovered that the upgrade has renamed the path of submodule Image captcha to `sites/all/modules/captcha0/image_captcha` instead of the correct `sites/all/modules/captcha/image_captcha` (renamed filename value in table system of database. Physical path not changed). After that I have been forced to reinstall the module.

This is simply not serious, This seems a Drupal or a module bug and I have spent very bad hours trying to figure out what went wrong when I followed steps one by one and was very cautious.

---
Tags: 7, updating, captcha
---


title: Can I have multiple favicons in D7

text:
# Question
Title: Can I have multiple favicons in D7
This favicon generator (recommended here) generates multiple favicon png files and code for the `<head>` section of your HTML pages. This is said to be better than a single favicon file which might not display correctly in some devices.

But I think "Path to custom icon" in D7's /admin/appearance/settings only accepts a single favicon file.

If so is there a way to use multiple favicon png files?

If I can only use a single image what is the best practice for the format of the file?

# Answer
> 4 votes
You're looking for the Head Module:

> This module provides a range of metatags that can be added to the document head of each available theme.
>
> In an attempt to keep themes clear of anything that could be considered optional, i have aggregated all the frontend related metatags you could ever need into one advanced theme settings page which can be found at admin/appearance/advanced

# Answer
> 1 votes
An alternative to the Head Module, if you'd like to avoid the overhead of a module, would be to use `hook_page_alter()` in your theme's `template.php`. This is a code sample in one of my themes (replace `mytheme`):

```
function mytheme_page_alter($page) {
  $path = '/' . drupal_get_path('theme', 'mytheme');
  $apple = array(
    array(
      'rel' => 'apple-touch-icon',
      'href' => $path . '/images/apple-touch-icon-60x60.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '76x76',
      'href' => $path . '/images/apple-touch-icon-76x76.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '120x120',
      'href' => $path . '/images/apple-touch-icon-120x120.png',
    ),
    array(
      'rel' => 'apple-touch-icon',
      'sizes' => '152x152',
      'href' => $path . '/images/apple-touch-icon-152x152.png',
    ),
    // etc.
  );
  foreach ($apple as $link) {
    drupal_add_html_head_link($link);
  }
}

```

# Answer
> 0 votes
There is a new module just for that! Here you go: Responsive Favicons

---
Tags: theming
---


# Question
Title: Bringing CKeditor, embedded content (e.g. iframe) and responsive design together
I like to bring together the usage of CKeditor with embedded content (for expamle youtube / issuu) in a responsive website.

I have so far:

CKeditor with Media module integration and Media-Youtube to simply embed youtube-content via the media-library. Making the videos responsive works like a charm with fitvids.

Main question: i'm interested to either generalize these components or find another solution to make this work. Do i have to write something similar to fitvids and media-youtube for every embed-type i want to use or is there a solution out there that i overlooked?

Other suggestions highly appreciated. I'm kinda stumped at the moment... Thanks!

Edit: For example i'd like to integrate issuu (http://issuu.com/) elements in the same manner like youtube-clips: the editor just adds a link inside the media library and submits it to the field. Right now, issuu only offers embeds with fixed dimensions, so they don't scale according to screen width.

# Answer
> 1 votes
FitVids lets you define your own custom vendors. You could broaden the scope of what it looks for by pointing it all all `<iframe>` elements:

```
$("#thing-with-videos").fitVids({ customSelector: "iframe"});

```

Or, you could define a custom CKEditor style so users could apply a class to responsive elements of their choice:

```
{ name: 'Responsive Embed', element: ['iframe', 'embed', 'video', 'object'], attributes: { 'class': 'media-responsive' } }

```

And then point FitVids at that class:

```
$("#thing-with-videos").fitVids({ customSelector: ".media-responsive"});

```

# Answer
> 1 votes
You can override youtube videos using CSS and media queries. Infact, most videos from Youtube, Vimeo etc are all available in an iframe. In projects in the past, I allow clients to just copy and paste an embed field into a ckeditor field wherever they like, at any dimension they please.

But, once the screen width is reduced to mobile, my CSS takes over, and resizes the video to fit the mobile template, to reduce overlapping, and fix any issue with video height.

E.g.

```
@media only screen and (max-width: 767px) {

.field-name-body iframe     {width:100%;height:200px;}

}

```

Is that what you mean, or I have I not understood the question?

---
Tags: 7, wysiwyg, media, theming, nodes
---


# Question
Title: Configure a block view via block settings
I'm developing a website for a comprehensive but not professional user. He has the permissions to configure blocks (in order to tweak minor things like ordering or so). Now I have a block view and I want to allow him to configure the number of displayed items for that block without giving him the permissions for view configuration in general.

Is there a way to put certain aspects of a block view configuration onto the configure block page or a similarly consistent way to achieve that?

(working on drupal 7 with views 3.10, btw.)

# Answer
> 2 votes
Views UI: Edit Basic Settings may meet your needs.

> "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or **number of items to display**. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.

---
Tags: views, blocks, users
---


# Question
Title: How can I get a list of the roles in a system, via the REST API?
Similar to How to Retrieve all Forums, how can I retrieve the list of roles in a system via the Services REST API?

This is Drupal 7, Services 3.x.

Are roles terms in a taxonomy vocabulary ?

# Answer
1. Create a custom service resource, (you'll have to create your own `access callback` and `access callback file`, unless you want to use DrupalGap which is tailored to the link mentioned here)
2. Then in your `callback`, try something like this:

return user\_roles();
> 0 votes

---
Tags: 7, users, services
---


title: CKEditor ACF Configuration Help?

text:
# Question
Title: CKEditor ACF Configuration Help?
I am new to configuring CKEditor on **Drupal 7**, and even with the UI, it has always been a pain. I am trying to have it to stop stripping / removing tags, specifically - code, pre, ins del, blockquote, q, dl, dd, dt. I have a test page which I use to test my site's styles and these are getting removed in both Full and Filtered. Grrrr...

Keep in mind I have no idea what I am doing here. Please help me figure this out so I do not waste another day on this. =(

**ACF's extra allowed content**

I have added the following there:

```
br; div; span; header; footer; section; aside; figure; a; img; strong; em; h1; h2; h3; h4; h5; h6; ins; del; cite; q; blockquote; code; pre; table; tr; td; th; thead; tfoot; caption; legend; col; ul; ol; li; dl; dd; dt;</code>

```

**config.js**

I have found config.js and added the following to get it to stop stripping out tags.

```
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.allowedContent = 'br div span;' +
    'header footer section aside figure;' +
    'a[!href]; img[!src,alt,width,height];strong em h1 h2 h3 h4 h5 h6;' +
     'ins del cite q blockquote code pre;' +
     'table tr td th thead tfoot caption legend col;' +
     'ul ol li dl dd dt';
config.extraAllowedContent = ' br div(*) span(*);' +
    'header footer section aside figure;' +
    'a[!href]; img[!src,alt,width,height];strong em h1 h2 h3 h4 h5 h6;' +
    'ins del cite q blockquote code pre;' +
     'table tr td th thead tfoot caption legend col;' +
     'ul ol li dl dd dt';
};

```

# Answer
> 0 votes
If you just want to disable the content filter altogether, you can use:

```
config.allowedContent = TRUE;

```

Also, make sure you're clearing your Drupal cache AND browser cache. The CKEditor JS files are heavily cached by the browser and I wasted lots of time banging my head against the wall before I realized this.

---
Tags: wysiwyg
---


title: Warnings after installation

text:
# Question
Title: Warnings after installation
I have installed the Recruiter distro. I have also installed the Respond and Selectivizr libraries under site/all/libraries. However I still take these messages: Warning: file\_get\_contents(sites/all/libraries/selectivizr/selectivizr.min.js): failed to open stream: No such file or directory in omega\_build\_js\_cache() (line 388 of /var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc).

and

Warning: file\_get\_contents(sites/all/libraries/respond/respond.min.js): failed to open stream: No such file or directory in omega\_build\_js\_cache() (line 388 of /var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc).

How can this be fixed? thanks

# Answer
Please check:

1. Folder and file names if they match the directory structure in the warning message
2. /var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc if the selectivizer and respond directory is included or correct
3. The permissions of the folder and file
> 0 votes

---
Tags: theming, distributions
---


# Question
Title: Views: Display filters as a HTML UL list of links with clean mark up
I have a View that has a filter which allows users to select nodes that contain specific taxonomy terms.

I would like to display this as a HTML list of links (`<ul>`). How can I do this?

---

## Steps I have tried

**1. Using Better Exposed filters**

This displays a filter as links. But the links are displayed wrapped in `<Div>` tags instead of a `UL` tag.

**2. Using Views template**

Using `views-exposed-form.tpl.php` lets you access the exposed form, but it doesn't let you access the actual widget the makes up the filter.

**3. Using Custom Code**

This page says you can turn a select list into links via a custom module. But it requires Javascript to make the links work, which seems bad practise to me

# Answer
I would also go for step 3 and you really need JS for that option. Another option is, structure the links as it looks when you do a search like so..

```
// Merge the option name or key into the link
$link = "your-view?category=" . $select_option;
// Create the link
$somearrayforULlist[] = l($select_option, $link);

```

So when you click one of the links, it would reload the page and your view will use the filter values in the URL in your form.
> 0 votes

---
Tags: theming, views
---


title: Map to collect nodes

text:
# Question
Title: Map to collect nodes
I have a content type with +3000 nodes, and it has a field set as Term Reference for countries. I would like to have a map that count all these nodes (maybe with Views), but all solutions I have found was to set a geofield using Gmap module, and in my case it will be hard to go through the +3000 nodes to give each node its location.

So is there is any module that can count nodes of each term, showing it on its country? Also if I would like to show only five countries instead of whole world map, is that a map library or map modules can do that?

# Answer
> 0 votes
Although it doesn't look too complicated, I'd normally use the following modules to easily add and display nodes on a map:

* Leaflet;
* Leaflet Views;
* Leaflet More Maps;
* Views;
* Geofield;
* Geocoder;
* Geocoder Autocomplete;
* GeoPHP;
* Entity;
* Entity Reference;
* Chosen;

I don't work with Taxonomy terms. Instead, I create a node type named, let's say "Category" and add the right categories as nodes instead of terms in a vocabulary. It is easier like this and offers me more flexibility in the future.

The Category content type is based on a form that only includes Title as field. I'm adding them manually, which is not as simple as adding tags (terms) with the autocomplete options. As an alternative, I think you could use Inline Entity Form to add Categories during node add form. Not sure though.

When adding nodes, you need:

* an entity reference field pointing to the Category (using Chosen could help, if you don't have 10k categories);
* a textfield using Geocoder text field with autocomplete;
* a Geofield using Geocode from another field.

Now, when adding nodes, you get the Google Geocoder autocomplete option and the geofield will auto-fill with the right coordinates.

Then, I'm using Views to display items on the map with Leaflet. Here you can choose displaying only first 5 items, based on whatever filter criteria and order options you'd like. The view is a block and has an Entity Reference relationship poiting from the node to the category node + a contextual filter NID type my-node-type, with content ID from URL argument that uses this relationship.

Block will show up only on Category node-type pages in the content area.

Doesn't look very simple but there are a few tutorials on how to achieve that with leaflet, geofield and entities on Youtube. There are other ways to solve your problem, like using EVA with DS, adding blocks as fields in your DS display.

---
Tags: views
---


# Question
Title: Using code field to display field from referenced entity
I have a content type of 'facility' which has an entity reference field ('manager') to a user. The user has a field 'telephone'.

Is it possible with a code field to display the manager's telephone number on the facility node?

I have played around with this but don't seem to be having any joy. I have looked for examples but can find none, so am beginning to think this isn't possible.

Any suggestions or advice most welcome.

(posted here at the suggestion of DS maintainer aspilicious)

Thanks, Martin

# Answer
Use views and a contextual filter with the entity reference relationship you have created. Use EVA to get the block as field in Display Suite.

Display Facility nodes, choose the right format (I'd go for Unformatted List). Create the relationship in the right panel choosing two references, one that points from Facility to User, then one the points from User to Telephone using the first relationship.

Use contextual filters, provide default value Content ID from URL, validation criteria Facility content type.

Add a field "Title" using the second relationship. Now you have a block that you can publish on your page. If you need it as field in DS, use EVA to create it.
> 0 votes

---
Tags: entities, display-suite
---


# Question
Title: Trigger the 'add more' button with javascript, to add a set amount of field values
Is there any way to add a certain amount of field values to a standard node add/edit form (when unlimited option has been chosen) using a select input?

At the moment I have this working using javascript by triggering click on the 'add another' button, waiting a bit using setInterval (as the button disappears), then looping as many times as I need to, so the new fields gradually appear. This sort of works, but is very very dirty. Is there any proper way to add a certain number of field values based on a select option, and doesn't involved waiting?

# Answer
> 0 votes
I had the very similar problem, but with a group of fields that all needed to be added in sync. Using setTimeout to trigger is problematic because of the guess work involved.

One of the ways to do this is to use the ajaxSuccess event to chain a list of requests. After searching for a solution to my problem, I ended up creating a small plugin called group-add-more. This can work with both Drupal 6 as well as 7.

---
Tags: javascript
---


# Question
Title: How to use responsive design with bootstrap views
I've come a little confused and stuck with my current learning. Whilst my efforts using Workbench, Panels, Views with Bootstrap 3 looks pretty good on my desktop, when testing the Responsive layout with the Web Developer plugin, it looks pretty dire for use with smaller resolutions ie phones, tablets etc. In this day and age, I'd rather now focus my efforts on those mediums primarily.

My issue is, my Views grids matrix (say 3\*4 cells) works well on the (1600\*900) desktop, but repeats the Views matrix layout on the smaller mediums, obviously not right; hoping it would be say, a list. I've done a little research and maybe I'm missing an extra enabled module and found this:

https://www.drupal.org/project/views\_responsive\_grid

Others say it's merely using the CSS (SPAN etc) but I'm confused with what I generally need to do as my findings aren't Drupal specific.

I need to get things like my user dashboard looking well for mobile, tablet layout etc and maybe my approach using Panel pages was now the wrong way, so I'm happy to restart those pages again, or do simply what I may be missing in the first place.

Can someone give me some indicators to the norm one needs to do to get things going?

Thanks for your help.

Please be gentle, I have an ongoing illness and the ongoing meds don't help with my cognitive ability so I'm not that dumb (-;

# Answer
I think your problem is in using Views grid format. That is table based and not responsive in the way you would want it. Tables can be responsive but in a table way (hiding of columns and inserting sliders etc).

You need to use 'unformatted list' as the format, and then for your 'row class' you need to set appropriate bootstrap col-\* classes and you have to get a bootstrap row class in there as well. To do that your best bet is to override the views template files and preprocess functions.

There are plenty tutorials etc available for that on the web.

Bootstrap provides the framework, you just need to make sure your html conforms and that you put the classes you need in the right places. It can be done in views without any major issues.

You should also look at these modules as they definitely will help you (provided you have read the twitter bootstrap documentation and understand at least the basics)

Views Bootstrap, Display Suite Bootstrap Layouts, Panels Bootstrap Layouts
> 4 votes

# Answer
Edit the View and under format select Unformatted list. In "Settings" under "Format" select "Row Class": col-md-3 col-sm-6 col-xs-12 or any other value.
> 4 votes

# Answer
There are a few ways to go about introducing the responsive design to your pages. As Reynolds recommended, go for **unformatted list** Format for your view rather than table/html list or grid.

In your view page, click on **Theme Information** link at the right side bottom end to see what template files are available to override.

On how to override a template file, read the following Drupal straight forward Drupal documentation:

https://www.drupal.org/node/1089656

Once you have successfully override a template file. Then open the file (that corresponds to your content type or view) and make your changes (don't forget to clear the cache i.e. drush cc theme-registry OR drush cc all OR from Performance). Example of of one row and three columns is as follow:

```
<div class="row ...">
    <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
    </div>
    <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
    </div>
    <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
    </div>
 </div>

```

You will need all your columns to be wrapped in a div with a "row" class. The above would give you one row with 3 columns. The columns would automatically resize for different display ports (extra small, small, medium and large). For more info on media queries and display ports see here http://getbootstrap.com/css/#grid-media-queries

For more info and practicing what you need, see the following examples (change them and you will see the result accordingly) :

http://www.bootply.com/qpQdj66d38 http://www.bootply.com/DPiMgjeIqK http://www.bootply.com/stwBZnj7Yh

Note: Should you have columns of varying heights, apply a fixed amount of height to the columns (divs with css class col-xx-xx).

Good luck, Bootply and Bootstrap documentation is your best friend.
> 1 votes

---
Tags: views, panels, theming
---


# Question
Title: How to combine two nodes based on common title in Views?
I have a Commerce site selling clothing. Some Product Displays have multiple Commerce Products associated with them, and some have only one Product associated with them.

For example...

```
Shirt - Large - $10
Shirt - Medium - $8
Pants - One Size Fits All - $20

```

I need to use Views to display the title and price fields, as well as a link to the Product Display. I am using the Taxonomy term (Content) view with the Relationship "Content: Referenced products". I added the Title field, the "Size" field, and the "Commerce Product: Price" field, and enabled the "Distinct" setting in the Query Settings section. The result is as follows (fields are separated by a dash):

```
Shirt - Large - $10
Shirt - Medium - $8
Pants - One Size Fits All - $20

```

But I need the two "Shirt" items to be combined into a single line, like this:

```
Shirt - Large:$10 - Medium:$8
Pants - One Size Fits All - $20

```

Is it possible to combine products that have the same exact title (in this case, "Shirt")? There is only one Shirt product display page, on which the customer can choose Large or Medium.

# Answer
> 0 votes
Are you using multiple taxonomy terms field to enable the Large, Medium,etc sizes?

On the Views when you click on that taxonomy field, is there a way to show all fields in one line combined instead of separating them? Then use the Rewriting options so that you display with something like this:

\[title\] - \[Sizes\]: \[Price\]

Not sure if it will work, but worth a try. Experiment with separating out the different tokens and combining them in the Rewriting option.

Oh, what Alex said might work too.

---
Tags: 7, views
---


title: How to merge these results?

text:
# Question
Title: How to merge these results?
I wonder why these results don't merge. This is the result of searching by postcode. As you can see it returns 2 times the same shop with another deal. I need it to return the shop once with both deals on it. Thanks in advance! Pictures below:

# Answer
Found two modules that might help with your issue:

Views Merge Rows \- provides a way to combine rows with the same content in the specified fields.

OR

Views Fields Combine \- Similar to the one above, but hasn't been updated since 2012.

Experiment and see which one works best. You may need to use Rewrite Option too.
> 2 votes

# Answer
> "You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.
>
> 1. Go and edit your view
> 2. In Advanced » OTHER section by enabling Use aggregation: Yes
> 3. In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct."

Taken from: How do I remove duplicates when using the random sort?
> 0 votes

---
Tags: views
---


# Question
Title: Can "No front page content has been created yet. Add new content" be removed totally?
I noticed that if there is content placed in the main content block, "No front page content has been created yet. Add new content" will appear on front page or perhaps any page. Most templates will be done in blocks, except node pages.

Can it be totally removed? If yes, how?

# Answer
Add this to your theme's template.php file

```
function THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['content']['system_main']);
  }
}

```
> 2 votes

# Answer
Easy. Specify a front page other than the default in your site configuration settings.
> 1 votes

# Answer
Actually you did not create an front page or home page yet.So you should create an page which will be your default home page.

So first create a page

And Go to

```
`Configuration->System->System Information`

```

and set the `url` Under `'Default front page'`

You also can create a template file for front page as `page--front.tpl.php`

For more info check front page template and front page
> 1 votes

---
Tags: theming
---


title: Cannot login to my website

text:
# Question
Title: Cannot login to my website
I've logged out my drupal 7.22 website and have no login/admin block. It's hosted locally.

I've tried the following URL queries, with no desirable results. The page remains the same and I cannot locate any block I can use to log in-

* `localhost/drupal/user/logout` (Prints Access Denied on Title bar)
* `localhost/drupal/user/login` (Prints User Account on Title bar)
* `localhost/drupal/?q=user` (Prints User Account on Title bar)
* `localhost/drupal/?q=user/login` (Prints User Account on Title bar)

Any help?

# Answer
> 0 votes
I've discovered a solution to this problem. I removed all \*.tpl.php files from the theme templates directory and placed only html.tpl.php back. localhost/drupal/?q=user Now brings up the login block.

The default admin black bar on top would not return this way however. To bring it back I had to follow this instruction.

# Answer
> 0 votes
Seems like you do not have .htaccess file in you website directory. Place it over there any check :)

# Answer
> 0 votes
Sounds like you accidentally removed the login block, or otherwise broke the functionality.

Open up modules/system/system.module, and put the following code right after

```
global $user;
$user->uid = 1;

```

Then reload any page on the site and you'll be logged in as the main admin user. Then remove the above code, and (now that you're logged in) fix what missing login block.

Note that anyone who loads a page of your site while that code is in place will be automatically logged in as the main administrator!

# Answer
> 0 votes
Ensure the apache Rewrite module is activated too !! This fixed it for me.

---
Tags: users, uri
---


# Question
Title: Show login or register to anonymous user fro flag
I created flag for nodes and trying to show a login or register link to anonymous users instead of the flag button on a node page (panels). A redirect to the signup form would be ok as well. I tried the Flag anonymous module but it doesn't work for some reasons.

Are there any other ways to realize this functionality?

# Answer
If I understand the question correctly:

* You should be able, through permissions, to restrict access to the Flags, so that anonymous users don't see it
* you could use the default user login block, or create a custom one that redirects users, and place that block in the same position as the Flags, with a message like "To Flag objects, you must first login" and then restrict that block to show only to anonymous users
> 0 votes

---
Tags: panels, flags
---


# Question
Title: Location to Call the function theme_uc_price($variables)
This function is located at `/public_html/location/sites/all/modules/ubercart/uc_store`

```
function theme_uc_price($variables) {
  $output = '<span class="uc-price">' . uc_currency_format($variables['price']) . '</span>';
  if (!empty($variables['suffixes'])) {
    $output .= '<span class="price-suffixes">' . implode(' ', $variables['suffixes']) . '</span>';
  }
  return $output;
}

```

So my problem is, where can I find the ubercart file that calls this function? So I could get the computation where they add up the products so I could tweak it.

Any help would be appreciated. :)

# Answer
Since it's a theme function, based on DrupalContrib theme\_uc\_price it's called about 12 times within the Ubercart Suite.

As an example from one of the functions that calls the theme function which is uc\_object\_attributes\_form.

```
theme('uc_price', array('price' => $option->price))

```

That's how Drupal uses theme functions.
> 0 votes

---
Tags: ubercart
---


title: theme individual block

text:
# Question
Title: theme individual block
I looked over the theme suggestion but when tried with dummy text, the block doesn't show any dummy text.

on view source, it showed "id=block-menu-menu-top-menu-navigation"

Tried naming block--top-menu-navigation.tpl.php and block--menu-menu-top-menu-navigation.tpl.php but dummy text still doesn't show up.

Perhaps my naming the files is wrong?

# Answer
The template file you have to create should be

**block--menu--menu-top-menu-navigation.tpl.php**

Hope that helps.
> 2 votes

# Answer
To know if your tpl file is valid, you can use Theme Developer module to aid you on what available tpl files you can use for a specific Drupal component. Check it out :)
> 0 votes

---
Tags: theming
---


# Question
Title: Views Grouping field:Add Ordered class to Grouping row
I use Views and Grouping field to integrate my data. But i need each grouping row ordered.

I want to override the views-view-grouping.tpl.php, and change the "view-grouping" class to "view-grouping-1","view-grouping-2","view-grouping-3"...

The original code is belowed:

```
    <?php

/**
 * @file
 * This template is used to print a single grouping in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $grouping: The grouping instruction.
 * - $grouping_level: Integer indicating the hierarchical level of the grouping.
 * - $rows: The rows contained in this grouping.
 * - $title: The title of this grouping.
 * - $content: The processed content output that will normally be used.
 */

?>
<div class="view-grouping">
  <div class="view-grouping-header"><?php print $title; ?></div>
  <div class="view-grouping-content">
    <?php print $content; ?>
  </div>
</div>

```

The File is located at all/module/views/theme/

Does someone meet the same problem before?

Thx for help.

# Answer
> 0 votes
Javascript?

```
$('.view-grouping').each(function(i){
  $(this).addClass('view-grouping-' + (i+1));
});

```

---
Tags: views, theming
---


# Question
Title: Add fix amount to all orders as packaging price
I want to add a fix amount to all orders as packaging price in commerce,I think first I need custom line item and named it as packaging price, then add that to orders with rules or in custom module, but this is just a idea.
**Anybody know how can I add a fix amount to all orders as packaging price** (I also have discount in our commerce system and used it) **?**

# Answer
I think you should check this module commerce fees maybe help you
> 2 votes

---
Tags: commerce
---


# Question
Title: Aligning the Article/Node Title next to image
I've been working on a theme just in my spare time and I'm trying to style the way the article/node is displayed. Currently its simply formatted to:

1. title
2. submitted info
3. image
4. Short summary/description
5. read more / login

I want the field layout to be somewhat like the one they use on the League of Legends website (I believe that site is using Drupal)I want to make it so they layout is basically like this part of the site:

However I am unsure how to do this and what files I need to edit, I've been styling the rest of the site using responsive.css however I'm not sure how to change the layout and style it all.

Any help with this would be much appreciated.

Thanks, Ben

# Answer
There are several ways you can go about re-structuring your html. Two options would be:

1. Overriding / creating template files for the content type that you are trying to modify.
2. Using a contrib module like Display Suite which gives you an interface to easily modify a content types structure and classes.
> 0 votes

# Answer
The simplest solution is to add `float: left` to your CSS file.

Analysing the example of League of Legends and their News section you can see the following structure:

Every post has been placed into a `div class="gs-container"` whit 2 containers in that:

* `div class="default-1-3"` which "surrounds" the node image
* `div class="default-2-3"` which "surrounds" the node title (`h4`), node summary (`div class="teaser-content"`), and the post date (`div class="horizontal-group"` ...)

Now, the CSS file says:

```
.gs-container > * {
float: left;
padding-left: 20px;
padding-top: 20px;
position: relative;
}

```

So anything placed directly after an element with `class="gs-container"` \[in our example `div class="default-1-3"` (image) and `div class="default-2-3"` (content)\] becomes among others **`float: left`** \- this is the key to achieve what you want.

What can you do: Simply render:

1. node image
2. node title
3. node summary and so on

and add a CSS class to the node image wrapper that has `float: left` property.

BTW: If you would like see how something has been done/structured you can use "Inspect element" in your browser (or other tools like FireBug) to see at least the HTML and CSS structure of a web page. If you would like to check what technologies has been used on websites you can use Wappalyzer.
> 0 votes

---
Tags: theming
---