# Question
Title: Custom module to redirect anonymous users from a specific url not working (yet)
I am trying to write a simple custom module to redirect anonymous users when they want to access certain urls, but it is not working. What am I missing?

Here's the entire code:

```
function mymodule_menu_alter(&$items){
    $items['mypath/%']['access callback'] = 'redirect_and_remember_url';
}

function redirect_and_remember_url(){

    global $user;
    if ($user->uid){
            return TRUE;
        }
    else {
        drupal_goto('subscribe', array('query'=>drupal_get_destination()));
    }
}

```

# Answer
Try it like this:

```
function mymodule_menu_alter(&$items){
   global $user;
   if (!$user->uid) {
       $items['mypath/%']['page callback'] = 'redirect_and_remember_url';
   }
}

function redirect_and_remember_url(){
   drupal_goto('subscribe', array('query'=>drupal_get_destination()));
}

```
> 1 votes

---
Tags: redirection
---


# Question
Title: How to display taxonomy term reference field as a rendered entity?
I have taxonomy term reference field which are displayed as checkbox.
Each taxonomy term has two fields
1. description and other
2. price
I want the description and price field to be displayed alongside the title in field(term refrence).
How can I achieve ut?

# Answer
> 1 votes
The function `taxonomy_term_view` is for displaying a taxonomy term as a rendered entity. If not specified explicitly with an extra parameter, it uses the view mode `full`, which displays all fields, one after the other. But you can adapt that in the admin backend, and also define other view modes. So in your case, the code would be like:

```
$term = taxonomy_term_load($entity->field_term_reference);
$term_view = taxonomy_term_view($term);

```

This generates a Drupal render array. In case you want to use this in a theme context, add one more line:

```
drupal_render($term_view);

```

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


# Question
Title: Restrict Users from creating + editing higher level accounts, but still able to create + edit lower level accounts
I'm trying to restrict the permissions of a custom user role so that they can create, edit and delete lower level accounts, but not have any access to create or edit Administrator accounts.

I've already tried Administer Users by Role and User Protect, but neither of these provide the functionality I need.

User protect allows me to lock down my Admin account, but a lower level user can still create an administrator account if they want. Administer Users By Role features an permission for 'Create new users', but no permission to restrict the level of user each role can create.

What I need is for a Sub-admin to be able to create and edit sub-admin accounts, but not create or edit Administrator accounts. Is there any way to achieve this?

# Answer
I finally Discovered the Role Delegation module, which provides the exact functionality described above. Apparently Role Assign also does a similar trick.

Both, however, allow the assigning of *multiple* roles to a single user, rather than forcing a single role. This allows a user to apply multi-layered permissions to a single user.

If there's any way to force a single role choice, it would be perfect.

**Update**

I tweaked my copy of the Role Delegation module to show radio checkboxes instead of conventional checkboxes. It doesn't inherit settings like 'default role for new users', but it avoids this multi-user issue.
> 3 votes

# Answer
The Organic Groups module may do a little more than you are looking for but it does have this exact functionality.

It can be setup in such a way where users will be assigned to groups and the group admin role can administer other users of that group.

The only other way that I've actually achieved this without OG is with a custom module. You can write in your own permission and then do a form alter to hide certain users unless they have that permission. This way can be pretty clean and certainly less configuration than OG, but OG will be more flexible.
> 1 votes

---
Tags: users
---


title: Flickr style image grid

text:
# Question
Title: Flickr style image grid
I want to display a grid of pure image fields (no text). I would like for every image on each row to have the same height (not every row must have the same height) and the total width of every row to be the same as their container. Just like images appear on Flickr. Is there a module to do this? (I am using Views to generate the grid.)

# Answer
I'm assuming this is the desktop Flickr site and not mobile (mobile the galleries are all same height and width as far as I've seen) but either way you can do this in your image styles and CSS.

You would want to make your view output in the image style that you make to constrain the height and/or width.

You can find tutorials on Drupal.org or online like this one: https://www.drupal.org/node/2152441 that will help get started. After that you would use custom CSS to make it look how you want.

Note: I know this is a vague answer but the question was a little vague so maybe it will help, maybe it won't?
> 1 votes

# Answer
Edit the image field in views and add a CSS class to the field. Then set the height and or width in your CSS.
> 0 votes

# Answer
Look into theme'ing your view...

http://www.ostraining.com/blog/drupal/views-templates/

http://drupalcontrib.org/api/drupal/contributions!views!theme!theme.inc/group/views\_templates/7

https://www.youtube.com/watch?v=1Cfc11\_sb5M
> 0 votes

# Answer
Try Jusitified Grid, which is a jQuery plug-in for achieving this kind of layout.
> 0 votes

---
Tags: views, 7, media
---


title: print value of email field from a node

text:
# Question
Title: print value of email field from a node
I am using the below code to get the value of email. It works fine if the field type is "Text". But the field type used is "Email"

```
<?php
  $node=node_load(14);
  print $node->field_contact_email[$node->language][0]['value'];
?>

```

Please help.

# Answer
> 2 votes
As it's an Email field, you need to query the array for `email` not `value`:

```
$node = node_load(14);
print $node->field_contact_email[$node->language][0]['email'];

// Outputs:
youremail@example.com

```

If you're intending on rendering the email address on a page, you should look into using field\_view\_value, which will give you a string of HTML markup for a field value. The benefit of this, is that it will use the rendering function for what ever field type you supply it with.

```
$node = node_load(14);
$email = field_get_items('node', $node, 'field_contact_email');
$output = field_view_value('node', $node, 'field_contact_email', $email[0]);
print $output['#markup'];

// Outputs:
<a href="mailto:youremail@example.com">youremail@example.com</a>

```

---
Tags: theming, entities, emails
---


# Question
Title: Overriding Page Title with Contextual Links
View Path: team/member/% Contextual Input: Numeric User ID, single variable

The purpose of my view is to 1) use Views Responsive Grid to layout the page appropriately, which I have done, and 2) leverage the power of views to include future content / fields / etc. After I finished building everything and themed it the way I wanted, I found that the page title was blank.

My question: Is there a way to override the page title before the HTML is processed for this Views path? Ideally, I would like the title to be: **"\[first name\] \[last name\] | Site Name"** The user's separated first and last names are available as fields.

I appreciate everyone's help with this! (view the bottom image in a new tab, it's pretty wide)

# Answer
It can be done by placing the following code in your theme's template.php file (please note that my fields were named field\_last\_name and field\_first\_name, and my view was a page display with the view name 'user\_stuff' - so please adjust your accordingly - you can inspect your values by installing devel and uncommenting the dpm statement).

```
function MYTHEME_views_pre_render(&$view){
  //dpm($view);
  if ($view->name == 'user_stuff' && $view->current_display == "page" && $view->total_rows > 0) {
    $first_name = $view->result[0]->field_field_first_name[0]['rendered']['#markup'];
    $last_name = $view->result[0]->field_field_last_name[0]['rendered']['#markup'];
    $site_name = variable_get('site_name', 'My Site Name');
    $view->build_info['title'] = "$first_name $last_name | $site_name";
  }
}

```

There is also no need for the pager and you should rather set your view to display 1 item only. Also note that you are outputting the rendered markup (as opposed to the raw value) so there is no need to sanitise the values.
> 1 votes

---
Tags: views, 7
---


title: VBO copy Field Decimal

text:
# Question
Title: VBO copy Field Decimal
I need to copy a value of one field to a decimal filed. When I try to do this with VBO and a token \[node:price\] I get an error: Only numbers and the decimal separator. Is there a way to copy fields into a decimal data type?

# Answer
I think I would just add a quick jquery script myself that converts to the right format and autofills it into the field on the 'change' event.

I dont know your level of expertise on jquery, but if needed i can provide you a small example
> 0 votes

---
Tags: views
---


# Question
Title: Drupal 7 update.php Notice: Array to string conversion in update_results_page() when running custom module update
```
Notice: Array to string conversion in update_results_page() (line 212 of /Users/timdaff/Sites/local-quest-skills-for-life/update.php).

```

I'm getting the above notice after running update.php on the update function for my module. It is a simple update to disable some modules I no longer require. I'm not a PHP guru and it appears to me I have everything correct.

```
/**
 * Disabling modules. Implements hook_update_N().
 */
function features_controller_update_6009() {
    $return = array();
    $modules = array('views_cache_bully');
    $modules[] = 'gauth';
    $modules[] = 'oauth_common';
    $modules[] = 'oauth2_common';
    module_disable($modules,TRUE);
    $return[] = array('success' => TRUE, 'query' => 'Disabling views_cache_bully, oauth, gauth, gauth_login');
    return $return;
}

```

# Answer
Per the docs, the return value should be a string (the message to show to the user after the update) or null.

Currently you're returning an array, hence the notice.
> 1 votes

# Answer
The return value you are using is the value `hook_update_N()` would return in Drupal 6. In fact, in Drupal 6 it was common to use code similar to the following one. (See `locale_update_6000()`.)

```
$ret[] = update_sql("DROP TABLE {locales_meta}");

```

That is the only case where Drupal code actually populate the `$ret` value; in the other cases, it just returns an empty array.

```
function comment_update_6003() {
  $ret = array();
  db_add_index($ret, 'comments', 'pid', array('pid'));
  return $ret;
}

```

Drupal 7 is especting a string to be returned, or `NULL`; Drupal core code usually doesn't return a string. An exception is supposed to be raised in case of fatal errors.

```
function aggregator_update_7002() {
  db_add_field('aggregator_feed', 'queued', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Time when this feed was queued for refresh, 0 if not queued.',
  ));
  db_add_index('aggregator_feed', 'queued', array('queued'));
}

```

Keep in mind that Drupal 7 takes the update description from the comment placed on top of the hook itself; in most of the cases, that is sufficient.
> 1 votes

---
Tags: 7
---


# Question
Title: Commerce create order when registering a new account
I would like to create an order automatically when a request for a new account is done. So far I have created a rule that triggers on "After saving a new user account". The product, in this case a membership is added to the cart, but I cannot seem how to update the order with the address details of the user ? I have tried creating a new entity, Commerce Customer profile, and setting its values but these values are not added to the order? Could it be that the new profile is not "connected" to the order? How should that be done? Any ideas welcome.

Thanx,

/bo

# Answer
Perhaps the question is unclear but really I need to know what steps to include in the rules to be able to extract the user details, and add these to the created order, and then invoice the user.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Where to start with creating the theme for selling?
I have the task to create the Drupal theme from the existing Wordpress theme that will be sold on ThemeForest.

This is the first time that I'm doing something like this, up until now I was doing the themes for concrete clients according to PSD files, but I think that I need different approach for this.

Until now I usually did the themes as Omega sub-theme, can I create the Omega 4 sub-theme in this case? Can I use base theme at all or I must create theme from scratch?

I noticed that a lot of themes are based on Bootstrap, is that maybe the best way for creating the theme or you suggest some other way (I know this is maybe the question for opinion but I'm looking for the simplest way for creating the theme and Bootstrap is maybe one of the most complicated ways, so because of that I need your opinion and suggestion).

It would be really helpful if you could direct me to some page or tutorial where I can find more information and choose the way in which I will create this theme.

# Answer
Themeforest audience is mostly end users. So, it does not matter what base theme you use as long as it makes you more productive.

That said, unlike Wordpress where you just upload the theme files zip, you will have to create your own distribution with the latest stable Drupal core, the set of contrib modules you want to theme, the base theme(if you are using one) along with your theme files and assets.

I suggest you start with a base theme of your choice rather than roll out from scratch. Its a huge time saver and most base themes come with sensible defaults, especially Omega 4.
> 1 votes

---
Tags: theming
---


# Question
Title: CKEditor doesn't load when using Bootstrap theme
I'm building a fresh site on Drupal 7.26 and the main Bootstrap 3 (7.x-3.0) theme from https://drupal.org/project/bootstrap.

My site also uses Organic Groups and Display Suite, along with many other modules. CKEditor 7.x-1.13 is installed. I have not edited the code of any file in the site, including the theme files.

**Problem**: When creating new content, CKEditor does not appear in the text area with 'filtered HTML' settings.

Details:

* My basic test user with only "authenticated user" role cannot use CKEditor to create or edit content. A Bootstrap-themed textarea is all that shows for all 'filtered HTML' text fields.
* My admin user, using the Seven theme in overlay for admin and editing, can access CKEditor everywhere I expect to see it. CKEditor buttons and layout are correct.
* I switched the site default theme over to Seven, and my basic test user could use CKEditor. Once the theme was switched back to Bootstrap, CKEditor went away.
* The really odd part: CKEditor loads properly for the basic test user in Bootstrap theme for all **comment entry** forms.

The only permissions I see for CKEditor are "Administer CKEditor access" and "Customize CKEditor appearance", which are both set only to administrator.

Resources I have read that are similar:

In the source code for a create node page in my basic test user's account, I see finally, at line 273 it has the scripts:

```
<script src="http://my.site.com/sites/all/modules/ckeditor/includes/ckeditor.utils.js?n1lvkb"></script>
<script src="http://my.site.com/sites/all/libraries/ckeditor/ckeditor.js?n1lvkb"></script>
<script src="http://my.site.com/sites/all/themes/bootstrap/js/bootstrap.js?n1lvkb"></script>

```

I'm wondering if loading the CKEditor js at the end is related to this problem. Since I haven't yet dug into coding in Drupal though, I'm not sure how to correct it. I'll be creating a Bootstrap sub-theme, and maybe I can address this problem there? Any advice on this would be greatly appreciated.

As I debug this, I'll add some edits at the bottom showing what I find.

Screen captures:

---

Updates:

1. I created a Bootstrap sub-theme and activated it. For a quick test I pasted the script sources for ckeditor into the head tag. In Firebug, when viewing a Page created by Panels, the console shows this error:

TypeError: Drupal.settings.ckeditor is undefined window.CKEDITOR\_BASEPATH = Drupal.settings.ckeditor.editor\_path; on line 5 of ckeditor.utils.js

I guess that means settings haven't loaded yet.

2. I removed the pasted-in script sources. After removing them, the above settings error no longer appears. Based on the tips in the CKEditor troubleshooting, I verified that php commands to print the vars scripts and page\_bottom are in place. Now, on a node creation page, Firebug reports these errors:

TypeError: a(...).on is not a function ...a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),"object"==typeof ... bootstrap.min.js (line 9)

# Answer
> 0 votes
Solved. The I am using the development version of jQuery\_update which provides a fallback version of jQuery to use on administrative pages. -- https://drupal.org/node/1524944

It determines whether or not to use the admin version based on if the current\_path() is found in the return value of path\_get\_admin\_paths(). Unfortunately for me, `node/add` is an administrative path. So, jquery\_update kicks in and loads jQuery 1.5.2 to be compatible with the administrative task. It seems CKEditor can't operate with 1.5.2. I noted above that CKEditor loaded without issue for a comment field on a node. Since viewing a node isn't an administrative path, the page was allowed to load jQuery 1.10 which works fine with CKEditor.

For now, I added an array of paths to exempt from admin status (node/add, node/add/post, etc) and added that to the evaluation in jQuery\_update. Content creation pages now load jQuery 1.10 and CKEditor appears normally.

UPDATE: in place of the array of exempt paths, I have put in place the patch posted by muschpusch at https://drupal.org/node/2141205 . It has solved this issue.

# Answer
> 0 votes
Same issue with bootstrap theme..ckeditor not loading.

Turns out its jquery\_update module issue which is loading admin version (1.5) in my case even when user is adding/editing nodes using our custom theme and not the admin theme.

Latest ckeditor needs minimum 1.7 version of jquery

patch here solves the issue. https://www.drupal.org/node/2141205#comment-9260565

---
Tags: 7, wysiwyg
---


title: Views XML individual taxonomy output

text:
# Question
Title: Views XML individual taxonomy output
I am using Views and Views Data Export to create a page of XML data from a specific node type.

The node type has a taxonomy field with unlimited output so that views returns all the selected terms as a comma separated value.

However, I need to output the taxonomy terms as separate XML nodes rather than a comma separated list of one.

So, I currently get this output:

```
<nodes>
 <node>
  <nid>12</nid>
  <categories>Corporate, finance</categories>
 </node>
</nodes>

```

I would like to get the following:

```
<nodes>
 <node>
  <nid>12</nid>
  <categories>Corporate</categories>
  <categories>finance</categories>
 </node>
</nodes>

```

The difference being that I have two **categories** fields instead of one.

Can anyone help, please?

# Answer
In your views panel, if you edit your taxonomy field, one of the options is "Multiple Field Settings", with a checkbox for "Display all values in a single row". If you uncheck this box, you will get multiple rows, however, it doesn't group them into one node. You get the entire node repeated. The setting mentions adding a "group by" to your display, but the data export display doesn't seem to support that.

So I did a search and found this article on drupal.org: https://drupal.org/node/1187712 It looks like there have been a couple of patches created for adding group by functionality. It doesn't look like they've been integrated into the base code, but maybe one of the patches will work for you.
> 0 votes

# Answer
I had success using views\_field\_view to accomplish this. I set up an attachment display in my view that takes an entity ID (nid) as its contextual filter and outputs just the fields I wanted. Then add a views\_field\_view field to the original view, and you can output the entirety of the *other* view as an individual field.
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: How can I a revert an overridden template to its default in a sub theme?
If a base theme overrides a certain template, how can I tell a sub theme to revert to the default template instead of using the overridden template?

Of course I could simply copy the default template to the sub theme's templates directory, but that's not an ideal solution because it duplicates code and one would not take advantage of future (security?) updates in the default template.

My ideal solution would be smart enough to undo the template override provided by the base theme, but still allow for other overrides on the module level.

# Answer
I don't know if there is a perfect solution to do that without any inconvenient. Here are two proposals :

---

## Altering the Theme Registry :

To prevent the base theme from overriding a specific template, an idea would be to alter the theme registry. The theme registry array is keyed by theme hook name, and contains informations returned from `hook_theme()`.

As Clive suggested above, you can achieve this by implementing `hook_theme_registry_alter()`. Here an example of how to revert theme overrides to preserve the original "*node*" template :

```
function example_theme_registry_alter(&$registry) {
  // Default template file path we want to use (relative to the Drupal root directory).
  $default = 'modules/node';

  // In Drupal 6, we can retrieve default template path in 'theme paths' array. The 1st key should
  // contain it, however 3rd party code might already have altered the registry...
  // $default = $registry['node']['theme paths'][0]; -> should be 'modules/node'

  // Reassign the template file path and theme path accordingly.
  $registry['node']['path'] = $default;
  $registry['node']['theme path'] = $default;

  // Reassign the name of the template file if needed (could have been overriden too).
  $registry['node']['template'] = 'node';

  // You may also need to unset some preprocess functions to protect template variables as well.
  unset ($registry['node']['preprocess functions'][11], ... , ... );
}

```

**This hook is executed as the theme cache is rebuilt, you will need to clear it to see the changes.**

This solution still "allows for overrides" on the module/theme level. However, since this code will always hook *after* modules and themes, you will probably need to bypass it every time you expect a change (e.g. brought by a new overriding template), just to be sure that what you see is what you expect, and to know which theme do what in the rendered page. So, if allowing module/subtheme overrides while preventing base theme overrides is required, you may want to try the 2nd solution.

---

## Bypassing specific theme overrides :

This is not the clean way but according to your needs and how specific it is, you may prefer to directly "tweak" your base theme :

* Templates : prevent override by renaming the theme template file : in the *node* example, one would rename `node.tpl.php` to `bypass.node.tpl.php` (or whatever).
* Preprocessing : comment out preprocess functions in the base theme's `template.php`, e.g: `themename_preprocess_node()`
* CSS, JS, ... : depending on how well your theme is structured, it can be easy or simply horribly boring to comment out the "overriding" part in these files.

The inconvenient here is that you'll have to redo these 3 steps every time you update or change the base theme, but until such a case happens, this will make it easier for modules and subthemes to manage overrides without messing with the theme registry.
> 1 votes

---
Tags: theming
---


# Question
Title: How can I use the Mail System module to send one e-mail differently than others?
**Problem**

I would like to configure Mail System to use a different mailing class (one that does not format e-mail with Mime Mail) for the "welcome (no approval required)" e-mail. Mail System supports adding a **New Setting**, which takes a *module* and a *key*. For *module* I selected *Core: user module*, but what should I select for the *key*?

**Background**

On my D7 site, I am using the Mail System module to manage e-mail. By default, everything is formatted by the Mime Mail module and sent with the Smtp module.

This is great for every message except the "welcome (no approval required)" email. The reason is that I am using Logintoboggan and that e-mail contains the link to validate the account; when it is formatted with HTML (processed by the Mime Mail module), then sometimes users on mobile phones are not able to click the validation link.

# Answer
These are the keys uses by the core user module:

* 'register\_admin\_created': Welcome message for user created by the admin.
* 'register\_no\_approval\_required': Welcome message when user self-registers.
* 'register\_pending\_approval': Welcome message, user pending admin approval.
* 'password\_reset': Password recovery request.
* 'status\_activated': Account activated. 'status\_blocked': Account blocked.
* 'cancel\_confirm': Account cancellation request.
* 'status\_canceled': Account canceled.
> 1 votes

---
Tags: emails
---


# Question
Title: Skip payment method selection in Drupal Commerce
I have just installed Drupal Commerce Module with Paybox system and i wondering how can i bypass the "`payment method selection`". In fact there's only one payment method currently, so i'd like to bypass that step and proceed directly from the first step of the checkout to the last checkout step where there is the Paybox Js redirection.

Anyone already doing something similar?

Regards, Geolim4

# Answer
> 2 votes
You would have to hide the payment method checkout pane via a form alteration, because the payment method still technically needs to be selected for the redirect page to show properly. However, if you just want to remove the "Review" page since you don't need it as an intermediate step for payment method selection, you could just move the payment method checkout pane to the "Checkout" page and disable the default review checkout pane.

# Answer
> 0 votes
If you mean in the payment gateway, yes i tried, but the form seem to be block, i mean there's no way to go further as the form is blocked on the current page (checkout review).

---
Tags: 7, commerce
---


title: Changing font size to percent in theme

text:
# Question
Title: Changing font size to percent in theme
I want convert font size in existing theme from px to percentage. The theme and the CSS. Should I change font-size in body and headers only, or better to change font size in all places in CSS? What is the correct way to specify font-size in percent in this particular CSS?

```
body {
  font-family: 'Open Sans', sans-serif;
  line-height: 160%;
  color: #666;
  font-size:13px;
  background: #fff;
}

h1 {font-size: 18px;}
h2 {font-size: 16px;}
h3 {font-size: 14px;}
h4 {font-size: 13px;}
h5 {font-size: 13px;}
h6 {font-size: 13px;}

```

# Answer
> 0 votes
This is the perfect place to use `em` instead of `px` for your font sizes. Change the font size in your `body` to `font-size: 13px;` or something, whatever size you want to be your standard size font.

Then, for all of the other elements, you can use `em` to adjust the size of the font based on percent. For example, `font-size: 1.5 em;` would be 1.5x larger than the standard size of 13px, and `font-size: 0.5 em;` would be 0.5x the size of the standard of 13px;

---
Tags: 7, theming
---


# Question
Title: How to display number of posts in author pane?
I have installed Advanced Forum and Author Pane modules.

Now I want to show user's post count instead of 'Last seen':

> Last seen: 2 weeks 6 hours ago

I could not see any guide in the docs so appreciate your help.

# Answer
> 0 votes
it appears you need another module that will feed this info to author pane. This module is User stats.

Apparently though User stats has only a development release for D7 and reading through this issue, I would be reluctant to implement it on a production site. Will keep you updated if I find a better way to deal with this.

Edit: I've tested the 'post count' functionality of the 7.x-1.x-dev version of User stats and it seems to be working fine.

---
Tags: nodes
---


# Question
Title: How to configure edit permissions for Panel panes?
Is there a way to configure edit (not view) permissions for a Panels 'pane'?

I would like to add a pane for 'custom content', for example above and below a view, so that the content manager role that I've setup can edit that part of the page. Seems really simple (and essential), but haven't found anything like this.

# Answer
> 1 votes
That blog post doesn't seem to have been followed up on. There is some discussion here regarding more granular permissions for Panels IPE:

https://www.drupal.org/node/1821618#comment-9502245

I mention it would be great to be able to change role permissions for an individual pane such as 'Move', 'Edit', 'Change Style'.

# Answer
> 0 votes
Have a look at Panels IPE: The Future.

> This feature allows users to designate Panels of various types as editable in-place. This means that users with privileges are given a button at the bottom of the page which allows them to dynamically add, remove and rearrange content on that page. It's much more limited than the typical back end editor, but is much more usable by content managers who are focusing highly on the content.

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


# Question
Title: Error when enabling Administration Language for Core Toolbar
I downloaded and enabled the `admin_language` module, and in one of its configuration settings, I enabled `Use administration language for the core toolbar`, after which it threw out this error:

> Notice: Trying to get property of non-object in \_menu\_build\_tree() (line 1377 of /var/www/html/includes/menu.inc).

The line 1377 is:

```
$tree_cid = 'links:' . $menu_name . ':tree-data:' . $GLOBALS['language']->language . ':' . hash('sha256', serialize($parameters));

```

I've done this before in another project and it didn't throw an error.

# Answer
> 0 votes
I'm guessing that `$GLOBALS['language']` wasn't accessible, hence the error. I checked the permissions again and it appears I needed to enable `Select administration language` and `Use all enabled languages`, and then the error went away.

---
Tags: 7, routes, i18n-l10n, toolbar
---


# Question
Title: How to override "Create @bundlename" text?
I'm using String Overrides module to override some strings on my site. I could override some strings like

"**Performance**" to "**Clear**" (`admin/config/development/performance`)

"**Content**" to "**List of Nodes**" (`admin/content`)

But it doesn't override "**Create @bundlename**" strings like

"**Create Article**" to "**New Article**".

When I navigate to `/node/add/article` it's still showing **Create Article** as title of the 'Node add form'.

I've cleared cache, but still not working.

Any suggestions?

# Answer
> 2 votes
You can try using Node Add title module ...

> Above module allows you to configure the title of the Node Add pages and the Node Editing pages.
>
> The default title of the page where users create new nodes is constructed by Drupal in a dynamic way that not always looks good. By default Drupal concatenates the word Create and the name of the content type. The result could be something like "Create Basic page" or "Create article". This is not always acceptable.
>
> With this little module you can replace Drupal's default concatenated Node Add page title and the Node Editing page title with a title of your choice for every content type.
>
> After installing this module you will see the following two new fields at the bottom of the content type configuration form:
>
> Node Add page title Node Edit page title Use these two new fields for overriding the titles of the new node creation pages and the node editing pages.

PS : Module is in Dev Version.... Test before you use..

If you are interested to change same using code you can use drupal\_set\_title

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'mynodetype_node_form'){
         drupal_set_title('My new title');
    }
}

```

# Answer
> 1 votes
For those who may be looking to override the string for node creation using string override, you need to use the following under Original : "Create @name"

# Answer
> 0 votes
This is the reason why it doesn't work the way you want it to. StringOverrides uses the localization functions, and the localization functions do not translate @params.

# Answer
> 0 votes
In `original Column` write `"Create @bundlename"`. In `Replacement Column` write `"New @bundlename"`.

Note : This will override for all the Bundles.

---
Tags: 7, string-overrides
---


# Question
Title: Taxonomy autocomplete is empty because of access control for anonymous users
I am using Finder, a great module for autocomplete searches. I am using it for autocompleting results from a taxonomy vocabulary. The way Finder works is it uses views for the autocomplete results. My view is a simple HTML list of all the terms from the vocabulary.

The taxonomy vocabulary is restricted only to logged in users. This causes the autocomplete to return empty results. I changed access settings in the view, but that didn't help.

Can anyone suggest a way around this?

I could simply redirect from the vocabulary path, but I'm not sure it's a good solution, since the data really needs to be private. How safe is it to just redirect?

# Answer
Changing the access settings didn't help because Drupal filters out items that are not accessible by the user currently viewing the view. There are a number of ways you can deal with this:

1. Use Vocabulary Permissions Per Role which gives finer grained control of taxonomies
2. Use Page Manager (part of ctools) to override the taxonomy page either by redirecting somewhere else or making your own page in Page Manager using Panels.
3. As you suggest, use a redirection module (or Rules perhaps) to redirect users away from the page. The data will be safe as long as the rule or redirection fires before anything is rendered.
> 1 votes

---
Tags: ajax, taxonomy-terms
---


# Question
Title: Overriding the logic of "request new password" in Drupal?
I currently have:

```
function mymod_menu() {
    $items['user/password'] = array(
        'title' => 'Request new password',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_pass'),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'file' => 'user.pages.inc',
    );
}

mymod_form_alter() {
if ($form_id == 'user_pass')
    {
        // do form alterations here...
    }
}

```

The first part isn't really necessary for editing the form. But my problem isn't the form. My problem is that I don't know how to change the IMPLEMENTATION of this form. I want the change the way the entire "forgot password" process works. I have a fully integrated login solution that relies on a separate database, and I now need to be able to access that database to generate a unique forgotten password url, based on different validation rules.

What would I have to override to change the way the forgotten password page works?

# Answer
The login system uses various core functions in the core User module to process logins and forgotten passwords. You really don't want to mess with those (don't edit them).

At any rate hook\_form\_alter cannot change what those functions *do* but it can change *which function* is called.

I would suggest a custom module that

1. Creates your own separate login page with the logic you desire
2. Has a function that sends an email with the tokenised link to your new form
3. Alters the user\_pass form to call the function in #2 instead of the standard function which you can do by editing `$form['#submit']`.
> 2 votes

---
Tags: users
---


# Question
Title: How can I filter content with conditional taxonomy terms?
I have created a vocab (called like apple) that contains; iOS: iPhone, iPad, iPod Mac OSX: Mac pro, Macbook air, iMac...

Now I need/want to create a page/view; when my customer select 'iOS' from first drop-down, they can select iPhone, iPad etc. from second drop-down. And my page will be loaded with chosen values.

İt will like a multi-conditional boxes.

How can I do that, could you help me please?

Regards.

# Answer
> 1 votes
You can use https://www.drupal.org/project/shs in combination with views.

From the project page:

Views (exposed filter)

* add a new filter using the field set-up as "Simple hierarchical select" or use "Content: Has taxonomy terms (with depth; Simple hierarchical select)" as a new filter
* use "Simple hierarchical select" as selection type
* select "Expose this filter to visitors, to allow them to change it"
* enjoy ;)

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


# Question
Title: How to hide Regions and Themes in the block setting admin page?
When editing the setting of a block you can specify Themes and Regions where the block is going to be shown.

I need to hide some Region and a Theme for a given role? Can I do this?

I tried with http://drupal.org/project/block\_access but is not useful for this.

# Answer
You can do it with dirty fix:

Add body class for required role(s), and hide with css conditions.
> 0 votes

# Answer
it's a bit late but for the people in the same situation :

```
function MODULE_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == 'block_admin_configure'){
        if(in_array('your_role_name',$user->roles)){
            hide($form['regions']);
            hide($form['visibility']); //for the visibility region
            hide($form['visibility_title']); //for the visibility region
        }
    }
}

```
> 2 votes

# Answer
To change the Region & Theme output, first locate the settings in the **Block Module block.admin.inc file on line 297**. Adjust region and theme by adding logic (like an if statement for user permissions).

You can use the following snippet as a starting point or start from scratch if you are comfortable writing it from the ground-up.

Include the following snippet in a hook\_form\_alter() function.

```
$theme_default = variable_get('theme_default', 'bartik');
  $admin_theme = variable_get('admin_theme');
  foreach (list_themes() as $key => $theme) {
    // Only display enabled themes
    if ($theme->status) {
      $region = db_query("SELECT region FROM {block} WHERE module = :module AND delta = :delta AND theme = :theme", array(
        ':module' => $block->module,
        ':delta' => $block->delta,
        ':theme' => $key,
      ))->fetchField();

      // Use a meaningful title for the main site theme and administrative
      // theme.
      $theme_title = $theme->info['name'];
      if ($key == $theme_default) {
        $theme_title = t('!theme (default theme)', array('!theme' => $theme_title));
      }
      elseif ($admin_theme && $key == $admin_theme) {
        $theme_title = t('!theme (administration theme)', array('!theme' => $theme_title));
      }
      $form['visibility']['regions'][$key] = array(
        '#type' => 'select',
        '#title' => $theme_title,
        '#default_value' => !empty($region) && $region != -1 ? $region : NULL,
        '#empty_value' => BLOCK_REGION_NONE,
        '#options' => system_region_list($key, REGIONS_VISIBLE),
        '#weight' => ($key == $theme_default ? 9 : 10),
      );
    }
  }

```
> 2 votes

---
Tags: blocks
---


title: CTools CSS cache error

text:
# Question
Title: CTools CSS cache error
While viewing my Status report, I came across this error under the `CTools CSS Cache` header:

> The CTools CSS cache directory, *ctools/css* could not be created due to a misconfigured files directory. Please ensure that the files directory is correctly configured and that the webserver has permission to create directories.

How do I fix this?

# Answer
That directory must be writable by the usre that runs the web server (apache, for example).

So you have to:

* go to **admin/config/media/file-system** and check the path of public files (may be **sites/default/files**)
* check which user runs web server (on Ubuntu could be "**www-data**", on centos/fedora/redhat could be "**apache**")
* using a terminal go to the **document root** of drupal and set the owner of the directory:

> sudo chown -R www-data:www-data sites/default/files (or apache:apache)

* if you couldn't use a terminal, use the ftp client or contact your hosting provider

PS: this instruction works on \*nix servers
> 4 votes

# Answer
As the error suggests, this is due to misconfigured permissions in the `ctools` directory. A quick fix would be to create the `ctools/css` directories in ***your project directory*** (not `all` or `default`) and set their permissions to `777`.

However, this is not a good fix because it doesn't follow the Principle of least privilege. So let's get to the root of it.

This problem likely arose when you created or copied the directory from somewhere into your project directory. Doing so will set the owner of the directories as your user. Normally, the `ctools/css` directory is created under the `www-data` user, and thus, we can simply `sudo chown www-data:www-data ctools` and `cd ctools; sudo chown www-data:www-data css` (on a linux machine)
> 2 votes

---
Tags: chaos-tool-suite, files
---


# Question
Title: How to Install multiple version of Drush?
I have Drush 6 installed in my system.

I need to install Drush 5 too (hosting doesn't support Drush6), how do I install Drush5 without uninstalling Drush6 and use both of them simultaneously, Drush6 for local development and Drush5 for SFTP.

# Answer
> 3 votes
In your .bashrc:

```
alias drush5=/path/to/drush5/drush
alias drush6=/path/to/drush6/drush

```

With this, `drush5` will give you Drush 5, `drush6` will give you Drush 6, and `drush` will give you whichever of these appears first on your `$PATH`.

Rename your aliases to suit.

# Answer
> 1 votes
One option on Debian/Ubuntu is to use the "alternatives" system to register multiple different versions as alternatives, and switch between them. That way, the command `drush` can be switched to point to different versions, without having to change any scripting you've done elsewhere.

However, this isn't as useful as you'd think, as switching between them is still a bit cumbersome: `update-alternatives` requires you to provide the full path to the version of Drush you want to make temporarily "primary".

With that in mind, this blogpost (disclaimer: my own) explains how to script the alternatives system to switch between Drush versions using something like `switchdrush VERSION` and sudo access. If you're not on a Debian-based \*nix, then that scripting should be adaptable, to instead just change any `/usr/bin/drush` symlink.

# Answer
> 1 votes
Thank you J-P!

The link to http://www.jpstacey.info/blog/2014-04-07/switching-between-drush-major-versions.html helped me a lot on Ubuntu.

However, you have to adapt the grep-command in case you are using a localized (non-English) OS/Terminal.

In my case (Ubuntu 14.04 LTS - German) i had to replace

```
command=`update-alternatives --display drush | grep "priority $version" | awk

```

With

```
command=`update-alternatives --display drush | grep "Priorität $version" | awk

```

---
Tags: drush
---


title: Add form to cart page

text:
# Question
Title: Add form to cart page
I'm wanting to add a custom form field to the DC cart page - **not** the *add to cart* page but the cart page. It wants to be specific to the cart rather than specific to individual line items which will then save to the order information to be available later. I've looked at dozens of questions and answers on the internet and done some digging of my own and haven't figured out even what would be the right hook to use. Any suggestions?

# Answer
> 1 votes
Use hook\_form\_alter() on its form ID. The form is built via Views, and I can't recall the ID off the top of my head, but any time I don't know the ID to use I just use a general hook\_form\_alter() and print out the form ID of every form on the page. You'll find it fast.

Depending on the type of data you're collecting and how you need it stored, it could be that you add a field to the base order type and then populate it based on the value of whatever field you add to the shopping cart form.

---
Tags: 7, commerce
---


# Question
Title: Drush and mysql database (with MAMP) connection problem
I have a problem running some drush methods involving database connection. I run the free version of MAMP.

If I run methods like ***si*** or ***pml*** I get no problems

But if I run the ***drush archive-dump*** method I get this error message:

```
Database dump failed.

```

look the capture:

# Answer
> 5 votes
The problem seems to be in mysql.sock location. I found a solution from here: http://www.razorsql.com/docs/support\_mysql\_mac\_mamp.html

## Short answer

> One way to change the socket location is to edit the MAMP start and stop scripts so that the mysql.sock location is the default. This can be done by editing the following files:
>
> /Applications/MAMP/bin/startMysql.sh
>
> /Applications/MAMP/bin/stopMysql.sh
>
> Replace
>
> socket=/Applications/MAMP/tmp/mysql/mysql.sock
>
> with
>
> socket=/tmp/mysql.sock

## How I solved the problem

I did

```
drush ard -v

```

to see what was going on.

```
Executing: mysqldump --result-file /tmp/drush_tmp_1352892897_50a381e13a71d/... --no-autocommit --single-transaction --opt -Q  ... --host=localhost --user=... --password=...
Database dump failed.

```

So I copied the mysqldump command and copied it to the command line and hit enter.

```
mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect.

```

After this I tried several methods to solve the socket issue after I found the solution from www.razorsql.com.

# Answer
> 4 votes
I had a similar issue, specifically when trying to use drush to pull a remote db and load it locally (drush-sql-sync). The error that I was getting was:

```
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

```

What is happening here is that (at least in my case) there is no socket file at that location. The easy solution is to create a symlink:

```
cd /tmp
ln -s /Applications/MAMP/tmp/mysql/mysql.sock ./mysql.sock

```

The effect of which is to route all calls for /tmp/mysql.sock to the appropriate MAMP specific path.

# Answer
> 0 votes
I had the same issue after upgrading OSX. I tried several things, none worked for me. I had all the symbolic links already created in the first place, I kept getting the following error:

> Drush was not able to start (bootstrap) the Drupal database.

I thought it was a mysql problem, but the following worked for me: I edited my `~/.bash_profile` once again, adding these lines:

```
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.4.4/bin:$PATH"

export PATH
export DRUSH_PHP="/Applications/MAMP/bin/php/php5.4.4/bin/php"
export PATH=/usr/local/bin:$PATH

```

Restart the terminal and voila - drush works like a charm again. Thanks to C13L0.

---
Tags: drush
---


# Question
Title: How do I call a function in a JavaScript file?
I have included a javascript in the module "myid" I've been developing in drupal by using this code:

```
function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");
}

```

This is my Javascript file "myid.js":

```
function myid_js_start(){
    alert("hello world");
}

```

Below is the code that creates a button that invokes an alert function:

```
$form['add_button'] = array(
    '#type' => 'button',
    '#value' => 'Take a picture',
    '#attributes' => array('onclick' => 'myid_js_start()'),
);

```

I dont know where did I go wrong. The button shows up but doesn't fire any alert function. Can anyone help me with this?

# Answer
> 1 votes
Try to write JS in drupal way like this:

```
(function($) {

    Drupal.behaviors.xyzModule = {
        attach: function(context, settings) {

//            $('.test', context).click(function() {
//                $(this).next('ul').toggle('show');
//            });

//myid_js_start();
            function myid_js_start() {
                alert("hello world");
                //console.log(' Hello');
            }

        }
    };

})(jQuery);

```

For More info visit here

# Answer
> 0 votes
This:

```
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");

```

Needs to be:

```
drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");

```

Note the forward slash before the path to the js file

---
Tags: forms, javascript
---


# Question
Title: Access only to home page for no authorized users
Anonymus should only have access to home page and see all content there. When anonymus click any link, he should be redirected to login page.

```
function template_preprocess(&$variables, $hook) {
  $access_pages = array('dp/admin', 'user/login', 'user/password');
  if (!$variables['is_front'] && !$variables['logged_in'] && !in_array($_GET['q'], $access_pages)) {
    drupal_goto('dp/admin');
  }
}

```

Is this right? Is there better way?

# Answer
> 1 votes
If your permissions are set perfectly, then installing this module may prove helpful in this case

Redirect 403 to User Login (r4032login)

---
Tags: redirection
---


# Question
Title: how to create user view with last login zero or never logged in
I am trying to create user view for those user who never logged in. For this i need a filter as last login is equal to zero. Any body knows how to select filter as last login is zero.

When i used Operator equal to zero it shows a message Invalid date format.

# Answer
> 1 votes
Yes, after long search i got a suitable answer If i put in operator is equal to value 1970. it gives me result basically 1970 consider as a zero value.

# Answer
> 0 votes
You can go for:
filter: last login
is less than: 1980-01-01
It should work

---
Tags: users, views
---


title: Ajax error when installing

text:
# Question
Title: Ajax error when installing
When installing Drupal 7.31 in the first page, I can't install with the following error message.

> An AJAX HTTP error occurred,HTTP Result code 2: debugging information follow, Path:htp://localhost/install.php?
> profile\_standard&locale-en&op\_do statustext: Unknown ResponseText:
>
> error page show : Fatal error:call to undefined function node\_types\_rebuild() in C:/APM\_setup/htdoc/includes/common.inc on line 7512
>
> line 7511---entity\_info\_cache\_clear(); 7512---node\_types\_rebuild(); 7513---//node\_menu() defines menu items based on node types so it needs to come 7514---//after node types are rebuilt. 7515---menu\_rebuild();

Every time i delete and again try to install this always it's same.

# Answer
> 0 votes
I had problem like this. You need to increase memory\_limit.

**For XAMPP:** you can change it globaly in php.ini (in xampp located in '\xampp\php\php.ini')

> memory\_limit = 8M // search for this "memory\_limit" and adjust it by your needs (min 64M)

**For WAMP:** right click on the WAMP icon, then navigating to the PHP folder/menu-thingy and selecting php.ini, and find memory\_limit (like on XAMPP)

After you made a change restart Apache and try to install Drupal from the beginning.

---
Tags: 7, installation
---


title: Decrypt automatic created drupal url

text:
# Question
Title: Decrypt automatic created drupal url
In my project url encryption and decryption are compolsary,so help me How to decrypt drupal automatically created url (eg: "q=content/testpage")?

# Answer
I'm not sure what you exactly want to do, but if I understood right you can do this with Pathauto and Global Redirect modules, so:

1. Go to *\[your-domain-name\]/admin/config/search/clean-urls* and make sure that Clean URLs is enabled
2. Install and enable Pathauto module and go to *\[your-domain-name\]/admin/config/search/path/patterns*, there you can fill in settings for your paths
3. Install and enable Global Redirect module, no additional configuration is required

URLs will be updated on cron run.
> 1 votes

---
Tags: 7, hooks, uri
---


title: Rollback entire server but keep content

text:
# Question
Title: Rollback entire server but keep content
Until recently I've only been doing mainly superficial support on a website. But now the question has been asked to revert the server the website runs on, to a few months ago. The website is Drupal, but runs in IIS with a Microsoft SQL database instead of MySQL. Now, I've never done a backup/restore procedure from a website, nor do I know what the risks are or what needs to be done. I was looking at https://www.drupal.org/node/22281, but I still don't feel wise/secure enough to know what I'll be doing. The main problem for me is; I need to keep the content of the website as it is now, but I don't know for certain where this is located/stored. The database? Changes in files haven't been done to the website as far as I'm aware, so I hope this won't amount to a problem.

Basically what I'm asking is; is there a way to be certain that a rollback of an entire server and then a restore of content wouldn't amount to any difficulties?

Any general (or specific) information would be much appreciated, Thanks

# Answer
You can find the database information in your settings.php file.

A simple export of that database should allow you to capture the site as it exists currently, then when you get the server reconfigured you can simply import the exported database.
> 0 votes

---
Tags: database, backups
---


# Question
Title: How to import nodes and their translations from a csv using Feeds?
Is there a way to provide the original and translated values of the title and the body in a csv for example, and the Feeds module to produce the translated nodes automatically (and synced with the original nodes - \[tnid\])?

I have tried using "Feeds: Entity Translation" but with no success.I have set the fields to be translatable but i don't see the translation fields available in the node-importer.

Any advice on the best practice on this?

Should i better go with a Migrate implementation? All ideas/implementations welcome!

Thanks.

# Answer
> 0 votes
While Feeds:entity translation should be awesome when finished you can try this Solution

> I created two feed imports. I forced the language field for each one. Two separated nodes were created for each content (one in each language) but it didn't links the translations. So I used a SQL query to finish the job, it's based on the feeds uuid :

I think he meant: based on guid not uuid

---
Tags: 7, feeds, i18n-l10n, importing-exporting
---


title: Using own Bootstrap 3 files

text:
# Question
Title: Using own Bootstrap 3 files
I would like to know how I can host my own Bootstrap 3 files (js, css) in the Drupal 7 Bootstrap 3 theme. I know I can deactivate CDN hosting inside the theme settings, but I can't get it to work. Can anyone of you guide me through?

# Answer
> 2 votes
I've had success utilizing the Bootstrap Library module.

> This module loads via libraries the Bootstrap files installed on /sites/all/libraries/bootstrap, regardless of the theme you are using. It does nothing else.
>
> When using Bootstrap themes is particularly helpful to:
>
> 1. Correct Browser Support issues, installing respond.js.
> 2. Update your Bootstrap version over your current theme options.
> 3. Just to avoid CDN files loading.

---
Tags: 7, theming, cdn
---


# Question
Title: Exclude a page from indexing on a per page basis
I would like to be able to remove a page from search engines (external and drupal). I want to add a checkbox on the content type to be able to specify which page should or should not be indexed.

My plan is to check via the hook\_node\_save if the checkbox is checked, and if so, edit the robots.txt to add a Disallow via the provided url. If the box is unchecked, I remove it from the robots.txt

This is complicated though. Does anyone has a better solution ?

Thanks,

# Answer
> 1 votes
I recommend installing the Metatag module. Once installed you will have a checkbox: **Prevent search engines from indexing this page** located on every node under Meta tags -\> Advanced.

# Answer
> 0 votes
Have a look at the noindex module. It should allow you to do what you want.

That is per-page configuration of indexing via the "robots" meta tag.

---
Tags: search
---


# Question
Title: Metatag: How to programmaticaly set a node's canonical URL
I am using the metatag module for defining several meta tags. As a default value, canonical tags use `'[current-page:url:absolute]'`. Now I want to create a module that sets the value of the canonical tag to some other url.

Setting `$node['metatags']['und']['canonical']['value']` to another string doesn't seem to work. Unfortunately, I also can't use an entity\_wrapper, since metatag doesn't define information for its custom fields, which is needed by entity\_wrapper.

Is there something else I could do?

# Answer
look into the hook: metatag\_metatags\_view\_alter().

```
/**
 * Implements metatag_metatags_view_alter()
 */
function mymodule_metatag_metatags_view_alter(&$output, $instance) {
  // Add Custom logic to overwrite the canonical tag here.
  $canonical = 'http://www.mysourceurl.com';

  // Alter canonical tag.
  $output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'] = $canonical;
}

```
> 3 votes

# Answer
The metatag module provides server hooks. You can find them in the metatag.api.php file inside the module.

The one you need is hook\_metatag\_metatags\_view\_alter.

```
/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 * @param array $options
 *   All of the options used to generate the meta tags.
 */
function hook_metatag_metatags_view_alter(&$output, $instance, $options) {
  if (isset($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'])) {
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = 'O rly?';
  }
}

```
> 2 votes

---
Tags: uri, meta-tags
---


title: Drupal 7 to D7 Migration

text:
# Question
Title: Drupal 7 to D7 Migration
I wan to migrate taxonomy terms from a D7 install to another. The taxonomy terms have fields added to them and also translations. Drupal Migration module would be the only option?

# Answer
> 0 votes
Use Taxonomy CSV import/export module. I used it once, works great...

# Answer
> 0 votes
I would look into using the Feeds module for this. Maybe this article can help.

# Answer
> 0 votes
Any of these following modules would help you to migrate your taxonomies:

Here is an article that explain how to do it without a module (manually).

---
Tags: 7, migrations
---


title: SQL replace() function in PDO

text:
# Question
Title: SQL replace() function in PDO
I'd like to convert the instructions from this answer into a general script that can be reused across projects.

I'm wondering how these commands can be written in Drupal 7 PDO format:

```
UPDATE `system` SET filename = replace(filename, 'sites/all/modules/contrib', 'profiles/distroname/modules/contrib');

```

Is the mysql replace function something generic to all SQL, or is it mysql specific? I understand this is an expression, but I'm not clear on how to use the PDO expression syntax in this case.

What are the advantages of writing it PDO, as opposed to just a simple `db_query()` with the sql query from above? In PDO, will this truly be db agnostic?

# Answer
> 2 votes
Would it be something like this?

```
db_update('system')->
  expression('filename', 'replace(filename, :old, :new)', array(
    ':old' => 'sites/all/modules/contrib',
    ':new' => 'profiles/distroname/modules/contrib'
  ))
  ->execute();

```

---
Tags: database
---


# Question
Title: How do I load all images and thumbnail for a multivalued image field in node view?
I have a content type with a multivalued image field. I want to make the image field render with one main image and all the thumbnail. When any of the thumbnail is clicked then it's respective image takes over the main image section. Something like amazon product images.

What I have thought about so far is to create a preprocess function for the field to load all images along with all the thumbnail then, with custom CSS and JS, customize its rendering, is this the right way to go about it? And how do I load all the thumbnails for the image field in node view?

# Answer
> 1 votes
You can use galleryformatter and then a bit css if you want

---
Tags: theming, entities, nodes, javascript, media
---


title: How to hack a module which has not API

text:
# Question
Title: How to hack a module which has not API
I am using the module Print for print/mail node's content. However, I have problems to send email. I want to hack the module, so it will use the PHP class PHPMailer instead, and will hard-code the sending of the email. Everythings works perfect, but the situation is that there is no API and I have hard-coded directly in the module, so when the module is upgraded, I will lost my coding. Is there any way of making a hook of the desired function so I will get the same working but will still be able to upgrade the module without problems? I will accept other solutions, but the question is more general (I maybe would need to do something similar with other modules which do not provide API in the future). Thanks!!!

# Answer
> 5 votes
Usually there are two situations: your hack may be useful for other users or your hack is very very custom and is not likely to be useful for other users.

In the second case you can go with arpitr answer.

If your hack can be useful for other users (like this case) you should open a new Feature request or bug issue in the module's issue queue where you can share your hack as patch to the module. This way:

* Other people can evaluate and discuss your code and solution pointing out any mistakes or bugs you are not aware of, improving your changes.
* Maintainers can commit your patch to the module so in next upgrade you don't lose your changes as changes are included in the new release.
* Any ohter module's user can benefit from the new feature.

The drawbacks is that your code must fit the general usage of the module, so your feature should not break others module's functionalities or usages. This may imply more work but benefits are good enough.

# Answer
> 4 votes
What I usually do, if I am hacking a module and the change is quite small, I create a patch. Patch is simply a difference of two states of code, giving you clear picture of what changes were made. Different ways can be used to create a patch. You can use the patch tool or you can also use git.

Keeping all patches file under sites/all/patches always help in quickly getting the alteration back in working after any code update. A must read by Angie will give you more insight on this.

In case if I am hacking a module and changes are heavy enough, in that case I keep such module in custom directory, being aware of that I am not interested in update path for such module. This is personal choice though :)

# Answer
> 3 votes
The Drupal hook system allows you to hook into other modules, even if they don't have an API of their own.

For example, every mail that you send with Drupal can be changed with hook\_mail\_alter.

Now your problem in specific, even has a module that changes the mailer to PHPMailer: https://www.drupal.org/project/phpmailer . The Drupal 7 version is still in dev, but even if it doesn't work like you want, you can learn a lot from the code. This module does not require you to hack core to change the mailer.

Another module you might be interested in is https://www.drupal.org/project/smtp. It allows you to send mails with an external SMTP (like GMail), if you are having trouble sending mail from your the webserver.

---
Tags: 7
---


# Question
Title: No HREF on Content menu on admin toolbar
I have a very odd problem that cropped up yesterday on one my sites. The site is Drupal 7 with the stock toolbar module installed. When you access the site for the first time logged in as an admin user, the Content menu link does not work. All the other menu links work fine. When you go to the Structure page next, the Content menu works correctly.

Looking at the source, the A tag for the Content menu does not have an HREF attribute. All the other menu links do. When you go to the Structure page, the Content menu has an HREF attribute as expected.

I looked at the menu\_links table and everything looks good.

I ran debug through the toolbar.module and the array data is correct.

I ran debug into the toolbar.tpl.php file calling render($toolbar\['toolbar\_menu'\]). The array data is correct.

I'm now looking to see what else might be causing the HREF to "disappear" from the Content menu.

Has anyone seen this before?

The first commenter mentioned looking at the static page source (great idea...DevTools has made me lazy ;) )

```
<li class="menu-9 path-admin-content">
<a href="/admin/content" id="toolbar-link-admin-content" title="Find and manage content.">
<span class="icon"></span>Content
<span class="element-invisible">(Find and manage content.)</span></a></li>

```

So the HREF is in the A tag. I'm looking at all the Javascript on the site now.

\** UPDATED \** I added the following code (from http://addyosmani.com/blog/mutation-observers/):

```
var observer = new MutationObserver(function (mutations) {
  // Whether you iterate over mutations..
  mutations.forEach(function (mutation) {
  // or use all mutation records is entirely up to you
    var entry = {
      mutation: mutation,
      el: mutation.target,
      value: mutation.target.textContent,
      oldValue: mutation.oldValue
   };
   console.log('Recording mutation:', entry);
  });
});
var options = {
  childList: true,
  attributes: true,
  characterData: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true,
  attributeFilter: null
};
var target = document.querySelector('#toolbar-link-admin-content');
observer.observe(target,options);

```

This is the output which confirms that something is modifying the DOM.

```
Recording mutation: Object {mutation: MutationRecord, el: a#toolbar-link-admin-content, value: "Content (Find and manage content.)", oldValue: "/admin/content"}
Recording mutation: Object {mutation: MutationRecord, el: a#toolbar-link-admin-content, value: "Content (Find and manage content.)", oldValue: ""}

```

How do I go about finding what is causing the change? What code fired the observer?

# Answer
> 0 votes
I found the answer to my original problem.

I went through the .info file and commented out JS files until the console no longer reported a mutation event. Turns out that there was some odd JS code:

```
jQuery( "li:nth-of-type(2) > a" ).removeAttr("href");

```

The selector is too vague. Guess what number the LI containing the Content menu is? It's 2! And this little bit o'code took the HREF right off!

Thanks to @Clive for suggesting mutation observers. Learned a lot from this bug.

---
Tags: routes, users, nodes
---


title: How to autofill text fields in form?

text:
# Question
Title: How to autofill text fields in form?
I have two pages, on the first page, the user types in an ID. Using hook\_form\_alter, I then override the submit function and add my own functionality that will then grab information from a database about the id, such as their name and email.

It then directs the user to a second page with empty fields asking for name, email etc. My question is, what is the easiest way I auto-fill these fields with the data fetched previously?

thanks!

# Answer
As mentioned by @abhiklpm using $\_SESSION and '#default\_value' from FAPI can do the trick.

Something like, after first form submission grab values you want to autofill and put them into current session simply by doing. Assuming 'first\_name' and 'last\_name' are form fields.

```
   $values['first_name'] = 'test';
   $values['last_name'] = 'test2';
   $_SESSION['module_name']['my_multistep_form'] = $values

```

Alter the second form to add '#default\_value' property to form elements.

```
 $form['first_name']['#default_value'] = $_SESSION['module_name']['my_multistep_form']['first_name'];
 $form['last_name']['#default_value'] = $_SESSION['module_name']['my_multistep_form']['last_name'];

```

Remember to unset values from $\_SESSION in second form submit handler, use

```
unset($_SESSION['module_name']); to unset the session.

```

You might want to have a look on ctools multistep forms as well http://internetdevels.com/blog/ctools-multistep-wizard-example .
> 0 votes

# Answer
You should check out https://drupal.stackexchange.com/a/54387/4387

```
function MYMODULE_some_form($form, &$form_state) {
  // If the form has been submitted, output something related to the submission
  if (!empty($form_state['values']['some_field'])) {
    // Get data from database and show second step fields.
    $form['user_name'] = array(
      '#type' => 'textfield',
      // ...
    );

  }
  else {
    // Otherwise build the normal form (first step).
    $form['user_id'] = array(
      '#type' => 'textfield',
      // ...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

```
> 0 votes

---
Tags: forms
---


title: Make field editable after date

text:
# Question
Title: Make field editable after date
Is it possible to make a field either editable or appear after a date?

I have a content type with a Title, Date and 'Winning Numbers' field. The winning numbers field should only be fillable/editable AFTER the Date in the date field has passed.

# Answer
> 2 votes
You van achieve this with hook\_field\_access (https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook\_field\_access/7). You can check the date value against current date from the $entity object and then set permissions.

---
Tags: entities, datetime
---


# Question
Title: Can I search Taxonomy terms within display suite
I don't think so, but I'm throwing it out just in case I am incorrect

# Answer
What do you mean by search?

You can apply ds layouts to taxonomies
> 0 votes

---
Tags: search, display-suite
---


# Question
Title: height of block with view containing exposed filter
I have created a block with a view containing an exposed filter (drop downbox, auto submit). Based on the selection in the dropdown, the visitor will see a short or long list of results. This block is located in the content region of one particular node.

The height of the block does adapt to this result, but unfortunately all elements below this block (i.e. the footer region) do not go below this block. They just remain on the initial height as when the page loaded.

How can I tell the footer to go below the block with the view automatically each time the filter is changed?

Your step-by-step help is highly appreciated!

Regards, Hans

# Answer
> 0 votes
Some html element wrapping the block has a fixed height. This height gets set the first time you load the page and thereafter it does not change (it could be done by a jQuery script). You will need to hunt it down in your web dev tools and alter it with a CSS rule that sets the height to auto, or you might even have to do it via jQuery.

Try with another theme (bartik) and see if it also happens. If it does not then it is theme related.

If you cant get it fixed then I suggest you create a custom region just below the content region that is used solely for the block. Just use a div for the custom region and only set the width if need be. On a block level element the height should by default be auto.

Look here how to add custom region.

# Answer
> 0 votes
I just wanted to inform you fellow drupalists, that a solution was provided to me and solved my problem.

The reason was a config setting in the (omega) theme to use equal heights. Desactivating this, solved my problem.

Hope this helps you as well.

Regards, Hans

---
Tags: theming, blocks, views
---


title: PDOException Deadlock

text:
# Question
Title: PDOException Deadlock
Yesterday I had a peek in visitors and I saw following PDOException in my logs:

```
PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: SELECT revision.order_number AS order_number, revision.revision_id AS revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail, revision.status AS status, revision.log AS log, revision.revision_timestamp AS revision_timestamp, revision.revision_hostname AS revision_hostname, revision.data AS data, base.order_id AS order_id, base.type AS type, base.uid AS uid, base.created AS created, base.changed AS changed, base.hostname AS hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision} revision ON revision.revision_id = base.revision_id WHERE (base.order_id IN (:db_condition_placeholder_0)) FOR UPDATE; Array ( [:db_condition_placeholder_0] => 6131 ) in DrupalDefaultEntityController->load() (line 191 of /var/www/vhosts/shopmybooks.com/releases/20141208090103/web/includes/entity.inc).

```

I can't seem to find any good solution for this. Drupal version 7.27

Any help?

# Answer
I had some similiar issue.

Problem was that drupal was cosuming 100% of cpu usage, sometimes making the execution of some queries to take to long and reaching the max timeout on LOCK\_TIMEOUT

If you have acccess to command line, check proccess, cpu usages, sql usage and so on

Hope it helps

There are some threads about drupal sites cosuming 100% of cpu (Kind of old but i had this problem recently), take a look

See this thread for a bit of debuging
> 1 votes

# Answer
We had a similar issue with the revisioning module over 18 months ago.

At the time there were bug reports on the revisioning module misbehaving and this resulting on server crashes. (See bug reports here and here.)

Unable to find a reasonable solution we did away with the problem by disabling the revisioning module. The crashes went away too. And we never got to the question because lack of time.

Since your error message points to the revision table I though this might be related to our past problems.

So, consider if you can do without the revisioning module as a quick solution.

Else, see if you can update the module to a more recent version. That may help too.

Good luck.
> 0 votes

---
Tags: database
---


# Question
Title: Search api autocomplete - how to show search form?
I use Search Api with Search api autocomplete module.

I made configuration of autocomplete module on Search Api page, but I do not see block for input.

Should I config anything else for it?

# Answer
> 1 votes
There should be a block named Search box in admin/structure/block, i think it is the search box by default of drupal.

Remember that this block uses a view that returns a JSON, you can specify which view to use entering admin/config/search/search\_autocomplete

---
Tags: search
---


# Question
Title: Change taxonomy list automatically generated paths
I made a dummy second hand car website, for which I made a taxonomy list "Popular brands". I've added this list to the front page, but each of the respective links (e.g. each brand) links to `popular-brands/[brand]` instead of `brand/[brand]`, how I'd like it to be.

The first is generated automatically upon creating this block view. Can I alter this path to become the latter?

The case can be seen live at ikhoefgeen.be (site is in Dutch by default, I'm not sure wether or not it automatically displays in English).

# Answer
Are you using pathauto?

Check patterns at admin/config/search/path/patterns and then update URL aliases
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Automagically relating nodes of a single content type
I have a content type (e.g. Target) which has a title and body. I will have about a 1000 nodes of this content type. I want to be able to create a view that renders not not only the title and body of this type of node, but also associated/related nodes.

I don't want to have to manually associate nodes (based on taxonomy or by adding an entity reference). Instead, I want the view to automatically search for the Title of a given node in the Body field of all other nodes of this type and associate those nodes that contain the given node's Title.

I'm new to Drupal, but believe I've gotten my head around the basics and have several Views configured and working. But I can't seem to find any guidance on achieving the above and not sure how to do that in Drupal/Views, although I know this is achievable in straight SQL.

Any ideas, advice?

# Answer
> 0 votes
Remeber that views is some kind a query builder, even better it gives you tools to alter its content, query and so on. See hook\_views\_query\_alter

---
Tags: nodes, views
---


# Question
Title: Drupal installed with Drush doesn't display home page
I installed Drupal with Drush and it all works fine and the welcome page appears as well. But when I try to log in (with whatever account) it shows me the: "Object not found! The requested URL was not found on this server...." page.

I am on Arch Linux. I checked the httpd.conf file and mode\_rewrite engine is enabled: "LoadModule rewrite\_module modules/mod\_rewrite.so"

I was also suggested to check the .htaccess file extension, but it has no ".txt" extensions.

Also, I went to index.php?q=user url and it did respond: opened the User account page.

I am still suspecting something with httpd.conf and .htaccess fils, but they look fine to me. I failed to find any resource related directly to this problem.

Just to clarify further. Both /drupal and /drupal/index.php urls are displayed without errors. But when I try to log in as an admin (or any user) and submit it, it shows the error page I described above. Which is a problem, because I can't even enable clean urls, as it requires permissions for that.

I checked if the httpd.conf file (as suggested by comment below) is configured to read the .htaccess file:

```
AccessFileName .htaccess

```

And although the file was missing that section, I found out that httpd.conf file reads .htaccess file by default, if not configured otherwise. Despite this, I added that line, but it still shows the same error when logged in.

Also, the following are the httpd.conf lines:

```
DocumentRoot "/srv/http"

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Deny from all
</Directory>

```

# Answer
> 2 votes
I think your true problem is that clean URLs aren't working (as evidenced by index.php?q=user does work). It may also suggest another Apache configuration problem.

Make sure your httpd.conf is configured to read .htaccess

```
AccessFileName .htaccess

```

I don't know the last time I saw a system that didn't have this (sometimes was different on older WAMP installs).

Then, browse to http://example.com/index.php?q=admin/config/search/clean-urls

Set clean URLs if you can.

If you can't set clean URLs, then you have an Apache configuration problem.

If browsing directly to http://example.com/index.php works, but http://example.com/ doesn't, then I suspect your configuration doesn't allow Apache overrides for that DOCROOT. That would also explain why clean URLs aren't working. The general option you need to set is `AllowOverride`. My general setup looks like:

```
<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com

  DocumentRoot /var/www/example/docroot

  <Directory /var/www/example/docroot>
    Options -MultiViews
    AllowOverride All
  </Directory>
</VirtualHost>

```

The `AllowOverride` line will

* disable index listings for directories
* allow the htaccess to reset the index order to use index.php first
* override other options that may be set in your httpd.conf

# Answer
> 0 votes
I did the following that solved the issue:

As I mentioned above, I am on Arch Linux where web root is /srv/http. And as @MPD suggested, I set the

```
AllowOverride All

```

In the httpd.conf file. But this didn't work. Then I followed @arpitr's suggestion to check if .htaccess file is being read at all and I discovered that it wasn't. I went back to the httpd.conf file discovered that I had changed AllowOverride All only in the following section:

```
<Directory />
    AllowOverride All
</Directory>

```

But as @MPD pointed out, it should have been changed under web root section as well:

```
<Directory "/srv/http">
......
    AllowOverride All
......
</Directory>

```

What confused me was the difference of web roots on different distros used by MPD and myself.

# Answer
> 0 votes
In my case, disabling `fast_404` module in settings.php did the trick

---
Tags: drush
---


# Question
Title: How to allow multiple email addresses on webform module?
The version of webform module im running doesn't support sending to multiple email addresses. Ideal users should be able to add all the different emails they what to send to in one box. Dose anyone have a workaround for this. Even if that means adding the emails in a "cc" form or separating the emails with a semicolon or comma.

-Thanks

# Answer
Are you able to upgrade to the latest version of webform?

1. On your webform page, click the "webform" tab, and then the "e-mails" tab.
2. Add a single e-mail address, and click add.
3. Either click edit, or after adding an email, you should see a settings page. The first label is "E-mail to address".
4. Make sure the custom field is selected, and enter a comma separated list of emails in this field.
> 1 votes

---
Tags: 7, webforms, emails
---


title: Merge Users from Prod to Staging/Dev

text:
# Question
Title: Merge Users from Prod to Staging/Dev
I have users registering on my prod environment, but I also have accounts created internally on my staging environment. Is there a drush command similar to sql-sync or Drupal module that will simply merge the user table without overwriting all users and credentials?

# Answer
> 0 votes
go through the discussion on https://groups.drupal.org/node/177179. You will get to know the answer of your question

# Answer
> 0 votes
You can use feeds to import all users from Staging/Dev

Then updating its passwords through a sql, because feeds let you import password without encryption only **Take in mind that no hook will be fired by doing it this way**

See this video for instructions

Another approach would be a sql selecting all user from dev users table (without nid) and put them into prod users table, but im not quite sure because i just saw that nid field is not AI. **Take in mind that no hook will be fired by doing it this way**

---
Tags: drush, database, users
---


# Question
Title: How do I rewrite the ID of an exposed filter field element?
I am desperately trying to a way that I can rewrite the ID of an exposed filter field element. I've gotten so far as to set up hook\_form\_alter where I can get the specific $form array that I need. When I look at that array using dpm($form) I can see where other info for that input element is contained, but there is no ID element in the array that I can see.

This is the current output that I'm concerned about from my exposed filters form:

```
<div id="edit-field-location-type-tid-label">Location Type</div>
  <div class="views-widget">
    <div class="form-item form-type-select form-item-field-location-type-tid">
      <div class="form-checkboxes bef-select-as-checkboxes">
        <div class="bef-checkboxes">
          <div class="form-item form-type-bef-checkbox form-item-edit-field-location-type-tid-370">
            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-370" value="370"  /> <label class='option' for='edit-field-location-type-tid-370'>Parks</label>
          </div>
          <div class="form-item form-type-bef-checkbox form-item-edit-field-location-type-tid-371">
            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-371" value="371"  /> <label class='option' for='edit-field-location-type-tid-371'>Historic Sites</label>
          </div>
          <div class="form-item form-type-bef-checkbox form-item-edit-field-location-type-tid-372">
            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-372" value="372"  /> <label class='option' for='edit-field-location-type-tid-372'>Marine Conservation Areas</label>
          </div>
          <div class="form-item form-type-bef-checkbox form-item-edit-field-location-type-tid-735">
            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-735" value="735"  /> <label class='option' for='edit-field-location-type-tid-735'>Urban Parks</label>
          </div>
          <div class="form-item form-type-bef-checkbox form-item-edit-field-location-type-tid-736">
            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-736" value="736"  /> <label class='option' for='edit-field-location-type-tid-736'>Other</label>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

```

Specifically, the markup I want to change is the following:

```
<input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-370" value="370"  />  <label class='option' for='edit-field-location-type-tid-370'>Parks</label>

```

I want to be able to rewrite the **id** of the input element and the **for** of the label element.

This I've got the following in my template.php file:

```
function parks_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-photo-gallery') {
    dpm($form);
  }
}

```

Looking at what dpm returns for the $form array I can see where in that array the info for these check boxes exist, but there is nothing in there that makes any sense in terms of rewriting the ID. What I'm seeing is the following:

```
form
  field_location_type_id
    #type
    #multiple
    #options
      370
      371
      372
      735
      736
    #size
    #default_value
    #theme

```

I was hoping there would have been an obvious ID element in that array, likely as a child to the child elements of the #options element but no such luck.

I've been looking for a solution for this for a couple of days now and I'm just spinning my wheels. Everything I can find is people customizing the wrapper classes and stuff, but no one getting this granular. Any help is greatly appreciated.

# Answer
**EDIT:**

I'm leaving the code below but just for kicks I went into my dev theme and did a hook\_form\_alter() to test another way of achieving what you want to do. What you are when you do the dpm() isn't the full output of what can possibly be changed in the HTML. You can do the following to change the ID.

```
<?php
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form); // Print out before change.
  // The 'created' was my form element, yours would be which checkbox you wanted to change.
  $form['created']['#id'] = drupal_html_id('my-new-id');
  dpm($form); // Print out after change.
}
?>

```

The images below show the changes in the ID and the dpm() output. They are for a select box but it should work the same for any form element.

**Before Change:**

**After Change:**

**The HTML Change:**

**Original Thought:**

I think you have to use hook\_theme\_form\_element() for this.

```
<?php
function <theme_name>_form_element($variables) {
  $element = $variables['element'];
  // Do something with checkbox
  if ($element['#type'] == 'checkbox' {
    // do something with element array like $variables['element']['#id'] = 'new value'
  }
  return theme_form_element($variables);
}
?>

```

The code above isn't tied to a certain form ID so you may have to do a little more processing to get to that piece but it should be a good starting point. Don't forget to make the ID's unique as they are originally.

Checkout the API docs for more information.

Or you can try preprocessing the form element as well, I have done this with other elements but not sure if I changed the ID's.

```
<?php
function MYTHEME_preprocess_form_element(&$vars) {
  $vars['attributes']['id'][] = 'another-id ';
}
?>

```
> 1 votes

# Answer
Why to change this?

See #id in the form api

> Description: Internal. Used to populate form elements' id property. In rare cases, you can set this value yourself on a form element, to override the default setting.
> 0 votes

---
Tags: forms, views
---


# Question
Title: How to bulk create an extra node for each user
I need to create an additional node for each authenticated active user on a Drupal 7 site.

The nodes will be populated with default content from taxonomies, and also with some field content based on content owned by each user.

Something like :

1. create node with author=user1
2. field 1= populated from a taxonomy
3. field 2= Count of number of nodes of content type A authored by user1 that are published
4. field 3= current date

And then loop through all active users creating a similar node for each one.

What's the best way to handle this? Ideally I'd like to do it in a way so that the batch node creation job could be triggered by a scheduled Rule in future.

The idea is to provide a report showing a snapshot of the account status at a fixed time.

# Answer
> 1 votes
Shouldn't be too difficult if you're ok with writing a custom module, I can't think of any other way to iterate through your user base.

1. Create the node type for storing your statistics with:
2. Write a custom module that does the following things:

See how you go and of course ask more, detailed questions about each step showing what you have tried if you really can't work it out through the documentation and existing questions/answers available here and elsewhere.

---
Tags: nodes, users, rules
---


# Question
Title: Fixing identical Latitude/Longitude data for markers on maps (bug)
I have a Drupal 7 project that I want to add location information (latitudinal/longitudinal) to most of my content types. Currently I have noticed that if there are multiple nodes that are shown on a map and if any of those nodes have identical latitudinal/longitudinal data, then the map markers are overlaid on top of one another and only the top map marker is visible. The markers under the top most marker can't be accessed (clicked to show data).

This essentially hides content, which is a type of bug, and if the content is hidden, most times you won't realize it is a problem.

This becomes a serious problem when you are generating map data from address locations. The user can be very vague with their address, and simply put their country ie: "Mexico". If other nodes are created with such vague data then the overlap problem occurs.

One was around this is to use the module "Google Map Field", which allows the user to use a map with a map marker when creating or editing content to specify where the node is referring to. The lat/long data is generated behind the scenes. It is very hard to get duplicated lat/long data when selecting the location on a map with a map marker. One problem with this is that the "Google Map Field" also allows them to enter their location by address, (ie:Eugene, Oregon, USA), if they don't want to do it with the map/marker. An admin can put a nice label on the field saying to only use the map/marker, and not put it in by address, but people often ignore instructions on labels.

We also need to have location (lat/long) data for Users "Profile2" profile. One problem with this is the "Google Map Field" does not work with Profile2, and gives a recursion error. The only way around this is to make the user put their lat/long data in by hand (not going to happen), or do it like we are currently doing it, where the user puts in their address and the lat/long data is calculated from that address. Again the problem where users can put in vague address location information and cause duplicate lat/long data that cause map marker obfuscation.

I have not seen any good solutions for this. I have thought of some custom solutions (some I don't know are possible, and currently purely hypothetical)

1)For "Google Map Field" somehow disallow the inputting of the location information through the address textbox, thereby forcing them to enter their address information from the Map/Marker. I am not sure what best ways of doing this are...Change the available fields for the module manually? Find a different contributed module that allows you to deny certain fields for nodes being created or edited? (does such a module even exists?)

2) A possible solution would be to create a module that goes through the Drupal database and finds tables that have latitudinal/longitudinal coordinates that are attached to content types. The module would check for identical latitudinal/longitudinal coordinates that were identical and change their coordinates ever so slightly (like adding a one-one-hundredth of a degree to one of the identical coordinates, there by making them non identical. Experimenting with this manually, I was able to change one-one-thousandth of a degree to one lat/long row for identical location coordinates and this corresponded to about a 1 block change in location (thereby making the 2 markers have different locations on the map). If you set this module up to perform this calculation and data alteration every time cron is run then you would then solve your identical lat/long data problem.

One potential problem I have thought of is that we would like, in the end to have our profile2 profile data synchronize with our Salesforce data, and if that was the case, then if the Salesforce data was altered, it would synchronize with our Drupal data, and then the lat/long data could potentially overwrite our changes our custom module made, thereby adding identical lat/long data (sort of un-fixing our fix). If we did have our Profile2 data synchronizing with Salesforce (which would sync every cron run), I had considered finding a way to make sure our custom module was run AFTER the Drupal/Salesforce sync module ran.

I'm posting these hypothetical solutions to you, the Drupal community because it is possible that one of you have already solved this problem, and have just not posted anything about it, or you might have a strong opinion about one of these solutions, one way or another. It might be possible that you have encountered this problem, but had no solution, even hypothetical in mind, and this posting to this forum helps you in some way.

Please, I would love to hear alternative solutions, opinions about my hypothetical solutions, or thoughts in general about this identical location map marker overlay problem.

Sincerely,

David Pugh

# Answer
Considering your SalesForce synch requirement I would go with 1) and do it via hook\_form\_FORM\_ID\_alter() in a small custom module. Simply set the address field's \['#access'\] to FALSE and use CSS to hide it.

You can even put the CSS inside your module instead of your theme and use drupal\_add\_css() to call it.

In case you haven't already come across it, the Drupal form API is really useful.
> 0 votes

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


# Question
Title: Is it possible to add permissions to a Ctools content type plugin?
Is it possible to add permissions to a Ctools content type plugin, similar to a node entity? I want to be able to check if a user has permission to add a certain content pane to a panels page through the IPE.

# Answer
> 1 votes
It should be possible using a ctools access plugin. From the linked site:

> Firstly, just like during work with Сtools content type, for the web developer it is necessary to call hook\_ctools\_plugin\_directory() to indicate that we have ctools plugins of specific type in our module:

```
/*
 * Implements hook_ctools_plugin_directory().
 */
function access_example_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'ctools' && !empty($plugin_type)) {
   return "plugins/{$plugin_type}";
  }
}

```

> Then in module folder we need to create "plugins" folder and "access" folder inside of “plugins” folder. Create plugin file with the name "access\_example\_plugin.inc" inside of "access" folder. Write the access rule by array in this file:

```
/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  // Plugin user-friendly name.
  'title' => t('Eldership rule'),
  // Plugin description.
  'description' => t('Controls access depends on eldership'),
  // Without required context plugin will now be shown in Panels UI.
  'required context' => array(new ctools_context_required(t('User'), 'user')),
  // Function which will allow or restrict access.
  'callback' => 'access_example_who_elder_access',
  // Plugin settings form.
  'settings form' => 'access_example_who_elder_access_settings_form',
  // Provides a summary descriptions depends on settings selected.
  'summary' => 'access_example_who_elder_access_summary',
);

```

It goes on to explain how to create the various callbacks but that's beyond the scope of this question I think.

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


# Question
Title: I cannot figure out how to add the search form to a child element in the menu!
I am trying to get something like this http://www.theverge.com/ on my website where you click the search icon and a search bar drops down, but I cannot figure out how to make it work. I assumed I could do it with menu\_build\_tree() but have failed quite a bit, so I moved onto THEME\_preprocess\_menu\_link() and have not figured out how to add a child element to a menu item that already exists to print my search form into.

I am pretty new to programming and even newer to Drupal, any suggestions would help me greatly!

# Answer
> 0 votes
The search button on that site looks like it is a menu item however you will find that it is a separate entity, nothing to do with the menu at all.

Usually that kind of thing is achieved using Javascript and AJAX. Javascript to make the form appear, and AJAX to submit it.

Have a look at the Popup module, it might be what you are after.

---
Tags: theming, routes
---