# Question
Title: Add class to body depending on role of author of user page
I need to add a class to the body based on the author of the user profile page. I have two roles on my site: standard and premium. I would like to create a body class to reflect this. So, if I am on a standard member's profile page (regardless of my role) "standard-member" would be added to the body classes. If I am on a premium member's profile page (again, regardless of my role) "premium-member" would be added to the body classes.

Is this something that can be done with the context module?

# Answer
> 4 votes
This can be achieved by using the template\_preprocess\_html function in the template.php file of your theme.

```
function yourtheme_preprocess_html(&$vars) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    $user = user_load((int) arg(1));

    if (in_array('standard', $user->roles)) {
      $vars['classes_array'][] = 'standard-member';
    }

    if (in_array('premium', $user->roles)) {
      $vars['classes_array'][] = 'premium-member';
    }
  }
}

```

---
Tags: theming, 7
---


# Question
Title: Get users by custom field and field type
I'm using `Drupal 7`.
I'm trying to get all users with custom field `field_id`:

```
$users = user_load_multiple(array(), array('field_id' => '123456789'));
var_dump($users);

```

and I got the following error:

PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.field\_id' in 'where clause': SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature\_format AS signature\_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data FROM {users} base WHERE (base.field\_id = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 123456789 ) in DrupalDefaultEntityController-\>load() (line 191 of C:\wamp\www\my\_proj\includes\entity.inc).

**My questions:**
1. How can get users by custom field ?
2. How to query the field type ? (is it text, int, float, etc..).

# Answer
> 2 votes
You'll need an `EntityFieldQuery` for that:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_id', 'value', $field_id);

```

There's no native way to query by type of field. To do that you'll need to use the `EntityFieldQuery::addTag()` method to add a custom tag to the query, and then use `hook_query_TAG_alter()` to manually join the `field_config` table into the query before it's run.

---
Tags: users, javascript, database
---


title: Tokens not working in entity form

text:
# Question
Title: Tokens not working in entity form
I put together a simple entity form and am trying to enter a few default token values for fields on the form. But when I choose something like \[site:current-user:mail\] from the list of available tokens, it displays literally as typed. Which is to say that, in the input box where the user's email is supposed to have been inserted, I'm seeing the text - "\[site:current-user:mail\]" instead in that field, which is a bit strange, since tokens seem to be working everywhere else on the site.

I'm using the latest stable version of drupal 7 and the entityform module.

# Answer
Install the **Field default token** module and then edit the entityforms type and save again with the desired tokens selected, and it should work.
> 1 votes

---
Tags: 7, forms, entities, tokens
---


# Question
Title: Unable to save title after hook_form_alter()
I have a node form for a specific content type that has many fields. I want to move these fields into field sets, and wrap that in a class to make it work with my theme. I've done this with hook\_form\_alter(), and everything is fine, for the most part. I am able to save fields, and the form is displayed correctly.

However, whenever I submit the node edit form, the title flips back to 'Array' and gives me the following errors:

```
Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen() (line 478 of mysite/includes/unicode.inc).
Notice: Array to string conversion in devel_watchdog() (line 531 of mysite/sites/all/modules/devel/devel.module).
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1565 of mysite/includes/bootstrap.inc).

```

Here is my implementation of hook\_form\_alter(). It's very simple; all it does is set up the fieldsets, copy the needed form elements into them, and then unset the original element:

```
/**
 * Implements hook_form_id_alter()
**/
function my_module_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_content_type_node_form':
      $form['fieldset1'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 1'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '<div class="grid_4">',
        '#suffix' => '</div>',
      );
      $form['fieldset2'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 2'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '<div class="grid_4">',
        '#suffix' => '</div>',
      );
      $form['fieldset3'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 3'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '<div class="grid_4">',
        '#suffix' => '</div>',
      );

      //move elements into fieldset1
      $form['fieldset1']['title'] = $form['title'];
      unset($form['title']);

      $form['fieldset1']['field_origin_location'] = $form['field_origin_location'];
      unset($form['field_origin_location']);

      $form['fieldset1']['field_task_override'] = $form['field_task_override'];
      unset($form['field_task_override']);

      //move elements into fieldset2
      $form['fieldset2']['field_equipment'] = $form['field_equipment'];
      unset($form['field_equipment']);

      //move elements into fieldset3
      $form['fieldset3']['field_additional_troubles'] = $form['field_additional_troubles'];
      unset($form['field_additional_troubles']);

      $form['fieldset3']['field_resolution'] = $form['field_resolution'];
      unset($form['field_resolution']);

      $form['fieldset3']['field_repair_parts'] = $form['field_repair_parts'];
      unset($form['field_repair_parts']);

      $form['seperator'] = array(
        '#type' => 'markup',
        '#markup' => '<div class="clearfix"></div>',
      );
    break;
  }
}

```

When I run a debugger and step through it at the time of the error, I see that $form\_state\['node'\]-\>title is set to 'Array', but otherwise I can't determine what is setting it to an array.

The error disappears when this form\_alter function is commented out or the module is disabled, so I know that something within this function is triggering the error.

Does anyone have clues of where to start looking to solve this issue? Is there, perhaps, some other thing that I need to do in order to move the form elements? Maybe I am missing a step? Or, is this maybe coming from another module's code and if so, is there a method to find that module?

# Answer
> 0 votes
Solved.

When I posted my code on here, I realized that I had a typo in Fieldset 2, where I was using '$form\['device'\]\['title'\] = ...' instead of '$form\['device'\]\['field\_equipment'\] = ...'

After fixing the typo, everything is working as normal.

---
Tags: forms
---


# Question
Title: Using an include file from a different module
I've got a module that I've created just for the sole purpose of sharing .inc files between multiple modules. The modules .module file is empty, as it doesn't do anything. But in the modules .info file I have included:

```
files[] = includes\Permissions.inc
files[] = includes\Roles.inc
files[] = includes\PermissionsInterface.inc
files[] = includes\RolesInterface.inc

```

And then in a module that is using these files (a different module), I have included:

```
use Portal\Permissions;
use Portal\Roles;

$permissions = new Permissions\Permissions();
$roles = new Roles\Roles();

```

I don't have any include or require statements, because I thought that was covered by the files\[\] declaration in the shared modules .info file.

However, I'm getting a PHP error that it can't find the class Permissions(). Just wondering what I'm doing wrong?

# Answer
> 1 votes
The `files[] =` declarations are only for classes you want to reference at runtime. The declaration should be in the module using the classes (not some other module).

If that doesnt work, look at the xautoload module for D7. Or, simply put `include 'includes/Permissions.inc';` into the top your custom module file using those classes/functions -- if you use Features, that's what features (for D7) does; adds an include for `features.inc`.

---
Tags: 7, .info
---


# Question
Title: How to "freeze" a View at the time of publishing?
I have a content type for publishing a node once a week (type A) - on Saturday night/Sunday morning - that needs to show, as an attachment, a list of some other nodes (type B) that go live daily during the week (one node a day) I have a view that puts together nodes of type B for 6 days of week - Monday through Saturday, so I have a filter on Post Date between 'last Sunday' and 'now' and I limit the number of nodes to 6. Then I use Viewfield to show the view of nodes B on content type A - and it all seems to work, but! (there are always those 'buts', right??) - I want to 'freeze' the View's content at the time of publishing - so if somebody will click on the type A node two weeks from now, the list of the type B nodes should be relevant to the week the type A node was published on - so, I need to somehow filter the type B nodes view using an "external date" parameter How do I do that?

# Answer
> 2 votes
I thought about the relationship angle and couldn't find one but I have been known to be blind in the past to things in front of me and instead went the `hook_views_pre_view()` route...

```
function YOUR_CUSTOM_MODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='last_sunday_and_now') { // or whatever your View is named

    // see what we have to work with...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('<pre>Before: ' . print_r($filters, TRUE) . '</pre>');

    // here on my box it is 'date_filter' so let's change things up

    $filters['date_filter']['default_date'] = // set this to whatever you want instead of "Last Sunday"
    $filters['date_filter']['default_to_date'] = // set this to whatever you want instead of "now"

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $value) {
      $view->display_handler->override_option($option, $value);
    }

    // let's see what we have...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('<pre>After: ' . print_r($filters, TRUE) . '</pre>');

  }

}

```

It's up to you to define the logic of what to set the dates to, but if this is sitting on a node, you can grab the post date of it via `menu_get_object()` pretty readily and then use any of the various date and time functions to create the dates.

# Answer
> 1 votes
It sounds like you need a relationship from parent node A, the `publish date` to be the filter for Nodes of type B. I think Views can handle this use-case out of the box.

So add like a `contextual filter` for the parent node A `NID` in your View for B stuff -- and then basically keep the rest of your view listing for type B the same.

Viewfield should be able to accept an argument for the View as the `type A parent NID that was published`.

---
Tags: nodes, datetime, views
---


title: Adding comments to pages

text:
# Question
Title: Adding comments to pages
Is it possible to add a the content type comments to a page? When I create a page and look to see what can be added into a panel comments are not available

Thank you!

# Answer
> 0 votes
You might be confusing things which makes your question hard to answer.

Please note that comments are not a content type, but they are part of nodes, and thus can be appended to any content type. Comment's can't be used inside the Panels module because they are part of a node (one is to import the whole node).

If you meant page rather then panel. Please make sure the comments module is enabled in modules. And then go to the 'basis page' content type and check the 'comment settings' tab (at the bottom) to see if comments are open.

---
Tags: 7
---


title: Drupal Events Calendar

text:
# Question
Title: Drupal Events Calendar
I can't show the main calendar as a page. What am I doing wrong?

I try to add to panel, but the finish button stops working in order to add it. Any idea?

I've added a snapshot:

# Answer
Seems like my copy of Drupal was having some problems after update.
> 0 votes

---
Tags: datetime
---


# Question
Title: Module hook to add_js to any entity type?
I want a hook that will let me conditionally add js/css to the page depending on the type of entity.

Since I am putting this in a module I cannot use a theme hook (because if the theme already defines the hook then Drupal will crash).

Ultimately, I want to do something like:

```
// SWTICH BY ENTITY TYPE
switch($entity_type){
    case 'eform':  // entity forms
        drupal_add_js( $theme_path . '/scripts/ajax_forms.js');
        break;
    case 'view':  // view pages (making this one up)
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWTICH BY CONTENT TYPE
switch($content_type){
    case 'services':
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWITCH BY NID
switch($nid){
    case '293': // Homepage
        drupal_add_js( $theme_path . '/js/global.js');
        break;
}

```

Right now I'm using `hook_node_view` to check content type & nid. Works great for nodes, but doesn't help me with non-nodes.

# Answer
> 1 votes
`hook_entity_view()` should do the trick

> Act on entities being assembled before rendering.

e.g.

```
function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  switch ($type) {
    case 'node':
      ...
      break;
  }
}

```

---
Tags: 7, hooks, entities
---


# Question
Title: Drupal way to create a dynamic url as a content type field
What would be the Drupal way to create a dynamic URL field on a content type.

Say I have a content type called 'dogs' and so I use that to catalog all the dogs I like on my site. Now I have created a view that lists in two columns 1) all the dogs that I like and 2) a link to search them on google. There are 100s so I would like to make a dynamic url field because I don't want to type in each google search to each record for the dog content type. So:

```
Title | Search Link

Maltese, http://google.com/#q=Maltese

Beagle, http://google.com/#q=Beagle

etc...

```

What's the best way to encode the field such that it says:

1) Get the title for this node (Maltese), 2) Append it to the string "http://google.com/#q=" 3) Make this my field\_dog\_search\_url

Is this something that can be done in the admin panel or is it better to use a hook. I'd rather use a hook than download and install yet another module just for this one instance, though I'm interested to know if there is a good module that handles this scenario.

# Answer
> 1 votes
If it were me I would rewrite the view column.

You could ether do this through a views template, or just rewriting the output of the column. The latter is probably the easiest, though I personally would use the template as it leaves the output to templates.

To rewrite the column, you could just add another title field, in the second field's settings make sure "Link this field to the original piece of content" is turned off, and then under "REWRITE RESULTS" you should be able to rewrite the output of the filed, and using replacement patterns you should be able to turn it into something like a link that says "search google" and pointing to `http://google.com/#q=[title]`

If you would like to do it through the template via a views template (again, that's the way I personally would do it) this will help get you started with that: https://stackoverflow.com/questions/15498918/how-do-i-manually-theme-views-in-drupal-7

# Answer
> 2 votes
You can do this through the UI. Select the "Rewrite Results" checkbox and "Output this field as a link". Then use replacement patterns to fill in the dynamic part of the URL.

---
Tags: entities, nodes, uri
---


# Question
Title: How to include any view into the same panel
To reduce duplicated panel pages for every view I want to display, I'd like to re-use the same panel (the same layout) for several views. The problem is that I can't find how to include ANY view in panel where view is passed by argument or URL. There are only particular Views Content panes available but this results in creating as much panel pages with URLs as there are views. And any changes in "common" panel content elements must be made for **every** panel page which is overkill.

There is analogue solution for nodes - predefined panel "node\_view" ("/node/%node") which can display ANY node's content passed in URL. There's an element "Node content" which does that. Is there similar solution for views? Thanks in advance!

# Answer
If you can use a PHP snippet in your panel you could use `views_embed_view($name, $display_id = 'default')` to render the view from url.

Let's suppose your panel's url is `/mypanel`. You can use `/mypanel/myviewsname/displayname` to access that panel with a particular view and display using the following code in a PHP snippet:

```
<?php
$display = arg(2)?arg(2):"default";
print views_embed_view(arg(1), $display);
?>

```

`arg()` gets a list of arguments passed through url. `views_embed_view()` embed a view in a PHP snippet and it will return nothing if no adequate view name is passed. This should work whenever `myveiwsname` is an actual view name and `displayname` is an actual display of that view or is not provided.

You may be able to include PHP in a panel only if you have PHP filter module installed.

**You should use PHP filter module with caution.**
> 0 votes

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


title: Rendering Commerce Order

text:
# Question
Title: Rendering Commerce Order
API function commerce\_order\_build\_content was deprecated, but I couldn't find one that was supposed to replace that. How do I drupal\_render() a loaded commerce order? As of now, I'm getting "call to undefined function" commerce\_order\_build\_content

# Answer
> 1 votes
Use entity\_view:

```
$build = entity_view('commerce_order', $order, 'full');
$markup = drupal_render($build);

```

---
Tags: 7, commerce
---


# Question
Title: How to I change the blogger's name button from all lower case to proper case in Omega 3.1 subtheme?
I want **firstname lastname's blog** to be **Firstname Lastname's blog**

# Answer
> 1 votes
You could always use mb-convert-case, or you could just target it with css and use text-transform: capitalize.

---
Tags: theming
---


title: PHP error with Computed field

text:
# Question
Title: PHP error with Computed field
here is my code:

```
$nid = $entity->field_empf_number['und']['0']['nid'];
$result = db_query("SELECT MAX(entity_id) FROM field_data_field_empf_number WHERE field_empf_number_nid = $nid")->fetchField();
if (isset($result)){
  $n = $result ;
  $node = node_load($n);
  $node->field_empf_stat['und']['0']['value'] = 'off';  //list field
  node_save($node);
}
$entity_field[0]['value'] = $result;`

```

when add new node (if there is previous node i mean the if statement return true ) this error message show up:

> Fatal error: Maximum function nesting level of '100' reached, aborting! in C:\wamp\www\finance\includes\database\database.inc on line 429

I googled but i did not found any answers.

# Answer
> 1 votes
Try to change the node\_save($node) to drupal\_register\_shutdown\_function('node\_save', $node). It will remove the old node saving process from the actual node saving. But I don't think, that type of code should have place within a computed field. The computed field good to modify the *same* field. It isn't designed for modifying other data of your system. These code should be in a custom module in hook\_node\_presave().

# Answer
> 0 votes
The code for the computed field should preferrably be placed in your module, not in your database. This will make your code much easier to debug so the abovementioned errors won't happen.

Use the computed field hook \- here is a nice (tutorial).

Here are some code examples.

---
Tags: 7, entities
---


title: How do I hide Devel tab from users?

text:
# Question
Title: How do I hide Devel tab from users?
I just noticed that Devel tabs are showing on my Basic Pages, even when the user is not logged in. Anonymous users should not see "View" and "Devel" tabs! I can't find a setting for this in the Devel configuration page. Any ideas how to prevent the tabs from displaying? Thanks!

# Answer
Duh... It isn't the Devel config that controls it. It's the "Access developer information" permission. Someone had turned it on for anonymous users. Doh!
> 1 votes

---
Tags: debugging
---


title: How do I Install Drupal Locally

text:
# Question
Title: How do I Install Drupal Locally
I have a html doc and css for a site that I do not currently have live. I want to use Drupal for the site but have a question about testing when changing the html/css into something compatible with Drupal: How do I check my progress to make sure things are working?

With an HTML doc, all I have to do is click the doc and it opens up in my browser. How do I test with Drupal in that way?

What steps do I take to install Drupal locally? I am running Windows, so do I use WAMP? I am a total noob, any help would be more than awesome.

# Answer
> 3 votes
Yes, you need to install Drupal locally to test the theme progress. There is a nice guide at http://drupal.org/node/307956, I hope it works for you. Please post back if you need more guidance. It is the easier way I know to get started with Drupal on your computer.

# Answer
> 1 votes
I would install XAMMP and run your local install from there. As another answer suggests, there is a simple guide (http://drupal.org/node/307956).

Converting html/css into a theme could be a lot of work for your first few tries. You'll need to learn a lot about them theme system and drupal in general. Lullabot has a good walk-through video available, also likely on their site Drupalize.me. This costs money, but would definitely minimize the time you spend doing your conversion. Specifcally, you'll get to see how they test their progress on a local server.

# Answer
> 1 votes
Personally, having used XAMPP and WAMP, if I wanted a quick and easy local install of Drupal, I would use Acquia Dev Desktop instead. Their tagline "Drupal made simple" says it all, really.

You can download it from here.

# Answer
> 0 votes
Most definitely consider what EddieN120 and mtro suggest.

I have been trying to download drupal sites from our clients and use them in Microsoft IIS, and have run into MANY issues. More IIS issues than Drupal. Part of the reason that I have not adapted the Acquia Dev or just a XAMMP set up is because the workstation which I use is filled with different versions of PHP.

Based on previous experience, Acquia Drupal is the easiest way to set up a local test site. It pretty much packages XAMMP/WAMMP along with other common tools.

# Answer
> -2 votes
Check this out: https://github.com/cyberswat/drupal-lamp It is pretty dang easy to install.

---
Tags: installation, theming
---


# Question
Title: Drupal callback :: Less CSS file with variable_get()'s
I am trying to create a custom module that programmatically creates a LESS file.

I created a menu callback that is a file. Here is hook\_menu()...

```
$items['sites/all/themes/universal/less/dynamic.css.less'] = array(
  'page callback' => 'jobs_universal_lessvars',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
);

```

Here is the callback.

```
function jobs_universal_lessvars(){
  header('Content-type: text/css');
  $output = '
    @color: #4D926F;
    body.notaclass {
      color:@color;
    }
  ';
  print $output;
}

```

And I call this to add it.

```
function universal_preprocess_html(&$variables) {
  drupal_add_css(drupal_get_path('theme','universal').'/less/dynamic.css.less');
}

```

I uploaded a static file to the above ^^ path, disabled the menu callback, and it processed/applied correctly. When I try to run this module, it's not included and I get an error saying

> LESS error: load error: failed to find sites/all/themes/universal/less/dynamic.css.less

Before you answer...

1. I have the LESS module installed
2. I have the LESS library uploaded correctly
3. I have tested that I can include a static .less file and have it process
4. I have tested the menu callback by manually going to the URL
5. I have tried it with and without calling header('Content-type: text/css');

I get it... it's not a file. But it "is", right? I could just call this function and have it create a new CSS file that's added, but it doesn't fulfil the requirements of the module. Help me? :) Programmatically creating files is very new to me!

# Answer
> 2 votes
It may appear like a file to the browser if you were to directly request that path in the browser, but drupal\_add\_css() and the LESS module deal with the file system directly and does not attempt to resolve file paths through Drupal's menu system.

drupal\_add\_css() will not add files that do not exist on the file system.

If you are attempting to have programmatically assigned variables within a .less file I would suggest checking out the Variables functionality that is available within the latest version of the LESS CSS Preprocessor module, documentation here: https://drupal.org/node/2139603

If you are truly trying to create a dynamically composed .less file, you first need to create the file in the files directory of the drupal install and then add that file with drupal\_add\_css().

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


# Question
Title: Multipage Registration form, Confirmation Page Security Issues?
I have a multipage registration form working on a site, but the confirmation page is supposed to show some of the information (account name and other data) after the account has been submitted/created. I can treat this confirmation page as the last page of the multipage form, but I'm concerned that the user can then press the back button on the browser, the session data will still be there, and they can then re-submit the same data again.

Another approach would be to end the session and display the data on a redirect page, but I could not find how Drupal 7 would pass this form data to the redirect page. There would be too much data to put it in the URL.

Does anyone have a suggested Drupal 7 method to achieve a confirmation page showing session data, but not allow the user to press back on the browser and re-submit the form again?

# Answer
After further investigation, it appears that one option is to make a confirmation page that is called after the form does it's final submission. Essentially, somewhere in the form alter or form functions near the end (after database operations), add a variable to PHP's $\_SESSION array that contains the Drupal form ID (a long string of random characters), and add to this array another sub-array that contains all the information you want shown on the confirmation page.

Then, in the confirmation function (or page if you want to do the .tpl.php version), pass the form ID as a variable in the url. Then use this form ID to get the array from the $\_SESSION array and retrieve the information.

As an example, see the drupal\_set\_message() function since it too uses the PHP $\_SESSION variable to pass information back to the user on the next page load.

To keep the user from using the browser-back button and resubmitting the same information again, check the $\_SESSION variable for the same form-id before committing user changes to the database and stop the attempt if the form-id's match. In some cases (e.g., registering for a new user account), Drupal will complain anyway if one tries to submit duplicate information to the database (e.g., username exists already).
> 0 votes

---
Tags: 7, users, forms, sessions
---


# Question
Title: How do I debug my Feeds import not importing a field
I have a Feeds import set up to import products into Drupal Commerce (from csv). My product type has a number of term reference fields that also need to be assigned a value by import. Most of these work fine (e.g.: field\_product\_unit, field\_product\_discount\_category), except one: field\_product\_group. I'm searching the taxonomy term by term name.

Importing the product group used to work at some point, but for some reason or other, it stopped working. Not a single value gets imported. I can't pinpoint when it quit on me. I don't see an obvious difference between the fields that do work, and the one that doesn't. The only slight difference is that product groups are hierarchical, and the other taxonomy lists don't use hierarchy.

I don't get any error messages or "I can't find this term" notices.

I've tried the following:

* checked and double-checked the names of the terms matching the csv values: they do.
* importing my taxonomy term name into a text field (to make sure it could find the input field): works fine.
* my taxonomy lists all use multilingual names and descriptions. To avoid a mix-up there, I reset it to a single language: no difference

How do I proceed now? How can I figure out what's going wrong?

# Answer
As a first step, you could check whether the field has been parsed properly:

In sites/all/modules/feeds/plugins/FeedsProcessor.inc:

Add `debug($item)` after line 180:

```
  public function process(FeedsSource $source, FeedsParserResult $parser_result) {
    $state = $source->state(FEEDS_PROCESS);

    while ($item = $parser_result->shiftItem()) {
       debug($item); // debug entry

      // Check if this item already exists.
      $entity_id = $this->existingEntityId($source, $parser_result);
     ...

```

debug() is a core function that lets you print out debugging information:

https://api.drupal.org/api/drupal/includes!common.inc/function/debug/7 and/or

http://blog.boombatower.com/drupal-7-debug-and-simpletest-verbose?utm\_source=buffer&utm\_campaign=Buffer&utm\_content=buffer5ee6f&utm\_medium=twitter

The result will be processed using drupal\_set\_message(), and will appear in http://example.com/admin/reports/dblog (probably, depending on your configuration).

You'll get one notice for each imported line, like:

```
User notice:

array (
  'title' => 'This is a test title',
  'body' => 'And a test body',
  'tax' => 'And a taxonomy term',
  '' => '',
)

```

Alternative: download (from http://drupal.org/project/devel, or `drush dl devel`) and enable the Development module (Devel in `admin/modules`), or `drush en devel` and use `drupal_debug()` or another tool from the devel module.
> 4 votes

# Answer
If the products are tagged with more than one group, the field won't be processed as singular terms because they will be arrays, right? I ran into this challenge recently and solved it with the Feeds Tamper Module.

On exporting my nodes from views as CSV files I chose the field "Taxonomy all terms" and chose the vocabulary. By default, Views will separate this field's multiple tags with a comma, but you can change the delimiter - I like pipes so I used them.

Then on your Feeds Import settings you can hit the tamper tab, and for that field, choose Explode. Tamper then will prompt you for the delimiter you chose, in this case, a pipe.

Hope this helps: https://drupal.org/project/feeds\_tamper
> 0 votes

---
Tags: taxonomy-terms, commerce, feeds
---


title: How Admin can logout other users?

text:
# Question
Title: How Admin can logout other users?
The users can logout visinting my-site.com/logout by themselves But is there any way Admin can logout other users?

# Answer
> 13 votes
If you go to `admin/user/user`, you can *block* the user, which will cause them to be logged out. After that, if you want them to be able to login again, you can just immediately *unblock* them. Also, if you as an admin change a user's password, they will be logged out and will have to use this new password to log back in.

If you want to get fancy, you could do something like this in a custom module as well:

```
function YOURMODULE_user_operations($form_state = array()) {

  $operations = array(
    'logout' => array(
      'label' => t('Logout the selected users'),
      'callback' => 'YOURMODULE_user_operations_logout',
    ),
  );

  return $operations;

}

function YOURMODULE_user_operations_logout($accounts) {
  foreach ($accounts as $uid) {
    sess_destroy_uid($uid);
  }
}

```

which would add a "Logout the selected users" option to that menu as well.

---
Tags: 6, users
---


title: Add checkbox to Ubercart checkout

text:
# Question
Title: Add checkbox to Ubercart checkout
It sounds quite easy, adding a checkbox to Ubercart's checkout form. The consultant I spoke to told be to use hooks, or try using the uc\_extra\_fields\_pane module, which I also cannot get to work properly (it's config page is not showing up). I'm using Ubercart 2 and Drupal 7.22.

# Answer
> 2 votes
In your custom module use the hooks defined in the Ubercart terms and conditions module.

---
Tags: ubercart, commerce
---


title: Large files on Pantheon

text:
# Question
Title: Large files on Pantheon
I run the website for a small nonprofit, and we're looking at Pantheon. I've imported my code and DB and gotten things basically working, but I have a question about serving large files. We're a choir and we have a couple hundred MP3s (recordings of rehearsals, so people can practice) that we need to serve. It's not high traffic at all - probably only a couple dozen downloads per week - but the files can be as big as 100M each.

A CDN would be overkill - all downloaders are local, not spread around the globe. And it's really not much traffic.

How should I host them? Just check them in to Git? They're not currently in `sites/default/files`, but I could put them there and use symlinks from their current location if that would help.

# Answer
> 0 votes
I wouldn't check them into Git, just create an Audio content type and have a file/audio field. I would just check Pantheon to see what the file upload limit is.

---
Tags: files
---


# Question
Title: D7: Create an administration page for my module
I have a custom module that sends an email with an order to the customer. I hardcoded the email body text in a string inside the module code but my client want to have control over it and I need to create an admin page for him:

I need to save it and use that text as a variable.

I started the page like this:

```
function shop_admin_settings($form, &$form_state) {
     $form = array();
     $form['mail_template'] = array(
       '#type' => 'fieldset',
       '#title' => t('Shop Email Template'),
       '#colapsed' => FALSE,
       '#collapsible' => TRUE,
     );

     $form['mail_template']['body'] = array(
       '#type' => 'textarea',
       '#title'  => t('Email template'),
       '#rows' => 10,
     );
     return system_settings_form($form);
 }

```

and use hook\_mail\_alter to append `$form['mail_template']['body']` to the existing email body

```
function shop_mail_alter(&$message, $form_state) {
$client_body = $form_state['mail_template']['body']
if (is_array($message['body'])) {
    $message['body'][] .= $client_body;
  }
}

```

Now if you please help me, I am a bit stuck:

1. I need to retrieve the body provided by client, I don't know how (my code is not correct)
2. Do I need to create a separate admin.inc in order to work? Or do I simply need to add a menu path like admin/config/system/shop and a corresponding callback?
3. Is it possible for client to use tokens inside the body?

# Answer
First of all hook\_mail\_alter() only has 1 parameter, no `$form_state`. Second of all, the system\_settings\_form() will save the form values into the variables table in the database. To access that value you should use variable\_get().

Now, your code should look like this:

```
// try to change body to something more specific to your module, like custom_email_body
$form['mail_template']['custom_email_body'] = array(
  '#type' => 'textarea',
  '#title'  => t('Email template'),
  '#default_value' => variable_get('custom_email_body', ''),
  '#rows' => 10,
);

```

then:

```
function shop_mail_alter(&$message) {
$client_body = variable_get('custom_email_body', '');
if (is_array($message['body'])) {
    $message['body'][] .= $client_body;
  }
}

```
> 4 votes

# Answer
for point 2) you are correct you need to create one custom menu hook in custom module in that hook

```
   $items['admin/config/system/shop'] = array(
       'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('shop_admin_settings'), //put the name of the form here
    'access callback' => TRUE
    );

```
> 0 votes

---
Tags: users
---


# Question
Title: How add additional css classes to description field in webform component?
I want to add additional CSS classes to webform component description field.

in default mode, this item is wrapped inside a div element with "description" class like below:

```
<div class="description">here is description text</div>

```

Now I want to add extra CSS classes beside description.

How can I do this? via a module and form alter operation or via theme functions hook?

Please guide me.

# Answer
> 1 votes
you can do this by using jquery on ready do this something like

```
jQuery(document).ready(function() {
         jQuery('#YOUR_FORM_ID .description').addClass('new-desc-class');
});

```

# Answer
> 0 votes
Looks like you are looking for webform classes module:

> A simple, small add-in that adds an editable class against each webform component to the webforms module.

Then, in your CSS use `.class-on-form-element .description` instead of `.class-on-description` \- one word more, but works just as well.

---
Tags: webforms, theming
---


# Question
Title: How to set up Apache solr search for Book Specific search
I have two books in my website (Drupal 7) and i am using Solr search.

I want to implement book specific search so that, if user is searching for Book1 content then it should show results from Book1 and not from Book2 and also let me know how to provide option of Book1 and Book2 near search bar so that we can filter the results.

I didnt find any module for this in drupal.Please provide me suggestions.

# Answer
If you are familiar with views this can be done with the following steps.

We have a contributed module for apache solr views, by installing this module you can change the views module to apache solr views i.e you can route the queries from database queries to apache solr.

**Working example :**

Step 1:

Download and install the apache solr views module.

Once the module is installed the following steps is equivalent to creating a normal view with an exposed filters.

Step 2:

Create a new view I have named book search (I have created a normal menu for the book search and added in the views path configuration i.e : " Path: /apachesolrfilters ", you can create a stand alone page or add it to any existing blocks), add fields and filters,

Fields : I have added content title, body & content type Filters: I have added Content: Published (Yes), Content: Type (exposed) & Content: Title (exposed)

Configure the filter content type to show only the book types book1 & book2.

Save the view and clear the cache.

Screen shot:
> 1 votes

---
Tags: nodes, search
---


# Question
Title: "Administer Taxonomy" is needed to make a user select a term
I need a user to select a term from a given vocabulary but the field is only available to a normal user if I enable "Administer Taxonomy" for them. Is there a way around this? Shouldn't I be using taxonomy for this?

# Answer
You don't need to give an user the permission to `Administer Taxonomy` in order to **use** a vocabulary. Assuming you are using Drupal 7, as the name implies `Administer vocabularies and terms` it's a permission that allows one to **edit** and/or **delete* a term from any vocabularies. It can also be specified per vocabulary.
> 1 votes

# Answer
You can install "Vocabulary Permissions Per Role":

> You have set up some vocabularies (with some terms) like Color (Red, Green, Blue) and Shape (Toroid, Cube, Sphere). Maybe you even have a vocabulary that controls who can view a specific node (with terms) like Access control (Editors, Colleagues, World). Here comes trouble: your precious editors want to add more Colors, or reorder the terms of the Shape vocabulary (probably they want to see Sphere before Cube, who knows,) and you do NOT want to grant your editors the administer taxonomy permission, as it grants too much power (and that implies too much sharing of responsibility). Without this permission they were NOT able to do the mentioned tricks: adding terms to a vocabulary but not to another, reordering/editing terms of a vocabulary but not another's, etc.

https://drupal.org/project/vppr
> 0 votes

---
Tags: 7, taxonomy-terms, users, security
---


# Question
Title: how to redirect page for anonymous users after number of times?
if any anonymous users come to my site after number if times they are accessed but i want redirect to register page after 4 time viewed content in my site.

please tell me is there any modules available in drupal 7.

# Answer
I don't think there are any contrib modules which can provide this functionality. This is not an ideal way but you can do it like this, I think:

1. Create a table (id, host\_name, hash\_code, visit\_count)
2. Whenever you opens your site you will check for host\_name, hash\_code, and visit\_count (if user is anonym)...

Example:

```
/**
 * 1 - I named the function as 'test' but this function must be called
 * at page load, that's why you need find where to call it. may be
 * TEMPLATE_preprocess_page() or HOOK_init()...
 * 2 - I can't say that here is everything is correct. Correct it if
 * something is wrong.. because I didn't test it...
 */
function test() {

  if(user_is_anonymous()) {
    $host_name = ip_address();
    $hash_code = genCode(35);
    $query = db_select('MY_tABLE', 'mt')
      ->fields('mt')
      ->condition('host_name', $host_name, '=')
      ->range(0,1)
      ->orderBy('id', 'DESC')
      ->execute()
      ->fetchAssoc();

    if(empty($query)/* This user is the first time came to your site */) {
      $record = array(
        'host_name' => $host_name,
        'hash_code' => $hash_code,
        'visit_count' => 1,
      );
      drupal_write_record('MY_TABLE', $record);
    }
    /* This means that the user is anonymous but not a new user */
    else {
      if(isset($_COOKIE['anonym_code']) && $_COOKIE['anonym_code'] == $query['hash_code']) {
        if($query['visit_count'] > 4) {
          drupal_goto('user/register');
        }
      }
      else {
        setrawcookie('anonym_code', rawurlencode($hash_code), 0, '/');
        $visit_count = $query['visit_count'];
        $new_record = array(
          'host_name' => $host_name,
          'hash_code' => $hash_code,
          'visit_count' => $visit_count + 1,
        );
        drupal_write_record('MY_TABLE', $new_record);
      }
    }
  }
}

// Helper function
function genCode($length) {
  $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  $string = '';
  for ($i = 0; $i < $length; $i++) {
    $string .= $characters[mt_rand(0, strlen($characters) - 1)];
  }
  return $string;
}

```

I am sure that there are tons of bugs in that function;) I didn't test it... Also You need to implement hook\_user\_login() to delete a record from MY\_TABLE right after the user registers and logs in.

P/S: Use this approach if you don't care about performance...
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal 7 Apache solr - how to index pages content instead of nodes content
I have a drupal 7 website with pages that include multiple nodes and I use Apache Solr as search module. It works but the results are very messy.

This is a page structure exemple:

As you can see, I have multiple nodes defined on my page. I'd like the indexer handles the content as page content but not like node content. In other words, I don't want the indexer handles this page as an addition of nodes but like an unique content.

In this case, I'd like to get a page URL as result but NOT multiple node URLs.

I hope it's clear enough. Thanks

# Answer
> -2 votes
If I get you right, you don't want to show nodes in search results which are only used to be referenced to from another node, correct?

First of all, you need to define which Content Types should be indexed by SOLR. For this go to your SOLR settings page and untick all Content Types you don't want to show up in your search results.

After this done, I would highly recommend you to install the Display Suite module. This Module allows you to create different View-Modes. Built in and among many others which are available when you enable them, is the "Search Index" View-Mode. After enabling it for your Content-Type you can set it up the way SOLR should index it. So in your case probably the best would be to show the full content of the referenced node in the search index.

I hope this brief hints and tipps will help you ... To explain the Display Suite with all its possibilities is not possible in one post, but you really should try it.

---
Tags: search
---


# Question
Title: Search only for the currently active language
How can I restrict the results from a default search in Drupal 7, to bring only the nodes that are in the current language?

My website has a three language switcher; the user chooses what language he wants to use when viewing the site. If he searches something, the result page bring results from other languages. Today I have only 3 enabled languages, but we plan to expand this to 6 or more.

# Answer
> 2 votes
You can use the global `$language` to know in which language you are. In Views, you can filter using "content:language -\> current user language."

# Answer
> 25 votes
There's a really elegant way to do this using the apparently undocumented `hook_query_node_access_alter()`:

```
function yourmodule_query_node_access_alter(QueryAlterableInterface $query) {
  $search = FALSE;
  $node = FALSE;

  // Even though we know the node alias is going to be "n", by checking for the
  // search_index table we make sure we're on the search page. Omitting this step will
  // break the default admin/content page.
  foreach ($query->getTables() as $alias => $table) {
    if ($table['table'] == 'search_index') {
      $search = $alias;
    }
    elseif ($table['table'] == 'node') {
      $node = $alias;
    }
  }

  // Make sure we're on the search page.
  if ($node && $search) {
    $db_and = db_and();
    // I guess you *could* use global $language here instead but this is safer.
    $language = i18n_language_interface();
    $lang = $language->language;

    $db_and->condition($node . '.language', $lang, '=');
    $query->condition($db_and);
  }
}

```

Note: this code is 100% based on the excellent Search Config module.

**User's vs Content language**

Some sites might have language detection configured to show the interface in the user's preferred language, while the page content is shown based on the URL or content language.

In that case, consider replacing

```
$language = i18n_language_interface();

```

with

```
$language = i18n_language_content();

```

# Answer
> 4 votes
I had the same requirements, and I used the Custom search module, which includes a submodule called **Custom Search Internationalization** : "*search content from all or current language only, and all label and selectors translation handling*" (note this module provides also several other helpful features like custom search blocks). Works perfectly.

# Answer
> 0 votes
I don't sure search core support it.

I see the project i18nluceneapi but it doesnot support version 7 at the moment.

I'm using searchapi and create facets Language :). It can use for your case, create facets and default filter on search page.

# Answer
> 0 votes
You can use the Display suite module where you can choose the option View Mode-\>Language which gives the search results in the current language that is in the current site language.

---
Tags: 7, search, i18n-l10n
---


# Question
Title: Where are the "Replacement Patterns" (Tokens) in "Set Data Value" in Rules?
Most of the actions in Rules allow you to use tokens, but seemingly the most obvious place where this would be useful, "Set a data value," does not seem to support it. Am I missing something? It seems like it would be pretty trivial to add support for this, but I can't find in the code why, for example, the "title" field in "create a new entity" supports tokens, but "Set a data value" does not. Thanks!

# Answer
> 2 votes
It depends on the type of the selected target data whether tokens can be used for the value or not.

For example if the target is a simple text field (e.g. `node:title`) then the value can be specified with tokens. On the other hand, if the selected target is for example an entity (e.g. `node:field-tags:0`), then token input is not possible.

When working with formatted text, it is necessary to drill down to the `value` column of the field. E.g. for the node body, specify `node:body:value`.

---
Tags: rules
---


# Question
Title: Edit user account how to check before update if the role check box is selected?
I have a module that when my user changes the user details `hook_user` onupdate, pushes these details to an external database. However I would like this to only work when role X is selected, else my module will not do anything. The role will not be in the users profile as this processing is happening before I update the users account.

Drupal 6 Thanks

**Update**

```
 function checkrole_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'submit':

  if ($edit['roles'] == 'Staff'){
  do xyz
    }

  }

```

# Answer
Use `hook_user_presave()` for any logic that you need to happen before user data is really updated, but also have access to new values:

> **Parameters**
>
> **`$edit`**: The array of form values submitted by the user. Assign values to this array to save changes in the database.
>
> **`$account`**: The user object on which the operation is performed. Values assigned in this object will not be saved in the database.
>
> **`$category`**: The active category of user information being edited.

You need to test against `$edit` argument.

---

For Drupal 6, you need `hook_user`.

> Act on user account actions.

Act when `$op == 'submit'`, as:

> **submit**: Modify the account before it gets saved.

Just as with Drupal 7, you must examine

> **`$edit`**: The array of form values submitted by the user.
> 0 votes

---
Tags: 7, users
---


title: Add "timestamp" type for MySQL

text:
# Question
Title: Add "timestamp" type for MySQL
I used Drupal 7 and the Data module to import a table into Drupal. I could import the orphaned table, but my table has a column of type "timestamp" which does not show up when I try to edit the schema of the data table. I get the following error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1067 Invalid default value for 'published': ALTER TABLE {resource\_profiles} CHANGE `published` `published` INT NOT NULL DEFAULT 'CURRENT\_TIMESTAMP'; Array ( ) in db\_change\_field() (line 2988 of C:\xampp\htdocs\drupal\includes\database\database.inc).

I followed http://drupal.org/node/1466122, and added the timestamp datatype to /includes/database/mysql/schema.inc.

Where can I edit the schema information for my data table?

# Answer
> 0 votes
Like Gian says, you can't have a default value of CURRENT\_TIMESTAMP for an int field.

Due to Drupal's database abstraction layer timestamp is not a supported field type.

This is due to not all databases supporting timestamp or now() as a field default value as apposed to mySQL where it is supported. The solution / work around if you're using mySQL is to add a query to your .install that modifies the field default to now() where the field type is int. See the Data Type doc page for further discussion: http://drupal.org/node/159605 or see here for more info on Drupals DB Schema: https://api.drupal.org/comment/48593

---
Tags: importing-exporting
---


# Question
Title: Get domain logo in views (using Domain Access module)
I'm using Domain Access module and I have different logo for each domain. I have setup logo for each domain in domain theme settings.

I have view which lists all the domains (over relationship with user profiles, because each user has it's own domain), but I'm not able to display the logos for each domain.

Is it possible to get the domain logo in views?

# Answer
I don't think you can do that with views only. You'll need to do some coding. The point is that your logos are not linked to your Domains, but to your themes.

So you need to get your theme based on the domain\_id, and then print the logo of the theme.

\[EDIT\]

If you look at the api of theme\_get\_setting, then you can see that you can pass as a second parameter the name of the theme you want the logo. So it should be something like:

```
$MY_THEME_ID = domain_theme_lookup($MY_DOMAIN_ID);
$logo = theme_get_setting("logo", $MY_THEME_ID);

```
> 2 votes

---
Tags: views, domain-access
---


# Question
Title: Bypass Redirect Rule which acts on user login, while logging through one time login link
I have a redirect rule in place which takes user to home page after login, I need to bypass this rule when a user logs in with one time url login link which is sent in account creation email.

I am assuming there should be condition I need to put in the redirect on user login rule,but I am not finding it.I tried by putting a condition that if the site current page url is account one time login url then rule should not trigger,but its not working as the condition does not satisfy.

# Answer
> 0 votes
Got answer for it https://drupal.org/node/480584 #25. In brief the key was text comparison in the current page url to match if user/reset exists.

```
{ "rules_am_redirect_user_logins" : {
"LABEL" : "AM redirect user logins",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
{ "NOT text_matches" : { "text" : [ "site:current-page:path" ], "match" : "user\/reset" } }
],
"DO" : [ { "redirect" : { "url" : "user-home" } } ]
}
}

```

---
Tags: rules, redirection
---


title: How to create aliases for file paths?

text:
# Question
Title: How to create aliases for file paths?
In my content type there is a file field; when I upload files, it creates a file path like sites/default/files/uploaded\_file.zip.
Is there a way to change this path to something like dl.example.com/uploaded\_file.zip? I checked the PathAuto module, but it doesn't seem to have this feature.

# Answer
> 1 votes
you have these steps:

1. create virtual host for dl.example.com domain and point it to something like `sites/default/files/dl/`
2. create some module and implement this hook: `hook_filefield_paths_process_file()`. have a look at FileField Paths module.

function filefield\_paths\_filefield\_paths\_process\_file($new, &$file, $settings, &$node, &$update) { ... }

# Answer
> 0 votes
You can try File Aliases

> The File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').

---
Tags: 7, path-aliases
---


title: How can I theme individual fields?

text:
# Question
Title: How can I theme individual fields?
I have views of ubercart products which are displayed in a table by standard drupal view standards. How can i theme individual product fields ?

views-view-field.tpl is having the complete product listed inside $output variable.. I want to solve this in a template file where all fields are available individually ..

# Answer
Inside the views-view-field.tpl.php, you can use the $row variable to get your other fields. If you're using the Devel module, just send a dsm($row); to get the path to the fields you want to access.

For example I've this inside a views field template, to check if a user have something inside the field "twitter\_account" :

```
$twitter_account = "";
if(isset($row->field_field_twitter_account[0]['raw']['value'])){
    $twitter_account = $row->field_field_twitter_account[0]['raw']['value'];
}

```
> 0 votes

# Answer
You could use Display Suite and DS Extras, then enable Field Templates. This gives you full control of the field markup in your view modes. It might also be a bit cleaner as well, depending on what you're trying to accomplish.
> 0 votes

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


title: file_save_data fails in CLI

text:
# Question
Title: file_save_data fails in CLI
I'm trying to create a file attachment in a Drupal content node from a command line script. When I'm calling `file_save_data()`, passing a `public://something` URL as destination, it fails. I've tracked down the failure to the `is_dir("public://")` call in Drupal's `file.inc` that somehow returns false.

Attachments work from the regular Web interface - there's r-x permission on all relevant folders. The script should be running under the same user as Apache - I call it from Apache in the first place, using PHP's `exec()`. When I call is\_dir(DRUPAL\_ROOT."/sites/default/files") - that is, on the underlying filesystem folder - it returns TRUE, so it's probably not permissions. Looks as if the URL wrappers are somehow off when running under CLI. There's no open\_basedir in php.ini, no safe mode either.

For completeness' sake, here's the relevant portion of the script:

```
//Drupal bootstrapping
define('DRUPAL_ROOT', getcwd());
require_once('./includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$user = user_load(1);

//Some irrelevant stuff here...
$file_content = file_get_contents($file_name); //Comes from somewhere else
$file = file_save_data($file_content,
        "public://".$file_name, FILE_EXISTS_REPLACE); //Returns false! :(

```

And here's how I call the script from my custom module:

```
function mymodule_entity_insert($entity, $type)
{
    if($type == "node" && $entity->type == "mytype")
    {
        $module_path = drupal_get_path('module', "mymodule"); //That's where the script is
        exec("php $module_path/thescript.php  ".
            ">/home/me/drlog.txt ".
            "2>/home/me/drlog.txt &");
    }
}

```

# Answer
Stupid bug. The script would change the current directory. Drupal code, it seems, assumes that it will be running from Drupal root, so the file attachment paths are relative internally. `chdir(DRUPAL_ROOT)` before calling file\_save\_data fixed it.
> 1 votes

---
Tags: files
---


# Question
Title: using EntityFieldQuery to find a custom taxonomy field
I have the following query which works:

```
$query = "SELECT field_code_description_value FROM {field_data_field_code_description} WHERE bundle = :vocabulary AND entity_id in (SELECT entity_id FROM {taxonomy_term_data} WHERE name = :name)";
  $results = db_query($query, array(':name' => $fund_code, ':vocabulary'=>'fund_code'));
  $terms = $results->fetchObject();
```

I'm trying to convert this into using EntityFieldQuery, as it seems to be the best way to go (and I need some practice), but I couldn't get it right. This is what I tried:

```
$query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type','taxonomy_term')
      ->entityCondition('bundle','fund_code')
      ->fieldCondition('taxonomy_term_data','field_code_description', $fund_code, '=')
      //->propertyCondition('vid', $fundCodeTaxonomy->vid);

    $results = $query->execute();
    foreach($results['taxonomy_term'] as $tid) {
      $term = taxonomy_term_load($tid);
      dpm($term);
    }
```

How do I properly use EntityFieldQuery here?

# Answer
> 6 votes
The `code_description` field does not appear in the `WHERE` condition of the original query. Therefore there is no need to add a `fieldCondition` on the `EntityFieldQuery` neither.

```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->entityCondition('bundle', 'fund_code')
  ->propertyCondition('name', $fund_code) ;

$results = $query->execute();
foreach($results['taxonomy_term'] as $tid) {
  $term = taxonomy_term_load($tid);
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}

```

However there is already the core function taxonomy\_get\_term\_by\_name doing exactly what you need here:

```
$terms = taxonomy_get_term_by_name($fund_code, 'fund_code');
foreach ($terms as $term) {
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}

```

---
Tags: database
---


# Question
Title: What settings from a zen sub theme are not saved as files?
Im duplicating a zen sub theme so that I can later modify the styling. Ive duplicated the theme folder and changed its name. Ive changed the .info file name, and ive changed the theme name for theme overrides in my template.php and theme-settings.php.

When I enable the new theme its very much like the old one but there are still some differences. Ive looked at the theme settings pages in drupal and applied the settings from the original theme to the new one, but there are still some differences.

What other settings to do with the theme would not have been copied across with the files and also arn't visible on this page?

The only module that Ive found that I think could be affecting the layout is Panels which controls a couple of pages. Ive changed the selection criteria from themeA to themeB so I dont think its this module causing the difference.

# Answer
> 0 votes
There are two major locations for theme configuration - be it a sub theme or a primary theme:

1. http://example.com/admin/appearance/settings/yourtheme

For a zen sub-theme, this page lets you configure display of logo, site-name, slogan, and more, including a couple of menus. Also the favicon (shortcut icon), breadcrumb settings, and more can be found here.

2. http://example.com/admin/structure/block

You need to configure each block's "Region Settings" (click "configure" on the right), to assign or adjust a region for the block to your new theme. The region settings provide a pull-down menu with available regions for each enabled theme.

If you want to duplicate settings from one sub-theme to another sub-theme, make sure you adjust all files in the theme folder (theme.info, template.php, theme-settings.php). If you do extensive theme pre- or post processing, and change themes frequently, you might want to roll these into their own custom modules (see How to modify module output via another module - whois module? for an example of the same functionality as theme pre-processing or custom module).

There might be additional settings in contributed modules - you mentioned panels.

---
Tags: theming
---


# Question
Title: Ajax not working with existing field in hook_form_alter
**If I add new select field and define ajax, all works fine**. Whereas if I attach #ajax to the existing select field it just does not work. (I can see ajax loader spining for a while and that is all.) I'm also getting error: "An illegal choice has been detected. Please contact the site administrator."

I'm suspecting my callback function is not correctly implemented. Is it valid to make changes to the form in the callback function?

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    //...

        // add wrapper to existing select field
        $form['field_event_1_role']['und']['#prefix'] = '<div id="select-event-role">';
        $form['field_event_1_role']['und']['#suffix'] = '</div>';
        $form['field_event_1_role']['und']['#options'] = array('_none' => t(' - '));

        $events_list_options = array('1' => t('1'), '2' => t('2'));

        // **add new select field with ajax - This is working fine**
        $form['test_select_ajax'] = array(
            '#title' => t('Test select ajax'),
            '#type' => 'select',
            '#options' => $events_list_options,
            '#ajax' => array(
              'event'=>'change',
              'callback' =>'event_roles_ajax_callback',
              'wrapper' => 'select-event-role',
            ),
        );

        // **attach ajax to the existing select field - NOT working?!**
        $form['field_event_1']['und']['#options'] = $events_list_options;
        $form['field_event_1']['und']['#ajax'] = array(
            'event'=>'change',
            'callback' =>'event_roles_ajax_callback',
            'wrapper' => 'select-event-role',
        );
    }

    // Ajax callback function
    function event_roles_ajax_callback($form, &$form_state) {
        $form['field_event_1_role']['und']['#options'] = array('populated' => t('populated'));
        return $form['field_event_1_role'];
    }

```

Additional info: The form I'm altering here is `registration_form` from Entity Registration module

# Answer
> 0 votes
Finally I got it working! Man this was a pain! Every bit of code is potentially a bomb.

Below is the code that is working:

```
function custom_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'registration_form' && $form['#bundle'] == 'free_registration_volunteer_call') {

            $options_first = custom_first_dropdown_options();
            $value_field_event_1 = isset($form_state['values']['field_event_1']) ? $form_state['values']['field_event_1']['und'][0]['value'] : key($options_first);

            // Setup field_event_1 select and bind ajax
            $form['field_event_1']['und']['#options'] = $options_first;
            $form['field_event_1']['und']['#default_value'] = $value_field_event_1;
            $form['field_event_1']['und']['#ajax'] = array(
                    'event' => 'change',
                    'callback' => 'custom_ajax_callback',
                    'wrapper' => 'field_event_1_role_replace',
            );

            // Setup field_event_1_role select
            $form['field_event_1_role']['und']['#prefix'] = '<div id="field_event_1_role_replace">';
            $form['field_event_1_role']['und']['#suffix'] = '</div>';
            $form['field_event_1_role']['und']['#options'] = custom_second_dropdown_options($value_field_event_1);
            $form['field_event_1_role']['und']['#default_value'] = isset($form_state['values']['field_event_1_role']) ? $form_state['values']['field_event_1_role'] : '';

    }

}

/**
* Ajax callback for Event roles dropdown
*/
function custom_ajax_callback($form, $form_state) {
    return $form['field_event_1_role'];
}

/**
 * Helper function to populate the first dropdown.
 */
function custom_first_dropdown_options() {
    $node = node_load(arg(1));
    $i = 0;
    if(!empty($node->field_events_for_volunteering['und'])) {
        foreach ($node->field_events_for_volunteering['und'] as $event) {
            if (!$i) $events_list_options['_none'] = '- Select Event -';
            $events_list_options[(string)$event['node']->nid] = $event['node']->title;
            $i++;
        }
        return $events_list_options;
    }
}

/**
 * Helper function to populate the second dropdown.
 */
function custom_second_dropdown_options($key = '') {
    if ($key) {
        $node = node_load($key);
        $i = 0;
        if(!empty($node->field_volunteer_roles['und'])) {
            foreach ($node->field_volunteer_roles['und'] as $role) {
                if (!$i) $role_list_options['_none'] = '- Select Volunteer Role -';
                $role_list_options[(string)$role['value']] = $role['value'];
                $i++;
            }
            return $role_list_options;
        }
    }
    return array();
}

```

# Answer
> 1 votes
for this you can delete this line

```
$form['field_event_1_role']['und']['#options'] = array('_none' => t(' - '));

```

The problem is most likely because of a requirement for FAPI ajax which is documented, though can be easily missed:

> Changes to the form must only be made in the form builder function (ajax\_example\_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

From AJAX Forms in Drupal 7.

The fact that you're setting the form element `[#options]` in the ajax callback is definitely a problem. The ajax callback should only return the array or HTML to be printed, not change the form. Only the return line should be in that callback.

The changes to your form should be made in the form\_alter. Also, you should use the form\_state array to check whether a value has been selected for your first dropdown. This will be updated during an AJAX request.

I recommend looking at the examples module, as well as these pages for more information on AJAX in FAPI. It can definitely be tricky.

---
Tags: entities, ajax
---


# Question
Title: Drupal 7 login form redirect back to page which they logged in on
```
$node->content['my_form'] = drupal_get_form('user_login');

```

I am creating a form that as outputted on http://site.com/datacollection/the-data-collection

When the user successfully logs in they are redirected to users/USERNAME

In drupal 6, the user would be redirected to the same page they logged in from...How can I reproduce this behavior?

# Answer
> 3 votes
* Create a action (admin/config/system/actions)

You have to use the token module and find the right token for the needed path. (Maybe someone else can point the right token for this behavior.)

* Create a trigger (admin/structure/trigger/user)

AFTER A USER HAS LOGGED IN -\> redirect to the path

# Answer
> 3 votes
There always a hook for that :) \_user\_login(&$edit, $account)

This hook is called just after a user log in. So you can make a drupal\_goto('') if you want.

# Answer
> 2 votes
If you're creating a form, you should just be able to set `$form_state['redirect']` to the appropriate path in your submit handler. That's what `user_login` is doing. Just make sure its submit handler runs before yours.

# Answer
> 2 votes
As Jimajamma pointed out, the user\_login\_block form logs the user in and leaves them on the same page. But the form is different from the normal login form.

If you want to present the normal login form on your page, and avoid the redirect, and leave the form on user/login unchanged, then the best way is probably to create your own login form which looks and behaves like the user\_login form except for the redirect. This snippet creates such a form:

```
function custom_user_login_form($form, &$form_state) {
  $form = user_login($form, $form_state);
  $form['#submit'][] = 'user_login_submit';
  $form['#submit'][] = 'custom_form_submit_redirect_current_path';
  return $form;
}

function custom_form_submit_redirect_current_path($form, &$form_state) {
  $form_state['redirect'] = current_path();
}

```

Then, you would change the form id in your code:

```
$node->content['my_form'] = drupal_get_form('custom_user_login_form');

```

---
Tags: users
---


title: How to use d3 word cloud in Drupal?

text:
# Question
Title: How to use d3 word cloud in Drupal?
I am using D3 word Cloud locally on my computer. It works fine. It gets the data from the database and displays it as word cloud on webpage. I want to place the output from it in Drupal website. How do I place it as a block?

**EDIT:** I have 2 JavaScript file, a JSON file and a HTML file. All these files I want to include. I just realised that the HTML file has this code,

```
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="../lib/d3/d3.js"></script>
<script src="../d3.layout.cloud.js"></script>
<script>
  var fill = d3.scale.category20();

  d3.layout.cloud().size([800, 300])
      .words(["This", "is", "some", "random", "text"].map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      }))
      .padding(5)
      .rotate(function() { return ~~(Math.random() * 2) * 90; })
      .font("Impact")
      .fontSize(function(d) { return d.size; })
      .on("end", draw)
      .start()
      ;

  function draw(words) {
    d3.select("body").append("svg")
        .attr("width", 800)
        .attr("height", 300)
      .append("g")
        .attr("transform", "translate(150,150)")
      .selectAll("text")
        .data(words)
      .enter().append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return fill(i); })
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; })
        .on("click", function(d) {
          var string_url = "http://etraining-dev/search/node/" + d.text;
          window.location = string_url;

  });;
  }
</script>

```

which is just script. I am not sure how to include these files and make it work. Can anyone help?

Thanks.

### Background

D3.js is a JavaScript library for manipulating documents based on data. I will need to add the d3 javascript library to the page, as well as the D3 word Cloud script. I then need some way of inserting the HTML5 canvas element in my content so that it can be manipulated by d3.

# Answer
# Option 1 - simple

### Generate a block using a custom module

Making a simple block module with drupal is really easy. The examples project includes a block\_example, this is a good starting point. The following is roughly what your module (d3wordcloud.module) should look like:

> * d3wordcloud
>
> + d3wordcloud.info
>     + d3wordcloud.module

*d3wordcloud.info*:

```
name = "D3 Word Cloud"
description = "Provides a block with awesome word cloud generated by D3."
package = custom
core = 7.x
dependencies[] = block

```

*d3wordcloud.module*:

```
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function d3wordcloud_block_info() {
  $blocks['word_cloud'] = array(
    // info: The name of the block.
    'info' => t('Display a pretty word cloud generated by D3'),
    'status' => TRUE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks
 */
function d3wordcloud_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'word_cloud':
      $block['subject'] = t("wordcloud");
      $block['content'] = '<div id="d3-wordcloud"></div>';
      break;
  }
  return $block;
}

```

Within the code that generates the block you can use drupal\_add\_js to include both the D3 js and the word cloud js. If you then copy the script you have in your html into a .js file as well you can put a drupal\_add\_js in for that as well. Wrap everything but the *draw* function as follows

```
jQuery(document).ready(function($) {
  // code that initialises drawing
});

function draw() {...

```

More drupal javascript info here

The actual block content then just has to return a placeholder for your wordcloud, eg `<div id="d3-wordcloud"></div>`. Your script looks like it draws straight into the body tag, so replace `d3.select("body")` with `d3.select("#d3-wordcloud")` so that the cloud ends up in your block.

## Option 2 - bit more drupally and extensible?

* Install the D3 module, which supplies d3 via the libraries api
* Create custom module (using parts of the d3\_example module as a template):

+ expose the D3 word cloud project as a library
    + make use of the word cloud in your block

## Option 3 - re-usable module

As option 2 but also create a fork or patch for the tagcloud module which uses your D3 word cloud library in place of its own display. This solution will give you a block for each taxonomy vocabulary tailored to the terms associated with the viewed node.
> 4 votes

---
Tags: 7, blocks, charts
---


# Question
Title: Modifying target vocabulary when migrating taxonomy terms with migrate_d2d
I'm working on migrating a D6 site to a nice, shiny, new D7 site, and as part of that migration, I need to split one large vocabulary (approx 12k terms) into two new vocabularies. I have the mapping figured out (done manually, with mappings stored in a custom table), so the only thing left to figure out is how to modify the destination vocabulary as needed. Here's what I have tried so far.

```
function nb_migrate_register_migrations() {
  // Define arguments used for all migrations.
  $common_arguments = array(
    'source_connection' => 'legacy',
    'source_version' => 6,
  );
  $vocabulary_arguments = array(
    array(
      'class_name' => 'NBPeopleOrganizationsTermMigration',
      'description' => t('Migration of People and Organizations terms from Drupal 6'),
      'machine_name' => 'PeopleOrganizations',
      'source_vocabulary' => '4',  // D6 Vocabulary ID
      'destination_vocabulary' => 'non_journalists',
    ),
  );
  $common_vocabulary_arguments = $common_arguments + array(
    'soft_dependencies' => array('NBUser'),
  );
  foreach ($vocabulary_arguments as $arguments) {
    $arguments += $common_vocabulary_arguments;
    Migration::registerMigration($arguments['class_name'], $arguments['machine_name'],
      $arguments);
  }
}
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }
    // Check to see if term is in $journalists.  If not, leave it as
    // non_journalists (as defined in migration registration), otherwise
    // change it to journalists.
    if (in_array($row->tid, $journalists)) {
      $this->destinationVocabulary = 'journalists';
    }
  }
}

```

So I've just defined one of the two new vocabs as the default when registering the migration, and then I want to modify the destination vocabulary if the source term is in my custom table.

The problem I'm having is finding what to modify to change the destination. As you can see above, I tried changing $this-\>destinationVocabulary, but that doesn't have an effect. The only other place I can see to change it is in $this-\>destination-\>bundle, but that is a protected property of the MigrateDestinationEntity class, and there is no setter function for that property. Looking at the row, I'm seeing that prepareRow isn't the place to do this, since it just has the source data for the term, not where it's going.

All that being said, what do I need to do to modify the destination vocabulary for a term on the fly like this?

Thanks.

# Answer
After poking around some more, I found my answer in this issue and the Migrate module documentation. Based on what I found there, this is what I came up with:

```
/**
 * Override of DrupalTerm6Migration. Only for People and Organizations vocabulary
 * since we need to split terms out to two new vocabularies.
 */
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Set field mapping for destination vocabulary, since we need to
    // set it on a row by row basis.
    $this->addFieldMapping('vocabulary_machine_name', 'vname');
  }

  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Create journalists array from nb_migrate_journalists table.
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }

    // Set value for name (mapped in constructor above) based on presence in $journalists array.
    $row->vname = in_array($row->tid, $journalists) ? 'journalists' : 'non_journalists';
  }
}

```

Basically it just creates a mapping between the destination vocabulary machine name and the vname variable, which is then populated in the prepareRow() method.
> 0 votes

---
Tags: taxonomy-terms, migrations
---


# Question
Title: How to automatically assign a (sequential) number to a user-created node
I'm designing a website for a group of academics. I've created a content type, called "Preprints," where users enter information about a paper they have recently submitted to an outside journal for publication. When created, these nodes are then listed on a Views page, also called "Preprints." The users, however, would like some way of tracking the order in which they submit their Preprint. Thus, I'd like to figure out some way of automatically assigning each node a number or a code. (For example, the first paper of the year would be assigned the code LPS13001, the second would be LPS13002, and so on.) My first thought was to do this through a custom field, but I haven't been able to figure this out. Any help would be greatly appreciated!

# Answer
The Serial module allows you to do exactly that. You can simply have an integer number that is incremented per content type and if you wanted a prefix you could do that in the display formatter.

> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.
> 1 votes

# Answer
I would create a custom field and then do a hook\_form\_alter. For example:

```
//This function we alter the form to add a custom submit handler
function module_name_hook_form_name_alter(&$form, &$form_state)
{
//Add a custom submit handler

 $form['#submit'][] = 'module_name_custom_submit';

}

//This is the custom submit handler, this will assign your custom field value
module_name_custom_submit(&$form, &$form_state)
{
  $form_state['values']['field_your_custom_field']['und'][0]['value'] = module_name_preprint_increment();

}

//This handles incrementing by one
function module_name_preprint_increment()
{
$type = "preprints";
  $nodes = node_load_multiple(array(), array('type' => $type));

  if (!empty($nodes)) {
    $pre_print_numer = "LPS";
    $pre_print_numer .= count($nodes) + 1;
  }
  else {
    $pre_print_numer = "LPS1"; //First preprint ever created
  }

  return $pre_print_number;
}

```

In short you need to hook your form, add a custom submit handler, then have a function that will do the incrementing for you. Refer to:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_FORM\_ID\_alter/7
> 0 votes

---
Tags: entities
---


# Question
Title: How to save a vote of an anonymous user only after registering using modal window?
Here is my usecase:

1. Only authenticated user can vote.
2. If an anonymous user tries voting, after the voting is done, the user is represented a modal window for login/register.
3. If the user registers or loges in, the vote is saved.

The vote calculation is done using cron or other module. I do not have tie up with any particular module (and fine with writing a basic one). I am currently trying my luck with Rules, Voting Rules, Fivestar and obviously, Voting API. For login/registration persona and fbauth is used, so no email verification is requierd.

A similar problem is discussed in A module that allows user to create content anonymously, then if they register, assigns the content to them, however my use case involved voting and email-free registration. Voting makes it more complicated while email-free registration (hopefully) makes it easier.

PS: I want to follow the same work flow for different nodes with plus1 (or similar) module, so a generic approach is requested.

# Answer
> 2 votes
You could store anonymous votes in a cookie, then on login/register, check to see if that cookie exists and cast the votes accordingly.

1. When an anon user tries to vote, use `user_cookie_save()` to save the Entity Type and Entity ID of the Entity that the user was trying to vote on in a cookie. Name it something like `pending_votes`. At the same time, you can trigger your modal login window. It's possible that a user won't login/register at that time and it's also possible that they will attempt to vote on other Entities before finally logging in. So you'll probably want to store the Entity Type and ID as a serialized array.
2. Then you can hook into a user logging in with `hook_user_login()` and check for the existence of the `pending_votes` cookie. If it's there, use it's contents along with `votingapi_set_votes()` to cast the pending votes. (delete the `pending_votes` cookie afterwards so they don't cast more votes each time they log in)

# Answer
> 0 votes
Lazy Registration was designed for a similar reason but I'm not sure how stable it is. Either way, it will provide a good starting point for you.

> The Lazy Registration module captures actions made by anonymous users and stores them against a temporary user account until they are ready to register.

---
Tags: 7, rules, rating
---


# Question
Title: Automatically translate double field select value, but not free text
I have created a content type with a `double field` field configured as a `Select list & Text field` with a list of predefined allowed values for the `Select List`:

```
0|my option a
1|my option b
2|my option c

```

When I create a node for that content type in my default language, I get to choose between the 3 allowed values and can input some free text in the text field (as expected).

However when I translate my node, I am unable to translate the options from the select list (I can choose between them but can't change them).

I would like to be able to translate the allowed values list once somewhere (ideally at content type level, but I'm happy to have an alternative) and have those values enforced at node level when I translate.

For instance:

* Default language (e.g English): I create 1 node with `1|my option b` as the select value and some free text
* Translation (e.g. Spanish): when I translate the node to Spanish, the select value becomes `1|mi opción b` (which can't be changed) and I can translate the free text for the input field

**Is there any way to automatically translate a double field select value (from one language to another), but not the free text (which can be translated freely) ?**

# Answer
Here is a simple workaround:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['instance']['widget']['type'] == 'select_&_textfield') {
    foreach ($element['first']['#options'] as $key => $label) {
      $element['first']['#options'][$key] = t($label);
    }
  }
}

```
> 1 votes

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


# Question
Title: How to override single function of theme's template.php using sub-theme?
**Target:** Drupal 7 Sub-Theme Development
I don't want to override whole template.php file. I just want to override single function of template.php file.

# Answer
> 5 votes
It really depends on the type of function:

* If it's a theme function (`theme_username()`) you could simply re-declare the function with your sub-themes name (`SUBTHEME_username()`).
* If it's a preprocess function, you can have your own version of the preprocess in your sub-theme, but IIRC the parent theme preprocess will still be invoked.
* If it's a your own function (not a standard HOOK based function), then you would have to put some of your own logic to allow other themes to overwrite it.

Maybe provide some more information on the function in question so that someone can give you a more specific answer.

# Answer
> 1 votes
You can use hook\_html\_head\_alter() to alter XHTML HEAD tags before they are rendered by drupal\_get\_html\_head().

```
function mytheme_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
      // I want a custom canonical URL.
      $head_elements[$key]['#attributes']['href'] = mymodule_canonical_url();
    }
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How to handle blog tags in a contrib theme?
In blog or blog-like sites, taxonomy is often used for tags and categories.

In Drupal 6, node.tpl.php files could use the $taxonomy variable if they needed access to an array of unrendered taxonomy links associated with the current node. This variable was often assumed by contrib themes to contain the post tags and\or categories, and it was rendered accordingly.

In Drupal 7, $taxonomy is no longer available.

What's the alternative? How should themers handle taxonomy? In particular, how should contrib themes do it, in order to maximally preserve visual compatibility with the 6.x version?

BTW, the bit about that in the "converting themes to Drupal 7" guide is probably incorrect.

# Answer
> 2 votes
To print the the default taxonomy field separate from the other content:

```
<?php
  <div class="content">
    hide($content['field_tags']);
    print render($content);
  </div>
  <div class="terms">
    print render($content['field_tags']);
  </div>
?>

```

This will only handle the default "tags" taxonomy. To follow discussion of an easier way to accomplish this, see this issue.

# Answer
> 0 votes
We can use taxonomy-term.tpl.php in our theme to theme the display of terms. Below are term related variables,

* $term\_url: Direct URL of the current term.
* $term\_name: Name of the current term.
* $name: the (sanitized) name of the term.
* $content: An array of items for the content of the term (fields and description). Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]). Use hide($content\['field\_example'\]) to temporarily suppress the printing of a given element.

---
Tags: 7, taxonomy-terms, theming
---


# Question
Title: Can I add text to a form file upload field?
Is it possible to add text/markup to a file upload field similar to the image below?

I thought that something like

```
$form['actions']['edit-field-upload']['#prefix'] = 'First';

```

in a hook\_form\_alter would work, but don't see anything.

# Answer
> 0 votes
You can add a #prefix to a file upload field using hook\_form\_alter, but I don't think it will give you what you're looking for

```
function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {  //custom content type of 'test'
    //custom field in the content type called 'field_test_upload'
    $form['field_test_upload']['#prefix'] = '<p>test prefix</p>';
  }
}

```

With the above code I have a custom content type of "test" and a custom field called "field\_test\_upload"

When adding a #prefix to the field I get the following results:

---
Tags: 7, forms
---


# Question
Title: How to include data-url-encode data using drupal_http_request()?
I am attempting to make a GET request using `drupal_http_request()`. A basic request works as expected but I need to include extra data. The example provided to me uses curl and the -G --data-urlencode option as shown below. What is the correct way to implement this type of request using drupal\_http\_request()?

```
curl -X GET \
  -H "Header-Example: Header Data" \
  -G \
  --data-urlencode 'include=gator' \
  https://example.com/1/endpoint

```

# Answer
`--data-urlencode` just appends `?foo=bar` to the end of the URL (encoded of course); `drupal_http_request()` has no special handling for query strings, it parses them directly from the provided URL with `parse_url()`.

That said, this would be functionally equivalent:

```
$data = drupal_http_build_query(array('include' => 'gator'));
$url = 'https://example.com/1/endpoint?' . $data;
drupal_http_request($url);

```

Request from Drupal:

```
GET /1/endpoint?include=gator HTTP/1.0
User-Agent: Drupal (+http://drupal.org/)
Host: example.com

```

Request from cURL:

```
GET /1/endpoint?include=gator HTTP/1.1
User-Agent: curl/7.30.0
Host: example.com

```
> 2 votes

---
Tags: 7, database
---


title: Advagg Cache-Control > 1 year

text:
# Question
Title: Advagg Cache-Control > 1 year
I am trying to use Advagg module. All's ok, but unshit.com states that all its css and js files Cache-Control is set more that a year.

In .htaccess

```
# Requires mod_expires to be enabled.
# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0

# Set up caching on media files for 1 year (forever?)
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
    ExpiresDefault A29030400
    Header append Cache-Control "public"
</FilesMatch>

# Set up caching on media files for 1 week
<FilesMatch "\.(gif|jpg|jpeg|png|swf)$">
    ExpiresDefault A2419200
    Header append Cache-Control "public"
</FilesMatch>

# Set up 2 Hour caching on commonly updated files
<FilesMatch "\.(xml|txt|html|js|css)$">
    ExpiresDefault A7200
    Header append Cache-Control "private"
</FilesMatch>

# Force no caching for dynamic files
<FilesMatch "\.(php|cgi|pl|htm)$">
    ExpiresActive Off
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</FilesMatch>

```

mod\_expires and mod\_headers are enabled.

I would be very grateful for any help.

# Answer
> 0 votes
https://www.rfc-editor.org/rfc/rfc2616#section-14.21 Thanks for pointing this out.
Answer will be in here eventually - https://drupal.org/node/2161115

---
Tags: .htaccess, css-js-aggregation
---


# Question
Title: Display flash, video, photo in slideshow
I want to build a views slideshow. How can I display several format in this slideshow like flash format, video formats and photos together?

I want to upload a flash file, two photos, and one video to show them in a slideshow. I'm using Drupal 7.14.

# Answer
The Views Slideshow module can loop through more than just Images. You can even have it look through rendered nodes or custom content.

By using the Views theme and template features and views slideshow you should be able to mix nearly any content you want.

There is a video by Bob Christenson that gives a very good intro to the Views Slideshow module. Though it is for D6, most of the content is similar enough to be useful in Drupal 7.
> 1 votes

# Answer
in this link there is a slideshow of images. by installing mediaFront module you can link the thumbnails to a player, in this way by clicking on any of the thumbnails the player will play the video. besides that many slideshow modules have been introduced.
> 0 votes

---
Tags: 7
---


# Question
Title: Working with template suggestions on Drupal 8
I need Drupal to use a **custom page template** if the URL contains a particular **\_GET** parameter.

In **D7** I would do something like this in the theme's template.php:

```
function mytheme_preprocess_page(&$variables) {
      if($_GET['isCustomTpl'] == true)
        $variables['theme_hook_suggestions'][] =  'page__myCustomTpl';
}

```

It doesn't work in D8 though (I would have been surprised by the opposite, considering all the architectural changes in the theme layer).

Any ideas?

Bonus question: is it possible to define such a function in a module, so that i can release it publicly without having the users to edit their themes?

# Answer
> 15 votes
You can implement the new `hook_theme_suggestions_HOOK_alter()` hook.

> Alters named suggestions for a specific theme hook.
>
> This hook allows any module or theme to provide altenative theme function or template name suggestions and reorder or remove suggestions provided by hook\_theme\_suggestions\_HOOK() or by earlier invocations of this hook.

You can use it like so

```
function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (\Drupal::request()->query->get('foo') == 'bar') {
    $suggestions[] = 'page__myCustomTpl';
  }
}

```

You can implement it in either a module or theme

---
Tags: 8, theming, hooks
---