# Question
Title: How to use the admin theme for webform email
I would like my html e-mails that are sent after a webform is submitted to use my admin theme. I tried using htmlmail module but that did not work.

Thanks for any assistance.

# Answer
> 0 votes
This has been asked before. You can use a webform email template.

https://drupal.stackexchange.com/a/82501/3279

For the template file you should be able to override the theme assigned to the template by trying one of the many approaches outlined on this page:

Force a page to be rendered in admin theme (overlay mode)

---
Tags: webforms
---


# Question
Title: Embedding Javascript in Content or Block Causes Misalignment of Regions / Overflow
When embedding Javascript, the content area seems to "overflow" past its container. I am pasting an example of how embedding Tweets can cause this problem. The content shouldn't be extending into the dark green area.

I am new to Drupal, but have basic web programming experience. Should I be looking at CSS rules for this? Could it be a quirk with a theme setting? Many thanks for any leads!

For reference, right now Tweets are being embedded by pasting this code block into the content (with Full HTML enabled):

```
<blockquote class="twitter-tweet" lang="en">
<p>TEXT & SUCH FROM TWITTER</p></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

```

Note that I intentionally pasted the same tweet twice so that it would better illustrate the problem.

Edit: Interestingly, the problem seems to resolve itself if I press "alt" while in Chrome or Firefox. The page seems to re-render slightly, filling in white space on the right. Perhaps this is because CSS is usually executed before JavaScript when rendering pages? I noticed this after bring up the inspector tool, which seemed to fix the problem.

# Answer
> 0 votes
Yes, CSS is the way to go with this. I had a similar problem with a twitter feed in a block. Using Chrome developer tools, I just targeted the twitter content without making adjustments to the block.

You definitely don't want to mess with the JavaScript if there isn't an option in your script tag.

---
Tags: javascript, theming, nodes
---


# Question
Title: Is it a good idea to mix node api and entity api?
I have a custom module that depends on several contrib modules. One of the contrib modules has a new version out and has switched to using entities. The code in the custom module is using node api hooks. I update it just for the change in the contrib module, there will be one hook that is using entity api e.g. hook\_entity\_presave().

Should I update everything to use entity api or will mixing the two be okay?

# Answer
> 1 votes
As long as you are sure everything you get will always be a node, there is no problem with mixing. Nodes are entities, after all, and node hooks and functions never got "obsolete" mark. It may be even beneficial, because you are making sure other node-related modules will continue to work with your module in a way you expect them to.

On the other hand, if you are getting something from that other module, and you can't guarantee it will always return a node, you should assume it might be any other entity, and either switch to entity approach totally, or filter what you got to make sure you only use node functions on nodes.

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


# Question
Title: How to make image alternative text as required be more web accessibility?
In Drupal 7, how can I set image alternative text as required in "Body" field (CKEditor), "image" field and file upload by using "Media" module?

---- updated info for betherwisser on Aug. 20, 2014 @ 12:17pm
I know there is a file types section in Media but it is different from what you mentioned. However, It does not have the Alt text field option there. Please see screenshot for details.

ALSO, there is an option on image file for Alt Text but I'm not able to make that as required. See below screenshot.

# Answer
> 4 votes
I found one of the solution by using EIM module. I understand this is not the best solution but this module able to enable Alt field required on image field by content type.

---- updated info on Aug. 22nd 2014 @ 11:12pm The EIM module adds checkboxes for the **fields of image** editing forms by content type. Including "**Alt field required**" and "**Title field required**". See below screenshot for details.

# Answer
> 3 votes
The media module should provide a field for entering alt, title, and descriptions for images. If you enter descriptive text in that field whenever you add an image, that should appear as the alt attribute when the content is rendered.

To modify attributes of the field, such at to make it required, edit the field definition:

---
Tags: media
---


title: image slider for drupal

text:
# Question
Title: image slider for drupal
I'm making my first drupal website and I want to have a image slider on the homepage. I would like there to be a page in the backend where the end-user can upload and choose which images are in the slideshow. I looked at the nivo-slider module but it only allows the creation of one slider and what I really need are two separate sliders one for English and one for French content.

Is there a module that has this functionality already? If I wanted to create something like this myself would that involve making a module or can it be part of my theme's code somehow?

# Answer
You can use the View Slideshow module and create many blocks of slider from the content you create.

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
> 6 votes

# Answer
There are lots of other sliders for this.

Dynamic display block

Featured Content Slider

jCarousel and more
> 2 votes

# Answer
Going to make this even easier for you...

Use field\_slideshow module...

http://drupal.org/project/field\_slideshow

and follow the easy setup here...

http://zugec.com/74-create-slideshow-using-field-slideshow-module
> 0 votes

# Answer
If you like the Nivo Slider, use Views Nivo Slider to create multiple Nivo Sliders. While it shows that it only has a development version for drupal 7, I use it and have not found any problems with it.
> 0 votes

---
Tags: 7, media, javascript
---


# Question
Title: How do I add a <body> class based on the visibility of a block?
Is there a way to add a CSS class to the `<body>` tag based on the visibility of a particular block on a page?

We have certain blocks that are visible on specific pages. It would be nice to be able to change CSS styles for related content depending on whether they are present.

How can I achieve this?

# Answer
> 3 votes
You have to do it via the template\_preprocess\_html function.

Add this to your theme's template.php file:

```
function MYTHEME_preprocess_html(&$variables) {
  // dpm($variables);
  $node = menu_get_object();
  if (isset($node) && isset($variables['page']['sidebar_first']['system_navigation'])) {
     $variables['classes_array'][] = 'system-navigation';
  }
}

```

In the above code I am looking for the system navigation block in the sidebar first region and if it is there I am adding system-navigation class to the classes array. I am also checking if I am on a node page via the call to menu\_get\_object()

You will have to adapt the code to your use case.

Install the devel module, then uncomment the dpm statement. Then look under the page variable at other variables without a # in front of them.

---
Tags: blocks, theming
---


# Question
Title: How to get list of contents of a particular content type programattically
How can i get a list of contents of a particular content type for example "Basic Page". I want basic page title list in a drop down.

I want list of nodes in a drop down and while selecting each will show the content body. How can i do this?

# Answer
To create a list of content with filters (e.g. by type) you probably want to use either Views or, if you have a reason to load whole entities by ID rather than individual fields, an EntityFieldQuery.

Since there may be a large number of nodes, this type of use case usually uses an autocomplete field by entity title rather than a dropdown.

To create a dropdown, you'll want to use the core Form API to create a form, and the `#options` array for the dropdown field would be provided by either the View or EntityFieldQuery you create.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: commerce unique identification number for each item on each transaction
What options are they to achieve a unique identification number for each item sold in a commerce store.

I want to have a unique number for each item on each transaction, the number needs to be unique across all transactions.

even if I have 5 of the same line item in an order I should still get 5 unique numbers.

I have a unique id number per item per order but i don't know how to achieve a truly unique id. Would appreciate any guidance.

# Answer
> 0 votes
prepend your unique id with the order number. Since it's already unique within the order, and presuming an order number is unique, \[order-number\]-\[unique-id\] should return a truly unique value with the added benefit of being traceable since the order number would have a searchable or reference-able value.

EDIT:

Further research yielded the module Field default token

```
This module enables to use tokens as field default values.

```

Using this you should be able to create the order-ID combination (or any other combination). To prevent user tinkering, I would also suggest Field Permissions:

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

```

# Answer
> 0 votes
There a two main options there:

1. Order ID
2. Line Item ID

The Order ID is unique across all orders.

The Line Item ID is per-line item on the order and is also unique across all orders. Each line item on an order has a unique Line Item ID.

---
Tags: commerce, entities
---


# Question
Title: drupal views images with different sizes
i want create a views show last news with image and title. first image news must be 300px * 300px and other news images 150px * 150px .

something like this :

# Answer
> 2 votes
Try the Image Matrix module

> Image Matrix module provides Views style plugin and content field formatter for displaying any number of images in magazine-like layout, arranging them at different sizes so that all images fit within a defined "square box".

Sample Image from module page

---
Tags: views
---


title: node_load not show taxonomy terms

text:
# Question
Title: node_load not show taxonomy terms
i dont know why

the script node\_load(7) output is :

```
public 'field_tags' =>
    array (size=1)
      'und' =>
        array (size=2)
          0 =>
            array (size=1)
              'tid' => string '2' (length=1)
          1 =>
            array (size=1)
              'tid' => string '3' (length=1)

```

why the field tags not filled with tag title ! it only shows tid's

does this is a normal behavior of Drupal node\_laod that it only load's primary id's of relational contents like taxonomy terms ?

# Answer
Yes, that is the correct and expected behaviour. Loading every entity referenced by a node every time it loads, could potentially get very heavy on the server very quickly. That's why referenced entities are lazy-loaded (albeit manually as far as core is concerned).

To load taxonomy term entities from the tid, you can use `taxonomy_term_load()`. If you want an (arguably) slightly more pleasant experience when working with entities/fields on code, check out the `EntityMetadataWrapper` class, which is part of the Entity API module.
> 0 votes

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


# Question
Title: Add HTML Chars To Breadcrumb Kickstart 2
How does one enable html special chars (eg. ® ) in the breadcrumb?

Apparently, the Kickstart 2 uses a custom Crumbs module and I can't figure out how to override the PHP generated as with a 'regular' Drupal theme since it doesn't use the core theme\_breadcrumb() function.

# Answer
> 0 votes
There are different parts to this answer.

> since it doesn't use the core theme\_breadcrumb() function.

By default, it does use theme('breadcrumb'). But you should have a look at the settings in admin/structure/crumbs/display.

But the check\_plain() that causes special characters to be double-escaped happens in theme\_crumbs\_breadcrumb\_link() and theme\_crumbs\_breadcrumb\_current\_page(), which you could also override.

You could also look at the $double\_encode option in htmlspecialchars(), so you could use your own version of check\_plain().

This being said: Simply omitting the sanitization for all breadcrumb links is a bad idea, and potentially exposes your site to script injection. If anything coming from a non-trusted source ends up in the breadcrumb, or if people add broken html into a node title or menu link title or elsewhere, this could cause broken or malicious html on your site.

I think the better option is to just use the literal character in the node title, instead of the html entity.

---

Some general info:

With Crumbs, every breadcrumb item title is provided by a plugin. The plugins take these from menu links, from the title / title callback of the router item, or elsewhere. In most cases there is already an existing plugin which provides the breadcrumb item title you need.

Otherwise you can write your own plugins. I can give you a hint about that, but I need more information where you want the special char to show up. (I will edit the answer then)

---
Tags: commerce, breadcrumbs
---


# Question
Title: Commerce cart line item to show original price, not the one with discounts subtracted
Using Drupal Commerce Kickstart, when the user is at the shopping cart and activated any kind of discount (most of the times, a coupon) the line item price in the Cart table is updated with the discount.

I'd like to show the original price there and let the Summary describe what kind of changes the prices went through.

Here is a screenshot that might help https://www.dropbox.com/s/matvseodarii41m/Screenshot%202014-08-19%2014.46.45.png?dl=0

I'd like the top Price value to be $395 and everything else could stay exactly like this.

How can I make this happen?

Thank you!

# Answer
> 3 votes
Maybe this could help you out. https://www.drupal.org/project/commerce\_price\_savings\_formatter

# Answer
> 0 votes
I am not sure if I have understand your instruction, maybe you could rephrase it ?

In my memory the price of the line item don't change, it's just the total that got influenced. Is that a fresh install of Kickstart ? Or does the coupon apply to the product specifically ? Or to the global cart ?

Anyway coupon/discount, if they are from a commerce module then it's triggering with rules, and the shopping cart or the chekout page are just views. You should have a look to these to change theirs behaviors.

In case you are not very familiar to commerce line item, you can check RandyFay video (It's one of the guys whom made commerce), it's very well explained :

---
Tags: 7, commerce
---


# Question
Title: Using Rules module to Auto Post the content to Linkedin Account
I am using Drupal 7. I used Feeds module for content from the RSS. So i can get the content from RSS Feeds. Now **Feed** Content types automatically saved with RSS Feeds content. So now I want to auto Post the **Feeds** content to the twitter,linkedin and facebook.I am using Twitter module.

So i can Auto post the content using rules module to Facebook. Same Time I Can Auto Post the content using rules module to twitter.. I want to post this content via rules module to linkedin.. I am using Linkedin module also. But it doesn't work for rules module ? Using linkein module for particular content types only. I want to post the content for particular user linkedin account?Admin can submit the content post to the linkedin account.But i want to auto post the content for particular user account?

Is there any way to auto post the content via rules module to linkedin account. I am in critical situation.Please anyone guide to me. Thanks in advance.

# Answer
> 1 votes
Have you tried the LinkedIn Module?

> This module provides integration with the LinkedIn API. At the moment it supports the following features:
>
> * Per-user OAuth authentication between LinkedIn and Drupal Post
> * LinkedIn status from node edit form (like the Twitter module)
> * Synchronise LinkedIn user profiles with a user profile tab in Drupal

For Drupal 7 it's still dev and there may or may not be any updates coming. But it would be a good place to start.

# Answer
> 1 votes
This module does't have this functionality. You need your own rules action or use php with rules (Using embed php with rules isn't the best practice). I did some digging and found proper function to run. linkedin\_status\_set\_status($status, $node); This is function from linkedin\_status module. I have not tested it anyhow but I am 99% sure this should work. Create new module and add

```
function YOURMODULE_rules_action_info() {
  return array(
    'YOURMODULE_set_inkedin_status' => array(
      'label' => t('Set linkedin status'),
      'parameter' => array(
        'node' => array(
          'type' => 'node',
          'label' => t('Node'),
        ),
        'status' => array(
          'type' => 'text',
          'label' => t('Status'),
        ),
      ),
      'group' => t('Linkedin'),
    ),
  );
}
function YOURMODULE_set_inkedin_status($status, node) {
   linkedin_status_set_status($status, $node);
}

```

---
Tags: 7, social-network
---


title: How to network Organizations?

text:
# Question
Title: How to network Organizations?
I'm running OG 2.7.

I need to make it so ORG A can connect/ network with ORG B.

ORG A says "I'm affiliated with ORG B and want to show that connection." Currently, they would just select from an entity reference field containing a list of all ORGS, pick ORG B, and then ORG B would show up on ORG A's page as "in their network".

The problem is, ORG B may not agree that ORG A is affiliated and thus would want to approve or deny the affiliation. So I'm looking for a way to provide the same networking effect with approve/ deny functionality.

I've searched high and low for any glimpse of a way to achieve and have found nothing. Any help would be greatly appreciated, even if it's just pointing me in the right direction.

Thank you in advance

# Answer
> 0 votes
AFAIK there's no module which does this out-of-the-box for organic groups - the User Relationships module does this for users (https://www.drupal.org/project/user\_relationships).

To achieve with groups, you could set up a similar system with flags and rules, i.e. someone can flag a group as a 'friend' or whatever, when they do, a rule sends a confirmation link to the friended group and they can then say they are friends with the other group (also using a flag). But I don't see why you'd do that as every person on the site is a user so you'd need to work out who has the ability to 'friend groups'.

A general observation - if you've looked around a lot for the functionality and it's not there, and it's fairly generic functionality (like 'friending') then you may be thinking in the wrong way about the problem and the problem may be solved by thinking about it different architecturally - I've been using Drupal for 8 years now and not had issues finding modules which fit to do the stuff I want to do.

HTH

Steve

---
Tags: organic-groups
---


# Question
Title: Drupal do not publish more current notes to other browsers than admin logs in
On my site eso-meetu.de Is a node created on 13 Juli, 2014 Drupal does not publish more current nodes to other browsers than the one i uuse to admister my site.

has someone any idea how to fix this or get closer to the error that populates this issue?

There are no errors in watchdog related to this also the server logs look fine

Even if I turn off memcache ore flush all caches the resul is the same.

# Answer
I looked at your site and all I see is "File not found.". If posts aren't showing up, check the view that is creating that list of content, it might be limited by a date range.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to display a view of products that are selectable
I am working on a site that will capture site details by the sales reps. They will also use the site to order products for the customer and at the same time enter the installation criteria of the product by uploading photos and filling out text boxes.

The site will need to display all the products (50) in a table like views would on the page at once. The products will need to have a check box to select each product and a quantity to be entered. The products entered will need to be saved to the specific site that the sales rep has sold to.

In the screen shot I am using panels to layout the form. I have highlighted in red the image I am currently displaying with html in panels.

I have tried a few modules like Entity Reference / Views and Commerce but cannot find the best way to tackle this. Can anyone point me in the right direction.

Thanks. Drupal 7.31

Screen Shot http://sitetrack.com.au/images/Screen\_capture\_1.PNG

# Answer
Save a lot of head-scratching (not all though;) and use Drupal Commerce Custom Product:

https://www.drupal.org/project/commerce\_custom\_product

It's not that you can't do this with 'normal' Drupal, it's just that Commerce Custom Product is set up to do precisely what you want... so might as well use it!

HTH

Steve
> 0 votes

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


# Question
Title: Fatal Error Call to undefined function SearchApiViewsQuery():placeholder
I am using **search api** and **views** module When I add fields Indexed user **first name** and indexed user **last name** and then use field **views combine fields filter** and add those two fields I get the **undefined function error**

Basically I want to add a keyword search option to the views which is using index values of a search api Is there any other option to implement keyword search in drupal

# Answer
> 1 votes
Have you tried using the Realname module on your site? I'd suggest doing it on a copy of the site to test first as it affects quite a lot of things, but if you're doing searches for names it may help, sounds like search api is getting confused trying to join the two fields, so perhaps a different approach may help.

https://www.drupal.org/project/realname

HTH

Steve

---
Tags: views, search
---


# Question
Title: How to hide purchased commerce product with Panels visibility rules?
Goal:

I want to hide the panel pane containing a view (containing a product display) when the user has purchased the product.

Set-up:

I have a commerce product entity (not display) which is flagged using Rules on behalf of the user who purchases the product. I've created a view to verify the rule and it works, linking the Prod ID to the User ID correctly.

I then have a view:

* View type: 'Content Pane'
* Filtered on: 'Content type: Product Display'
* With a field 'Content: Product Reference' with 'Add to Cart line item type : Commerce node checkout'

The view is displayed in a panel pane and appears as a standard 'add to cart' button. This is also ok and users are able to purchase the product, (which then provides a link to some premium content).

The problem:

In panels, I have a visibility rule on the pane containing the 'add to cart' button. The visibility rule looks for the flag attached to the product and shows it only if the flag is NOT there.

However, the product is always visible.

I've also tried the same procedure, but flagging the 'product display' instead, but with the same result.

I think it's probably that I'm not using the right context or relationship, either in views, panels or both. I've tried a few, but am now at the stumbling in the dark stage. I'm pretty stumped as I thought panels visibility rules would only offer options that were available/in scope. Any help/guidance much appreciated!

---

## EDIT after comment #1 below:

I've added some screen grabs of the panels settings and output.

Panels content screen. Top-right panel shows two ways I tried to put the "add to cart" button in. The views method works, the direct panels method does not.

Relationships in Panels. I thought this would make the correct entities available to visibility rules, etc. but apparently not.

Panels output. The main content (overriden node type) is at the bottom. The "add to cart" button is on the right, and should only appear before purchase, but is always there. The contact details (left) should, and does, only appear after purchase.

Very brief diagram of entity relationships.

Further to the orginal description, the following might be useful:

* Content access module with per-node access control is used to control access to "Contact details" content.
* There is an option in visibility rules that can base visibility on access of current user to a particular bit of content, which I have tried, and seemed to target the correct content, but didn't work (so obviously wasn't).
* This suggests to me that it's a matter of getting the correct vars in scope using panel contexts.

# Answer
I solved this by using the flag module and rules.

In summary: When the customer buys access to the hidden content, a rule is triggered that flags the content author on behalf of the customer. Panels can set visibility of a pane based on whether this flag exists between author and current user viewing the page.
> 0 votes

---
Tags: commerce, panels, views, flags
---


# Question
Title: user_profile_form doesn't show profile2 information
I'm trying to modify the user\_profile\_form, but it isn't working. My regular user edit information shows up, but not my profile2 information.

```
    function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/jvectormap.min.js'; // You should place jvectormap js files into MYMODULE/js folder
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/jquery-jvectormap-mi-counties.js'; // This is US counties generated file (see #1).
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/county-select.js';
    $form['mi_container'] = array(
        '#type' => "container",
        '#states' => array(
            'visible' => array(// action to take.
                'select[name="profile_main[field_states][und]"]' => array('value' => 187),
            ),
        ),
    );
    $form['mi_container']['micounties_markup'] = array(
        '#markup' => '<div id="micounties" style="width: 600px; height: 400px"></div>', // Define own width and height.
    );

  }
}

```

Why wouldn't this work?

# Answer
You've implemented `hook_form_FORM_ID_alter()`, which only fires for a single form (user\_register\_form in this case).

If you want to catch multiple forms in a single function, you need `hook_form_alter()`:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
  ...
}

```
> 1 votes

---
Tags: forms, users
---


# Question
Title: Cannot get theme_links__system_main_menu($variables) to fire now matter what
i've added the code below to my theme's template.php file. i've cleared the cache too. but this just isn't firing no matter what. i'm not getting any errors either.

anyone have any experience with this function? i am using a sub-theme of the Adaptive theme. don't know if that has anything to do with it.

```
function spn_at_links__system_main_menu($variables) {
 echo '<script>alert("sys menu func running")</script>';
 $html = "<div class='myclass'>";
 $html .= "  <ul>";
 foreach ($variables['links'] as $link) {
   $html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
 }
 $html .= "  </ul>";
 $html .= "</div>";

 return $html;
}

```

yes my theme name is spn\_at with an underscore. i have other theme related function working just fine in the template.php file. big thanks for any help w/ this

# Answer
The Adaptive theme never calls links\__system\_main\_menu from its page.tpl.php file, hence providing an override has no effect and it falls back to theme\_links. If you want to override it you will have to provide your own theme suggestion in preprocess hook function.

Look here for more info: THE DEFINITIVE GUIDE TO DRUPAL 7
> 0 votes

---
Tags: routes, theming
---


title: How to limit one role per user?

text:
# Question
Title: How to limit one role per user?
How do I limit one role per user?

I want to see a select form field, instead of checkboxes for roles when I go to /user/#/edit.
So far I tried overwriting the `$form['account']['roles']` in template.php, replace the checkboxes with a select dropdown, but failed.

# Answer
I finally got it working! The following will change the registration and profile forms to output role selection as a select form field.

Include the following in the module:

```
//replace roles checkboxes in registration form with select field
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_register_form') {
    $form['account']['roles']['#type'] = 'select';
    $form['account']['roles']['#required'] = TRUE;
  }
}

//replace roles checkboxes in profile form with select field
function MYMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_profile_form') {
    $form['account']['roles']['#type'] = 'select';
    $form['account']['roles']['#required'] = TRUE;
  }
}

//hack for registration & profile forms, attaches the authenticated role
function MODULE_user_presave(&$edit, $account, $category) {
  if (isset($edit['roles'])) {
    is_array($edit['roles']) ? '' : $edit['roles'] = array ( $edit['roles'] => $edit['roles'], 2 => '1' );
    $edit['roles'] = array_filter($edit['roles']);
  }
}

```
> 2 votes

# Answer
You will be best using hook\_form\_alter().

You can edit the registration form & user edit form and change the type in a custom module.

```
function register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id= 'user_register_form') {
    $form['user-register-form']['roles'] = array(
      '#type' => 'radios'
      // …
    );
  }
}

```
> 3 votes

# Answer
There is a module Single User Role to assign single role to per user. This module is also compatible with role delegation module.
> 1 votes

---
Tags: 7, users
---


title: How to pull node history into a view

text:
# Question
Title: How to pull node history into a view
Is there a way to add a relationship to the node history table in views. If not, is there a module which can do it?

As it turns out the history table is already available under views as part of the content section (field 'Has new Content').

# Answer
> 0 votes
As it turns out the history table is already available under views as part of the content section (field 'Has new Content'). It is just a bit limited in use as it brings in the current user only as a user relationship.

Luckily there is a patch to fix that.

# Answer
> 2 votes
Download Views Field View module and install it.

Next create a new view that shows content revision instead of content. See image below.

Pull in the fields you want to see. See Image below.

Add a views contextual filter. See Image below.

Add the Content: Nid field as the contextual filter. Image below.

Configure the field as below.

Next edit your original view that pulls over the current content. Add a field and select the Content: Nid. Make sure to uncheck the Create Label checkbox. We just want the number. Then check the exclude button.

Now we add the views\_field\_view to the view via the field section of the view. You should select Global: View.

Now we configure it like the image below.

Save your view and now you should be able to go and see each node along with the historical data.

---
Tags: views, nodes
---


title: Bootstrap Accordion Adapting

text:
# Question
Title: Bootstrap Accordion Adapting
I'm adapting my bootstrap html theme to Drupal 7 and want to use some of the features of Bootstrap 3 theme.

In Bootstrap theme, there is a code for accordion menu like this:

```
/**
 * Implements theme_bootstrap_bare().
 */
function bootstrap_bootstrap_accordion($variables) {
  $elements = $variables['elements'];

  if (empty($variables['id'])) {
    $accordion_id = 'accordion-' . md5($elements);
  }
  else {
    $accordion_id = check_plain($variables['id']);
  }
  $output = '<div class="accordion" id="' . $accordion_id . '">';
  foreach ($elements as $id => $item) {
    $output .= '<div class="accordion-group"><div class="accordion-heading">';
    $output .= '<a class="accordion-toggle" data-toggle="collapse" data-parent="#' . $accordion_id . '" href="#' . $id . '">' . check_plain($item['header']) . '</a></div>';
    $output .= '<div id="' . $id . '" class="accordion-body collapse in"><div class="accordion-inner">';
    $output .= render($item['content']);
    $output .= '</div></div></div>';
  }
  $output .= '</div>';
  return $output;
}

```

My problem is, how can i use this code in my theme for all menus in sidebar region?

# Answer
> 4 votes
Download Views Bootstrap and create a view for the menu you want to display as accordion. For your view format choose Bootstrap Accordion

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


# Question
Title: Drupal 7: Display latest articles by an author with bio
I have a content type called "Author" and have an author field on other content types which has a reference to the "Author" CT. (e.g. News Article having an author field)

The "Author" CT has these fields:

* Title (Author Name)
* Image
* Bio

I'm using Panels on Drupal to create pages and I want to display Author pages like /author/author-name with Views, Panels, etc to display the Author name as Title of the page, author image and bio on top and the latest nodes by that author below all that bio.

I've created a view called Author with a contextual filter Content: Author but I'm unsure about how to use this on a Panel.

How do I go around this process to embrace panel pages and views to create author pages?

# Answer
> 0 votes
OK, so here's what I did.

I created a panel page with a selection rule as **Node Type = Author**.

I changed the URL pattern (pathauto) for Author content type as **author/\[node:title\]**

Then I created a view with a content pane called *Author Archives* with a Contextual Filter set to **Content: Author** and set the option *WHEN THE FILTER VALUE IS NOT AVAILABLE* to **Provide default value: Content ID from URL**. This view then looks for the author ID in the URL and then displays all the content posted by that Author.

I then dropped that view pane on the panel page that I created before with other page elements like *node being viewed: Title* for Page title as Author name, *node being viewed: Image* as the author image and *node being viewed: Body* as the Author Bio.

After saving this panel, when you go to any author node (/author/author-name) -- you'll see an author archive with Author name, image, bio and all the latest articles from the view.

# Answer
> 0 votes
If you create a views panel pane (available as a views display mode) and place that with panels, then you can accept arguments from the panels context when editing the view. The display will have panels argument options controls that other display modes do not offer.

---
Tags: nodes, panels, views, chaos-tool-suite
---


# Question
Title: Attach js file to every page w/term reference widget in Drupal 8
I have begun trying to port a small, simple module that I maintain to Drupal 8.

It was originally written (not by me) in Drupal 6 and used `hook_init()` in combination with `drupal_add_js()` to attach its scripts to every page.

Both `hook_init()` and `drupal_add_js()` have been deprecated in Drupal 8. I only really need to attach scripts to pages that have a taxonomy term reference widget (and in fact much of my logic has already been moved into a `hook_field_widget_taxonomy_autocomplete_form_alter()`.) Scripts are now added via `#attached` which I understand, but since I don't have the `$form` array or object in `hook_field_widget_taxonomy_autocomplete_form_alter()` I'm not sure where to add the `#attached` element.

I'm also not clear if `#attached` is used *instead of* or *in addition to* a \*.libraries.yml file. Does every single module with its own script.js need to declare a \*.libraries.yml file?

How do I attach my custom js file to every page with a taxonomy term reference widget in Drupal 8?

# Answer
'#attached' works for any element. You should have an element in scope in that alter hook. Also you should have a `mymodule.libraries.yml` to declare your script.
> 1 votes

# Answer
Ok, so here's what I had to do. In mymodule.libraries.yml:

```
drupal.mymodule.widget:
  version: 1.x
  js:
    js/myscript.js: {}
  dependencies:
    - core/jquery

```

In `hook_libraries_info()`: Nothing. I didn't use this.

In `hook_field_widget_taxonomy_autocomplete_form_alter()`:

```
  $path = drupal_get_path('module', 'mymodule');
  $element['#attached']['js'][$path . '/js/myscript.js'] = array('every_page' => TRUE);

```

I'm still figuring out how exactly to get jQuery working in the script itself but this attaches the javascript to the page.
> 1 votes

---
Tags: 8, entities, taxonomy-terms, javascript
---


# Question
Title: Content referencing the referenced content
I've been searching and cannot find a way to achieve this: display content referencing a content that is referenced by the content being displayed.

It may be somewhat confusing but I'll do my best to be clear:

I have two content types: 'Company' and 'Service' As you can imagine a Company provides many Services, so there is an Entity Reference field in Services that points to the Company providing it.

That's it: Service content points to Company content in a many to one relation, many services point to one company (the company that provides them)

When I display a Service, I also display the company that provides it through the Entity Reference field.

Now the tricky part is: When displaying the page for a Service, I'd like to also show (e.g. in a sidebar) the other services provided by the Company that the displayed Service is pointing to.

I'm using Panels and Views on Drupal 7.

Please note: this is not a simple 'related content block', that's what I am using to display the company providing the content or when displaying the Company content

# Answer
> 0 votes
I don't see any problem here. or any difficulties to do this.. You only need a block with services of certain company, so you can create a views block , pass company id as argument (by contexual filter), and exclude current service from it.. But, I don't think that simply assigning it to region can help you, because you will need to fetch company id from service page and pass it to view block. I think the solution will be to implement hook\_block\_info and hook\_block\_view hooks to create another block and fetch company id from service page and display it..

example:

```
function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'company_service':
        // there is multiple ways to get field value from entity. In this example I am it getting with entity_metadata_wrapper function from Entity API:

        $service_node = menu_get_object();
        $service_wrapper = entity_metadata_wrapper('node', $service_node);

        $company_id = $service_wrapper->field_company->value(); // I don't know the structure of your entity fields, that's why we assume that $service_wrapper->field_company->value() will get company_id..

        $block['subject'] = t('Company services');
        $block['content'] = views_embed_view(VIEW_NAME, DISPLAY, $company_id);
      break;
  }
  return $block;
}

```

---
Tags: entities, views
---


title: How to disable SASS in Omega 4?

text:
# Question
Title: How to disable SASS in Omega 4?
I tried to set up SASS as part of an Omega 4 theme on a VPS server, but I'm now drowning in Ruby permissions and versioning issues. It's causing far more sysadmin type work than a CSS generator is worth for this project.

The Omega 4 docs repeatedly state that SASS is helpful but not essential to Omega 4 and that you can simply write CSS the old-fashioned way, which is what I intend to do - but they don't say anything about how to stop Omega trying (and failing) to apply SASS all the time.

How can I completely disable the SASS element of Omega 4?

I can't find anything relevant in the theme settings. I've tried simply removing / renaming the `sass` folder in my subtheme and clearing caches, but I'm still getting Ruby / SASS related errors that look like this:

> Error: File to import not found or unreadable: singularitygs.

I want it to completely stop trying to do anything related to SASS.

---

From reading around, it sounds like it's common to have a Drupal production server run Omega 4 with no SASS, and for people to have SASS on their development server then upload the CSS output to production when they're happy with it. Sounds sensible. But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

# Answer
> -1 votes
If you've used `drush omega-guard`, it's not so simple.

In the end, two Drupal.SE and two StackOverflow questions later, the only way I could get Omega 4 to behave and stop freaking out trying to run Ruby every time I touched any directories was brute force, deleting every ruby-related file in the subtheme directory.

Uninstalling Ruby didn't help, so it can't have been something in Ruby. Rebooting didn't help, so it wasn't a process left running. Copying or renaming the subtheme folder didn't help, so it wasn't some system thing set to watch a directory by name. Renaming the guardfile didn't help, so it wasn't a process scanning for guardfiles, so it seemed it must be something in the subtheme folder.

I think deleting the guardfile is enough, but am not sure.

I don't know which file was the one that finally fixed it, but the only non-directory remaining files after my purge were:

Or, the short answer is, don't use Omega 4 theme and its drush commands if you're a themer. Omega 4's drush commands make system-level changes without an option to undo them: system-level changes are for Linux sysadmins, not Drupal themers.

After lots of research and two SO questions I think that the omega drush command makes these changes by accessing the inotify Linux kernel library from the PHP command line which can only be turned off by writing your own PHP CGI script to access the same api. Either that or it modifies .bashrc. If you're a themer whose skillset doesn't stretch that far into sysadmin territory, I'd advise against using the drush commands bundled with Omega 4 - at least until someone writes a `drush omega-unguard` script.

# Answer
> 0 votes
> But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

There seems to be a major misunderstanding here.

Compilation of SASS is invoked by **you**, it's not an automatic action that a server will just take upon itself to perform. Your remote VPS will not be set up to try to auto-compile SASS into CSS unless you, or someone else with access to the server, has set it up like that. The very fact that you've had to setup and install ruby on the remote serve should hopefully make that obvious.

Having that stuff on your production server is wrong anyway, you should prepare your distribution locally (read: compile SASS, minify/uglify js, etc), and sync that. That way you can never have any problems.

Your comment below the question is correct: if you don't want to compile SASS, then simply don't run `bundle exec guard`, `compass compile`, or whatever other method you're using to instigate the compilation.

If you haven't told any process to watch/compile your SASS files, then no process will be able to do so. The power is yours.

---
Tags: theming
---


title: Problem adding html to blocks

text:
# Question
Title: Problem adding html to blocks
I seem to have a problem when adding html to a block (i'm using ckk editor), if i toggle Source it loses them html id tag. If I save the Block without toggling, it works fine, but when I go back in to edit the block afterwards, it has lost the div id tag. I have attached a pic which shows the problem in 3 steps. I have it set to Full HTML throughout.

# Answer
I thinks, you must twig ckeditor config file, and set config.allowedContent = true. Please, see docs http://docs.ckeditor.com/#!/guide/dev\_allowed\_content\_rules

This links below can help you.

https://stackoverflow.com/questions/15659390/ckeditor-automatically-strips-classes-from-div

CKEDitor removes class names, even with the exception in config
> 2 votes

---
Tags: blocks, wysiwyg, theming
---


# Question
Title: My website suddenly started giving Error 200 on anything AJAX related!
The other day my website suddenly started acting weird. When using the Flag module to flag content, i get a 200 error! The content does get flagged once i refresh the page, but when clicking the flag link i get this error below.

When editing any of my Views, and say i click on the THEME INFORMATION link to modify the theme files i get another 200 error (see image).

When trying to open modal forms, same thing. This problem seems to have come out of nowhere overnight, as my site was ok, i went to sleep, next day problems. Now, i get the error on both my own theme (when say flagging content) and also on the Admin theme (Seven) when say editing a View. So i would guess that its related to a module rather than the theme? Anyone have any idea how i can go about figuring out whats causing this? My JS is not good at all so im beat here, been on this for a few days now :(

Any help would be much much appreciated.

When flagging a content:

When editing a View:

# Answer
You've made a change somewhere that is adding `<?php` to the beginning of all responses.

In "When editing a View" above, you can see this `<?php` at the beginning of the response text. Everything after the `<?php` is valid JSON and so likely the valid response.

I looked at your home page at http://www.spiritmolecule.com and it also has `<?php` added to the beginning of the HTML source. This causes the `<STYLE>` tag to be ignored. `<?php<STYLE TYPE="text/css">` gets interpreted as a single unrecognizable tag and so the CSS statement afterwards is displayed as text on the browser.

HTTP=200 normally means OK (no errors) which makes sense since it was able to respond, just it has the junk `<?php` in front. Of course, in a file processed by PHP, `<?php` means the file is about to start some PHP code instead of HTML/JSON markup. Did `<?php` get added to a file NOT processed by PHP (and so `<?php` is passed thru as response text)?

Only you can know what you did to get `<?php` added to the beginning of all responses, HTML or JSON. Do you recall any other files that you changed before going to sleep? Since the `<?php` gets added to many (or all?) responses, it is likely in a common file.

Good luck troubleshooting!
> 1 votes

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


# Question
Title: Setting #element_validate in a form (not form alter) removes original #element validation
I have an element with set #element\_validate (in hook\_element\_info) and I use this element in a custom form. The problem is that when I try to add an additional #element\_validate to the element in the form it overrides the original validate callback (the one set in hook\_element\_info).

So my question is, is there any way how to add an additional #element\_validate in a custom form without having to use form\_alter?

hook\_element\_info:

```
'ELEMENT_NAME' => array(
  '#input' => TRUE,
  '#tree' => TRUE,
  '#process' => array(..),
  '#element_validate' => array('original_validate'),
),

```

form:

```
$form['TST'] = array(
  '#type' => 'ELEMENT_NAME',
  ...
);
$form['TST']['#element_validate'][] = 'new_validate';

```

And then only new\_validate is present when on 'process' callback of the element (as well as when the form is build). When I don't set the 'new\_validate' the 'original\_validate' is still present on 'process'.

Other elements (tried a few date ones) seem to behave the same way. E.g. #element\_validate added in form declaration overrides the own element's one defined in hook\_element\_info.

# Answer
> 1 votes
You can create validate callback for the entire form and validate the element in that callback.

```
$form['#validate'][] = 'new_validate';

```
Also separate validate callbacks can be attached to 'submit' ('preview', 'cancel' etc) buttons within the form. And the element can be validated there as well.
```
$form['submit_button']['#validate'][] = 'new_validate';

```

---
Tags: forms
---


title: Multi Page Selection VBO

text:
# Question
Title: Multi Page Selection VBO
Is there a way to achieve multi-page selection. Everytime I go to the next page, my selection gets lost. Any chance to keep my selection over multiple pages?

# Answer
> 0 votes
There is a patch for same feature https://www.drupal.org/node/1207348

---
Tags: views
---


# Question
Title: How to render videos url in a template page using Video Embed field?
I have done some research on how I can render on a node .tpl page a youtube video, but couldn't find a solution. The module I am using is Video Embed field and Drupal version is Drupal 7.

When doing a print-r content I can see a list of values but I'm unsure on how I can use them to show my video.

Here is the code

```
 [field_video_url] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [video_url] => http://www.youtube.com/watch?v=dS4JR0BbKO8
                                        [thumbnail_path] => public://video_embed_field_thumbnails/youtube/dS4JR0BbKO8.jpg
                                        [video_data] => a:21:{s:5:"xmlns";s:27:"http://www.w3.org/2005/Atom";s:11:"xmlns$media";s:29:"http://search.yahoo.com/mrss/";s:8:"xmlns$gd";s:32:
                                        [embed_code] =>
                                        [description] =>
                                    )

                            )

                    )
[#formatter] => video_embed_field
        [0] => Array
            (
                [0] => Array
                    (
                        [#theme] => video_embed_field_embed_code
                        [#url] => http://www.youtube.com/watch?v=dS4JR0BbKO8
                        [#style] => normal
                        [#video_data] => Array
                            (
                                [xmlns] => http://www.w3.org/2005/Atom
                                [xmlns$media] => http://search.yahoo.com/mrss/
                                [xmlns$gd] => http://schemas.google.com/g/2005
                                [xmlns$yt] => http://gdata.youtube.com/schemas/2007
                                [gd$etag] => W/"CUACRn47eCp7I2A9XRZbFU8."
                                [id] => tag:youtube.com,2008:video:dS4JR0BbKO8
                                [published] => 2011-12-12T08:23:43.000Z
                                [updated] => 2014-08-20T08:36:07.000Z
                                [category] => Array
                                    (
                                        [0] => Array
                                            (
                                                [scheme] => http://schemas.google.com/g/2005#kind
                                                [term] => http://gdata.youtube.com/schemas/2007#video
                                            )

                                        [1] => Array
                                            (
                                                [scheme] => http://gdata.youtube.com/schemas/2007/categories.cat
                                                [term] => Tech
                                                [label] => Science & Technology
                                            )

                                    )

                                [title] => Introduction to Theming Basics for Drupal 7
                                [content] => Array
                                    (
                                        [type] => application/x-shockwave-flash
                                        [src] => http://www.youtube.com/v/dS4JR0BbKO8?version=3&f=videos&app=youtube_gdata
                                    )

                                [link] => Array
                                    (
                                        [0] => Array
                                            (
                                                [rel] => alternate
                                                [type] => text/html
                                                [href] => http://www.youtube.com/watch?v=dS4JR0BbKO8&feature=youtube_gdata
                                            )

                                        [1] => Array
                                            (
                                                [rel] => http://gdata.youtube.com/schemas/2007#video.related
                                                [type] => application/atom+xml
                                                [href] => http://gdata.youtube.com/feeds/api/videos/dS4JR0BbKO8/related?v=2
                                            )

                                        [2] => Array
                                            (
                                                [rel] => http://gdata.youtube.com/schemas/2007#mobile
                                                [type] => text/html
                                                [href] => http://m.youtube.com/details?v=dS4JR0BbKO8
                                            )

                                        [3] => Array
                                            (
                                                [rel] => http://gdata.youtube.com/schemas/2007#uploader
                                                [type] => application/atom+xml
                                                [href] => http://gdata.youtube.com/feeds/api/users/yLF5zO6ghZcOXKHRWTipvw?v=2
                                            )

                                        [4] => Array
                                            (
                                                [rel] => self
                                                [type] => application/atom+xml
                                                [href] => http://gdata.youtube.com/feeds/api/videos/dS4JR0BbKO8?v=2
                                            )

                                    )

                                [author] => Array
                                    (
                                        [0] => Array
                                            (
                                                [name] => Drupalize.Me
                                                [uri] => http://gdata.youtube.com/feeds/api/users/Lullabot
                                                [yt$userId] => yLF5zO6ghZcOXKHRWTipvw
                                            )

                                    )

                                [yt$accessControl] => Array
                                    (
                                        [0] => Array
                                            (
                                                [action] => comment
                                                [permission] => allowed
                                            )

                                        [1] => Array
                                            (
                                                [action] => commentVote
                                                [permission] => allowed
                                            )

                                        [2] => Array
                                            (
                                                [action] => videoRespond
                                                [permission] => moderated
                                            )

                                        [3] => Array
                                            (
                                                [action] => rate
                                                [permission] => allowed
                                            )

                                        [4] => Array
                                            (
                                                [action] => embed
                                                [permission] => allowed
                                            )

                                        [5] => Array
                                            (
                                                [action] => list
                                                [permission] => allowed
                                            )

                                        [6] => Array
                                            (
                                                [action] => autoPlay
                                                [permission] => allowed
                                            )

                                        [7] => Array
                                            (
                                                [action] => syndicate
                                                [permission] => allowed
                                            )

                                    )

                                [gd$comments] => Array
                                    (
                                        [gd$feedLink] => Array
                                            (
                                                [rel] => http://gdata.youtube.com/schemas/2007#comments
                                                [href] => http://gdata.youtube.com/feeds/api/videos/dS4JR0BbKO8/comments?v=2
                                                [countHint] => 17
                                            )

                                    )

                                [media$group] => Array
                                    (
                                        [media$category] => Array
                                            (
                                                [0] => Tech
                                            )

                                        [media$content] => Array
                                            (
                                                [0] => Array
                                                    (
                                                        [url] => http://www.youtube.com/v/dS4JR0BbKO8?version=3&f=videos&app=youtube_gdata
                                                        [type] => application/x-shockwave-flash
                                                        [medium] => video
                                                        [isDefault] => true
                                                        [expression] => full
                                                        [duration] => 1153
                                                        [yt$format] => 5
                                                    )

                                                [1] => Array
                                                    (
                                                        [url] => rtsp://r3---sn-5hn7su7k.c.youtube.com/CiILENy73wIaGQnvKFtARwkudRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                                                        [type] => video/3gpp
                                                        [medium] => video
                                                        [expression] => full
                                                        [duration] => 1153
                                                        [yt$format] => 1
                                                    )

                                                [2] => Array
                                                    (
                                                        [url] => rtsp://r3---sn-5hn7su7k.c.youtube.com/CiILENy73wIaGQnvKFtARwkudRMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                                                        [type] => video/3gpp
                                                        [medium] => video
                                                        [expression] => full
                                                        [duration] => 1153
                                                        [yt$format] => 6
                                                    )

                                            )

                                        [media$credit] => Array
                                            (
                                                [0] => lullabot
                                            )

                                        [media$description] => Discover hundreds more Drupal tutorial videos at Drupalize.Me/Videos.

```

I tried the code below but it doesn't work.

```
    <?php print $content['field_video_url]']['#formatter'][0]['#url'];?>

```

I had looked at his link but I'm not really understanding how it is working for him https://stackoverflow.com/questions/21282194/drupal-7-calling-video-embed-field-from-template-file

Many thanks for your help.

# Answer
If you are not trying to do anything fancy, and it is a module-provided video field, Drupal's `render` function should be enough:

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

```
> 0 votes

---
Tags: 7, theming, nodes, files
---


title: Submit webform via POST on restful API

text:
# Question
Title: Submit webform via POST on restful API
I'm trying to submit JSON data directly to a webform through some restful resource. My thought was to create a webform, enable webform\_service, and then post directly to the endpoint. This lead me to try something like this:

```
curl -vv -X POST -H "Content-Type: application/json" -d '{"title":"Contact Us", "submitted[contact_fullname]": "my name", "submitted[contact_email]": "test@example.com", "submitted[contact_message]": "test message"}' http://localhost/api/contact_us.json

```

But this does not work. In fact without the "title" value I get "title field is required", which seems to be trying to create a new webform, and in fact if I provide a title, a new webform is, in fact, created. But this is not what I'm looking to do - I'm trying to submit a new entry into the existing webform.

I thought that perhaps there's a different resource that I should be submitting form data to:

```
curl -vv -X POST -d 'submitted[contact_fullname]=sundartest&submitted[contact_email]=test@lp.com&submitted[contact_message]=test_message' http://ike.localhost/api/contact_emc.submission

```

But obviously this is wrong and I'm just guessing!

Any pointers on how I can accomplish this?

# Answer
https://stackoverflow.com/users/763010/tyler-frankenstein created a grate article that can be found here

you might also find https://stackoverflow.com/questions/10428014/steps-to-make-a-mobile-application-using-drupal-as-a-back-end-or-service/13662041#13662041 useful it has links to articles that describe services in full.

I'd also advise a couple plugins Firefox: poster Chrome: postman

http://drupal.org/node/1795770 might be more applicable it's how to login, post a comment, and loggout from curl hope it helps.
> 2 votes

# Answer
Per the comment previously, I'm just closing this with the solution that worked for me:

How to submit webform programmatically with Ajax?. It must be done with as an AJAX POST with JSON data, rather than form data.
> 0 votes

---
Tags: webforms, services
---


# Question
Title: hide a DIV on node edit form, but display on node creation
I have a field that is part of a conditional related to several field collections. As such, it needs to be rendered when adding or editing a form. However, once the node has been created, I don't want users to be able to modify the value. So on the edit page, I want to hide the DIV surrounding it.

I thought I could trick it with CSS in Panels, but add and edit use the same page and the same CSS shows in each.

# Answer
> 2 votes
As both answers above mention, there are two ways to hide a field on the node edit form:

1. via css.
2. via a form alter hook.

# CSS Solution

On the node creation page the body tag has class "page-node-add", but on the edit node page - "page-node-edit", so you can hide the field with CSS in your theme like so:

```
.page-node-edit .field-name-field-myfieldname {
  display: none;
}

```

The CSS-based solution has two main caveats:

1. An astute user will be able to unhide the field, modify it, and submit the form. There is nothing on the server-side checking to prevent submitting a change.
2. If you're using the admin theme on node edit, then adding custom css to the page is a bit more complicated than just adding this line of CSS to your front-end theme's stylesheet. You'll need to either add it via a custom module, or hack the admin theme (not recommended), or implement a custom child-theme of the admin theme.

For these reasons, I recommend the second option, **use a form alter hook to hide the desired field**:

# Hook\_Form\_Alter Solution

You should add the following snippet in a custom module enabled on your site. You may either remove the form element entirely with `'#access' => FALSE` or leave the form element visible but non-editable using `'#disabled' => TRUE`.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'MYNODETTYPE_node_form') {
    if (isset($form['#node']) && isset($form['#node']->nid)){
      // Prevent editing a field once the node has been created by
      // hiding the field entirely on the edit form.
      $form['field_MYFIELDNAME']['#access'] = FALSE;

      // Alternatively, if you want to display the field, but prevent
      // it from being edited, you can disable the form element.
      $form['field_MYFIELDNAME']['#disabled'] = TRUE;
    }
  }
}

```

This solution has no caveats really, and is probably the better solution.

# Answer
> 3 votes
Whene you go to node create page, the body tag has class "page-node-add", but on edit node page - "page-node-edit". So you can add CSS code:

```
.page-node-edit #your_div_id {display: none;}

```

# Answer
> 0 votes
You should inspect the node object to see if there is a nid, which is the primary identifier for the node table. If there is a nid, it is the edit page, and if there is no nid, then it is creation page.

Something like this:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'MYNODETTYPE_node_form) { // check for the node edit form
    if (isset($form['#node']) && $form['#node']->type == 'MYNODETTYPE'){ // check for your bundle here
      if (!isset($form['#node']->nid)) { // a node exists
        // create form

      }
      else { // no node exists yet
        // edit form
      }
    }
  }
}

```

---
Tags: 7, nodes, panels
---


# Question
Title: How can I disable a region at with the context module at all pages but the <front> (home page)
How can I disable a region at with the context module at all pages but the (home page).

I've been trying to disable a region on all pages, except the , without having to write all the paths. I can't make the wildcards `* ~` work on the `<front>` page.

In the condition field, I've tried to put alot of different combos i cant show here, because my post is deemed spam:

Imagine me using * ~ wildcards in front and in back of all the ways you can write the front page path: eks. `http//www.domain.com/` same goes for `<front>` with all the different combos.

Which one is supposed to work? Hope you get the idea.

Thanks! Best Regards Elias

# Answer
> 2 votes
Set `~<front>` in path. This will exclude only the front page.

I just tried it and it works properly.

---
Tags: 7
---


# Question
Title: javasript invoking custom module to update user response
I have created Multiple choice questions in drupal . One node (page ) has one mcq . The answers are displayed by simple radio buttons and javascript . Now I am planing to give some dynamic behavior to users . When a user click the wrong option , I want to capture the response in a custom table in drupal , having userid , nodeid . can I invoke a custom module by the present javascript which gets the userid and nid and update the table . I did some research , and found that form hook is the way to do such things ,But i have hard time understanding this. Can someone please give me right direction .

Thanks a ton !

# Answer
So, lets start from the top.

You have a table with userid, nodeid, responseid declared in a hook\_schema. This will create the table.

Then, you declare with hook\_menu a callback to capture incorrect values and db\_insert them into the table.

Then, on the form page with the multiple choice, you extend the behaviour that if the answer is incorrect upon click, it makes an ajax request with the item selected and the node id to the callback, and the callback will determine the user from the current user session, and store it in the table.

So for the content type, you will probably have a multifield for the potential answers, and a single field with the relative id for the correct answer. So if the content creator creates five answers, and the first item is the correct item, a hook form alter will need to extract and #attach the correct answer so that the behaviour on the page can pick it up, use it to determine which of the items is the correct one, extract the field id of the incorrect items and then ping it to the server.
> 1 votes

---
Tags: nodes, hooks, javascript
---


# Question
Title: custom generate pdf with the header displaying only in the first page
I'm using print module to generate pdf files from the drupal content. Here I use `tcpdf` library. The pdf files are working fine. But I want to customize the pdf files, here I want to display header in only the first page of the pdf file and the rest of the pages should display no header, but the footer should be common.

How can I customize the pdf generation? Is there a way that I need to change some thing in template files or library files. I tried to look into the tcpdf's `lib-handler` files - `print_pdf_tcpdf.pages.inc`. But I could find nothing related to restricting header.

Help is appreciated.

# Answer
This might only be possible if you are printing multiple individual nodes to one PDF by overriding the provided print themes.

A solution that will work no matter what is to add your own class that extends the PrintTCPDF class. You should ideally do this in your own module, but I will show you here how to hack the print\_pdf\_tcpdf module.

Add a new file to the folder print\_pdf-\>lib\_handlers-\>print\_pdf\_tcpdf and name it

```
print_pdf_tcpdf_no_headers.class.inc

```

Add the following contents to that file:

```
<?php

class PrintTCPDF_No_Headers extends PrintTCPDF {
  public function Header() {
    if ($this->page > 1){
      return;
    }
    parent::Header();
  }
}

```

Open the print\_pdf\_tcpdf.pages.inc file and change line 65 - 66 from this:

```
// create new PDF document
  $pdf = new PrintTCPDF($orientation , 'mm', $paper_size, TRUE);

```

to this:

```
// create new PDF document
  $pdf = new PrintTCPDF_No_Headers($orientation , 'mm', $paper_size, TRUE);

```

Open file print\_pdf\_tcpdf.info and add the following:

```
files[] = print_pdf_tcpdf_no_headers.class.inc

```

Clear your cache and your pdf's will print with a header on page 1 only.

If you want to also print other nodes with headers on all pages you will have to implement some conditional logic in print\_pdf\_tcpdf.pages.inc file which creates the class needed ( PrintTCPDF or PrintTCPDF\_No\_Headers)
> 2 votes

---
Tags: theming, files
---


# Question
Title: How to solve the warning of CAPTCHA session resuse attack
I am using captcha module (7.x, 1.0 v), When i select the image & click on upload button. Then image uploaded successfully but show this warning message also.

How to solve this issue. Please help. Thanks.

# Answer
This is a bug in CAPTCHA module you are using. Module should be compatible with core, and file upload is one of the core functionalities of Drupal. Please report this bug to module's issue queue.

But you are not helpless. As a workaround, you can use Multi-Step Registration module. Keep CAPTCHA on first step only, and put profile photo in a second step. It will keep conflicting fields on separate forms, preventing them from interfering with each other.
> 2 votes

---
Tags: 7, captcha
---


# Question
Title: Alter webform value submitted by webform
I'm using a Webform, which have 3 fields:

\- number of table (enter by user)

\- price per table (default webform value)

\- total amount to pay (calculation using formula, in webform is hidden field with no default value)

The calculation formula should be:
total amount to pay = number of table * price per table

What I want to do is add in total amount to pay after calculation and submit to webform.

I'm writing the codes as below but it does not work.

```
function my_module_validate($form, &$form_state) {
  if ($form_id == 'webform_client_form_7'){
        $form['submitted']['total']['#value'] = $form['submitted']['number_of_tables']['#webform_component']['value'] *  $form['submitted']['price_per_table']['#value'];
    }
}

```

Am I writing anything wrong?

# Answer
> 2 votes
List of issues with your code (random order):

* You are taking `$form` by value, not by reference, so all changes you make to it are local, scoped to function body only. Make it `my_module_validate(&$form, &$form_state)` if you want to have a chance to alter form - but see next points, too.
* You are passing values around using `$form` instead of `$form_state` \- things that can change in the form's lifetime belongs to `$form_state` rather than `$form` (yes, simplification, but a good starting point). In specific case of Webform module that may be needed, but you are coding against expected practice, so you should expect some difficulties when doing so.
* You are using validate hook for something that is not validation. You should rather prepend additional save handler for this purpose.
* You calculate on input. Usual practice in Drupal is to save user data "as is", and do formatting and calculations at output. It allows greater flexibility and retroactive changes if algorithm change. Again, it's not set in stone, and your situation may need other approach. It's OK, as long as you remember that's not quite the way Drupal was designed to work.

Tobias Kirsch posted nice summary, and I fully agree with it:

> What this means in your case: neither the validation nor the submission function of your form might be the right place for you to achive this. Maybe it would be better to add this calculation when the user is shown his submitted values. Honestly I think webform as a beginning might not be the right module to achieve this

---
Tags: 7, webforms
---


title: How to add a custom url to user menu?

text:
# Question
Title: How to add a custom url to user menu?
I've create a theme for user login page with different style and everything is good. When a user log in to my site in his profile he can see a user menu and add content link.
I don't want to show /user page when user click on user menu , I want to show /user/% ?
Any advice ?

# Answer
> 0 votes
You can achive it by using **Pathauto** module

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.

Reference

You can also use **Menu token** module

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).

# Answer
> 0 votes
You cannot add wildcards to menu item paths. I do not know why you want to do this as it is not neccessarry - when a logged in user clicks on "/user" he gets to his account page.

---
Tags: routes, users
---


# Question
Title: View Render output in bootstrap tab style
I have an Unformatted list style view with 2 grouping:

Grouping field Nr.1: Allestimento. Grouping field Nr.2: Descrizione

(allestimento and descrizione fields are excluded from display.)

Now I want alter the output of the tpl files to render the 2 groupin like bootstrap tabs (group n1) and nested pils (group n2). http://getbootstrap.com/javascript/#tabs

But i have no idea how can i do this... I made this by jquery but something the page not render this so I prefare do it by php... I hope you can help me.

Thanks

# Answer
> 1 votes
In my opinion it's better to create two seperate view (display blocks). One shoud be grouped by Allestimento and other one by Descrizione. Create for the page custom template and add tabs there.

# Answer
> 0 votes
I'd use the views templating system to create markup exactly how bootstrap wants it then include the javascript - you can work out which templates to override by clicking the theme information link in the view.

In practice it's the sort of thing that is a hell of a lot easier if you do a Entity field query and return a block with the correct markup from a small custom module because you'll have to fiddle about with 2 or 3 views templates to get the right output, but it should be possible with views.

---
Tags: views, theming
---


# Question
Title: Media module - CKEditor embed not working - jQuery is not defined
I'm trying to use the media module along with CKEditor in a Drupal7 build. I've enabled the modules, added the embed media button to the editor's toolbar and it works to a point - the image uploads, and styles/variations created. But I can't actually embed it as the final screen of the overlay (type in alt text, choose size etc) the buttons stay as 'fake' buttons.

Looking in console the error is Jquery is not defined.

Anyone have a fix for this?

# Answer
I worked around this by changing the admin jquery version down to 1.7 using the Jquery Update settings.
> 1 votes

---
Tags: javascript, wysiwyg, media
---


# Question
Title: Only show result when the author has a relation with the current user
You might already suspected it, I'm talking about groups. I've a content type what represents groups, the node/group is referred in a field (`field_group`) on the user entity. With this relation I want to define "permissions" in views.

For example the blog I build now displays content of all groups, no matter what group you are in, the view will always display all blog nodes. Now I want only to display the nodes what have an author with a `field_group` value equal to the currently logged in user its `field_group` value.

How should I do this in views? Some people mentioned to use contextual filters, I tried some common options but it didn't resulted like expected...

Please, let me know if you know a working setup.

Thanks ~ F.

# Answer
Found out how it should be done if you can refer to an author.

My setup:

1. add relation ship `Content : Author` as "author"
2. add relation ship `User: Group (field_group) - Appears in: user:user.` with the relation to "author".
3. add contextual filter `User: Group (field_group) - Appears in: user:user.` with at "When the filter value is NOT available" -\> "Provide default value" -\> "PHP Code" the following code: `global $user;
$data = user_load($user->uid, TRUE);
return $data->field_group['und'][0]['nid'];`
> 1 votes

---
Tags: views
---


# Question
Title: How to to get the prices centered in the node:teaser with commerce price savings formatter?
I am pretty new to drupal and I have a problem with formatting the price in my drupal shop. I am using commerce sale price -module and commerce price savings formatter -module.

In the default view, the price shows ok, in the right position. But in the view (node:teaser) it shows the prices in the wrong position. I have tried everything to get the prices centered (modifying the css), but they are still on right side all the time. I would also like to remove the line above the price if its possible.

Here is the link to my shop: http://www.oladevelopment.fi/mifuko/content/home-shop

Ant ideas on how I can get the prices shown in the way I want?

# Answer
> 0 votes
Add this in your CSS:

```
table.commerce-price-savings-formatter-prices{
width: 100%;
}

```

Also, you can add:

```
.commerce-price-savings-formatter-price .price-amount{
display: block;
padding-top: 5px;
}

```

Prices looks much better with this.

If `width:100%` doesn't work try to use `width:100% !important;` because width is already defined in module's theme.

To remove line above price add this to your CSS:

```
table.commerce-price-savings-formatter-prices tbody{
border-top:0;
}

```

Also, if it doesn't work, use `border-top:0 !important;` instead `border-top:0;`

To minimize the space between prices add to CSS:

```
table.commerce-price-savings-formatter-prices-down{
margin: 0 auto;
width: 50%;
}

```

Important part here is `width: 50%;`, change this percent to see which space you want to have, the more percent is the more space will be between prices. Again, use `!important` if doesn't work.

You can also add this to your CSS to make prices look better (to make it equal at the bottom edge):

```
table.commerce-price-savings-formatter-prices-down tr td{
vertical-align: bottom;
}

```

Don't forget to clear cache.

---
Tags: views, commerce
---


# Question
Title: Entity Reference - Not required to be in database
I have a content type `Proposal` with a entity reference field `Proposed by`. This is an **autocomplete** field that targets **Users** in the application. You can give in multiple users that are in the application.

But now I would like to give the possibility to the user that they can give in user that are NOT in the application. So they can enter email addresses from random persons, they will receive an email with a link to register. But how can I get this data? Because it's not saved when the user isn't in the application.

I tried to do this with hook\_node\_validate but this is the result I get:

```
array (size=1)
'und' =>
  array (size=4)
    0 =>
      array (size=2)
        'target_id' => string '26' (length=2)
        '_weight' => string '0' (length=1)
    1 =>
      array (size=2)
        'target_id' => null
        '_weight' => string '1' (length=1)
    2 =>
      array (size=2)
        'target_id' => string '' (length=0)
        '_weight' => string '2' (length=1)
    'add_more' => string 'Add another item' (length=16)

```

So no email address that I gave in.. Just a target\_id = null. How could I do this?

# Answer
> 1 votes
Entity Reference can reference entities only. It would be a really big hack to the module to allow non-entities to be referenced. But there is no need to.

There are dedicated modules for exactly what you are trying to do. Instead of Entity Reference, create User Relationships. Use User Relationship Invites submodule, it

> allows users to specify a relationship to a user that they invite to join the site.

Invitation is done by using e-mail, so it seems this will fully satisfy your use case.

---
Tags: 7, ajax, users, entities
---


# Question
Title: How to display a specific field instead of Title with Entity Reference
I Have two entities.

```
**Students**
Title
Body

**Cours**
Title
Body
CoursRefNumber

```

I can associate many Cours for each students. To do that, I create a Entity Reference on Cours for student.

When I create a new Student, I see al the Available Cours List. Instead of showing Title In the Listbox, How can I display the CoursRefNumber .

Thanks a lot.

# Answer
If you edit your entity reference field you'll see an "Entity Selection" fieldset section. There is a "Mode" field in there that defaults to "Simple" which just lists the entity titles. You can change that to "Views" which lets you use a custom View to display the selection.

You'll want to create a View first. Just create the View to display the fields you want. That could be the Cours Title and CoursRefNumber if you want.
> 2 votes

---
Tags: entities
---


# Question
Title: I disabled a module and my website turns into code
I am working on an old Drupal website. I disabled the Electric Embers subscribe module - to get rid of a newsletter subscription option to a dead list. Previously my website was in off-line mode, but otherwise worked. Now the website looks like pure text or code.

www.rachel.org

I checked the database and the ee-subscribe module is still enabled.

Unfortunately I didn't make a backup before turning off this module. However, I've never seen turning off a module cause so much havoc.

I currently cannot use my admin log in or do anything directly through drupal.

**Update**
When does Drupal 5 change the filename field in the system table? The problem occurs when it sets the "filename" field to "modulename.info" (or .install or .js) for 10-20 modules. I can manually set it to "modulename.module" but the fix only lasts an hour or so.

I don't think that cron is running as there are no cron jobs scheduled and I do not use poormanscron. However I don't know how to test this.

# Answer
> 1 votes
Try using Drush if you have installed it.

```
> drush dis your_module_name
> drush cc all

```

# Answer
> 0 votes
I've seen this before, although it appears your running Drupal 5.x, no longer supported nor secure. I forget why I saw it last time, but it shouldn't be hard to set straight. As Chris Rockwell indicates, check your server logs to see if there's any permissions related errors (i.e., can not access filex.php) I don't know what kind of host your own but ensure your permissions are correct. Here's *the* essential drupal page for this: https://drupal.org/node/244924

This page might nail it for you? https://drupal.org/node/172729

# Answer
> 0 votes
I went through the system table and changed all the filename values for modules to have .module extensions. So of the filenames had been set to .info, .install, or .js extensions.

Now the "website is offline" message appears properly and the admin user can login.

I still haven't figured out what caused the problem in the first place. I'd like to be able to install/uninstall modules without problems.

# Answer
> 0 votes
Make sure you did not set 0 (zero) for status field for any core modules. Because what you see on the page is all the .info file data. This means, Drupal does not work beyond reading .info file details. Also, check custom modules, if any, for debug code. Check also 'system' module.

---
Tags: 5
---


# Question
Title: Entity Form to insert data into Custom Entities
I am finally getting to Entity Construction Kit. I have built out my entity with fields, I have also set up a feed to import data into the entity.

However, I also need to build a form that will push data into the entity fields in the database. I need to know how to do this. I have search and have yet to find anything that explains or shares knowledge on how to handle this.

Has any built a form that will insert data into the database without a custom coded module?

I do not want to add data from the 'entity list' tab. I actually have a use case where I need to insert several rows of the same thing. So, for instance when doctors show up at an event yet they don't give us there information I still need to insert 5 MD's showed up for the event.

Hopefully this makes sense. Any help is greatly appreciated!!!

# Answer
> 0 votes
this sounds like something Views Bulk Operations or Rules could do, eg you make a "url link" (with Rules Link module) to call an action to add a doctor to an event. You could make more than 1 link, and ever link could have a custom `?number_of_doctors=N` value on it to update the Entity with `N` number of blank doctor entries.

---
Tags: entities
---


# Question
Title: Is there any possibility to migrate translations from Drupal 5 based project to Drupal 7 project?
I have a legacy Drupal 5 project which is currently moved to a newer Drupal 7 platform, but the old project also contains a lot of custom translation sets. So I am wondering if there is any possibility to migrate those translations to the new project?

# Answer
**Solution:** There is a build-in possibility to export translation strings for each language into .po files in Drupal 5 projects as well. Export form is available under the "admin/settings/locale/language/export" admin menu.
> 2 votes

---
Tags: migrations, i18n-l10n
---


# Question
Title: make sure hook cron is only run once a day setting
I'm building a `hook_cron` in my module but I actually don't want it to run at a maximum of once a day. Is there a Drupal setting for this or do I need to check when the last cron was run and see if that was at least 24 hours ago? How do I do this?

I'm using drupal 7

# Answer
I would check the implementation of `hook_cron()` in the Examples module.

The exact implementation is here, it's pretty straightforward!

Basically, you're setting the next execution time (in the example code as `cron_example_next_execution`) of your cron run as the very last step in your `hook_cron()` implementation, and then checking it as the very first thing.

If the variable doesn't exist, then cron will fire off your task, and then set it!
> 8 votes

# Answer
This below code will help to run the cron once in a day

```
function hook_cron() {
$cron_last = variable_get('cron_last');
if ( date('ymd', $cron_last) != date('ymd', time())) {
  //your code here
  variable_set('cron_last', date('ymd', time()));
}  }

```

variable\_get('cron\_last') is declared in common.inc
> 5 votes

# Answer
Have a look at the Elysia Cron Module. This offers you a lot of functionality for crons.
> 3 votes

---
Tags: cron
---


title: permission for user profile image

text:
# Question
Title: permission for user profile image
I would like to give permission for user profile image to registrant users only. i.e. anonymous user who visit the site can see the default profile image only in the user list and registrant users can see the real image of the user. How can I make it? Does it required changing the setting or utilizing view? Thanking you in advance

# Answer
The easy way then is to hard code this into your theme.

Open your template.php file in your theme's root folder. Add the following function in that file:

```
function MYTHEME_preprocess_user_picture(&$vars){
  if (!$vars['logged_in']) {
    // user is anonymous
    $path = variable_get('user_picture_default', FALSE);
    $style = variable_get('user_picture_style', FALSE);
    if ($path && $style) {
      $vars['user_picture'] = '<img src="' . image_style_url($style, $path) . '" />';
    }
    else {
      $vars['user_picture'] = '';
    }
  }
}

```

Replace MYTHEME with the machine name of your theme (similar to the MYTHEME in MYTHEME.info file). Then make sure you add a default picture at:

```
admin/config/people/accounts

```

The easiest is to just paste in this in the Default picture text box:

```
public://default-picture.png

```

and under the folder sites/default/files include the default-picture.png file. But that is obviously just a suggestion and you can put your picture anywhere.

If you don't see any default picture when viewing the site as anonymous then your default picture path is incorrect. Test it by creating a new user without a picture.
> 1 votes

---
Tags: media, users
---


title: Two variables in function

text:
# Question
Title: Two variables in function
I know this is my fault and lack of knowledge of php . Sorry about this .
I have a function in my `template.php` .

```
/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$vars) {

    if ($vars['node']->type == 'article') {
        // Remove Add comment link from teaser.
        unset($vars['content']['links']['comment']['#links']['comment-add']);

        // Remove login/register to comment link.
        unset($vars['content']['links']['comment']['#links']['comment_forbidden']);

  }
}

```

When i want to add a variable like **`&$variables`** to function , it does'nt work .

```
/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$variables, &$vars) {

    if ($vars['node']->type == 'article') {
        // Remove Add comment link from teaser.
        unset($vars['content']['links']['comment']['#links']['comment-add']);

        // Remove login/register to comment link.
        unset($vars['content']['links']['comment']['#links']['comment_forbidden']);
  }

    if($variables['view_mode'] == 'teaser') {

        $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__teaser';
        $variables['theme_hook_suggestions'][] = 'node__'.$variables['nid'].'__teaser';
        $temp = drupal_get_query_parameters();
        if(isset($temp['show_mode']) ) {
            $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__teaser__'.$temp['show_mode'];
            $variables['theme_hook_suggestions'][] = 'node__'.$variables['nid'].'__teaser__'.$temp['show_mode'];
        }
    }

}

```

Any advice ?

# Answer
> 2 votes
The `$variables` argument is passed by reference so you can name it whatever you want. There are two common conventions in Drupal for $variables in hook\_preprocess functions:

1. Name it `$vars`
2. Name it `$variables`

I suspect you found some code that you want to use that used `$variables`; but your existing preprocess function uses `$vars`. Simply change the references to `$variables` to `$vars` in your code above and remove the `$variables` argument:

```
/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$vars) {

  if ($vars['node']->type == 'article') {
    // Remove Add comment link from teaser.
    unset($vars['content']['links']['comment']['#links']['comment-add']);
    // Remove login/register to comment link.
    unset($vars['content']['links']['comment']['#links']['comment_forbidden']);
  }

  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser';
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser';
    $temp = drupal_get_query_parameters();
    if(isset($temp['show_mode']) ) {
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser__'.$temp['show_mode'];
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser__'.$temp['show_mode'];
    }
  }
}

```

---
Tags: theming
---


# Question
Title: Webform populate text component with encoded url values
How to populate a webform component with encoded values. For exampmple my url http://example.com/abc?submitted%5Bthis%5D=1

I tried to use token \[current-page:query:this\] but it doesnt work.

# Answer
You're on the right track. It looks like you have a syntax problem with your URL param itself. If you're trying to get the value of `?this`, remove the `sumbitted` and `[` (%5D) and `]` (%5B). So your URL with the param will look like this:

```
http://example.com/abc?this=1

```

With that URL, `[current-page:query:this]` should return `1` (or `TRUE`).
> 0 votes

---
Tags: webforms, tokens
---


# Question
Title: Enable View Library tab for Media module
The screen shot for the Media module description shows the View Library tab. On my content type I can only see the first 3 tabs Uploads, Web and Library. The final tab "View Library" is not available. This site consists of 1000's of images thus such a tab is very useful. Let me know what is the way to enable this.

# Answer
The image you've attached from the drupal.org media module page appears to be an outdated screenshot of the module. I believe you can use the "Library" tab. The "View Library" tab shouldn't be there in the latest version of the module.

There is more information on the tab title changes in this issue: https://www.drupal.org/node/1886994
> 1 votes

---
Tags: 7, search, media
---


# Question
Title: Add validation on views bulk operations form
I have a content type on which I added a custom validation that there can't be more than 7 items of that content type that is marked as 'sticky'. That validation was added on the add and edit pages through `omhm_mod_form_blog_node_form_alter(&$form, &$form_state, $form_id)` with the line `$form['#validate'][] = 'omhm_mod_form_nouvelle_node_form_validate';` and my custom validation `omhm_mod_form_nouvelle_node_form_validate`.

Now I have to make a page with views bulk operations with the same custom validation in place ... how can I do that ?

I'm trying to add the custom vbo validation `views_bulk_operations_form_validate($form, &$form_state)` to my `omhm_mod_views_bulk_operations_form_alter($form, &$form_state, $form_id)` hook with the line `$form['select']['submit']['#validate'][] = 'omhm_mod_carrousel_views_bulk_operations_form_validate';` but nothing happens.

# Answer
> 0 votes
Your `omhm_mod_views_bulk_operations_form_alter($form, &$form_state, $form_id)` takes `$form` by value, not by reference, so any changes made to `$form` are scoped to the function only. That's why `$form['select']['submit']['#validate'][]` changes nothing. It should be `omhm_mod_views_bulk_operations_form_alter(&$form, &$form_state, $form_id)`

When you fix mistake I pointed above, and it will not help, be sure to test if your hook is run at all, and if it is, then test if your validator is. It'll be needed for your next question, if you will need to ask it.

---
Tags: views
---


# Question
Title: If a search yields no results is it possible to show an alternative set of results?
I'm using Views to override a search administered through Search API. If a search yields no results is it possible to show an alternative set of results? For example, if I searched for "grettrr" and no results were found I'd get the usual "No results found" message, but underneath this message another message that says "Take a look at these instead" would display along with a set of alternative results. These alternative results could be shown based on specified taxonomy terms.

# Answer
It is possible: Under the "Advanced" panel of your view (collapsed to the right of the screen), add a new behaviour to the "No results behaviour", then add a "Global: view area" reaction. You can add any view there.
> 0 votes

---
Tags: theming, search
---