# Question
Title: Backup_Migrate Module able to Create Backups but NOT Restore them
* Using Drupal 7.37, Omega4-SubTheme
* Acquia Dev-Desktop Stack (Development)
* Windows 7 HP
* Using Backup\_Migrate-3.1.

1. I set up my Backup and Migrate settings to back up my entire website-code and the corresponding Database.
2. This is set to copy the Backup to a subfolder in my C:\ Folder directory.
3. Back up and Migrate saves the Backups fine and I can see them when I navigate to my Backup-Folder.
4. They are saved as Zipped-Files.
5. If I try to restore using one of my Backups, I get an error (next item).
6. Exception: Unable to create directory 'C:\Drupal-Temporary/backup\_migrate\_556bb93614fe3/docroot/C:' in Archive\_Tar-\>\_error() (line 635 of C:\Users\Chandra Swa\Sites\drupal-7\modules\system\system.tar.inc).
7. There appears to be some problem in reading a "Temporary" directory, not my actual saved Backup directory.
8. What is causing this error; what does it even mean; is there a fix?

Thank you for your time to read this. I have tried to be as thorough as possible.

# Answer
Please try with the Patch mentioned on following URL: https://www.drupal.org/node/2320969#comment-9564267

Patch for make full site restore (and full site backup) work on Windows. The main problem was in assumption that directory separator is always '/' but that's not true on Win. So wherever i've found '/' in operation on paths i've changed them to DIRECTORY\_SEPARATOR constant.

Thanks!
> 1 votes

---
Tags: backups, files
---


# Question
Title: Filter users in views with a mandatory role and another role that is optional
Suppose I have a Role A and Role B. As per my requirement The Role A is mandatory for a user and the Role B is a good to have role. I want to filter out the users in the views. So If a user has only Role A, he should be listed. If the user has both the roles he too should be listed but if the user has Role B only he should be restricted. Please Suggest.

# Answer
You can put condition in View's criteria.

1. Go to your view and step ahead to filter.
2. Put first filter as. For example you have role as category A and category B.

Add following filters which can be helpful as per your scenario.

```
   Select content:role (condition : is one of A and B)
                    OR
   Select content:role (condition : is one of A)
                    AND
   Select content:role (condition : is none of B)

```
3. Don't forget to add OR and AND condition in between filter fileds.

Hope this will be helpful.
> 1 votes

---
Tags: views, 7, users
---


# Question
Title: Drupal Commerce age gate on Add to Basket?
I'm building a Drupal Commerce store for a client and some of the products are alcohol which requires me to add a popup modal with some text about age laws when they click "add to cart".

How can I do this? I've seen the 'add to cart confirmation' module but I want to display custom markup and only for certain products. The other projects I've seen are in the sandbox and not well documented on how they are used.

# Answer
First you can add a popup callback for certain products in the add to cart form alter.

e.g.

```
function my_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // if this is the alcohol
    $form['submit']['#ajax'] = array('event' => 'click', 'wrapper' => 'age_check_popup', 'callback' => 'my_module_age_check');
}

function my_module_age_check($form, &$form_state) {
    ctools_include('modal');
    ctools_modal_add_js();
    $commands = array();
    $commands[] = ctools_modal_command_display('title', theme('my_module_age_block'));
    print ajax_render($commands);
    drupal_exit();
}

```

Then you'll need to handle the clicks in the popup to either add the product or cancel (just close the popup).

You could do this via hook\_menu() callbacks or by rendering a form with buttons in the popup.

Edit:

Implement hook\_theme() to create a new template file for your popup content.

e.g.

```
function my_module_theme($existing, $type, $theme, $path) {
    return array(
       'my_module_age_block' => array(
          'template' => 'my_module_age_block'
        ),
     );
 }

```

Then add a template file my\_module\_age\_block.tpl.php and put your HTML content in here.
> 0 votes

---
Tags: commerce, javascript
---


# Question
Title: How to find the origin of variable in Drupal
Maybe this a compound question, please bear with me: I need to find out why the meta tags are not being printed on the homepage of a theme. The problem is that in `html.tpl.php` I've got this line: `<?php print $head; ?>`.

In other pages, the meta tags are being printed ok, but not on the homepage. When I look at the `page--front.tpl.php` it doesn't include any header info or markup (only the markup from the menu downwards and I can't figure out:

1. Why the difference and;
2. Where is the `$head` being defined.

And yes, the content of the homepage does have tags added to it.

Can anyone point me in the right direction?

# Answer
Looks like you should debug the code not in theme but in the module.

I assume you use the metatag module. It adds all the metatags in metatag\_html\_head\_alter().

Check what is your front page. If it is a View of a Panel, metatags are handled in a different way.

In the metatag module you can specify separate tags for the front page - check this setting. It might override your content metatags.
> 1 votes

---
Tags: 7
---


title: Forms API #states with multiple radios

text:
# Question
Title: Forms API #states with multiple radios
I've got one `radios` element:

```
$form['trip_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new trip'),
    'existing' => t('Use an existing trip'),
  )
);

```

I've got some `#states` prepared:

```
$trip_states = array(
  'visible' => array(
    ':input[name="trip_radios"]' => array(
      'value' => 'new'
    )
  )
);

```

And some other elements that use `$trip_states` for their `#states`:

```
$form['itinerary_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new itinerary'),
    'existing' => t('Use an existing itinerary'),
  ),
  '#states' => $trip_states
);

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => 'Itinerary name',
  '#required' => FALSE,
  '#states' => $trip_states
);

```

The `title` form element (and many others) properly listens to the `#states` condition and works just fine. However, `itinerary_radios` always shows up no matter what (if anything) is checked on `trip_radios`. Why does a *visible* *condition* on a radios element's **#states** not listen to another radios value?

# Answer
> 6 votes
In misc/states.js, it looks for the closest form-item, form-submit, or form-wrapper. Here's the line:

```
$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);

```

This does not play well with the way radios are themed, and states.js does not find anything to toggle. Wrapping the itinerary\_name radios in a container and applying #states to the container item is what I would call the quickest workaround.

```
$form['itinerary_radios'] = array(
  '#type' => 'container',
  '#attributes' => array(),
  'radios' => array(
    '#type' => 'radios',
    '#options' => array(
      'new' => t('Create a new itinerary'),
      'existing' => t('Use an existing itinerary'),
    ),
  ),
  '#states' => $trip_states
);

```

---
Tags: javascript
---


# Question
Title: How to get user current location and display node attached with current location?
I am developing a deal based site in drupal 7. I am using addressfield, geocoder, leaflet and views module to display deals node on leaflet map.

I am able to attach exposed filter "**city**" so that use can search deals on specific city but I want it like groupon site, where they recognize visitor city and displaying all deals related to visitor current city.

How can I get user current city and display all content related to user city on leaflet map and node view.

Thanks

# Answer
You might want to use SmartIP to get the ip/location of the visitor. Or enter a location in the user profile.

Then in the leaflet view, as filter use proximity. This way you can select the distance from the user to the node you want to filter on.
> 1 votes

---
Tags: views, entities, javascript, location
---


# Question
Title: How to remove the comma between Link multi-value field
I am using the Link module's link field. When I create a multi-valued field, it automatically adds a comma between them. I would like to remove this comma. For some other field types, such as term reference, I believe there is a way to set this in the UI, but I don't see this for the Link field.

# Answer
I figured it out. I forgot that I wasn't using a display mode but a views field display. I found that on the field settings, it gave you the option of setting the separator, which was a comma by default. I removed the comma and my issue was solved.
> 1 votes

# Answer
My suggestion would be to modify the way the links are displaying using the Display Suite module's field templates. Field templates gives you a high level of control over all the ways Drupal outputs the fields.

I found this tutorial that is pretty in depth, but in short you want to add the Display Suite module, enable it and the "Display Suite Extras" module that comes with it.

Next go to the display suite settings and enable "Field Templates." This is under Structure \> Display Suite \> Extras.

Once those are enabled, find the display settings for your content type (Structure \> Content Types \> YOUR CONTENT TYPE \> Manage Display.

On that page, in the vertical tabs at the bottom you'll see an option to set a layout. Select "One column" or "Reset". Selecting a basic layout here will enable the additional features Display Suite offers.

After your layout is set, you'll see many more options on each field for how it is displayed. You can set the field template to "Expert" and you'll get control of the wrappers, prefix and suffix content (i.e. comma or no comma), and a lot of other stuff.

I hope that points you in the correct direction. Play around with DS a bit and I think you'll really like the control it gives you.
> 1 votes

---
Tags: navigation
---


# Question
Title: Integer thousands separator in add node form
I need to place thousands separator on integer field type in add node form when the user is typing a number in the field. Is there any module or quick solution for this problem?

# Answer
you can quickly and easily build a custom module around this:

```
<form>
    <input type='text' id="input">
</form>

<script>
    jQuery('#input').keyup(function (event)
    {
        var value = jQuery('#input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('#input').val(valuewithcomma);
    });
</script>

```

adapted from here

**EDIT**
This code has been modified and works in Bartik theme, using an Article content type with an integer field 'number' - it simply resets the value of the input and strips the commas before the form is submitted to the server:

```
<script>
    jQuery('.page-node-add-article .field-name-field-number input').keyup(function (event)
    {
        var value = jQuery('.page-node-add-article .field-name-field-number input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('.page-node-add-article .field-name-field-number input').val(valuewithcomma);
    });

    jQuery('.node-article-form').submit(function()
    {
        var text = jQuery('.page-node-add-article .field-name-field-number input').val();
        var newtext = "";
        for (var i = 0; i < text.length; i++)
        {
            var c = text.charAt(i);
            if (c != ',')
            {
                newtext += c;
            }
        }
        jQuery('.page-node-add-article .field-name-field-number input').val(newtext);
    });
</script>

```
> 3 votes

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


# Question
Title: How to import the webform without changing the node id ?
I am trying to import a webform from another drupal installation, but it was changing the node id of the webform. How can i preserve the node id of the webform ? Is there any module for importing without changing the node id

# Answer
> 0 votes
There are no module allow you to do it, but if you want to transfer webform I suggest you to use Webform share module.

Also, if you just want to determinate webform by any unique id, you should use UUID module.

---
Tags: nodes, importing-exporting
---


# Question
Title: What is difference between field tables?
What is the difference between a content\_field\_myfield and field\_data\_field\_myfield in the db?

# Answer
> 1 votes
First used for field in Drupal 6.x versions.

Second used for fields in Drupal 7.x version.

---
Tags: 7, entities, database
---


# Question
Title: Any success using Vagrant + Samba for Drupal Projects?
I was desperately hoping that I'd be able to mitigate the ridiculously awful performance of Drupal in our Windows + Vagrant dev environments by using Samba rather than Virtualbox shared folders, but so far I've had exactly zero success. Has anyone else succeeded? If so, anything you can share to help?

I haven't been able to get past this error when attempting to mount the network share:

> Failed to mount folders in Linux guest. This is usually because the "vboxsf" file system is not available. Please verify that the guest additions are properly installed in the guest and can work properly.

We're running:

* Win7/Win8 host
* Ubuntu 12.04 guest
* Vagrant 1.6.3 + vb-guest plugin
* Virtualbox 4.3.12

I've seen indications around the Google-sphere that I can SSH into the guest and do some magical symlinking, but my vagrant box is powered off when the mount fails. I can't access the box.

Help?

# Answer
> 1 votes
The git project Druphpet is doing exactly what you want to achieve. https://github.com/alehkot/druphpet

It's using a Samba server under your guest(Ubuntu) accessible via Windows explorer: "\192.168.9.10\data"

For sure you Drupal website becomes really fast, because your webserver is accessing files locally(inside Linux)

The only problem with this approach is that every modifications of your Drupal code inside your Windows text editor (themes, custom module...) become slower because not local.

The other problem is that when the vm is off or crashed, you can't access your Drupal files anymore.

---
Tags: virtual-machine
---


# Question
Title: Disable creating new taxonomy terms in term reference field
I need to limit the user to the already create terms through `admin/structure/taxonomy/VOCABULARY/add` in auto complete mode, But when the user types new terms it will be added to the list. How do I can limit the user to the terms list?

# Answer
The content taxonomy module adds additional functionality to prevent new terms with the autocomplete widget.

> **D7 and Content Taxonomy**
>
> The module provides extensions to Drupal's core Taxonomy Term Reference Fields. At the moment, following extensions are available:
>
> * Parent term selector in the field settings (for options lists)
> * Options for new terms in autocomplete (Autocomplete Deluxe widget supported as well):
>     + Allow and insert new terms (default behaviour)
>     + Allow and insert new terms into a separate vocabulary
>     + Deny any new terms
> 2 votes

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


# Question
Title: Is it good to declare API details as constants
I am writing a custom module for payments and using stripe payment method to accept payments on site.

i have a payment form on site and functions are written in above mentioned module.

right now my stripe api details are placed in a function and this function is called wherever i need to use them ( stripe publishable and private keys ) but i am not sure if i am doing it right because it might be not a safe approach to use api details directly in code

so i am thinking about re-writing the code to save the details in database ( using set\_variable ) and then fetch them wherever they are needed.

can you help to figure out the most safe approach to save my details and use them.

another options is to declare them as constant at top of module but then they will be available globally that is also not secure.

# Answer
> 1 votes
I've seen both approaches, variables & constants, with storing API credentials. I've also seen private keys stored outside the webroot.

## Security Concerns

In all these cases you have, roughly, the same level of security. An intruder needs to penetrate (code injection) and discover your credentials. You *could* argue that with constants or external files are more "secure" since an intruder is unlikely to know about those, whereas he will likely know the `variables` table will have many goodies in it, but as any security-minded person will tell you, security through obscurity just isn't security.

Anyone that has access to inject server-side code will eventually figure out how to grab everything if they're so motivated. Given that, your best bet for security is to prevent penetration in the first place.

* Keep all your whole software stack (Drupal, contrib modules, web server, database, & OS) up to date.
* Be proactive about monitoring any odd errors occurring in Drupal / web server logs.
* Follow good programming practices (e.g. understand how to defend yourself against SQL injection, XSS, and other attacks)
* Don't install modules / PHP libraries from an untrusted source
* Keep up to date about any news with Drupal/PHP or any exploits related to your entire stack (e.g. drupal.org has security mailing list for recently discovered exploits)

Unless you're a high profile target, the most likely attacks you will see are script bots hitting you with well known exploits. As such, the above advice should keep you covered. Just keep in mind, the bigger you are the more time you should be investing into security.

## Practical Concerns

With all that said, I'd say the only other difference between the different methods of securing credentials is usability. If these are credentials that a developer should only ever touch, constants/secure files should be fine. If these are credentials that can change (e.g. module reuse across many sites) and you want other non-developers to change them, then the variable approach is the way to go.

---
Tags: 7
---


# Question
Title: How do we use drupal_add_library(), drupal_add_css() and drupal_add_js()?
How do I use `drupal_add_library()`, `drupal_add_css()` and `drupal_add_js()` in Drupal 8?

I am porting a module that uses those functions. I am following what reported in this post, which says these functions have been removed in favor of `#attached`, but I am not able to attach these files to my configuration page.

The error I am getting is the following:

> Uncaught PHP Exception LogicException: "You are not allowed to use js in #attached"

How do I attach CSS and JavaScript to a page?

# Answer
> 6 votes
Drupal\_add\_js() and Drupal\_add\_css() are quite simple to write in Drupal 8.

We basically create a `module_name.libraries.yml`file having list of all the jss and css that we wish to use.

An example of which is

```
name_of_the_key: // This would basically work as a key for you.
  version: 1.x
  js:
    js/name_of_your_js_file.js: {}  // Name of your js file
  dependencies:  // Adding dependencies if you have any.
    - core/jquery
    - core/drupalSettings
  css:
    theme:
    css/name_of_the_css_file.css: {} // Name of your css file.

```

This would basically add all the files but would not attach these files to your page/form.

So in order to attach the js and css to your page/form, you simply replace

```
drupal_add_js()
drupal_add_css()

```

with

```
$form['#attached']['library'][] = 'name_of your_module/name_of_the_key'; // Name of the key would be the key that you have defined in module_name.libraries.yml file.

```

***So if your module uses different js and css file at different points in a forms/pages you could define n number of keys in your libraries.yml file and use it accordingly.***

Source: https://www.drupal.org/node/2274843 and guidance form AjitS.

# Answer
> 4 votes
You can no longer add standalone CSS or JS files, you need to make everything a library.

Unless you have something that's dynamic, it's a bit of work to define it, but easy enough.

That change notice is outdated, common problem. It however does have a bold note that links to change records for adding javscript settings (not the same as inline JS as it is static and only conditions definitions/configuration).

There are also some pretty extensive docs available here: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

If you're building javascript dynamically and need to add that, then that's a bit more complicated. You can for example add it as a standalone head element yourself, but then you won't get things like weights/dependencies. That's also documented on the link above, but the recommended approach for that is to write a JS file and then trigger different behavior through javascript settings.

---
Tags: javascript, 8
---


# Question
Title: Dependent multiple selection drop down in drupal form - illegal choice error
I'm new to Drupal , in my project I have 2 multiple select drop down box. I don't know how to do dependent multi select drop down action in drupal form alter function using ajax.

Single selection dependent drop down selection is working. But when i tried the same in case of 2 multi select dependent drop down i couldn't find any solution . On multi select error "An illegal choice has been detected. Please contact the site administrator." is shown.

Please help me how to use 2 multi select dependent drop down in drupal.

Here is my code : here "field\_department" is the 1st multi select drop down. "field\_policy\_categories" is the 2nd muti select drop down. i want 2nd drop down values corresponding to 1st field's multi selected options.

```
function policy_node_form(){
$form['field_department'] = array(
    '#type' => 'select',
    '#title' => 'Department',
    '#multiple' => TRUE,
    '#options' => array(
        '' => t('-Select-'),
        '1444' => t('department1'),
        '1445' => t('department2'),
        '1446' => t('department3'),
        '1447' => t('department4'),
        '1448' => t('department5'),
        '1449' => t('department6')
        )
);
$form['field_policy_categories'] = array(
    '#type' => 'select',
    '#title' => 'Categories',
     '#multiple' => TRUE,
    '#options' => array()
);

}
function page_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'policy_node_form') {
$category = array();
$category[''] = '- None -';

$form['field_department']['und']['#ajax'] = array(
    'wrapper' => 'policy_category_list',
    'callback' => 'ajax_policy_category_callback',
    'method' => 'replace',
);

$form['field_policy_categories']['#validated'] = TRUE;
$form['field_file_upload']['#validated'] = TRUE;

if (isset($form_state['values']['field_department'])) {

    $array_departments = array($form_state['values']['field_department']['und']['0']['tid']);

    $query = db_select('field_data_field_department', 'f');
    $query->join('taxonomy_term_data', 't', 'f.entity_id = t.tid');
    $query->join('taxonomy_term_hierarchy', 'h', 't.tid = h.tid');

    $query->condition('f.entity_type', 'taxonomy_term', '=');
    $query->condition('f.bundle', 'policy_categories', '=');
    $query->condition('f.field_department_tid', $array_departments, 'IN');
    $query->condition('h.parent', 0, '=');
    $query->fields('f');
    $query->fields('t');
    $query->fields('h');
    $result = $query->execute();

    $policy_vid = taxonomy_vocabulary_machine_name_load('policy_categories')->vid;

    $category[''] = '- None -';

    foreach ($result as $record) {
        $parent_arr = taxonomy_get_parents_all($record->tid);
        $parent_level = sizeof($parent_arr);
        $parent_level--;
        $parent_tid = $parent_arr[$parent_level]->tid;
        $parent_name = $parent_arr[$parent_level]->name;
        $category[$parent_tid] = $parent_name;

        $policy_children_arr = taxonomy_get_tree($policy_vid, $parent_tid);
        foreach ($policy_children_arr as $key => $policy_children) {
            $depth = '';
            for ($i = $policy_children->depth; $i >= 0; $i--)
                $depth .= '--';
            $category[$policy_children->tid] = $depth . $policy_children->name;
        }
    }

    $form['field_policy_categories']['und']['#options'] = $category;
} else {

    $form['field_policy_categories']['und']['#options'] = $category;
}

$form['field_policy_categories']['#prefix'] = '<div id="policy_category_list">';
$form['field_policy_categories']['#suffix'] = '</div>';

$form['#validate'][] = 'form_validate_policy_add';
}
}
function ajax_policy_category_callback($form, &$form_state) {

return $form['field_policy_categories'];
}

```

# Answer
> 2 votes
To try take your second $form\['field\_policy\_categories'\]\['und'\]\['#options'\] to individual function instead of inside hook\_form\_alter().

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

  if ($form_id == 'policy_node_form') {
    $form['field_department']['und']['#ajax'] = array(
      'wrapper' => 'policy_category_list',
      'callback' => 'ajax_policy_category_callback',
      'method' => 'replace',
  );

  $form['field_policy_categories']['#validated'] = TRUE;
  $form['field_file_upload']['#validated'] = TRUE;

  $form['field_policy_categories']['und']['#options'] = categories_options($form_state);

  $form['field_policy_categories']['#prefix'] = '<div id="policy_category_list">';
  $form['field_policy_categories']['#suffix'] = '</div>';

  $form['#validate'][] = 'form_validate_policy_add';
}

function categories_options($form_state) {
  // option go to here
}

```

.

---
Tags: forms, ajax
---


title: Prepopulate the field twice

text:
# Question
Title: Prepopulate the field twice
I'm using Entityreference Prepopulate module. Is there way to pre-populate the field more than once?

**Example:**

```
example.com/add/node/custom&field_venue=92,92,92,183

```

I want the field venue to prepopulate 3 times. I can only do this if I type in the referenced node on the field, but I want it to prepopulate from the URL.

# Answer
> 0 votes
D7; Just adjust your contentype, fields names, and token.

```
<a class="your_class" href="node/add/your_node_type?field_1=[token]&field_2=[token]&field_3=[token]">Your title</a>

```

---
Tags: entities
---


# Question
Title: Can composer-dependent PHP libraries be used with the Libraries API?
I'm trying to include a PHP library called Geocod.io in my custom module. I am also trying to use the Libraries API. So far I have:

* Downloaded geocod.io to sites/all/libraries
* `composer install`'ed in sites/all/libraries/geocodio
* Started creating a `hook_libraries_info()` function with the following contents:

```
return array(
  'geocodio' => array(
    'name' => 'Geocod.io',
    'vendor url' => 'http://geocod.io',
    'download url' => 'https://github.com/davidstanley01/geocodio-php',
    'version arguments' => array(),
    'files' => array(
      'php' => array('geocodio/vendor/autoload.php'),
    ),
  ),
);

```

I have no idea what to put for 'files', is the path the the autoloader the right thing to do? Are these two ways of including things even compatible? I'm a bit stumped as to what to do next, I want to use the geocod.io library and I want to do it the most correct way. Other questions that mention these issues don't seem to include anything about how to list the files/versions.

# Answer
This is not really a direct answer to your question, but as an alternative to using the Libraries API (which I too have struggled with in this context), check out the Composer Manager module. It works nicely for PHP libraries installed via Composer, and takes care of the autoload seamlessly.
> 0 votes

---
Tags: composer, theming
---


# Question
Title: How to create a responsive theme with Omega?
How can I create a responsive theme with Omega?

So far when I wanted to theme, I unchecked the reponsive design because I don't know how to theme responsive in Omega!

Any suggestions about how to achieve this?

# Answer
> 2 votes
So, there's plenty of good documentation on both Omega 3 and Omega 4. Depending on what your background is and what your experience level is there are a number of ways to approach responsive design. I suggest defining your needs for a responsive website, and then seeing how Omega can help you. If not Omega, than the Zen and Adaptive themes are also well documented. There are free tutorials and videos on youtube, your question here is too generic to answer.

---
Tags: theming
---


# Question
Title: How do I set a custom path for feeds feed items in views?
**Update**

I tried doing what Nikhil and the referenced threads said, but I'm still have trouble. I should have been more clear initially on what the problem is. When I go to `<new-feed-node-path>/feed-items` I'm given a page not found. That is, `localhost/shows/<show>/feed-items`. The URL in views for that page used to be `node/%/feed-items`, and I changed it to `shows/%/feed-items`. The paths of the feed items themselves works fine, ie. `localhost/episodes/<episode-title>` is working.

---

In pathauto settings I put:

```
Pattern for all Feed paths

shows/[node:title]

Pattern for all Feed item paths

episodes/[node:title]

```

And then in the feeds\_defaults\_feed\_items view I put `shows/%/feed-items` in place of the default path, `node/%/feed-items`. I also tried `shows/[node:title]/feed-items`. I created a new feed each time to test.

# Answer
> 0 votes
The solution is to

Create a simple rule to delete and create url aliases after the content was saved, for the feed content type. Used a pattern `episodes/[node:title]` which will give you the result.

Refer:

1. https://www.drupal.org/node/1161202
2. https://www.drupal.org/node/1210128

---
Tags: 7, feeds, views, path-aliases
---


title: Set CSS class for the comment block

text:
# Question
Title: Set CSS class for the comment block
Could you please advice how to set additional CSS class for the comment block using Drupal hook. I'd like to paint the author and date of the comment with green color if the author of comment is not the author of a node.

Something like

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

    if ($author_comment_id !== $author_node_id) {

        $form['#attributes']['class'][] = 'add-class';
    }
}

```

The problem is that I don't see the #attributes for comment block via dsm ($form). Maybe I'm using the wrong hook? Is there any different way to achive this?

Could you please help?

# Answer
> 1 votes
I would do it by adding a new template for the block. See Drupal 7 Template (Theme Hook) Suggestions

> block--\[region|\[module|--delta\]\].tpl.php base template: block.tpl.php Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> block--module--delta.tpl.php
>
> block--module.tpl.php
>
> block--region.tpl.php

# Answer
> 0 votes
You may use this function `template_preprocess_comment`

> template\_preprocess\_comment(&$variables)

---
Tags: hooks
---


# Question
Title: use jquery to add a div wrapper to a dynamically created drupal modual div
I need to add a div with class=row around a bunch of divs that are being dynamically created by a drupal module (cant do it in the view either)

i was trying this, but since it is created dynamically, it does not work:

```
$("#row").prepend("<div id='edit-secondary-wrapper'/>");

```

this is the div that the module spits out that i want a row around

```
id='edit-secondary-wrapper'

```

# Answer
> 1 votes
You may be looking for this

```
$("#edit-secondary-wrapper").wrap("<div class='row'></div>");

```

This wraps the div with id 'edit-secondary-wrapper' with a parent div with class 'row'.

---
Tags: javascript, theming
---


# Question
Title: How to make a relation between nodes in drupal 7?
I need to create a relation between to nodes in drupal 7 without taxonomy.. because I don't have taxonomy option for drealty\_listing.. And after I need to create a view regarding these relation.

# Answer
Entity Reference module works well. But If you need to create a view, you may use Entity View Attachment module. This module attaches a view to a node.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I allow all users to access only a certain type of entityform?
I need that all users (anonymous users too) have access to the submissions of a certain type of entityform.

I can set the permission *View any entityform submission* and it works but for all types of entityform. I also try with hook\_access

How can I allow all users to access only a certain type of entityform but not for all types of entityform?

# Answer
> 0 votes
Finally I got a solution:

1. Alter the hook\_menu\_alter to call a new `access callback` for the entityform submissions:

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

```
2. Check in the new `access callback` if the user is annonymous and the type of the entityform:

```
function _mymodule_entityform_access($op, $entityform = NULL, $account = NULL) {
    global $user;
    if ($user->uid == 0 && $op == 'view' && isset($entityform) && $entityform->type == 'entityform_type') {
        return TRUE;
    }

    return entityform_access($op, $entityform, $account);
}

```

# Answer
> 0 votes
In filter. Just add.

> content: type =\> is one of (put check mark on all those content types you want. )

And then add permission for that view.

The another way is.

* Go to permission section under people admin menu.
* Navigate to node section.
* You will find your content type name with VIEW,EDIT,DELETE permission with each users.
* Just put check mark for the user you want to them able too see.

Hope this will work.

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


# Question
Title: Views exposed filter to search multiple fields
To my knowledge there hasn't been an option in drupal 7 to create a single exposed filter in a view which searches multiple fields, while in previous versions there existed modules to do just that.

Using the `or` operators is fine but then you get multiple fields in the form.

Add `Global: Populate filters` and you can have a single field but then the view never shows anything.

Is there any way or module that will make this work?

**Edit:** What I didn't notice was the field operators. For some reason the default operator for text fields in views is `=`, while a proper search function needs `contains` or `has word`. I've been looking for the reason I couldn't get it to work for almost 6 months now. Wow. What a pain. /facepalm

# Answer
> 13 votes
Yes, you can have multiple fields search in a single exported filter using `Global: Populate filters` and Views filter populate module.

Check this answer.

# Answer
> 12 votes
In Drupal 7, you can use

```
Global: Combine fields filter

```

to get the desired functionality. By using the same, you can select multiple fields on which you want to perform search.

# Answer
> 6 votes
I know this question has been answered already, but thought I'd chime in that there's another filter called "Search: Search terms" which basically emulates the Drupal node search and searches the whole node for the entered keywords. You can't select any fields to specifically search, and I'm not sure if it uses the "Search Index" view mode etc. But it works very well.

More info: http://drupal.org/node/680442

---
Tags: 7, views, search
---


# Question
Title: Ajax callback returns value but wrapper isn't filled
I'm stuck because whatever I do my wrapper is never filled with my callback, any idea ?

```

  $form['show_liste_produits'] = array(
   '#type' => 'button',
   //'#attributes' => array('onclick' => 'return (false);'),
   '#value' => t('Lister les produits'),
   '#name'  => 'awesome-button',
   '#ajax' => array(
      'callback' => 'stockerAll',
      'wrapper' => 'listeProduits',
      'method'   => 'replace',
      'effect'   => 'fade',
    ),
  );

  $form['listeProduits'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('listeProduits'),
    ),
  );

function stockerAll($form, $form_state){
 return 'test';
}
```

Thank you in advance !

**EDIT:** In fact in the network tab I get this, maybe the selector isn't working ? Moreover, my empty container isn't displayed after page load actually, maybe is it the source of the problem ?

# Answer
> 0 votes
Edit your code into the code below:

```
 $form['show_liste_produits'] = array(
     '#type' => 'submit',
     '#value' => t('Lister les produits'),
     '#ajax' => array(
         'callback' => 'stockerAll',
         'wrapper' => 'listeProduits',
     ),
);

$form['listeProduits'] = array(
    '#type' => 'container',
    '#attributes' => array('id'=> 'listeProduits'),
);

```

If it doesnt work,make sure first if `stockerAll` is called. Insert `watchdog('test','test');` in `the stockerAll` function . After doing so, run the program, check your drupal database, particularly the `watchdog` table and check whether 'test' is in the latest log.

```
function stockerAll($form, $form_state){
    watchdog('test','test');
    return 'test';
}

```

If `stockerAll` is called, clear cache of the browser to make sure the updated code is the one executing. Else, there's something wrong with the way you invoke your function.

---
Tags: 7, forms, ajax
---


# Question
Title: How do you combine exposed filter string text searches into one input field for Drupal 7 Views?
Currently I have a bunch of exposed filters in my view but I want to combine them where I can search them using only one input field. How can this be done?

# Answer
If you want to be super-flexible in your search, essentially searching through the whole listing rather than just a particular field or two, I'd suggest you simply add the '**Search Terms**' filter.

If you go to add another filter to your view, you can narrow the options by the 'Search' related ones and select the 'Search Terms' one:

You can name it anything you want, but it will essentially search through your entries the way a regular search does - so, by default, it will search through all fields that are displayed on your node, not just the ones you're displaying in your view at the moment. Hope that makes sense - just another option to consider in the mix. :-)
> 15 votes

# Answer
Set your basic filters. And then add the 'global: combine fields filter'. Set it to exposed. Select the fields you want to use as filter field.
> 1 votes

# Answer
In Drupal 7, if you don't want to use any of the other module, you can use *Global: Combine fields filter* to get the desired functionality. By using the same, you can select multiple fields on which you want to perform search.
> 1 votes

# Answer
Views filters populate module might be helpful for your issue.

> This is an utility module. Its sole purpose is to fill in one blank that seems not easy to be done using normal views, which is to use one exposed string filter to search on multiple fields.
>
> Bear in mind, that, for now, only populates STRING exposed filters, so those filters that take an array (options) or special types won't work, although it may not be difficult to extend it.

Also check this answer.
> 0 votes

---
Tags: views
---


# Question
Title: How to translate the description metatag for a view
I have a multilingual site based on drupal 7 with Internationalization i18n and Metatags modules. I made a multilingual view and it works fine, I could translate all entities except the view-description (and of course the metatag description). I would like to have for each language a different meta tag description of the view.

As I can read in this issue, it seems there is still no solution.

Is there any workaround? Thank you for replying.

# Answer
> 1 votes
You could add something in the html.tpl.php along these lines:

```
  <?php
  if((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'fr')){ ?>
      ...Your metatag here...
  <?php
  }elseif((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'de')){ ?>
      ...Your metatag here...
  <?php } ?>

```

> views\_get\_page\_view() finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.

Source

This line of code may come in handy as well, to figure out which view:

```
$view = views_get_page_view();

```

Source

Is this enough to help you on the way?

---
Tags: views, i18n-l10n, meta-tags
---


# Question
Title: How to autoupdate quiz question to newest version?
We have round about 200 quizzes with 5-10 questions. And most of the questions were updated by us. But we realized that quiz shows only the old versions.

Only solution so far is to check quiz by quiz and click updated to newest version question by question.

In settings I didn't find any possibility to auto switch to newest version as soon as the question got updated.

Any ideas to solve this problem?

Of course, we can switch every question to newest version as soon as we update them. But what about all the aprox 1000/2000 questions in system that still run on old version instead of newest?

quiz.info: `version = "7.x-5.0-alpha8+14-dev"`

# Answer
> 1 votes
According to the issue queue its says that the update issues only happen when manual revisioning is enabled. You can find out more here: https://www.drupal.org/node/1652936 Also make sure to update to latest version and run update scripts.

---
Tags: quiz
---


title: How is block different from mini panel?

text:
# Question
Title: How is block different from mini panel?
I am a newbie in Drupal.

Can anybody explain how is block different from mini panel.

# Answer
> 3 votes
Mini panels allows you to use layouts, so you can have rows and columns within a mini panel block. Making life way easier when it comes to applying css.

In addition, it allows you to attach other things, such as views, other blocks, etc.. In contrast, if you use a regular block, you can only do one thing at a time with them.

So if you have lots of blocks, it can be messy if you want to change the block position. While if all the blocks are inside a mini panel, you can move them all at once.

Don't think of it as mini panel vs block. Think of it as mini panel being a block management system.

---
Tags: 7, blocks, panels
---


title: Use drupal #states to check a radio

text:
# Question
Title: Use drupal #states to check a radio
I would like to translate some jquery .change functionality to use #states in the form api.

```
var radio1 = jQuery('input:radio[name=radio_1]');
var radio2 = jQuery('input:radio[name=radio_2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});

```

Logic:
If radio1 value 0 is selected then radio2 value 1 will be selected.
If radio1 value 1 is selected then radio2 value 0 will be selected.
if radio2 value 0 is selected then radio1 value 1 will be selected.
if radio2 value 1 is selected then radio1 value 0 will be selected.

Looking at form\_example\_states\_form() shows that the syntax is:

```
'#states' => array(
  'action_to_take_on_this_form_element' => array(
    'jquery_selector_for_another_element' => array(
      'condition_type' => value,
    ),
  ),
),

```

What's missing for me is "action\_to\_take\_on\_this\_form\_element". I don't know how to select value 0 or 1 of the radio button; all I have in terms of viable options is checked/unchecked (see drupal\_process\_states() for a list).

What I currently have

```
'#states' => array(
  'checked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 0,
    ),
  ),
  'unchecked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 1,
    ),
  ),
),

```

and this doesn't seem to work. I need something like checked\[0\] in order to select the value 0 radio button.

Edit: Here is the working code. Would like to not use inline js.

```
function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 0,
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 1,
  );

  $form['#attached']['js'][] = array(
    'data' => "var radio1 = jQuery('input:radio[name=radios1]');
var radio2 = jQuery('input:radio[name=radios2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});",
    'type' => 'inline',
  );

  return $form;
}

```

Demo video: https://www.youtube.com/watch?v=lXfMFaTTVes

# Answer
You can use the form\_api #after\_build property to set a callback where you can manipulate the individual radio button elements (not the grouped "radios" element).

```
function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['#after_build'] = array('your_form_after_build_function');

  return $form;
}

function your_form_after_build_function($form) {
  $form['radios1'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 1),
    ),
  );

  $form['radios1'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 0),
    ),
  );

  $form['radios2'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 1),
    ),
  );

  $form['radios2'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 0),
    ),
  );

  return $form;
}

```
> 7 votes

# Answer
Since #states is bugged for radios at the moment, another option might be to use an #ajax callback, as long as the extra server requests don't cause a problem for you:

```
function my_form($form, &$form_state) {
  $form = array(
    'radios1' => array(
      '#title' => 'Radios 1',
      '#type' => 'radios',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      '#prefix' => '<div id="radios1-ajax-wrapper">',
      '#suffix' => '</div>',
      '#ajax' => array(
        'callback' => '_my_ajax_callback',
        'wrapper' => 'radios2-ajax-wrapper',
      ),
    ),
    'radios2' => array(
      '#title' => 'Radios 2',
      '#type' => 'radios',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      '#prefix' => '<div id="radios2-ajax-wrapper">',
      '#suffix' => '</div>',
      '#ajax' => array(
        'callback' => '_my_ajax_callback',
        'wrapper' => 'radios1-ajax-wrapper',
      ),
    ),
  );

  if (isset($form_state['triggering_element'])) {
    switch ($form_state['triggering_element']['#name']) {
      case 'radios1':
        unset($form_state['input']['radios2']);
        if ($form_state['values']['radios1'] == 0) {
          $form['radios2']['#default_value'] = 1;
        }
        elseif ($form_state['values']['radios1'] == 1) {
          $form['radios2']['#default_value'] = 0;
        }
        break;

      case 'radios2':
        unset($form_state['input']['radios1']);
        if ($form_state['values']['radios2'] == 0) {
          $form['radios1']['#default_value'] = 1;
        }
        elseif ($form_state['values']['radios2'] == 1) {
          $form['radios1']['#default_value'] = 0;
        }
        break;
    }
  }

  return $form;
}

function _my_ajax_callback($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'radios1':
      return $form['radios2'];

    case 'radios2':
      return $form['radios1'];
  }
}

```

I wouldn't recommend this as a long-term solution though.

---

My original idea below suffers from the same #states bug as encountered when using an #after\_build function, hence the strikethrough.

~~Given that the #after\_build method is slightly bugged with the radios type, an alternative method that seems to work for me is to build the form out of individual radio elements and change the radio groupings using #attributes. That way you can set #states in your form constructor without needing an #after\_build function:~~

```
function my_form($form, &$form_state) {
  $form = array(
    'radios1' => array(
      '#type' => 'container',
      '#prefix' => '<label for="edit-radios1">Radios 1</label>',
      '#tree' => TRUE,
      1 => array(
        '#type' => 'radio',
        '#title' => 'One',
        '#return_value' => 1,
        '#attributes' => array(
          'name' => array(
            'radios1',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios2"]' => array('value' => 2),
          ),
        ),
      ),
      2 => array(
        '#type' => 'radio',
        '#title' => 'Two',
        '#return_value' => 2,
        '#attributes' => array(
          'name' => array(
            'radios1',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios2"]' => array('value' => 1),
          ),
        ),
      ),
    ),
    'radios2' => array(
      '#type' => 'container',
      '#prefix' => '<label for="edit-radios2">Radios 2</label>',
      '#tree' => TRUE,
      1 => array(
        '#type' => 'radio',
        '#title' => 'One',
        '#return_value' => 1,
        '#attributes' => array(
          'name' => array(
            'radios2',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios1"]' => array('value' => 2),
          ),
        ),
      ),
      2 => array(
        '#type' => 'radio',
        '#title' => 'Two',
        '#return_value' => 2,
        '#attributes' => array(
          'name' => array(
            'radios2',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios1"]' => array('value' => 1),
          ),
        ),
      ),
    ),
  );

  return $form;
}

```

~~Note that I've changed your "Zero or One" radios to "One or Two" for this example because another bug in core means a radio with a value of 0 always gets checked when the form is built. If you absolutely must use a value of 0 then you'll need to work around that bug in some way.~~
> 2 votes

# Answer
Have a look here:

Instead, you must use 'value' =\> 'name', where 'name' is the name of the radio option that you require to be selected. In your example it could be '1' instead on 1.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to print taxonomy id of the current taxonomy term
I have custom taxonomy term pages which I'm using to override forum pages and I want to emulate advanced forum node/add/forum/tid button so I have to get tid but don't know how, I can only find examples on how to print tid of the current node.

# Answer
> 1 votes
You can use below code to get Taxonomy id by Taxonomy Name

```
 $taxonomy_term = taxonomy_get_term_by_name('Taxonomy Term Name');
 $tid = $taxonomy_term>tid;

```

# Answer
> 0 votes
You can use taxonomy\_get\_term\_by\_name and use arg(3) (those are the URL args find out more about those here in the docs) or something similar to pull the name. That function should return an array of match term objects. There should be more information on the taxonomy.module docs that could help as well, you can find them here: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/6

I have experience in D6 but not as much as D7 but something like that should work or a custom query but I'd advise against those since there is already a function for it in the API.

---
Tags: views, 6
---


# Question
Title: How to rearrange EVA fields in profile2?
I augmented a profile2 profile with two Eva views.

Now, I would like to re-arrange them. For that, I would like to see those fields in the Manage display tab. I tried to explicitly create those missing fields, looking in vain for an Eva view type.

Anyone having met this problem ? Thanks.

# Answer
I installed Profile2(7.x-1.3) and Entity Views Attachment(7.x-1.2) on Drupal 7.34.

When you create two eva fields in your respective views and set "Entity type" as Profile and Bundle as "Your profile name" as shown in the following figures: Entity Type - Profile, Bundle - Custom. "Custom" is the name of the profile I created.

After saving the views with their respective eva fields , the fields for display automatically appear in the "Manage Display" tab of your profile as shown below(note the fields with prefix EVA) :

Here you can reorder EVA fields with ease.

And this is how the views are rendered in the user's profile page :

I included above screenshots, in case you have missed some settings. If you still can't see the required fields, then create a new issue here for EVA or here for Profile2. Hope I could be of help. Please excuse me for my late reply as I am new to Drupal.
> 1 votes

---
Tags: users
---


# Question
Title: Can't add a new field of type entity reference!
Other field types can be added, but only a field of type "Entity Reference" can't be added.

I am getting a status message "Die Einstellungen wurden gespeichert."(Configuration has been saved), but it should redirect me to the manage field of the content type in which I am adding the content type.

Can someone please help me with this?

# Answer
It was my browser's cache.

On clearing my browser cache I was able to see the Entity Reference field as well.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: What hook is triggered when adding / updating and deleting taxonomy?
I need to update some value in database when a taxonomy term is added or updated or removed. What is the proper hook to use here ?

# Answer
Take a look at the taxonomy.api.

Looks like you're gonna want to take a special look at hook\_taxonomy\_term\_insert, hook\_taxonomy\_term\_update, and hook\_taxonomy\_term\_delete.
> 1 votes

---
Tags: 7, taxonomy-terms, hooks
---


# Question
Title: How to add additional display (view mode) for all node types?
Firstly, I've seen this question, have followed the steps in the answer by FranCarstens to no vail.

To clarify: I want to add custom views to all content types. (as a side question, would be nice to know how to target a specific node type, if possible).

I've created the modules, enabled it but it doesn't show as an option in any of my content types.

What am I missing?

Thanks!

# Answer
The programm way from related quedtion should work, but it doesn't, you can try to use the following module: https://www.drupal.org/project/entity\_view\_mode

> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.
> 1 votes

---
Tags: 7
---


# Question
Title: Redirect to a custom page in hook_init()
I need to redirect users to a custom page using `hook_init()`.

I have tried `drupal_goto()`, but it is not working fine. By using drupal\_goto(), it is looping and it is not giving the correct result.

So, for that, I have checked a condition using `drupal_get_destination()`. But, it is not working correctly.

Here is the code:

```
$destination = drupal_get_destination();

foreach($compatible_arr as $key => $val) {
if(isset($browser_arr[$key])) {
    if(version_compare($browser_arr[$key], $val, '<')) {
        //print strpos($destination['destination'], 'browser-limitations');
        if(strpos($destination['destination'], 'browser-limitations') == '') {
            drupal_goto($base_url.'/browser-limitations/', array('query' => array('version' => $val)));
        }
    }
}

```

I am using this condition in order to check the browser version using the Mobile Detect module. But, I am not getting the correct result. Is it safe to use drupal\_goto() in hook\_init()? Or else, is there any function to use it?

# Answer
If you define the redirect in hook\_init, then it would work for non cached pages. But in case of Cached pages it would not work.

So it is recommended to use hook\_boot instead of hook\_init.

hook\_boot would help you in redirecting for cached pages as well.
> 1 votes

# Answer
In your code, you just need `header()` (a PHP function) instead of `drupal_goto()`.

```
$destination = drupal_get_destination();

foreach ($compatible_arr as $key => $val) {
  if (isset($browser_arr[$key])) {
    if (version_compare($browser_arr[$key], $val, '<')) {
      //print strpos($destination['destination'], 'browser-limitations');
      if (strpos($destination['destination'], 'browser-limitations') == '') {
        $url = $base_url . '/browser-limitations?version=' . $val;
        header('Location: ' . $url);
        exit;
      }
    }
  }
}

```

It is better you put your code in hook\_preprocess\_page() instead of using `hook_init()`.
> 0 votes

# Answer
Ok, from reading you code again, I think I understand what you are trying to achieve.

First, you want to get the current path ("destination"). This is not the way to do that:

```
$destination = drupal_get_destination();

```

`drupal_get_destination()` is used when redirecting a user *after* some event (like a form submission). In your case, this will return nothing (or at least not what you expect). Which is why your code triggers an infinite loop: the checking if `$destination` contains `browser-limitations`will always fail, as `$destination` is treated as an empty string (or contains some other path than the current one).

You must use:

```
$destination = current_path();

```

This will give you the current internal path, the path that is currently being loaded.

Then, you probably want to check if you're on the `browser-limitations`page BEFORE looping. Saves you a few ms. And finally, `drupal_goto()` expects an internal path, so you can simplify your final call (no `/` in front or after, don't worry about `base_path()`).

```
if (!preg_match('/browser-limitations/', $destination)) {
  foreach($compatible_arr as $key => $val) {
    if(isset($browser_arr[$key])) {
      if(version_compare($browser_arr[$key], $val, '<')) {
        drupal_goto('browser-limitations', array('query' => array('version' => $val)));
      }
    }
  }
}

```

Try that.
> 0 votes

---
Tags: hooks
---


title: Drupal Web Form put on the content

text:
# Question
Title: Drupal Web Form put on the content
How can I move the Web form from the bottom of the content area to the top of content area?

Where is the setting for this? Is it possible to move where the webform is displayed? The web form is in the bottom, and I need it to be in the top.

# Answer
You can do this with your theme.

In your node.tpl.php (or any of it's derived tpl.php files, like node--CONTENTTYPE.tpl.php) you'll likely see a point where something like this is going on:

```
print render($content);

```

before that content is rendered, add

```
print render($content['webform']);
hide($content['webform']);

```

so the full code code snippet should look something like:

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

```

Basically what your doing is telling drupal to:

1. render out the webform.
2. hid the the webform from any other render attempts.
3. render out the rest of the page content.

Another option would be to render out the webform as a block, which would mean you could load it in any other part of the site. The option for that would be located in the webform's individual edit screen, under form settings, advanced settings (down at the bottom), and "Available as block."
> 1 votes

# Answer
If you enabled this Webform to have a block, then go to Structure -\>blocks, look for a webform block, move it to the top content region or in the highlighted region.
> 1 votes

---
Tags: webforms
---


# Question
Title: Does hook_node_submit() fire on feed import?
If I implement `hook_node_submit()`, will it be invoked when I import nodes from a feed?

# Answer
I believe hook\_node\_submit() only gets fired when submitting a node form. So the answer to your question is no.

I think you might be better off using hook\_node\_presave(). This hook is invoked from node\_save() before the node is saved to the database.
> 0 votes

---
Tags: 7, feeds, nodes
---


# Question
Title: Programmically populate select list with hook_form_alter
I have no trouble populating other fields, but am struggling with populating a select lists #options. Anyone know of a slick way of going about that or have any good reference material?

# Answer
I'm not sure to understand what do you want but here is a sample of code I've that may answer to your question.

```
$form['remise'] = array(
    '#type' => 'select',
     '#options' => array(
        0 => t('Sur les catégories & les marques'),
        1 => t('Sur les catégories uniquement'),
        2 => t('Sur les marques uniquement'),
     ),
    '#title' => t('Remises'),
    '#required' => TRUE,
    '#default_value' => 0,
  );
```
> 1 votes

---
Tags: forms
---


title: Get Term ID from URL

text:
# Question
Title: Get Term ID from URL
Possible to get the current URL then grab the term id from it.

com/fishing-report/lakename

lakename being the term. Can i get the Term ID?

# Answer
> 1 votes
Basically you would have to do:

```
$path = current_path();
$path_array = explode('/', $path); // Doing this you would get the array of all the elements that there in the url.

```

Once you have the array of items in the array, you would have to do

```
$term_name = $path_array[1];

```

So in **$term\_name you would have lakename**, which is your **term name**.

Once you have the name, simply do

```
$term_object = taxonomy_get_term_by_name($term_name);

```

**$term\_object would have the object of the term.**

For more detail: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy\_get\_term\_by\_name

# Answer
> 0 votes
Use `taxonomy_get_term_by_name()` & `arg()` functions to get a taxonomy id from a URL term name. For example, from the URL above...

```
  $term = arg(1);
  $terms = taxonomy_get_term_by_name($term);
  $tid = (count($terms) > 0) ? array_pop(array_keys($terms)) : null;

```

Note: `taxonomy_get_term_by_name()` will return zero or multiple terms (it outputs an array of found taxonomy object with the tid being the keys) so you might need to check to see any term objects are returned.

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


title: New subscriber notification

text:
# Question
Title: New subscriber notification
How can I get an email notification when there is a new subscriber? I can't find this setting on the Simplenews module, but I do find "Send e-mail" in "Configuration \> Actions".

Does Simplenews has this feature? Can *Send e-mail* actions make this work? if so, how?

# Answer
Enable the **Simplenews Rules** module within the Simplenews project. It will add 2 events *A user has been subscribed* & *A user has been unsubscribed*.

Use the subscribe event combined with your *Send mail* action to send a message on user subscription.
> 3 votes

---
Tags: 7, emails, notifications
---


# Question
Title: Drupal shortcuts - link with question mark included
When I add a link to shortcut set which looks like this:

admin/work?date\_filter

shortcut module changes this question mark sign "?" into this "%3F" and this link doesn't work anymore. I believe I can't avoid it - looks like it's a bug, so my question is how to add link as a shortcut programically?

# Answer
The shortcut module is more strict about valid URLs it can use compared to what the menu module will allow (e.g. no external URLs, no query param).

One way to circumvent this is to use `hook_menu` in a custom module to define a valid path that redirects where you want it to go and add that path to your shortcut set.

```
function MYMODULE_menu() {
  $items['MYMODULE/work'] = array(
    'access arguments' => array('access content'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('admin/work', array('query' => array('date_filter' => 'XXX'))),
    'type' => MENU_CALLBACK
  );
  return $items;
}

```

This makes `MYMODULE/work` a valid path for your shortcut set.
> 1 votes

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


title: Hiding fields from RESTful services?

text:
# Question
Title: Hiding fields from RESTful services?
So, this may be a stupid question because it seems pretty basic to me, but I can't find any information about this on here or elsewhere. Is it possible to specify fields to be visible/invisible to RESTful requests in Drupal 8? I would expect that this should be possible to configure--or, at the least, that fields hidden from the display would not be accessible via such requests.

Is this possible, or is there something that I'm simply not understanding here?

# Answer
The only way to do this is using field access (hook\_entity\_field\_access()) and denying view access to fields that you don't want to be visible.

The primary use case that the default rest.module/entity integration aims to support is data synchronization. My standard suggestion for anyone who wants to offer public services on a site or build a custom frontend is to consider writing and defining services tailored for that specific use case.

It's also quite possible that more flexible solutions will be developed in contrib, one of those is relaxed, I don't know if it helps with this specific use case, though.
> 1 votes

---
Tags: 8
---


# Question
Title: redirect or rewrite /user/xx links to a module page
This should be easy to do, but its very hard to Google.

Within the admin and surrounding workflows, various links point to user/foobar. I have a different page to display users, say /faces/xx. I want to intercept (or rewrite) every url linking to user/foobar/ to faces/xx.

Pathauto lets you customize what paths user profiles have. If I set that to /faces/\[user:uid\], it will create aliases overriding my module router; so that faces/xx looks the same as user/foobar previously did. That is *not* what I want.

You can redirect users on login or other triggers. That is also *not* what I am looking for.

Most likely, I can override something in my module that intercepts user/foobar calls and does a `drupal_goto('faces/xx')`. Or there is a url\_alter that I can override that writes out the user/foobar links. That, or something similar, is what Im looking for.

EDIT -- sample code from the module that generates the faces page

```
function faces_menu() {
    $items = array();
    $items['faces/%'] = array(
        'title'             => t('Face'),
        'access callback'   => true, // more complex in reality
        'page callback'     => 'faces_page',
        'page arguments'    => array(1,2),
        'type'              => MENU_CALLBACK,
    );
    return $items;
}
function faces_page($uid) {
    global $user;
    $output =  array(
        'faces-page' => array(
            'magic'     => voodoo($uid),
            '#theme'    => 'faces_pages'
        )
    );
    return $output;
}

```

and ofcourse theres a faces\_theme() to match it.

# Answer
> 0 votes
d'oh! thanks to @geoff above .. this seems to work (in a module called 'faces')

```
function faces_user_view($account, $view_mode, $langcode) {
    if ($view_mode=='full') {
        drupal_goto('faces/'.$account->uid);
    }
}

```

---
Tags: users, redirection
---


# Question
Title: Can you stop embedded Flickr Images from following their link if the user clicks the image, thus leaving your Drupal website?
* Using Drupal 7.37, Omega4-SubTheme
* Acquia Dev-Desktop Stack (Development)
* Windows 7 HP

Using Media Module with the Flickr provider Module installed, the Media\_YouTube, and the Media\_SoundCloud providers installed as well (along with their dependencies).

1. I set up some dummy-content via a customized Create-Content node. Added Flickr-Images as a field-type bundled with various tags to distinguish properties of my Media-Files for later categorization. I have other Media-File-Types and their Providers installed as well (Media\_YouTube, Media\_SoundCloud) and they work fine without adding outbound-site-leaving-links.
2. Then I set up Views to output all the content of the website along with respective fields. All this works and displays small representations of the media in a table along with my added fields.
3. In this Views display, Flickr embedded-images show up fine and can be styled, but unlike YouTube-Videos or SoundCloud\_Audio-Files, Flickr-Embedded-Images will leave the website when clicked. Both YouTube and SoundCloud do not exhibit this behavior and instead only play their respective Media.
4. Is there anyway to block, stop, or (best) redirect the Flickr-Images to show their associated node rather than linking to Flickr?
5. I have tried every configuration Option I can find. I have tried options in the Create-Image-Content node GUI but I see nothing to suppress the outbound-links. I have tried the Views-Display GUI, but again, I see nothing in the Views-Settings that suppresses the outbound-links. And I have also tried the Administration\>\>Configuration\>\>Media\>\>File-Types setting for my Image-File-Types (this control-panel is very mysterious). In none of these locations can I come across something which shuts-off this outbound behavior.
6. I have spent much time trying all kinds of option-permutations and searching for any kind of documentation but have come up with no solution.
7. Is there an option-solution or a css-workaround or do I have to abandon the Flickr-provider-module because this is its hard-wired behavior?

# Answer
For now I have completely disabled Flickr as well as Media\_YouTube and Media\_SoundCloud in favor of using the Media\_Oembed Module. Media\_Oembed handles the all of the above Embed needs (and more). In Media\_Oembed, the Flickr Module does not out-link. Probably a better overall solution in general.

**There are two OEmbeds!!** At first, I tried Oembed, which is still in beta (as of 2015-06-03) and I could not get it to work; I don't know what the problem was, but Media\_oEmbed seems to work fine.
> 0 votes

---
Tags: navigation, media, nodes, files
---


title: Add class to image in view

text:
# Question
Title: Add class to image in view
Is there a way to add a specific class to the img tag in a view? I'd prefer to use a template to perform it. I can see how I can change what classes the image is wrapped in, but I don't see a way to edit the classes of the img tag itself.

I see there's a way to edit the image field using **views-view-field--field-image.tpl.php** however the only variable I can see that is available is $output.

# Answer
> 3 votes
If `.myclass img { your code goes here }` is not good enough and you must have the class inside the img tag, then:

1) Download and enable the Image URL Formater Module

2) On your view's picture field, select url as format.

3)

**Option A)** In the rewrite results field type `<img src="[field_image]" class="yay-we-did-it">`

**Option B)** if you want to use the .tpl.php file, put this inside it.

`<img src='<?php print $fields["field_image"]->content; ?>' class='yay-we-did-it'>`

---
Tags: views, theming
---


# Question
Title: Assigning global var to session variable?
I want to assign the user name to a SESSION variable, yet this is not working.

> $\_SESSION\['loveleytest'\] = $user;
>
> $\_SESSION\['thelovelytest2'\] = $user-\>name;

What should I do?

# Answer
For assigning user\_name to a session variable you would directly do something like

```
global $user;
$_SESSION['thelovelytest2'] = $user->name;

```

I think the issue with your code may be:

1. It is not able to retrieve the `global $user` variable.
2. You might not have defined the global $user variable.
3. Because you did `$_SESSION['loveleytest'] = $user`, thats why the issue is there.

I am also curious to know which was the exact issue.
> 0 votes

---
Tags: sessions
---


# Question
Title: Global Combine fields filter (Views) does not include Referenced Entities (Content Type)
I have an Content type which contains another Content type, I managed to put in place the relationships using `Entity Reference` I also configured Views module to display the contained content type, the problem is when creating a Global Combine fields filter I can't search with the contained Content type, it always returns an empty result. Is something wrong with my approach ?

# Answer
> 1 votes
This is not possible with Global Combine fields filter at the moment, see also the feature request for the Entity reference module.

This is possible though with the Views filters populate module. You can use any field of a referenced entity or field collection of which you setup the relation with in your view.

Howto :

* Like the instructions on the module's page describe, first step is to add the fields you want to search on in an OR combination of filters. With Drupal6 that would have been by using the 'Views Or' module; with Drupal7 this is just a filter group with internal operator set to 'Or'. These individual filters should not be exposed.
* Then these filters can be exposed as one input by adding the module's provided filter called 'Populate filters', found on the 'Global' section. Expose it and check the filters you added in the Or group.

---
Tags: views, entities
---


# Question
Title: How do I make the nodes referenced by organic group content also be OG content?
I have an organic group called 'newsletter'. I have two content types - 'issue' and 'article' - in 'issue' (which is set to be a group content type), there is a node reference field to articles, and many articles in a single issue, using an inline entity reference form.

I want to put an issue inside an organic group, for access control. I also want the articles that the issue references inherit that group content relationship without having to explicitly set the group for every single piece of content.

The group is public, but the content is private. I don't want anyone to access group content until they go though a process and purchase access via the commerce\_licence\_og module.

The article (content referenced in entity reference field) isn't added to the group content, though the issue itself is. I felt that a group reference for every article is redundant, and I would rather the article inherit the issue's access and status as group content rather than have a bunch of redundant fields and is automatic, not requiring additional admin steps.

Is there an easy way to do this? Do I HAVE TO make the articles group content in the UI?

# Answer
Here is the solution I've come up with.

It works, but might not be the most elegant solution. I didn't think that this would matter too much, since it's only being called on node save, but I'm open for comments and suggestions.

```
/**
 * Ensure that referenced nodes belong to the same organic group
 *
 */
function MODULE_node_presave($node) {

  if ($node->type == NODE_TYPE) {

    $og = og_get_entity_groups('node', $node);
    $nids = get_referenced_nodes($node);

    foreach($nids as $nid){

      $child_node = node_load($nid);

      //Set the values
      $values = array(
        'entity_type' => 'node',
        'entity' => $child_node,
        'state' => OG_STATE_ACTIVE,
      );

      //Add this node to the group
      $gid = array_values($og['node']);
      $result = og_group('node', $gid[0], $values);

    }
  }
}

/**
 * Helper function - get all node reference fields of a node
 * @param $master_nid - the node id of the referencing node
 */
function get_referenced_nodes($master_node) {

  $fields = field_info_instances('node', $master_node->type);

  $items = array();

  foreach($fields as $field){

    if($field['widget']['module'] == 'inline_entity_form'){
      // Get the node reference items for this field
      $items[] = field_get_items('node', $master_node, $field['field_name']);

    }

  }

  // Loop through and grab the nids
  foreach ($items as $field) {
    foreach($field as $target){
      $nids[] = $target['target_id'];
    }
  }

  return $nids;

}

```
> 0 votes

---
Tags: 7, nodes, organic-groups
---


title: path_to_theme() return "modules/system"

text:
# Question
Title: path_to_theme() return "modules/system"
I am trying to render the theme logo as a block.

When I call `path_to_theme()` in page.tpl.php, it returns a true path, but when I call it in modulename.module, it returns "modules/system".

# Answer
> 11 votes
Whenever I'm stuck in a module, or a context that `path_to_theme()` doesn't return what I'd like - I use the following to access the current globally selected theme.

```
global $theme;
$path_to_theme = drupal_get_path('theme',$theme);

```

For instance if I am in a subtheme, or a slighly different flavour (mobile vs. desktop) of my theme, I use `$theme` that to get my active theme.

# Answer
> 2 votes
When inside a theming context (e.g. a theme function or a template file), `path_to_theme()` returns the path to the *current themed element*, not the current active theme. So, when you call it from a theme, it returns the theme, but when called from a module, it returns the path to the module that created that themed element.

Since you're calling it in `foo.module` and you're getting `modules/system`, it's likely you're calling it from a theming context that does not have a custom implementation of `page.tpl.php`. Thus, it defaults to core's path for the base templates: `modules/system`.

If you're trying to get the path to the active theme, use `path_to_theme()` outside of a theming context.

Otherwise, you can use:

```
variable_get('theme_default', 'bartik')

```

to get the default theme, or:

```
global $user;
print $user->theme;

```

to get the current user's theme.

# Answer
> 2 votes
I had this same issue. I found that it was because I only had a page--front.tpl.php template file and not a page.tpl.php template. I added the page.tpl.php and everything worked again :)

# Answer
> 2 votes
I also encountered this problem when I am calling path\_to\_theme function inside a region .tpl file.. Using the code concept of Mr. electblake

I created a function in my Drupal theme template.php like this:

```
function mythemepath() {
global $theme;
$mythemepathvar = drupal_get_path('theme', $theme ) ;
return $mythemepathvar;
}

```

And now I can simply call it from any of my template files.

```
<img src="<?php echo mythemepath(); ?>/images/imagethumbnail.png" />

```

# Answer
> 1 votes
The only time that it occurred with m was because there wasn't an theme\_preprocces\_node (or page if your problem is on an page file) on my theme. So it was pointing to some module that have it.

To solve, I've just declared the preprocces like:

```
function mytheme_preprocces_node(&vars)
{

}

```

and magically it worked.

---
Tags: theming
---


# Question
Title: Using rules, how do I assign an action to a vbo list item based on its position in the list?
I'm using rules and conditional rules. I have an action set that is using a vbo list (4 node titles sorted by post date desc) to flag nodes on the list. This works fine. However, I need to make the first item on the list sticky and the 2nd item on the list promoted. Then I need to remove sticky and promoted from the 3rd item.

Do I need to be using alert\_entity\_list:0 and alert\_entity\_list:1 or should I be looking for alert-list-item:0, etc. ... or am I way off base?

# Answer
I should have posted this as my answer and not as a comment to my question. As stated above, the answer would be entity-list:0 token.
> 1 votes

---
Tags: rules
---


# Question
Title: How can I change field suffix due to its value
I have a field which is of type number.

I have a view where this field is shown with its suffix. I want it to change when the value of a field is more than 1.

Is it possible to do something? Maybe some preprocess function or some module?

Thanks for any help.

# Answer
Views Conditional would be worth giving a try. The module pages says -

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> Equal To Not Equal To Greater Than Less Than Empty Not Empty Views conditional allows you to output text based on the result of the condition.
> 1 votes

# Answer
One of the option thats possible is to write a view field tpl for that field.

Writing a tpl would give you an option to handle 0, 1 and more than 1 options in one go.
> 0 votes

---
Tags: entities
---


title: How to select fields from content type

text:
# Question
Title: How to select fields from content type
What is the best way to do a db query for fields in a content type?

I need to get specific fields from a content type, but only where the 'featured' field value is 1.

```
<?php
        $query = new EntityFieldQuery();

        $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'mycontenttype')
          ->propertyCondition('status', NODE_PUBLISHED)
          ->fieldCondition('field_mypdf', 'value', 'NULL', '!=')
          ->fieldCondition('field_mypdf', 'fid', 'NULL', '!=')
          ->fieldCondition('field_mypdf_image', 'fid', 'NULL', '!=')
    ?>

```

Originally, I was doing something along the lines of:

```
<?php
$query = "SELECT node.nid AS nid, 'node' AS field_data_field_news_node_entity_type, 'node' AS field_data_field_news_date_text_node_entity_type, 'node' AS field_data_field_news_teaser_node_entity_type, 'node' AS field_data_field_news_body_node_entity_type, 'node' AS field_data_field_news_video_node_entity_type, 'node' AS field_data_field_news_video_image_node_entity_type, 'node' AS field_data_field_mypdf_node_entity_type
    FROM node
    INNER JOIN field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')";
?>

$result = db_query($query);

<?php foreach ($result as $row) : ?>

    <div class="featuredArticle">
        <?php print $row->field_mypdf_value; ?>
        <?php print $row->field_mypdf_fid; ?>
    </div>

<?php endforeach; ?>

```

# Answer
> 1 votes
I think choice is in between EntityQuery and db\_select and EntityQuery seems to be a better choice for Entities as it takes care of joining different fields for you.

Reference Link: EntityFieldQuery vs Db\_select() -

@Bart says: -

> I think that the main reason prefering EntityFieldQuery over db\_select is that you don't have to know about the lower-level structure, in other words: how stuff is stored in the database. This improves loose coupling.

@Berdir comment:-

> This is correct, although it goes even further. The field storage is pluggable. The default implementation stores field data in a separate table per field in the database, but it can be replaced, there is for example an implementation which allows to store field data in MongoDB. If you want your code to be portable and not just work on your specific site configuration, you must use EntityFieldQuery.

---
Tags: entities, nodes, database
---


# Question
Title: How to Disable Whole Form from hook_form_alter?
I've got a form I want to be disabled when certain criteria are met. According to the Form API I thought `$form['#access'] = FALSE;` would be sufficient. But no dice.

Instead, I'm doing this, which feels wrong, plus I get an error, "Warning: implode(): Invalid arguments passed in form\_builder()"

```
foreach($form as $key => $element){
          unset($form[$key]);
}
$form['#prefix'] = 'Bad user. Don\'t access this form!';

```

Kind of a big stick approach. What's the right way to do this?

# Answer
Drupal doesn't cope with the form being removed in such a way because it is expecting certain things in the form array after you have altered it.

That's why you are getting that error, because form\_builder() does this:

```
if (!isset($element['#id'])) {
  $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
}

```

but you have removed `$element['#parents']` when you looped through unsetting everything, including `#parents`.

If you want to loop through all form elements are remove them the correct way would be to use element\_children(), which will loop through the keys of child elements but skip properties of the current element.

So to loop though child elements you would do this:

```
// Remove all elements from this form.
foreach (element_children($form) as $key) {
  unset($form[$key]);
}

```

Alternatively you could restrict access like this, which could cause you less side effects if other modules are expecting form elements that you have deleted.

```
// Restrict access to all elements in this form.
foreach (element_children($form) as $key) {
  $form[$key]['#access'] = FALSE;
}

```

If the form is a page though, not in a block or something, then it might be better to use hook\_menu\_alter() to block it as Shawn said in his answer.
> 6 votes

# Answer
There are many solutions here. One solution is to just disable the submission button:

```
$form['actions']['submit']['#disabled'] = true;
$form['#prefix'] = 'Bad user. Don\\'t access this form!';

```

A more elegant way might be to just disable access to the form altogether. For example, using `hook_menu_alter` to set the form page callback to redirect away from the form.
> 3 votes

---
Tags: forms
---


# Question
Title: Upload Image in system_theme_settings form using Zen on Domain Access System
I want to upload the image as the background in the settings page of the zen theme.

In zen , It's easy to add an extra field in the theme-settings.php and it's worked at the single site system.

However,I want to add this feature to the domain access Website.

And I got some error message.

I just write the code as belowed:

```
$form['background_file'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Background'),
    '#required' => True,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  );

```

picture above appeared correct.

But when i push the upload button.

I got the error message belowed

> ```
> Notice: Undefined index: system_theme_settings in drupal_retrieve_form() (line 806 of /Library/WebServer/Documents/official/includes/form.inc).
> Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'system_theme_settings' not found or invalid function name in drupal_retrieve_form() (line 841 of /Library/WebServer/Documents/official/includes/form.inc).
> Notice: Undefined index: var in variable_realm_form_system_theme_settings_alter() (line 618 of /Library/WebServer/Documents/official/sites/all/modules/variable/variable_realm/variable_realm.module).
> Notice: Undefined index: background_file in file_ajax_upload() (line 271 of /Library/WebServer/Documents/official/modules/file/file.module).
> Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Library/WebServer/Documents/official/modules/file/file.module).
>
> ```

and i really don't know how to fix that.

I just referenced the content below and i can't find the answer.

Does someone fixed this situation before?

thanks a lot.

# Answer
The form needs to be able to find system\_theme\_settings() when getting rebuilt via ajax.

`form_load_include($form_state, 'inc', 'system', 'system.admin');` inside of theme-settings.php `hook_form_system_theme_settings_alter()` should do the trick.
> 2 votes

# Answer
```
$form['theme_extra']=array(
    '#type'         => 'fieldset',
    '#title'        => 'Extra Image',
    '#description'  => 'Image Fieldset',
    '#collapsible'  => TRUE,
    '#collapsed'    => FALSE,
    '#weight'       => -10,
  );
$form['theme_extra']['background_file']=array(
        '#type'     => 'managed_file',
        '#title'    => 'test title',
        '#description' => 'description',
        '#required' => FALSE,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
        '#default_value' => theme_get_setting('background_file'),
        '#upload_validators' => array(
          'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
      );

```

This code !!
> 2 votes

---
Tags: theming, media
---


title: Send Bulk emails as bcc in Drupal

text:
# Question
Title: Send Bulk emails as bcc in Drupal
I am using Drupal 7. I have used Views Bulk Operations (VBO) module to send an email, which is working fine. Now Problem is that email is going as **TO** , all other user are able to see other emails id.

I want to send as Blind carbon copy (bcc). Can anybody tell, how we can do this?

Thanks

# Answer
> 0 votes
Simply you can do this by using Blind Carbon Copy module.

> The BCC module injects a BCC header in all e-mails sent by Drupal, which allows you to receive copies of all e-mails sent by your website.

---
Tags: views, 7
---


# Question
Title: "the website encountered an unexpected error.Please try again later" after db_update
Drupal responses "the website encountered an unexpected error.Please try again later" after running db\_update statement in my custom module. I always do this without any error. Any suggestion pls!

```
function mobile_user_form_submit($form, $form_state){
    $deposit=$form_state['values']['deposit'];
    $status =$form_state['values']['status'];

    $id = $form_state['values']['hid'];
    drupal_set_message(t($id ." / ". $deposit." / ".$status));
    if($id != ""){
    db_update('mobile_users')
        ->fields(array('deposit' => $deposit, 'status' => $status, "updated" => date('Y-m-d H:i:s')))
        ->condition('id', $id)
        ->execute();
    drupal_set_message(t('successfully saved.'));
   }
}

```

After comment db\_update() statement, it is ok no error message show.

Thank you,

------ Solved -------

And I try to update manually that record in mysql, in the field "deposit" I got an error message "Please select a value not more than 127". I found myself I set wrong datatype in deposit field, I was willing to set Integer datatype but I was not awared what I had set I set tinyint. After chaning tinyint to integer, "the website encountered an unexpected error.Please try again later" also removed.

Thanks

# Answer
Once try to insert manually in mobile\_users(phpmyadmin) table with same data. Then check for any errors, if not then check recent logs/apache error logs for more suggestions.
> 1 votes

---
Tags: 7, database, forms
---


# Question
Title: Unable to configure SMTP authentication support module
In Drupal v7.36 & 7.37, after installed and enabled SMTP Authentication Support module, I still can't find the menu function under configuration/system to config this module for all related email setting.

# Answer
> 0 votes
Try to clear cache and go to the following path: admin/config/system/smtp or Home » Administration » Configuration » System » SMTP Authentication Support

# Answer
> 0 votes
Try clearing the cache either from the terminal using:

> drush cc all

or from the UI, going to

> Admin -\> Configuration -\> Development -\> Performance

Clear the cache once and you would be able to see the Menu under configuration/system

---
Tags: 7, emails
---


# Question
Title: Hooks called after installation profile is installed?
I'm stuck writing an installation profile.
There are certain things that I want to do only after the installation is completed.

I analyzed top ten installation profiles and checked the documentation, but I couldn't find it. I might be missing something small though.

Is there such hook? If not, how can I execute something at the end of the installation?

Thanks!

---

**UPDATE**

I know for `hook_install` and `hook_install_tasks`, and they are not exactly what am I looking for.

They both are called *during* the installation. I want to execute code *after* the installation has been completed.

For example, setup Backup & Migrate schedules. If I do this using `hook_install_tasks()`, the cron run at the end of installation does not seem to work properly/in full, and I get errors when `backup_migrate` tries to write to private directory. Private directory is set up properly and if I just re-run the cron afterwards, it works as it should.

# Answer
> 2 votes
Move your post-installation hooks to a module/part-of-your-profile (that can implement any hook and move things around even after the system modules is installed).

That way you can overcome problems like custom block's BLOCK\_VISIBILITY\_LISTED not working on profile installation hook\_install()?, and have a solid last installation step, that makes all your final configs.

bonus * why not even *choose* or make configs in that installation step's form\_alter() ;)

# Answer
> 1 votes
Here's an example of a feature revert done at the end of the installation.

```
/**
 * Implements hook_install_tasks().
 */
function MYPROFILE_install_tasks($install_state){
  $tasks = array(
    'MYPROFILE_setup_cleanup' => array(
      'display_name' => st('Cleanup'),
      'display' => FALSE,
      'type' => 'normal'
    ),
  );

  return $tasks;
}

/**
 * Cleanup install task.
 */
function MYPROFILE_setup_cleanup() {
  features_revert();
}

```

# Answer
> 1 votes
Module Site pre-install and post-install hooks might just do what you need. It's installed as a library and registered with your installation profile. The module provides two hooks: `hook_site_pre_install()` and `hook_site_post_install()`. They are run before the installation tasks and then after *Finished* task.

*From module page:*

> Sample Use Cases
>
> Here are some scenarios where you'd want to use this approach:
>
> You need to configure certain site settings before installing a module that requires those settings (`hook_site_pre_install()`). You need to modify user passwords, tweak menu paths, or adjust settings (such as the site name) that would otherwise be bashed if set in `hook_install()` in the installation profile (`hook_site_post_install()`).

I usually use it to e.g. enable Shield module in certain environments at the very end of the installation.

# Answer
> 0 votes
It's hooks **hook\_install** and **hook\_install\_tasks**

# Answer
> 0 votes
You can add tasks to be run after the "Finished" task by implementing hook\_install\_tasks\_alter().

---
Tags: 7, installation-profiles
---


# Question
Title: Custom personal contact form with webforms
We want our users to be able to contact each other directly, but not give away the email address of the user account.

Personal Contact forms do just this, however, we need a few more fields and other triggers to happen alongside this. Things that webforms already does.

What I'd like to do is use a %get parameter to pass the id of the user they are contacting into the form, and pre-populate the email into a hidden field. This will allow me to use the webform email function to notify user 2 that user 1 would like to contact them.

So there are two users involved. User 1 = logged in user. User 2 = the person they are contacting.

The url would be mysite.org/webformid?uid=2

Where the uid is the id of contact 2.

Using that id, the webform could pull their email into a hidden form field.

Is this possible?

Heather.

# Answer
You can use hidden fields in your webform which are associated with user's details, such us email, id etc.
> 0 votes

---
Tags: webforms, emails
---


title: Need to get field tid from taxonomy

text:
# Question
Title: Need to get field tid from taxonomy
Trying to retrieve tid from field\_report\_group in my module. I can not seem to be able to grab it. Any help would be appreciated.

# Answer
Assuming you have a variable containing the entire structure that you have added.

Try

```
$taxonomy['8942']->field_report_group['und'][0]['tid']

```
> 2 votes

# Answer
Depending on the context you are loading the term (template or module) there may be more appropriate ways but a general one is to use:

taxonomy\_get\_term\_by\_name if you don't have the tid

taxonomy\_term\_load if you do have the tid

and taxonomy\_get\_tree if you want to load the whole vocabulary
> 0 votes

# Answer
You should use `field_get_items($entity_type, $entity, $field_name);`
> 0 votes

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


# Question
Title: Display youtube video using Media Oembed in the node
I have embedded youtube video in an article using media+media\_oembed+media\_internet modules.Media(my field) is a field collection item with two fields - media and caption field.I have custom themed(necessary for my custom bootstrap template) media using theme functions according to file type whether it is an image or video.For image i have used picture module and displayed it as below.This is written in the theme\_preprocess\_field function.:

```
$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name,$display = array('label' => 'hidden','type' => 'picture','settings' => array('picture_group' => 'main_story_image','fallback_image_style' => 'w555xh372', 'image_link' => '')), $langcode = NULL

```

When i try to display embedded youtube video using the code below i get an icon and a filename with a link.

```
$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name, $display = array('type' => 'media_oembed'), $langcode = NULL);

```

How do you find out the correct formatter for the media\_oembed module? I got the media\_oembed from media\_oembed/themes/media\_oembed.theme.inc.

# Answer
First of all i got all the default displays in my drupal site using the function : field\_info\_formatter\_types().Since media is a file entity, the formatter should be file rendered.Then i had to give the file view mode in the settings array to show the way i wanted it.I created a custom view mode called article\_page(machine name) and added oembed formatter.Here is the final code.

```
$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name,
            $display = array('type' => 'file_rendered','settings'=>array('file_view_mode' => 'article_page')), $langcode = NULL);

```
> 0 votes

---
Tags: media
---