# Question
Title: How can I translate the title of taxonomy term pages when using i18n?
On the page of translated taxonomy term "*Site Development*" there is Russian source Term name in the title tag and in the page title (h1). You can see the problem at http://tlito.ru/en/categories/site-development

I often use the i18n module, but what kind of error/problem could be causing this?

# Answer
OMG! one more field "Name" appears on taxonomy Categories, do not know why. and this field was not translated. after I deleted it everything become ok!
> 0 votes

# Answer
Yet another interesting multi lingual challenge, this one related to taxonomies. The reason for your issue might be because of one reasons explained below.

# Use a recent i18n version

Make sure you're using that the version of the i18n module is at least version 7.x-1.8, because it might be because of a bug in the 7.x-1.7 version of it.

# Use the correct translation mode

You also want to check the "translation mode" that you've specified within admin/structure/taxonomy/categories/edit (whereas "categories" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate". Attention: after changing this value, be aware that you then also have to:

* enter a translated value for each of the tags and
* revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.

Obvious, if you have other taxonomies with the same issue (like "categories" in your case), you should repeat this for those others also.

# Consider the Title module

Possibly related to this issue is that titles that do not get translated in a site using the i18n module, is most often because of the Title module that has not been enabled. From the module's project page (bold markup added here):

> After enabling the module as usual, visit the Manage fields page of the content type, **taxonomy vocabulary** or "comment type" which you wish to replace fields of and click the replace link. That's all.

FYI: I have not yet run into any situation where I had to install/enable this module to get multi language site to work as I want.
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: Authentication page before loading the main website
I am using Drupal 7. I need any user(who has not logged in) to just see the login screen only for authentication before he can traverse the actual website.

How this can be done?I tried to do it using Panels but without success.

# Answer
You can use this module

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Allow users to login using either their username OR their e-mail address.
> * Allow users to login immediately.
> * Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> * Customize the registration form with two e-mail fields to ensure accuracy.
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.
> * Optionally display a user message indicating a successful login.
> * Optionally combine both the login and registration form on one page.
> * Optionally have unvalidated users purged from the system at a pre-defined interval.
> * Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).

Or you can add this code as well:

```
    global $user
    if ($user->uid  == 0  && $_GET['q'] == 'node') {
      drupal_set_message("Access Denied: Please Login");
      drupal_goto('user/login', drupal_get_destination());
    }

```
> 1 votes

---
Tags: panels
---


# Question
Title: Recommended modules for managing Content access?
I am looking for an access module.

Probably, the most popular is the Content Access module. But what modules are exist for that as well?

Also, when it says I have to rebuild the links (or permission, I don't remember) right after installation, what exactly does it do?

# Answer
> 2 votes
# Recommended modules

Here is what I consider as the "shortlist" for such modules (quotes are from their project pages):

* Content Access.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
* Taxonomy Access Control:

> Access control for user roles based on taxonomy categories (vocabulary, terms).
>
> + Automatically controls access to nodes (based on their taxonomy terms).
>     + Configuration page for each user role.
>     + Three node access permission types: View, Update, Delete.
>     + Two term access types: View tag, Add tag.
* Simple Access (RC4 version only for D7):

> This module allows administrators to make some nodes private and/or editable by certain user roles. It can manage viewability, editability, and/or deletability and provides an easy way to make nodes accessible by only a group (or groups) of users. It is perfectly suited for making private nodes that are only viewable to certain 'access groups'.
>
> Access groups are based on roles. So for example, my site has roles entitled "Coach Level 1", "Coach Level 2", and "Coach Level 3". I can create an access group called "Coaches" and assign all of these roles to it. Then when I assign a node to be viewable only by "Coaches", only users who are a member of these roles will be able to view.
>
> Nodes that are not assigned to any access groups will remain viewable by all users, so all nodes will remain viewable when activating this module. And nodes only become private when they are assigned to an access group. The end result is that this module can be enabled for a site with existing nodes without making them all invisible.

**Special case**: Organic Groups, which provides 'Groups' for Drupal users, and management of Access Control based on these groups. A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

My "recommended" module is Content Access ... Also because of al sorts of integrations with the Rules module.

For more details, refer to Access Control modules.

# Rebuilding permissions

About "Rebuild permissions": any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "installation" (actually "enable") of a module, when rebuilding permissions is also required. Makes sense? Clear enough?

---
Tags: 7
---


# Question
Title: Unable to submit form to database in custom module
I am building a custom module and I'm unable to get the form to talk to the database. The section for uploading to the file system works fine.

This is MyModuleBlock.php

```
<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module;

/**
 *  @Block(
 *    id = "my_module",
 *    admin_label = @Translation("Add Image"),
 *  )
 */

class ImageBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
      // stuff here;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['image'] = array(
      '#title' => t('My Module'),
      '#type' => 'managed_file',
      '#upload_location'=> 'public://images/',
      '#required' => FALSE,
    );

    $form['submit'] = array(
      "#type" => 'submit',
      '#value' => 'Upload',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function submitForm($form, FormStateInterface $form_state) {
      MyModuleDB::add();
  }
}

```

The MyModuleDB.php (I am trying out plain text to see if any errors or anything pops up):

```
<?php

namespace Drupal\my_module;

class MyModuleDB {
    static function add(){
        db_insert('my_table')
            ->fields(array('image' => 'img1'
            ))->execute();
    }
}

```

I'm at a total loss here. The tutorials I've found claim that this should work out fine, but it isn't working for me at all. I even tried inserting into the database directly from submitForm() in the main block class. I also tried to add redirects to the submitForm(). I'm thinking the issue is in that function, but I don't see what the issue could be.

# Answer
> 2 votes
If you write a block, use `\Drupal\Core\Block\BlockPluginInterface::blockSubmit` for submission

# Answer
> 2 votes
What your `submitForm()` should do is shown from `AggregatorFeedBlock::blockSubmit()`, for example.

```
public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration ['block_count'] = $form_state->getValue('block_count');
  $this->configuration ['feed'] = $form_state->getValue('feed');
}

```

See the code of `AggregatorFeedBlock::blockForm()` too.

```
public function blockForm($form, FormStateInterface $form_state) {
  $feeds = $this->feedStorage->loadMultiple();
  $options = array();
  foreach ($feeds as $feed) {
    $options [$feed->id()] = $feed->label();
  }
  $form ['feed'] = array(
    '#type' => 'select',
    '#title' => $this->t('Select the feed that should be displayed'),
    '#default_value' => $this->configuration ['feed'],
    '#options' => $options,
  );
  $range = range(2, 20);
  $form ['block_count'] = array(
    '#type' => 'select',
    '#title' => $this->t('Number of news items in block'),
    '#default_value' => $this->configuration ['block_count'],
    '#options' => array_combine($range, $range),
  );
  return $form;
}

```

---
Tags: blocks, 8
---


title: How to embed images with blocks

text:
# Question
Title: How to embed images with blocks
Am newbie to Drupal this is my first question

i want to embed my images on the blocks body, so i tried below code to embed

```
<div class="topsection">
    <div class="wrapper">
      <div class="topleftsection">
        <div class="socialmediaimage"><a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image2','','sites/all/themes/custom/themename/images/facebook_top_hover.png',1)"><img src="sites/all/themes/custom/themename/images/facebook_top.png" alt="Facebook" width="18" height="18" id="Image2" border="0" title="Facebook"></a></div>
        <div class="socialmediaimage"><a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image3','','sites/all/themes/custom/themename/images/twitter_top_hover.png',1)"><img src="sites/all/themes/custom/themename/images/twitter_top.png" alt="Twitter" width="18" height="18" id="Image3" border="0" title="Twitter"></a></div>
        <div class="socialmediaimage"><a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image4','','sites/all/themes/custom/themename/images/gplus_top_hover.png',1)"><img src="sites/all/themes/custom/themename/images/gplus_top.png" alt="Gplus" width="18" height="18" id="Image4" border="0" title="Gplus"></a></div>
        <div class="socialmediaimage"><a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image5','','sites/all/themes/custom/themename/images/linkedin_top_hover.png',1)"><img src="sites/all/themes/custom/themename/images/linkedin_top.png" alt="Linkedin" width="18" height="18" id="Image5" border="0" title="Linkedin"></a></div>
        <div class="socialmediaimage"><a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image6','','sites/all/themes/custom/themename/images/skype_hover.png',1)"><img src="sites/all/themes/custom/themename/images/skype.png" alt="Skype" width="18" height="18" id="Image6" border="0" title="FourBends"></a></div>
      </div>
      <div class="toprightsection">
        <div class="emailsection">
          <div class="email">Email :</div>
          <div class="contacus"><a href="mailto:contactus@xxx.com">contactus@xxx.com</a></div>
        </div>
        <div class="countrysection">
          <select name="Country" class="countrylist">
            <option>India</option>
            <option>USA</option>
          </select>
        </div>
      </div>
    </div>
  </div>

```

i having page.tpl and page--front.tpl in my custom theme, the images are only loading on page--front.tpl, please refer screenshot

But for other pages for example user login page the images are not loading, please screenshot 2

When i inspect with firebug on the image src the url added with the "**user**" ,this is the reason behind why the images are not loading

http://localhost/projects/drupal/dev/user/sites/all/themes/custom/themename/images/facebook\_top.png

# Answer
> 1 votes
The image links are the problem here, I think. The images are shown on the front page but aren't shown on **other** pages. So, on the **front** page it understands the image link (by adding the `http://localhost/` in front of the image link you gave) but on the other pages, for example on `http://localhost/node/3` it tries to show an image from `http://localhost/node/3/sites/all/themes/custom/themename/images/facebook_top.png` but there is **no** image on this address.

Therefore, use the **full** link (`http://localhost/sites/all/themes/custom/themename/images/facebook_top.png` etc).

# Answer
> 0 votes
Click image to enlarge

You can do it by changing to the text format to Filtered HTML or Full HTML

Then you can do it manually by typing `<img src="url.jpg">` OR If you are using a module like CK Editor you can add it through the icon bar.

---
Tags: blocks, media, nodes
---


title: Drupal Ajax breaks after one fire

text:
# Question
Title: Drupal Ajax breaks after one fire
This is a very frustrating and recurring problem for me because it seems to come and go at random, one minute it is working beautifully, the next moment I make a change and it breaks. Even if I change everything back the way it was and clear the cache again it is still broken.

I have a form, in the form is a table that allows users to enter ingredients into the form. There is a "More ingredients" button. Once clicked an AJAX call is made and the form is rebuilt and a new row is appended to the table. For some reason This "More ingredients" button has been broken. On click, it adds one ingredient, then on the second click, nothing. The button will not even trigger the receding animation as it does other buttons, it is as if the button has just disapeared...

Here is the code.

relevant form function

```
 if (isset($form_state['add_ingredients'])) {

//reset add ingredients under form_state
unset($form_state['add_ingredients']);

//Get number of added ingredient for proper naming below.  Allows us to use row theme instead of table theme for loading only an ingredient.
$ing_number = count($node->recipe_ingredients['ing']);

//Be sure ajax returns proper row number.
$form_state['ing_number'] = $ing_number;

//Add ingredient to our ingredients array.
array_push($node->recipe_ingredients['ing'], array('ri_id' => NULL, 'name' => '', 'quantity' => '', 'unit_key' => '',  'note' => '', 'weight' => $max_weight + 1));

//Theme this row only, uses $ing_number to designate it will only be themed by row theme function, not table.
$form['recipe_ingredients']['ing'][$ing_number] = array(
    '#theme' => 'ingredients_row',
    '#row_number' => $ing_number
    );

$form['recipe_ingredients']['ing']['1'][]
. . .

$form['recipe_ingredients']['recipe_more_ingredients'] = array(
'#type' => 'submit',
'#name' => 'ingredientadd',
'#value' => t('More ingredients'),
'#description' => t("If the amount of boxes above isn't enough, click here to add more ingredients."),
'#weight' => 1,
'#submit' => array('recipe_more_ingredients_submit'),
'#limit_validation_errors' => array(),
'#ajax' => array(
  'callback' => 'recipe_more_ingredients_js',
  'wrapper' => 'ingredient-list',
  'effect' => 'fade',
  'method' => 'append'
  )
);

```

Submit

```
function recipe_more_ingredients_submit($form, &$form_state) {
//Set Drupal's form rebuild option to true...  not sure if this is really needed...
$form_state['rebuild'] = TRUE;

// If they clicked the more ingredients button, flag it in form_state['add_ingredients']
  if ($form_state['values']['recipe_ingredients']['recipe_more_ingredients']) {
   $form_state['add_ingredients'] = TRUE;
  }

}

```

Ajax Callback

```
function recipe_more_ingredients_js($form, &$form_state) {

return $form['recipe_ingredients']['ing'][$form_state['ing_number']];

}

```

Row theming function

```
function theme_ingredients_row($variables) {

$form = $variables['form'];

$row_number = $form['#row_number'];

// Build the table row.
$row = array(
    'data' => array(
    drupal_render($form['ri_id']) . drupal_render($form['quantity']),
    )
  );
  $row['data'][] = drupal_render($form['unit_key']);
  $row['data'][] = drupal_render($form['name']);
  $row['data'][] = drupal_render($form['note']);
  $row['data'][] =  '<button class="ing-remove" type="button">Remove</button>';

//Start HTML of row
$output = '<tr ' . ' id="' . 'ing-' . $row_number . '"' . '>';

//Wrap each cell in proper HTML tags
foreach ($row['data'] as $key => $value) {

    $output .= '<td>' . $value . '</td>';

}

$output .= '</tr>';

watchdog('ROW', $output, null, $severity = WATCHDOG_NOTICE);

return $output;

}

```

# Answer
> 1 votes
Sadly that still doesn't work... The problem is not that php, it calls the website only the first time. The second time the button is broken. It does not click, call Drupal or anything. Also any buttons added to page with ajax do not work either, even though their pre-loaded counterparts work perfectly fine with jquery.

---
Tags: forms, ajax
---


# Question
Title: Products do not show under category in Commerce Kickstart
I am building a site on top of Commerce Kickstart, no demo.
I created a category, but when creating a product of that content type it does not show under the category.
I do provide a menu link to the product but it still does not show.
I can see it from Manage Products.
What am I missing?

# Answer
Here's the proper steps for creating a new product type with matching product display (so you always have a 1:1 relationship of content type to product variation type.)

When making a variant it will ask to create a matching content type for the product display - which it sounds like you've opted for this.

On your created Product Display content type, make sure you add the existing Product Category term reference field. The Commerce Kickstart 2 catalog is very specific to its initial setup (demo or no demo, regardless.) It does some work to hijack the callback path for the provided taxonomy vocabulary.

In fact, for best results you should make sure the new content type mimics the default product display until you're familiar with how it all works.

Lastly, Commerce Kickstart 2 comes with the Inline Entity Form module. It is opinionated that products will always be created from the node form, not individually. So make sure you're creating nodes and populating the products through there.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create a single page checkout for donations but standard cart/checkout for for other ecommerce?
I am currently using Commerce for handling selling physical products but also donations.

I would like to have a one page donation that includes the amount and entering their credit card information but still allow the standard cart/checkout process if they are doing physical products.

Is there any way of doing both because it seems that I can only pull off one or the other?

Here is an example of a single page.

# Answer
> 2 votes
You can use Commerce Buy One Click module.

The Project page says

> Commerce Buy One Click Module allows customers to checkout directly from the product page with just one click, skipping the annoying checkout steps.

For more info go through the module documentation.

# Answer
> 1 votes
Consider donation and product buying are different task.

If user go for donations, call one step checkout form by redirecting it to payment gateway and allow user to add his credit/debit card details to process it.

And if user go for purchasing physical product call standard checkout process.

# Answer
> 0 votes
Also you can commerce\_express\_checkout for your case. Maybe you will need in some additional modules with commerce\_express\_checkout

# Answer
> 0 votes
Maybe you want to try/experiment with the Commerce Donate module. Excerpt from its project page:

> provides a donation line item type along with a donation product and product display.
>
> In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

**Note**: refer to this tutorial/screencast also for a great introduction to this module.

---
Tags: commerce
---


# Question
Title: How to let a user change their own username?
I can't seem to figure out how to let users change their own username. I'm running Aegir with about 10 Open Atrium sites. With permissions I've checked "change own username" for the master Aegir site, as well as the Open Atrium sites. For giggles, I enabled every role to "change own username"..

But when I try to change my username in OpenAtrium and click save, it confirms "changes have been saved", but the username doesn't actually change. This has ballooned into a huge issue for us. I'm hoping there is some obvious dumb thing I need to do. Thoughts?

# Answer
Changing a username inside a hosted site is completely up to the OpenAtrium Drupal installation. Aegir does not usually interact with this.

I just verified that it works OK on a clean Aegir 3 install with a standard Drupal site.

So @Bisonbleu's comment seems correct:

> That's done in permissions. In Drupal 7, go to admin/people/permissions and look under User: Change own username.
> 1 votes

---
Tags: aegir, distributions
---


# Question
Title: How to implement a Drupal Commerce multi-select membership donation form?
Something like this using Drupal Commerce? You select from a select list multiple options of which everyone has a price right? And so it adds it as a total below in a field like a cart, but in a same page and then below you fill your details and continue?

Or not a chance with Commerce and have to go with some other alternatives? Note I'm looking for Drupal friendly solution, not a PHP programmer here.

Cheers everyone for help!

# Answer
> 2 votes
I know you are asking about the form specifically, but it isn't clear to me how you are actually managing your 'memberships'. Something like CiviCRM that has full membership management tools can be integrated with both Drupal and with Commerce. There is a module for the latter, but we have found it problematic and have instead done the Commerce to CiviCRM integration using Drupal Rules and the CiviCRM Entities modules.

# Answer
> 1 votes
Maybe you want to try/experiment with the Commerce Donate module. Excerpt from its project page:

> provides a donation line item type along with a donation product and product display.
>
> In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

**Note**: refer to this tutorial/screencast also for a great introduction to this module.

---
Tags: 7, commerce
---


# Question
Title: How can I add a real name field beside username to user information?
I want to add a real name field beside the default username when I creat a new user in `admin/people/create`. How can I do this?

I have checked the RealName module but is not doing what I need.

# Answer
> 9 votes
Simply add a textfield (or two, if you want first/lastname) to your users at admin/config/people/accounts/fields. That will allow them to enter their realname and it will be displayed on the user profile page.

And if you want to display that name in various places (like node author), that's exactly what Realname module is for. It allows to configure the displayed name based on tokens (which can either be profile fields or user fields).

# Answer
> 3 votes
You can add fields to the user in "Administration » Configuration » People" and then manage the fields.

# Answer
> 2 votes
The best module for this is https://drupal.org/project/name, I would guess. It manages given, last and middle names and all sorts of suffixes and prefixes like "Dr.", "Jr." and so on. It even has settings for the order of first and last name, so an asian user could choose to display his last name first and a european user his first name.

# Answer
> 0 votes
Install the Profile2 module and Entity API, then add a 'real name' textfield to the user profile.

Profile2 is recommended over the core profile fields, because as the module page says:

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!

# Answer
> 0 votes
The Real name module, once you understand it, is simple, but there are no instructions at all (!?).

Here is my version of short instructions to help folks out there: For Drupal 7 only.

1. If needed, create a text field in Account Settings \> Manage Fields.
2. In the Real name settings (Config.\>People), there is a link to browse all tokens options: simply use your desired field instead of core User name. Your custom User fields will appear as token options.

The name shown for accounts will automatically be replaced by the chosen token or profile field.

---
Tags: 7, entities
---


# Question
Title: Can I set a cron for deleting and re-indexing Search API daily?
Using Commerce Kickstart 2.

When we add new products, the facet search index does not re-index automatically as it says it does (Maybe because we are using some Aggregated Fields?) -Whatever-, we have to re-build the index manually to get certain search fields to work.

I read a bit and it -seems- as though the standard cron tasks -should- add to the index, but that ain't happening.

So: Is there a way to create an 'Re-build Index' to a list of nightly Cron jobs?

# Answer
If you have Drush on your server, you can use the `drush search-api-reindex` command. This way you don't need to invoke a cron, but can force a reindex.

Note: You'll need to run `drush search-api-list` first to get the numeric identifier for the index when you run the re-index command.

Reference more info here: http://drushcommands.com/drush-6x/search-api/search-api-reindex
> 0 votes

---
Tags: commerce, cron, search
---


title: Flexslider carousel using template.php

text:
# Question
Title: Flexslider carousel using template.php
**Views** with **flexslider** takes lot of times in rendering items/images.

Situation is that I have more than 5 flexslider carousels on the front page. So I changed to go without view with flexslider.

I am trying to use flexslider carousel using template file. Due to flexslider.css, I am not able to see `.slides>li` .

See following lines:

```
.flexslider .slides > li {
    display: none;
}

```

Even not able to see any slider movement there. Somehow I tried according to https://stackoverflow.com/questions/7539542/trying-to-get-flexslider-jquery-slider-to-work-with-drupal

Can anybody help me to create flexslider without view or manage display? I want to create using tpl files.

# Answer
The common and very accepted way is to use a module and do everything from the UI:

I used Flexslider and it's a great module - If I remember correctly, you can use it's **field** display-option directly, without using Views. An "Instant" slider alternative could be the module "Content glider", but I'm not sure if it's responsive (the word responsive doesn't come up in the modules' page) so Better try the Flexslider **field set** first.

For better performance in slider image-replacement (and in general) you could try turning on Caching and Aggregation, and use modules like AvgAgg, Boost, and some others, it's a whole subject.
> 0 votes

---
Tags: javascript
---


# Question
Title: Unable to add css class to a Panels region
I wish to add custom css classes to specific regions in a panels page.

I understand from this question Add a class to a panels pane that I should be able to do this pretty trivially from the settings menu on the pane or region itself, however, there is absolutely no option to do so.

I am using panels 7.x-3.5 with Panels Bootstrap in Drupal 7.

No matter what layout setting I use - Boostrap, custom style etc - I never get any option to add css classes.

The boostrap settings has a handful of drop down boxes, the custom style settings has a heap of options but no ability to add css classes.

Do I need to over-ride a template somewhere? This should be trivial...

# Answer
The option to add a CSS class is on the actual pane content. In a Bootstrap panel region the cog on the left gives you the option to set the grids up. If you need to add a class to that you will need to find the template file for the region you are using and copy it to your theme/sub-theme and add the class there or write a cTools plugin for that yourself. The ability to add a class is on the actual content panes that you add inside the region, so for instance if you were to add a view pane into the left region inside your panel you could place that view inside a bootstrap .well or bootstrap .alert using the cog on the right hand side (the cog on the content inside the region) of the content pane. So you can add the class to the content pane via settings that way.

If you need to add a class to the whole region you need to copy your template file for your layout to your theme. So if you were using Bootstrap three column stacked you would copy `bootstrap-threecol-stacked.tpl.php` to your templates folder in your theme. And modify the outer div for the region you want inside that template file. The regions are actually listed in that template file (you will see them inside the file). You can modify any of those template files inside the module, if you want to see what template files have what markup turn theme debug on and inspect your HTML of the page (see here for how to do that).

There is this module where you can add the alert or well into a region: https://www.drupal.org/project/panels\_bootstrap\_styles but I've never actually used that one and it looks limited. I would stick to the bootstrap panel layouts and proper templating, or cTools plugins for these types of things work great also. You can write them like that module does for just about any markup you need :)

You can also use a module like Semantic Panels to do this, it was a little overkill for something like adding a CSS class so I didn't add it before but you may find it easier to use.
> 1 votes

# Answer
I guess adding css class programmatically in `THEME_preprocess_html` will work. the Add a class to panel page body element suggested a solution to do this using `menu_get_item()`.
> 0 votes

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


# Question
Title: How to combine 3 line charts in a single chart, using the Views integration of the Charts module?
I want to create a line graph using the Highcharts library which shows 3 series in a single chart. I have visualization API, views, highcharts library etc. installed in my Drupal website.

I succeeded already in creating a chart which shows only 1 serie, but couldn't get it to work with 3 series yet.

The X-axis is taxonomy terms and Y-axis is the value of nodes on this term (relationship: Taxonomy terms on node).

The view I created has a filter and it filters the views with 3 content types I wanted. So I want to show these 3 content types as 3 different series (line charts), instead of just 1 line chart with everything together.

Here are some relevant details of the view I created:

This is the line chart I was able to create so far:

Here is what I want to achieve (using data that are different though):

**How can I visualize my 3 series (for 3 different content types) in a chart similar to the above one?**

# Answer
After diving into deep on visualization with Drupal, Charts module gives us the opportunity to do this, either by using the Views integration of Charts (to create charts without coding PHP snippets), or by using the Charts API (used as a developer module that provides a unified API for the integration of various charting solutions into Drupal).

This is from the `Readme.txt` file, incuded with the Charts module:

> ## Creating Multiple Series and Combo Charts in the UI
>
> When using Views to build your charts, you may find it difficult to retrieve more than a single set of data generated by a COUNT() query. For example if you wanted to retrieve the age of all your site users, but display "Male" and "Female" values in a column chart at the same time, constructing the underlying table of data is quite difficult.
>
> To solve this problem, you can combine multiple charts on top of each other. The "parent" chart provides the global information, such as the height, width, title, and other properties. Charts that are "children" provide only data and (optionally) a secondary axis. After you've assembled the first series of data in your chart according to the instructions in the "Creating Charts in the UI" section, add a new display to the same view of the type "Chart Add-on". The "Chart Add-on" type is added the same way you would add a new Page or Block display, from the "+ Add" menu at the top of the view configuration.
>
> After this new display has been added, find the setting for "Combine with parent chart" and change this value to point at the parent chart you have already assembled. Then adjust the settings for the child chart to pull in different data (often by overriding the filter settings). Now you can go back to your parent display, and see that the results from the child chart have been merged into the results from the parent chart. You can even use this approach to combine different types of charts, such as a line chart over the top of a column chart. Note that not all chart types can be combined together and invalid combinations may cause your chart to throw errors.
> 1 votes

# Answer
Here are some additions to the previous (accepted) answer:

* Even though the question is related to HighCharts as the charting library (one of the engine used by the Charts module to actually render charts), it should also work for anybody using the (interactive) Google Charts library instead. Either of both libraries have their advantages and disadvantages, simply pick the one that best fits your needs/requirements. And remember that at any time you should be able to switch between either library, though there should not be any significant difference between the rendered charts.
* The content of the `Readme.txt` file quoted in the previous answer, is now also included in the Community Documentation about Charts, i.e. within Steps to create charts using the views UI. That community documentation also includes a subsection with Charts HowTos.
* Whenever using the Views integration of the Charts module, keep this golden rule in mind: you may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.
> 1 votes

---
Tags: 7, views, charts
---


# Question
Title: Translate custom field in countries module
I am using the Countries module in a multilingual site and I added a custom field to it.

The countries itself support translation for its own field, but is there a way to translate content for the custom fields added to it?

# Answer
> 0 votes
Consider using the Entity Translation module to get this to work.

In doing so, if you run into an error like "The entities of type Country do not define a valid base path: it will not be possible to translate them.", then review the issue about "Countries is not integrating properly with Entity Translation" (status = needs review).

---
Tags: i18n-l10n
---


title: How to get nodes from Google Search?

text:
# Question
Title: How to get nodes from Google Search?
I'm using CSE in my drupal website and due to some technique restrictions i couldn't use Solr search.

My news portal gives a " RELATED CONTENT " block to each article using tags similarity but i'm not very satisfied with the result.

I wonder if there's a way to integrate Google Search (like solr module does) to return back (in a view) a list of similar nodes by searching the title for example.

# Answer
> 1 votes
What you're describing is a content recommendation system. This isn't what Google CSE is built for and implementing the way you describe would likely result in poor results.

You're better off implementing one of Drupal's existing recommendation modules or some other 3rd party recommendation service (e.g. OutBrain).

Some of Drupal's recommendation modules include:

---
Tags: search
---


# Question
Title: Can Commerce Kickstart be used to add Drupal Commerce to an existing site?
I want to add the Drupal Commerce module to my existing Drupal website. Is there any way I can use the Commerce Kickstart dstribution for an existing Drupal site?

Seems like you're supposed to use Commerce Kickstart when you're starting to build your Drupal site, but I already built mine.

According to the Commerce Kickstart website it says: "*Anyone who wants to skip weeks of configuration to build a commerce site on the Drupal Commerce framework*".

Is it really that hard to install the Drupal Commerce module without Commerce Kickstart?

I'm not creating a big store, I just want to sell 1 or 2 items.

# Answer
> 3 votes
No, you can not install an installation profile after Drupal has already been installed. What you can do is make a separate installation with Kickstart Commerce and compare configuration when you're stuck.

How hard Commerce is to install depends on you previous Drupal experience. If this is your first time around with Drupal, it will be pretty hard. But if you're already familiar with entities, views and rules, you'll be fine.

# Answer
> 1 votes
If you are new to Drupal e-Commerce - and have neither Drupal Commerce nor Ubercart - realize they are two different cart systems and that Ubercart is arguably better integrated to Drupal and Ubercart does a whole host of things especially in modules extensions Drupal Commerce does not. You did not say if you installed Drupal 6 or 7 - but if you installed Drupal 6, go back and re-install or upgrade to Drupal 7 - as Ubercart for Drupal 6 is version 2 of Ubercart and for Drupal 7 it is version 3 and the two are like night and day. You will find many of the top level Drupal Core code contributors are also Ubercart contributor developers also. That should rest my case.

# Answer
> 0 votes
Maybe you should consider using the Commerce Backoffice module. It provides the backoffice functionality present in Commerce Kickstart (V2). It contains these sub-modules:

* Commerce Backoffice **Product** (commerce\_backoffice\_product).
* Commerce Backoffice **Order** (commerce\_backoffice\_order).
* Commerce Backoffice **Content** (commerce\_backoffice\_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular, and prevents that you have to install the entire Commerce Kickstart distribution. And there is a great video introduction about it also.

If you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).

---
Tags: 7, commerce
---


# Question
Title: How to overriding specific Omega_Kickstart CSS files in a subtheme?
I'm using Commerce Kickstart (Version 2).

I created a new theme, which is basically a copy of the commerce\_kickstart\_theme. So it's a subtheme of omega\_kickstart which is, itself, a subtheme of omega v3.

Even though the child theme has various css files for global, narrow, normal, it -looks- as though the theme actually reads in the css from the parent theme... ie. the OMEGA and is ignoring same-named files in my subtheme.

Eg. if I have a file global.css in my subtheme, it is ignored and the omega\_kickstart/global.css is used instead.

The same goes for the various alpha files. Eg. I copied alpha-mobile.css into my theme folder. But the file being @imported is the /omega/alpha/css/alpha-mobile.css.

My understanding is that if a same-named css file was in your theme directory it -replaced- the file from the parent. But that doesn't seem to be happening.

Any ideas?

# Answer
> 0 votes
A few things you may want to check (since none of these items are incuded in the question):

* make sure you cleared the cache (if not that explains what you experienced).
* make sure the file permissions are correct (if not the webserver will not be aware of the newly created subtheme).
* make sure you enabled the sub-theme (only creating it is not sufficient).

---
Tags: commerce, theming
---


title: How output field in $view->result?

text:
# Question
Title: How output field in $view->result?
I need get to field views in calendar module template.

`print_r($view->result)` output this: https://jsfiddle.net/36pbj7bb/

How output event\_calendar\_status?

I type this:

```
<?php print $view->result[0][_field_data][nid][entity][event_calendar_status][und][0][tid];   ?>

```

But I get:

> Cannot use object of type stdClass as array in

Any help?

# Answer
> 1 votes
Views rows and entities are objects so I would think it should be this:

```
$view->result[0]->_field_data['nid']['entity']->event_calendar_status[LANGUAGE_NONE][0]['tid'];

```

but I'm guessing a little bit.

Also note the use of quotes in the array keys and the use of the LANGUAGE\_NONE constant instead of 'und' for the field language.

If you still have trouble then try using the Devel module to see the structure of the view object variable.

There is information available via Google for how to use the Devel module to debug.

---
Tags: views
---


# Question
Title: Is there a required format for table name prefix?
I know that in MySQL installations it must end in an underscore like `prefix_` but I want to know if that is also the required format for Postgres and SQLite.

# Answer
> 2 votes
There is no requirement for the prefix to end in an underscore for any type of database but it can be beneficial for readability.

It is just a string of characters that Drupal prepends to table names in queries so it can contain any characters that are legal to use in table names in your chosen type of database.

Database prefixes are also not necessary at all unless you are using a single database for multiple purposes, for example you have all your drupal tables prefixed with drupal\_ and then have other non-drupal tables without a prefix or with a different prefix.

That way you can easily tell which tables are for what.

This is usually only necessary if your hosting provider limits the number of databases you are allowed or sometimes in some more advanced Drupal configurations.

The way Drupal uses it is that if you use one of the db functions like db\_select(), db\_insert(), db\_update(), db\_delete() it automatically appends any prefix value you have configured.

When using db\_query() it will also do this for any table name wrapped in braces, eg:

```
db_query("SELECT * FROM {node}");

```

---
Tags: database
---


# Question
Title: How to map uid in users table data to the entityid in feild table to retrieve data of the users in drupal7
I would like to retrieve data related to users with the uid in users table.

But the uid is not mapped in the feild\_data tables which has entity\_id and entity\_type.

How are these two ids mapped in drupal database 7

# Answer
For the `field_data_*` tables, when the `entity_type` is **node**, the `entity_id` & `revision_id` are the foreign keys into the node table. You can use this to `JOIN` into the users table.

```
  //@TODO: Replace field_data_* with the field table in question
  $fields = db_select('field_data_*', 'f');
  $fields->join('node', 'n', "n.nid = f.entity_id AND n.vid = f.revision_id AND f.entity_type = 'node'");
  $fields->join('users', 'u', "u.uid = n.uid");
  $new = $fields
    ->fields('f')
    ->fields('u',array('uid'))
    ->execute()->fetchAll();

```
> 0 votes

---
Tags: database
---


# Question
Title: How to check which node should be posted on which domain?
I am looking for a feature which should be able to check the node destination before save it in the database. This will be used in multi site Drupal set up.

And it must be work like if node 1 has already created in site1 and I want to save node 2 in site2 then it save the node with nid=2 in the site2's node table.

Which means the nid must continues its sequence regardless of domains. Here, database and codebase are same only tables are having different prefixes.

# Answer
Consider using the Domain Access module. Here's an excerpt from its project page:

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.
>
> The module uses Drupal's Node Access system to determine what content is available on each site in the network. Unlike other multi-domain modules for Drupal, the Domain Access module determines user access based on the active domain that the user is viewing, rather than which group or site the user belongs to.
> 0 votes

---
Tags: multi-sites, subsites
---


# Question
Title: Custom views field handler with relationship support, but without table
I created a custom field handler following the very useful explanations here,
Custom views handler without table

The field handler picks the entity from each row and renders it in some way. (For simplicity lets just assume it renders a link to the entity using entity\_label() and entity\_uri(). It actually does more awesome stuff, but this is irrelevant here.)

Unfortunately, I found that I cannot configure a relationship when using this field handler. E.g. if I have a relationship "The node author", then I might want to render the title + link for the node author instead of the node.

Is there anything more I need to enable support for relationships?

```
/**
 * Implements hook_views_data().
 */
function EXAMPLE_views_data() {
  $data = array();
  $data['EXAMPLE']['table']['group'] = t('Custom');
  // #global is a special flag which let's a table appear all the time.
  $data['EXAMPLE']['table']['join']['#global'] = array();

  $data['EXAMPLE']['custom_handler'] = array(
    'title' => t('EXAMPLE field handler'),
    'help' => t('EXAMPLE field handler'),
    'field' => array(
      'handler' => ExampleViewsFieldHandler::class,
    ),
  );

  return $data;
}

```

I could also post the code of the field handler class, but I supposed it is not really that relevant..

# Answer
Ok, I found one way to do this: Instead of registering just one handler, you register one handler per entity type. To save time, we can reuse the stuff already registered by Entity API, with entity\_views\_data(). This means, of course, the module needs to add Entity API as a dependency.

```
/**
 * Implements hook_views_data_alter().
 */
function EXAMPLE_views_data_alter(&$data) {

  foreach (entity_get_info() as $entity_type => $info) {
    if (!isset($data['views_entity_' . $entity_type]['rendered_entity'])) {
      // Only register for those entity types where Entity API already did its job.
      continue;
    }
    $data['views_entity_' . $entity_type]['EXAMPLE'] = array(
      'title' => t('Entity display plugin'),
      'help' => t('The @entity-type of the current relationship rendered using an entity display plugin.', array('@entity-type' => $info['label'])),
      'field' => array(
        'handler' => ExampleViewsFieldHandler::class,
        'type' => $entity_type,
        // The EntityFieldHandlerHelper treats the 'entity object' data
        // selector as special case for loading the base entity.
        // @todo Not sure if we really need this.
        'real field' => 'entity object',
      ),
    );
  }
}

```

And below is the field handler class, just a bit simplified.

Maybe it does a bit more than we really need here. E.g. we don't really need to create a render array for each row, we could work with html directly. But I think it is a good start.

```
class ExampleViewsFieldHandler extends \views_handler_field {

  function query() {
    // do nothing -- to override the parent query.
  }

  /**
   * Run before any fields are rendered.
   *
   * This gives the handlers some time to set up before any handler has
   * been rendered.
   *
   * @param object[] $rows
   *   An array of all objects returned from the query.
   */
  function pre_render(&$rows) {
    /**
     * @var string $entityType
     * @var object[] $entities
     */
    list($entityType, $entities) = $this->getResultEntities($rows);
    // Build the entities.
    $builds = $this->buildMultiple($entityType, $entities);
    foreach ($rows as $rowIndex => $row) {
      if (isset($builds[$rowIndex])) {
        /** @noinspection PhpUndefinedFieldInspection */
        $row->example_field_builds[$this->position] = $builds[$rowIndex];
      }
      else {
        /** @noinspection PhpUndefinedFieldInspection */
        unset($row->example_field_builds[$this->position]);
      }
    }
  }

  /**
   * @param object[] $rows
   *
   * @return mixed[]
   *
   * @see EntityFieldHandlerHelper::pre_render()
   */
  protected function getResultEntities(array $rows) {
    $relationship = !empty($this->relationship) ? $this->relationship : NULL;
    $field_alias = isset($this->real_field) ? $this->real_field : NULL;
    // Some views query classes want/allow a third parameter specifying the field name.
    /** @noinspection PhpMethodParametersCountMismatchInspection */
    list($entityType, $entities) = $this->view->query->get_result_entities($rows, $relationship, $field_alias);
    return array($entityType, $entities);
  }

  /**
   * @param object $row
   *
   * @return string
   */
  function render($row) {
    /** @noinspection PhpUndefinedFieldInspection */
    return isset($row->example_field_builds[$this->position])
      ? drupal_render($row->example_field_builds[$this->position])
      : NULL;
  }

  /**
   * @param string $entityType
   * @param object[] $entities
   *
   * @return array[]
   *   A render array for each entity.
   */
  protected function buildMultiple($entityType, array $entities) {
    $builds = array();
    foreach ($entities as $rowIndex => $entity) {
      $builds[$rowIndex] = array(
        '#markup' => entity_label($entityType, $entity),
      );
    }
    return $builds;
  }
}

```
> 1 votes

---
Tags: views
---


# Question
Title: Maintenance Page -> Show a specific block
How to make a block available on the maintenance page (e.g. jQuery Countdown) ? Is it about setting right permissions?

# Answer
> 3 votes
You cannot. The maintainance page is used for when you have put the site offline, or when the site is experiencing trouble.

1. When you put the site offline, you typically will be doing database migrations, updates and the likes.
2. When Drupal puts the site offline, there is trouble; e.g. the databaseserver cannot be reached/is crached etc.

In case 1. You don't want your average users to reach the database, after all, no-one knows what state that database is in. The whole point of bringing it down, is to avoid people writing and reading from a crippled, stateless and changing database.

Since Drupal stores its blocks or their configuration in the database, Drupal cannot should not read from the block system.

From the relevant code:

```
// The bootstrap was not complete. So we are operating in a crippled
// environment, we need to bootstrap just enough to allow hook invocations
// to work

```

That said, you can still modify the maintainance template. Just be very carefull with calling Drupal API's and/or the database in there. The maintainance theme is there for the cases when these are not available. And if they are not, your users are going to see ugly fatal errors (or nothing at all).

# Answer
> 0 votes
This answer might come a little late but might be helpful.

What you can do is coding the maintenance page directly from Drupal admin/config/development/maintenance

Here is an example using bootstrap.

Hope this helps you.

---
Tags: 7, blocks, maintenance-mode
---


# Question
Title: How to safely remove fields from create content - project
I am customizing the Project Management (pm) module. When I create a new Project content type I do not need some of the fields such as price and currency for my particular application. I am concerned that if I use the Fields UI to delete them that when a new version of pm is release that I'll have problems installing it. I also worry that I might mess up the database.

I have made these fields hidden, but they still appear on the create new Project content page.

Are my worries baseless?

# Answer
Normally I would suggest just hiding the unwanted field via a hook\_form\_alter, either by setting `$form['unwanted_field']['#access'] = FALSE`, or by using the hide() on that element. If the field is a required field, you'll want to alter that property as well, or set a value before hiding it or setting '#access' to false.

if you want to actually delete the field, you can use drush to run field\_delete\_field(). For example, `drush eval 'field_delete_field("unwanted_field")'` should work (untested).
> 0 votes

# Answer
The Field Permissions module works, but I decided that my situation was so simple that I created a new content type for tasks and another for projects using the model of the pm modules. It works well.
> 0 votes

---
Tags: entities
---


title: Rendering a region after rows

text:
# Question
Title: Rendering a region after rows
Having code issue.

I am rendering a the regions\[ad\_spot\] = 'Ad Spot' so that it shows up after the first row.

For some reason it is not showing the region even tho I have put a block in there. So far I have not had an issue with my other regions I have made.

http://dev-honey-in-the-wild.pantheon.io/

Code is here: https://codeshare.io/bHx5N

Am I doing this correctly?

thanks!

# Answer
I'm absolutely against to add code in templates...

but your problem is here:

```
<?php if ($row_id == 0): ?>
  <?php print render($page['ad_spot']); ?>

```

I think this is always FALSE.
> 1 votes

---
Tags: views
---


# Question
Title: How do I link to a local/internal file in Drupal 7?
Is there a way to get and display a local file's path in Drupal 7?

We have very large files on intranet, so I would like to instead display the file locations.

The ideal scenario would be to browse & select a file. Then instead of uploading the file drupal would save the file path i.e. x://projects/shared/example.mov

# Answer
> 1 votes
This is a solution for Intranet deployments only.

Install the Any Menu Path and the Filter Allowed Protocols modules.

Enable both modules and add "file" to the configuration \> text format \> allowed protocols.

Edit the link in your menu to read file:///directory/file.html. Check the box labeled "No Path Validation" and save.

If it still doesn't work, check to make sure your browser doesn't need extensions or privacy settings adjusted to accept the file:/// protocol.

---
Tags: files, navigation
---


title: Links inside SVG have undefined events

text:
# Question
Title: Links inside SVG have undefined events
I have a problem with a site I'm developing in which I have a US map with each state as a polygon defined in an svg. Each of those polygons is wrapped in a link so users can click on a state to be taken to information about that state.

Code layout: `<svg...>
 <a xlink:href="...">
 <polygon ...><title>{stateName}</title></polygon>
 </a>
</svg>`

The problem I'm having is when someone clicks one of these links I get several errors: `TypeError: this.href.match is not a function in googleanalytics.js line 36, col 66
 ...rupal.settings.googleanalytics.trackOutbound && this.href.match(/^\w+:///i))
TypeError: target.protocol is undefined in overlay-parent.js line 575
 if (href != undefined && href != '' && target.protocol.match(/^https?:/)) {`

After some experimentation I narrowed it down to those functions having undefined events.

The googleanalytics.js function is: `...
$(document.body).bind("mousedown keyup touchstart", function(event) {
...`

The overlay-parent.js function is: `...
Drupal.overlay.eventhandlerOverrideLink = function (event) {
...`

I assume this has something to do with the links being nested in the svg for some reason but I can't find any good information on why or how to get around that.

I tried using a jquery.svg.js plugin but that had no impact.

Using: Drupal 7.34 jQuery 1.10.2 (via ajax.googleapis.com) Google Analytics 7.x-2.1 (googleanalytics.js) jQuery Update 7.x-2.4 (replace/misc/1.9/overlay-parent.js)

If any other info is needed to help figure this out let me know.

Thanks in advance for any help you can provide!

# Answer
> 1 votes
The issue is the way the google analytics module tracks clicks. It adds mousedown, keyup, and touchstart events to the body and tries to match the clicked position the the closest anchor. When it encounters a click on an SVG element it gets confused and is not able to properly match the closest anchor.

There are a couple options to remedy this:

1. Using :after on your anchors to create a block that covers up the SVG elements.
2. Using `pointer-events: none` on all SVG elements inside your anchor.
3. Turn off click tracking in your Google Analytics settings.
4. Unbind click tracking on your map page only with something like `$('body.mymappage').unbind()`
5. Manually patch the GA module:

Change the line (googleanalytics.js):

```
$(event.target).closest("a,area").each(function() {

```

to:

```
$(event.target).closest("a,area").not(".svg-anchor").each(function() {

```

The first 2 options are documented here, and a codepen example fix is here.

---
Tags: 7
---


# Question
Title: Try to add in different views to a single page, keep getting "Error" message?
I have a panel where I'm pulling in 7 different views pages in different regions, and when I try and save it, I keep getting the same message-- "The website encountered an unexpected error. Please try again later."

So, I went to the specifics of the error and this is what it says:

PDOException: SQLSTATE\[22001\]: String data, right truncated: 1406 Data too long for column 'panel' at row 1: INSERT INTO {panels\_pane} (did, panel, type, subtype, shown, access, configuration, cache, style, css, extras, position, locks, uuid) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13); Array ( \[:db\_insert\_placeholder\_0\] =\> 41 \[:db\_insert\_placeholder\_1\] =\> block\_layout\_row\_2\_col\_2\_row\_1\_region\_1\_ \[:db\_insert\_placeholder\_2\] =\> views \[:db\_insert\_placeholder\_3\] =\> review\_entries \[:db\_insert\_placeholder\_4\] =\> 1 \[:db\_insert\_placeholder\_5\] =\> a:0:{} \[:db\_insert\_placeholder\_6\] =\> a:15:{s:23:"override\_pager\_settings";i:1;s:9:"use\_pager";i:0;s:14:"nodes\_per\_page";s:1:"5";s:8:"pager\_id";s:1:"0";s:6:"offset";s:1:"0";s:9:"more\_link";i:1;s:10:"feed\_icons";i:0;s:10:"panel\_args";i:0;s:12:"link\_to\_view";i:1;s:4:"args";s:0:"";s:3:"url";s:0:"";s:7:"display";s:7:"block\_6";s:14:"override\_title";i:0;s:19:"override\_title\_text";s:0:"";s:22:"override\_title\_heading";s:2:"h2";} \[:db\_insert\_placeholder\_7\] =\> a:0:{} \[:db\_insert\_placeholder\_8\] =\> a:1:{s:8:"settings";N;} \[:db\_insert\_placeholder\_9\] =\> a:0:{} \[:db\_insert\_placeholder\_10\] =\> a:0:{} \[:db\_insert\_placeholder\_11\] =\> 0 \[:db\_insert\_placeholder\_12\] =\> a:0:{} \[:db\_insert\_placeholder\_13\] =\> cc38c8a0-a223-4b16-91ca-7426f802c8f8 ) in drupal\_write\_record() (line 7308 of /srv/bindings/2ed870ecae69481598cc782d3c4e9589/code/includes/common.inc).

Does anyone have any idea how to fix this?? Thanks!

# Answer
As the error says the data for some columns is too long. I had the same problem in some where else, so I simply opened the phpmyadmin, found the column and change it's type to something else with more capacity. In my case the type was `blob` and I changed it to the `long blob` and it worked.

Try this and I guess it will work
> 0 votes

# Answer
The Machine-Name of the panel ("block\_layout\_row\_2\_col\_2\_row\_1\_region\_1\_") is too long (40 characters), as it is defined by as varchar(32). I guess it comes form your blocks machine name. You may name the block different, to get a shorter name. I had a similar problem with a view display name, where the subtype gots to long so I had to choose a shorter display machine name.
> 0 votes

---
Tags: views, panels, debugging
---


title: Remove duplicate messages

text:
# Question
Title: Remove duplicate messages
How to remove any duplicate messages of a certain type.

For example when performing 2 searches using the search api module before rendering the page the message `"To perform a search you must enter at least 3 characters"` may be displayed twice.

# Answer
> 1 votes
Use the following function to remove any duplicate messages of a certain type:

```
/**
 * @param $type - the type of messages that should be checked
 *
 * Removes any duplicate messages from the messages session
 */
function remove_duplicate_messages($type) {
  $stack = array();
  if(isset($_SESSION['messages'][$type])) {
    foreach($_SESSION['messages'][$type] as $k => $msg) {
      if(in_array($msg, $stack)) {
        // Message is already set - remove it
        unset($_SESSION['messages'][$type][$k]);
      } else {
        // Add message to stack
        $stack[] = $msg;
      }
    }
  }
}

```

Example use:

```
remove_duplicate_messages('warning');

```

---
Tags: 7, status-messages
---


title: Image not displaying in email

text:
# Question
Title: Image not displaying in email
I have views with three fields (Title, Image, Price). I want to send this view as email to registered user. I am using Mime mail to send email.

Email works fine but images are not displaying in email. Thanks.

# Answer
> 2 votes
I had this same problem few days back. Try to Inspect that broken Images, your Image might have source like this: `src="https://ci4.googleusercontent.com/proxy/a0ulmqxF3B*******************************************gMzBa5MRdHDhrBXYc8KaMYIvFZ2HAf3P_lOwFrg=s0-d-e1-ft#http://yoursite/logo.png"`

So if you are trying to send email from your local then probably they did not get cached by some google service because probably google can't access your local, try access.log for any issues. Some other are also facing the same problem: https://productforums.google.com/forum/#!topic/gmail/q47KoUYQXPw

this problem still persists on my local it has nothing to do with mime mail, or any other module, in fact I was able to send emails with images using only print-email- module try this https://www.drupal.org/project/print

Hope this helps you. al PS: If nothing helps try to send mail form live or your development site, you won't face this problem there, because there problem here is google not given access to your images at local machine.

---
Tags: views, media, emails
---


# Question
Title: TimePicker Rendered by an Ajax Callback Function Doesnt Show Up
I have a select form element that fires an ajax callback function everytime its value changes.

```
$form['template_options'] = array(
  '#type' => 'select',
  '#options' => array(
     1 => t("Student"),
     2 => t("Employee"),
  ),
  '#default_value' => 1,
  '#title' => t('Select'),
  '#ajax' => array(
    'callback' => 'myid_select_template',
    'wrapper' => 'myid_dynamic_input_information',
  ),
  '#suffix' => '<div id="myid_dynamic_input_information"></div>',
);

```

The function `myid_select_template` is a callback function triggered when the select form element changes it's value.

```
 function myid_select_template($form, &$form_state){
     $form = array();

     $form['form']['birthdate'] = array(
         '#title' => t('Date of Birth'),
         '#type' => 'date_popup',
         '#timepicker' => 'timepicker',
         '#date_format' => 'd/m/Y',
         '#date_year_range' => '-100:+0',
         '#default_value' => date("Y-m-d H:i:s", time()),
    );
    return $form;
 }

```

I already enabled Date API, Date Pop-up and Date Picker module. I notice that the date\_popup form element doesn't show when I place it in a form not rendered in ajax callback function.

The HTML below is an output of an ajax callback function:

```
<div class="container-inline-date">
    <div class="form-item form-type-date-popup">
        <label>Date of Birth </label>
        <div id="" class="date-padding clearfix"></div>
    </div>
</div>

```

The HTML output below is the output of a working Date Picker not rendered by ajax function:

```
<div class="container-inline-date">
    <div class="form-item form-type-date-popup form-item-birthdate">
        <div id="edit-birthdate" class="date-padding">
            <div class="form-item form-type-textfield form-item-birthdate-date">
                <label for="edit-birthdate-datepicker-popup-0">Date </label>
                <input type="text" id="edit-birthdate-datepicker-popup-0" name="birthdate[date]" value="27/07/2015" size="20" maxlength="30" class="form-text">
                <div class="description"> E.g., 27/07/2015</div>
            </div>
         </div>
     </div>
</div>

```

I notice it is rendered incompletely. Why?

# Answer
> 1 votes
You are confusing what an AJAX callback does in Drupal with what a form builder does. See `ajax_example_autocheckboxes()` that adds a number of checkboxes basing on the number selected in a select field.

```
  // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;

  // Omissis...

  for ($i = 1; $i <= $num_checkboxes; $i++) {
    $form['checkboxes_fieldset']["checkbox$i"] = array(
      '#type' => 'checkbox',
      '#title' => "Checkbox $i",
    );
  }

```

The AJAX callback is pretty simple. (`ajax_example_autocheckboxes_callback()`)

```
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

```

Its description says what an AJAX callback does when used with a form builder.

> Callback element needs only select the portion of the form to be updated. Since #ajax\['callback'\] return can be HTML or a renderable array (or an array of commands), we can just return a piece of the form.

As side note, if you just want to show a form element, or also hide it, basing on the value selected for another form element, there is the #states form API property.

```
$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

```

---
Tags: forms, ajax, datetime
---


# Question
Title: Override field template with custom module
Instead of adding tpl files (in this case, media-youtube-video.tpl.php) to the theme. How can I override field templates from a custom module? Including when the field is used in a View.

# Answer
> 12 votes
I'm sure there must be an easier way to do this but this is what I typically do:

1. *Register* an overriding theme implementation with the Drupal theme registry. So, in `mymod_theme()`, add a new item. The `variables` key must match that of the `media_youtube_video` theme i.e.

```
/**
 * Implements hook_theme().
 */
function mymod_theme() {
  return array(
    'my_media_youtube_video' => array(
      'variables' => array('uri' => NULL, ...), // see media_youtube_theme() for this
      // bundle the template file with the module itself
      // i.e. theme/my-media-youtube-video.tpl.php
      'template' => 'my-media-youtube-video',
      'path' => drupal_get_path('module', 'mymod') . '/theme
    )
  );
}

```

2. *Add* a preprocess hook for the original theme implementation and *suggest* your new implementation here.

```
/*
 * Implements hook_preprocess_media_youtube_video().
 *
 * Or more generally, hook_preprocess_THEME().
 */
function mymod_preprocess_media_youtube_video(&$variables) {
  // If your overriding implementation is not a template but
  // is implemented in a different file,
  // then remember to include the file explicitly at this point..
  $variables['theme_hook_suggestions'][] = 'my_media_youtube_video';
}

```

Suggestions are evaluated by the theme system in a LIFO fashion. You can read more about this here.

Suppose you are aware that another module is also following the same approach as this one to override the implementation, then you can implement `hook_module_implements_alter()` and force your `hook_preprocess_THEME()` (see above) to be called last. You can read about `hook_module_implements_alter()` here.

This holds good for Views also. In summary, you just need to find out the correct unique name of the original theme implementation you want to override (typically defined in the source module), add a preprocess hook and add your overriding suggestion there.

# Answer
> 4 votes
You can also decalare new theme in module this way:

```
/**
* Implements hook_theme().
*/
function yourmodule_theme($existing, $type, $theme, $path) {
  $theme = array();

  $theme['field__field_nameofyourfield'] = array(
    'render element' => 'content',
    'base hook' => 'field',
    'template' => 'field--field-nameofyourfield',
    'path' => drupal_get_path('module', 'yourmodule') . '/templates',
  );

  return $theme;
}

```

Then put in a /template directory file that contains field template like this (standard) and name it field--field-nameofyourfield.tpl.php:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

After clearing cache your theme will use this filed template unless it's not overriden by theme itself, which means you can still override this template in your theme.

---
Tags: 7, entities, theming
---


# Question
Title: Custom user_register_form for Auto Assign Role registration pages
I'm using a function\[a\] to get custom templates to work for all pages, including role registration pages set by Auto Assign Role. By setting the role registration path to `user/register/<rolename>` I'm able to use `page--user--register--rolename.tpl.php` to make custom pages.

What I'm trying to do now is use a custom user\_register\_form for each role registration page. Using this function\[b\] I'm able to use `user-register-form.tpl.php` to customize the registration form. This affects the form for both role pages though. I tried using the Field Permissions module, but because an anonymous user will be using both forms it's of no use here.

I'm thinking I need to change what user-register-form template the page itself is looking for, but I can't figure out how to do that.

a.

```
function THEMENAME_preprocess_page(&$vars) {

  if (isset($vars['node'])) {

    $suggests = &$vars['theme_hook_suggestions'];

    $args = arg();
    // Remove first argument of "node".
    unset($args[0]);

    $type = "page__type_{$vars['node']->type}";

    $suggests = array_merge(
      $suggests,
      array($type),
      theme_get_suggestions($args, $type)
    );
  }
}

```

b.

```
 function THEMENAME_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'THEMENAME_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'THEMENAME_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'THEMENAME_preprocess_user_pass'
    ),
  );
  return $items;
}

```

# Answer
I think if you already have a template file for the form user-register-form.tpl.php, you should be able to use a preprocess like this:

```
function MYTHEME_preprocess_user_register_form($vars) {
  // if role2
  // use other theme
}

```

There should be no need to define your own themes with hook\_theme
> 0 votes

---
Tags: forms, users, theming
---


# Question
Title: How to get the user ID from the last profile page?
So, I have a user's profile page where there is a Message button. When I click the message button it should redirect me to a custom page with a form in it. How can I get the user ID from the profile page I visited in order to know where to send the message?

# Answer
The easiest way would be to add the user id as a ref argument to the form url in your message button, on the user profile page:

```
<a href="/path/to/custom/form?userid=<?php print arg(1); ?>">go to custom form</a>

```

Then, on your custom form:

```
$args = drupal_get_query_parameters();
$userid = (isset($args['userid']) ? $args['userid'] : false);

```
> 3 votes

# Answer
You can access the user id from the **URL** of user profile page. The url will be like **/user/userid**. You can access it by arg(1).

Hope this helps..
> 0 votes

---
Tags: 7, users, emails
---


# Question
Title: How to migrate Drupal Commerce configuration between environments
I'd normally use features to migrate changes from a dev server to a live one, however it seems drupal commerce doesn't fully support features, which leaves me in a tight spot.

How would you suggest to migrate the changes over without causing disruption? The live site is updated constantly.

Any help would be much appreciated.

# Answer
Commerce Features has helped me in the past.

Apart from that, you're looking at update hooks (or possibly the Configuration Management module).
> 2 votes

---
Tags: 7, commerce, features
---


# Question
Title: What are the database tables related to comments in Drupal 7?
I received a lot of spam comments in one of my websites running on Drupal 7. I googled for a solution to delete them in bulk and came up on

```
DELETE FROM comment WERE status = 0

```

The query worked but the database size did not shrink significantly and I realized out that in addition to the 'comment' table there was another table called

```
 field_data_comment_body

```

which housed the body of the comment.

I would like to know which all tables are related to comments in Drupal 7

# Answer
> 1 votes
Run these on your PhpMyAdmin:

```
TRUNCATE TABLE comment;
TRUNCATE TABLE field_data_comment_body;
UPDATE node_comment_statistics SET comment_count = 0;
TRUNCATE TABLE field_revision_comment_body;

```

**Take care: all the comments will be deleted!**

# Answer
> 2 votes
I know following tables. 1. comment 2. field\_data\_comment\_body 3. field\_revision\_comment\_body 4. node\_comment\_statistics

Beside that, I think, comments are also stored in any other tables installed by modules, and linked to comment modules.

# Answer
> 0 votes
So, the question is which tables are related to comments in Drupal 7? Not which SQL commands to run ;-)

If you haven't added any fields to the comment entity (for any content type), the correct tables has already been mentioned:

* comment
* field\_data\_comment\_body
* field\_revision\_comment\_body
* node\_comment\_statistics

For each field you add to the comment entity you get two more tables.

Example: For a content type "blog", you have added an email field to the comment. In other words you find a field with machine name "field\_comment\_email" (or similar) on admin/structure/types/manage/blog/comment/fields. Then you have two more tables:

* field\_data\_field\_comment\_email
* field\_revision\_field\_comment\_email

This quickly gets messy. To repeat what @Clive said ;-)

> Deleting comments directly from the comment table is a very, very bad idea, you should use the API functions.

---
Tags: 7, comments, entities
---


# Question
Title: Checklist(s) for simplifying upgrades from Drupal 6 to 7 or higher in the future?
Is there any checklist to configure before upgrade for better deciding?

Is there any checklist for it after upgrade?

# Answer
> 2 votes
I have used the Upgrade status module on the past to better understand how much work will be involved in upgrading a site from a mayor version to the next.

Also, depending on how many modifications, or modules you have, it will also make the process easier.

One more tip: Check the Drupal documentation, and remember Youtube is your friend.

# Answer
> 1 votes
Just follow the 20 steps for successful upgradation from Drupal 6 to Drupal 7. These steps are listed in the Community docuentation page Upgrade process.

# Answer
> 0 votes
# Identify the hacked modules and/or themes

Often times when you're considering upgrading you also want to have an answer to the question like "Are there any tweaks (hacks) in any of our contributed modules that we need to be aware of?".

Especially if somebody else first created the D6 site, and you're in charge of the D7 upgrade.

Guess what, there's a module for it, it's called Hacked!. Here is a quote from its project page:

> ... scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

# Evaluate module alternatives

When upgrading you might have to replace some module with another module, for various reasons, such as:

* The module is not yet available (or released) in the new Drupal version.
* The module will never be upgraded to the new Drupal version, because of some Drupal core changes, or changes in other modules it depended on.

Or you may want to take advantage of adding new features, etc in your upgraded site.

So there are quite some situations where you will have to decide between multiple contributed modules, such as:

* A stable module.
* A module that's on the horizon.

Whenever I have to decide between multiple modules, I often use the (23) criteria that I ever documented in "maintenance scorecards" (within the Community documentation about "Comparison of Charting modules"). Those scorecards are actually "applied" to charting modules, but the same criteria can be used, I think, to mostly any type of module comparisons.

# D8 module status

The D8 Module Status site provides an interesting summary of various contributed modules, about their D8 readiness. Here is a quote about it:

> ... a daily script that runs the tests of all the mentioned projects below and displays a summary.

---
Tags: installation, updating, upgrading
---


# Question
Title: How to return drupal error message in php cli
I am programmatically saving nodes with corresponding photos into a D7 content type. It's working well sometimes, and failing on others, and I am sure it has something to do with a form field not having the right data.

Typically this would throw an error when manually uploading via the Drupal content type form, but I am using the PHP CLI. How can I output that message to the CLI?

I tried 'print $messages' which is what is used for web pages, but, alas, that is not working.

Thanks

# Answer
Since you are using the command line, have a look at PHP's input/output streams. These let you write data out to where your environment would be expecting to receive output.

Alternatively, you might want a look at Drupal's built-in logging with watchdog(). You can see the messages it generates in Administration \>\> Reports \>\> Recent log messages.
> 1 votes

# Answer
You don't mention the method you are using to save the nodes. If you are using drupal\_form\_submit(), then you can get the errors by calling form\_get\_errors().
> 0 votes

# Answer
If you would use `drupal_form_submit()`, this should work:

```
if (drupal_is_cli() && $errors = form_get_errors()) {
  print_r($errors);
}

```

However when using `node_submit()` and `node_save()`, I believe it's bypassing the validation rules.

Otherwise you can do something like that:

```
// ...
node_save($node); // After this call we'll get a nid.
if (!$node->nid && drupal_is_cli()) {
  drush_print(sprintf("Failed to create a node: %s of type: %s.", $node->title, $node->type));
}

```

or check out the following one-liner:

```
$node->nid ?: drupal_is_cli() && printf("Failed to create a node: %s of type: %s.\n", $node->title, $node->type);

```

Eventually you may try to print the error messages via:

```
print_r(drupal_get_messages());

```
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: How do I print the edit link on a node page if the currently logged-in user has the permission to edit the node?
I'm using Display Suite custom fields to have the edit link rendered somewhere else on the node page. Is there an easy way to verify the currently logged-in user has the permission to edit the node?.

So far I tried this code.

```
global $user;

if (node_access('update', $nid, $user)) {
  echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
}

```

What code should I instead use?

# Answer
> 1 votes
It might be that you don't have access to the node object, in which case changing to the following should work...

```
<?php
  global $user;
  if ($node = node_load(arg(1))) {
    if (node_access('update', $node, $user) == true) {
      echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
    }
  }
?>

```

---
Tags: 7, nodes
---


title: Taxonomy terms with conditional field

text:
# Question
Title: Taxonomy terms with conditional field
50 terms and each term needs to have radiobuttons or "other".

Food - **o** in price - **o** extra price

Drinks - **o** in price - **o** extra price

WiFi - **o** in price - **o** extra price

So "in price" and "extra price" are radiobuttons. User clicks "extra price" and he gets conditional text field (integer) where he can write the extra price. Result after choosing "extra price" should look like this:

Food - **o** in price - **o** extra price - \_________ €.

There are 2 things that come to my mind. Making separate vocabulary out of each term, each containing terms "in price" and "extra price", make separate integer field in content type and use conditional field module.

But that would mean i would have to create 50 vocabularies and 50 integer fields for 1 content type and its possible that there will be more terms in the future.

2nd option would be creating 50 fields instead of using taxonomy and use Select or other module but that also seems to be overdoing it to have 1 content type with over 50 fields just becouse of this option

# Answer
With a module, creating a form and using the drupal ajax function to switch the input field on/off might be a solution.

check out this example from deckfifty: form api using ajax example

partial code:

```
function deckfifty_example_form($form, &$form_state) {
  $form['fox_color'] = array(
    '#title' => t('Specify the color of the fox:'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', 'brown', 'black', 'white')),
    '#ajax' => array(
     'callback' => 'deckfifty_fox_ajax_callback',
     'wrapper' => 'deckfifty_fox_ajax_wrapper',
   ),
 );
 $form['fox_wrapper'] = array(
    '#type' => 'markup',
     '#prefix' => '<div id="deckfifty_fox_ajax_wrapper">',
    '#suffix' => '</div>',
 );

 $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Save'),
);

 return $form;
}

```
> 0 votes

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


# Question
Title: How to update a module's view programmatically using hook_update_n?
We're writing some update functions for a custom module. This custom module provides some views:

```
/**
 * Implements hook_views_default_views().
 */
function mymodule_views_default_views() {
  $views_dir = drupal_get_path('module', 'mymodule') . '/views';
  $views_files = scandir($views_dir);
  $views = array();
  foreach ($views_files as $filename) {
    if (substr($filename, -4) == '.inc') {
      include_once $views_dir . '/' . $filename;
    }
  }
  return $views;
}

```

There are several `.inc` files from the view export ui and all those views are provided.

**Now:** some of those views should be updated. We usually just export and re-import them using the view ui (and override existing views). We wondered, **how would this be possible programmatically**? How to tell views which files to import again and override?

```
function mmodule_update_7001() {
  // what goes here?
}

```

Thanks for any ideas!

# Answer
we ended up adding the following code inside the `update_n` function:

```
  $views_dir = drupal_get_path('module', 'mymodule') . '/views';
  $views_files = scandir($views_dir);
  $views = array();
  foreach ($views_files as $filename) {
    if (substr($filename, -4) == '.inc') {
      include_once $views_dir . '/' . $filename;
      if (isset($view) && is_object($view)) {
        views_save_view($view);
      }
    }
  }

```
> 0 votes

---
Tags: 7, views, updating
---


title: Add prefix to the error message

text:
# Question
Title: Add prefix to the error message
How I can add some prefix to the all error messages?

Example:

```
This field is required!

```

and I need

```
Error: This field is required!

```

I'm using Clientside Validation module for error messages in my forms.

# Answer
> 3 votes
You can override the output by implementing theme\_status\_messages in your theme.

You could work from something like this. See $myprefix that I've added.

```
function MYTHEME_status_messages($variables) {
  $display = $variables ['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $myprefix = $type == 'error' ? 'ERROR: ' : '';
    $output .= "<div class=\"messages $type\">\n";
    if (!empty($status_heading [$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading [$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $myprefix . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $myprefix . reset($messages);
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

---
Tags: 7, webforms, forms
---


# Question
Title: Show workbench moderation comments on node view page
I use the Workbench modules suite: Users do change the state of content items (moderate) and can enter a comment about that change.

This status change history can be seen in the tab `node/node_id/moderation`.

I want to include that view at the bottom of every node view page.

Do you have any suggestions how to achieve that? Maybe the Display Suite module is useful for that (it has some computational field stuff)?

# Answer
I would achieve this using Computed field Module.

* Install Computed field module
* Create a new field of type `computed`
* In the field settings, On the Computed code (PHP)

`$entity_field[0]['value'] = $entity->log;`
* Now in manage display make this computed field visible. That's it.

Note: *This is just one way of achieving it.*

Instead of installing any modules, You can also **write tpl file** for the particular content type and display the log message.
> 1 votes

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


title: Views fields as Columns in table

text:
# Question
Title: Views fields as Columns in table
I have a content type called **Pets**, which only has title and description. In Pets there are only 3 data (set by Admin) Cats, Dogs and Mouse. User can select only from these data and cannot add more Pets.

After the Girls register in the site they can hit the checkbox to select the pets they have in their profile.

However, I want to have a Views table where I want to list the Girls' profile like: (that's the table I wanted to make)

**Name** ------ **Age** -------- **Dogs** ---------- **Cats** ----------- **Mouse**
Tina ----------- 21 ------------ Yes ---------------- No ----------------- No
Lita ----------- 27 ------------- No ---------------- Yes ----------------- Yes

When I add **Pets** title in the views it just shows as:

**Title**
Dogs
Cats
Mouse

but I want to change the fields(dogs, cats, mouse) as Columns and have **Yes** or **No** in the rows. I just tried Views Flipped Tables Module but wasn't able to do with it. any suggestions please ?

# Answer
> 1 votes
You could try to use Views aggregation.

1. Define the relationships of the fields.
2. Under Advanced \> Other enable aggregation
3. Add fields of the animal nodes and define the grouping as "count" in the field's aggregation settings.
4. Define no results bahaviour as "No" and rewrite the result as "Yes". Define 0 as "no result". All in the field settings.

Hope that helps!

cheers, j

# Answer
> 0 votes
Views Aggregator Plus does it. You don't necessary have to aggregate but it make a table as you want

# Answer
> -1 votes
In View -\> "HEADER" section is available know.. Write HTML as separate table.

```
 <table><tr>
<th>Name</th><th>Age</th><th>Dogs</th><th>Cats</th><th>Mouse</th>
</tr></table>

```

and for field settings make it as grid.. and also you require above Views Flipped Table module. It's my small suggestion.

---
Tags: 7, views
---


# Question
Title: Block not displayed on translated views page
I'm having an issue where my menu block doesn't appear on certain pages in a different language.

I have my main navigation shown in a menu block and it appears on my news view at `mysite.com/consumers/news/year/2015` and articles at `/consumers/news/article-title`

The problems is there is content in other languages and the block does not appear on `/fr/consumers/news/year/2015` nor `/fr/consumers/news/test-fr-article`

The block is not restricted to any users, roles, languages or content types. The visibility filter is set to **Only the listed pages**

```
consumers*
fr/consumers*

```

but it just doesn't show up on those specific French pages for some reason.

# Answer
Ok, I figured out the issue was there was a menu position rule for `consumers/news*` in any language appearing under a menu item in the English language menu. I set this rule to be English only then replicated it for French language items under the French menu
> 1 votes

---
Tags: i18n-l10n, blocks
---


# Question
Title: Difference between drupal_write_record and db_insert
I want to know what is the difference between drupal\_write\_record and db\_insert example : can i translate that `drupal_write_record('MyCustomTable', $Myrecord, $primary_key);` to an insert query ?

thank you

# Answer
`drupal_write_record` doesn't know by itself whether to do the insert or the update, but this is determined by the existence (or not) of the 3rd parameter: `$primary_keys` which defaults to `array()` while `db_insert` is to insert new record to database.

according to drupal\_write\_record API documentation

> **$primary\_keys:** To indicate that this is a new record to be inserted, omit this argument. If this is an update, this argument specifies the primary keys' field names. If there is only 1 field in the key, you may pass in a string; if there are multiple fields in the key, pass in an array.

Also

> Do not use `drupal_write_record()` within `hook_update_N()` functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use db\_insert() or db\_update() to save the record.
> 1 votes

---
Tags: database
---


# Question
Title: Drupal role does not appear in Views Filter
According to one post, I added Author uid in contextual filter but user role still does not appear in the filter. Any other lead help?

# Answer
By default, views of content only get access to the UID of the author. Add a relationship to the user to gain access to all the user-related fields, including your custom ones
> 3 votes

---
Tags: views
---


# Question
Title: Prevent Field From Updating On Follow Up Saves?
Use Case:

On *Page A* (Content Type A), there is a select list with options **A** and **B**

*1st Rule for Choice A*

User selects **A**, and a field "Date You Chose Letter" (a date field) captures the *current DateTime*.

*2nd Rule for Choice B*

User selects **B**, and the same field "Date You Chose Letter" (a date field) captures the *current DateTime*.

Easy enough.

But, when the User returns to *Page A*, makes some changes (and assume "A" is still selected) the 1st Rule triggers again, updating the "Date You Chose Letter" field with a new current Date/Time

The goal: Do not update the "Date You Chose Letter" field after the initial selection. So I need to set in stone.

# Answer
You can write a small custom module to lock down the original value of the field on edit, probably using hook\_form\_FORM\_ID\_alter would be the clearest way.

Difference between create new and edit node in form alter provides a decent example, try that. Basically, you have to check in the $form object for an existing node. If it's an edit form, you have a node id already; if it's a new node, you don't.
> 0 votes

---
Tags: rules
---


# Question
Title: Error in drupal "Notice: Undefined index: extension in require()..."
I am seeing this error on my page

> Notice: Undefined index: extension in require() (line 207 of /home/....../public\_html/includes/filetransfer/sftp.inc).

I have no idea from where. I tried doing search but I did not see any help. Could you please guide why this message is poping up on all the pages.

# Answer
There is not an sftp.inc in the filetransfer folder in Drupal core by default. Perhaps more information on your contributed modules in use, a custom module, Drupal version, etc. might help...
> 1 votes

---
Tags: debugging
---


# Question
Title: How to implement pager in custom page template?
in my theme I need a custom front page which displays a filtered set of news and paginated. The news are nodes with content type=news, and every one has a field "is topnews", so that only the freshest topnews is displayed at the top and all other news are displayed (with another layout) below the topnews.

So I created a page--node--9.tpl.php (which corresponds to the "empty" frontpage I created in the drupal backend), and used this code to get the topnews:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->fieldCondition("field_news_typ","value","Topnews","=");
$query->propertyOrderBy("created","DESC");
$query->range(0,1);
$result = $query->execute();

```

Then I output the topnews with its special HTML and use this code to get all other news:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->propertyOrderBy("created","DESC");
$result = $query->execute();

```

In the iterator loop I check the node-id against the topnews-node-id and output regular HTML for the news if they don't match. Now I want to add a pager to the mess so I can paginate the "normal news", but adding a `->pager(3)` to the second query before the `execute()` call does not work and a `var_dump(theme("pager"))` returns `NULL`.

So there are two questions:

a) how do I make a pager (bonus points: the end result should be an AJAX pager which loads the HTML for ordinary news!) and

b) how do I move all that logic out of the .tpl.php and instead follow the "proper" drupal way? I imagine that having the "ordinary" and "topnews" HTML in separate .tpl.php files would be helpful in implementing said AJAX paging.

# Answer
This can and should almost certainly be done entirely with the Views module (which is/will be in Drupal 8 core!). The filtering of your content by type and the value of the "top news" field can all be done with Views, along with the ajax pager. You can then use the Views attachment display type to attach those news items which do not have the "top news" box checked. You may also want to look into the Nodequeue module for ordering content in more ambiguous ways than just the most recent or whatnot, but you can also use Drupal's "sticky" setting on nodes that you want to keep at the top of the list and highlight, format them differently, etc. Views also allows you to rewrite the output of every item in the results in the UI or using tpl files. Views, my friend. Views.
> 1 votes

---
Tags: theming, paging
---