# Question
Title: How to prevent the login block to be shown twice?
When I open my web without being logged in, the login block appears twice. Once in sidebar and once in header (at least I hope it is header section), as shown in this screenshot:

However, in structure/blocks I have it set in sidebar only.

Any idea how to fix this, so that the login block is only shown once? Theme is ANDROMEDA: https://www.drupal.org/project/andromeda

# Answer
> 1 votes
Follow the steps, Using which can solve your problem.

1. Go to Blocks under structure admin menu.
2. You will find user login block in Header section.
3. If you have added your custom login block then there is no need to have default login widget in header. So change it to null.
4. If you have default login then just check to put it in appropriate block.

This are the two cases according to your question description.Answer back if not solved.

Please do mention some more description if this solution won't work.

# Answer
> 0 votes
It could be because of some theme setting that is turned on, so check if that's the case and if so, turn that theme setting of.

Alternatively, do not display the block in the sidebar (at least until you find the solution for removing it from the header, if that's what you prefer).

Also, consider editing your question to also explain which theme you are using (with link to it on drupal.org). Or mentioned that you're using a custom theme, if that is the case.

# Answer
> 0 votes
If you found the element in firebug, you can also try hiding it with css.

---
Tags: blocks, users
---


# Question
Title: What is the naming convention for theme region template files?
I want a custom template for every theme region, but I'm not sure of the naming convention. For example, with the following information the .info file, would **region--header.tpl.php** be a correct template name for the *Header* region?

```
regions[header] = 'Header'
regions[sidebar_first] = 'Sidebar First'
regions[content] = 'Content'
regions[footer] = 'Footer'

```

# Answer
> 4 votes
Yes, the naming scheme is **region--\[region\].tpl.php** where **\[region\]** is the region machine name defined in the theme info file. See Drupal 7 Template (Theme Hook) Suggestions for more information. You will need to flush your theme registry cache for the template to take effect.

---
Tags: theming
---


# Question
Title: drupal 7 default table to store form values
I am new to drupal and creating a module consist of a form. Now I want to store values in database, please tell me what is the default table in drupal to store form values? Like in WordPress we have wp\_option table to save data. Is there any default table in drupal or I have to create new one? What is the exact use of node table?

# Answer
You can use Drupal variable system, please read the following article: https://www.drupal.org/node/1111260

You can create you own table, just use hook\_schema for it: https://api.drupal.org/api/function/hook\_schema/7

If you to get information from your users by form and store it, please check the module webform: https://www.drupal.org/project/webform

Node table used for storing main information about nodes (it's some type of content). Node can by "Article" or "News", etc. More you can read here: https://www.drupal.org/documentation/modules/node
> 0 votes

# Answer
The default table to store values in database is the variable table; you can use `variable_set()` to store values and `variable_get()` to get those values.

```
//Example:
variable_set('app_id', $form_submit['values']['app_id']);
variable_get('app_id');

function test_form_submit($form, &$form_state) {
  $app_id = $form_state['values']['app_id'];
  $app_secret = $form_state['values']['app_secret'];
  $app_code = base64_encode($app_id . ':' . $app_secret);

   if ($form_state['values']['app_id'] && $form_state['values']['app_secret']) {
     variable_set('app_id', $form_state['values']['app_id']);
     variable_set('app_secret', $form_state['values']['app_secret']);
     drupal_set_message(t('App Code data Saved app_id= ' . variable_get('app_id') . ' app_sec=' . variable_get('app_secret')));
  }
}

```
> 0 votes

---
Tags: 7, hooks, database
---


title: Grab Node ID from URL of Current Page?

text:
# Question
Title: Grab Node ID from URL of Current Page?
How do I grab the Node ID in the URL of the current page and pass it through a link?

1) The URL on the current page is in the format: website.com/parameter/parameter/parameter and the third parameter is the Node ID. 2) I want to grab that Node ID and put it into a link on that page like Link

The screen capture illustrates this.

screen capture

# Answer
1) You just need to add a contextual filter of "Content: Nid".

2) Then select Provide Default Value, type: Content ID from URL.

3) Add a field of Nid and check mark the box that says "exclude it from display".

4) Add a custom field, `<a href="blahblahblah[nid]">Deliberables</a>`

PS: Make sure the nid field is above the custom field so the custom filed can use the nid token.
> 0 votes

# Answer
Build your own token!

Your token then could analyse the current URL - double and triple validate it (don't let your page be hijacked!!!) - and return the discovered node-id.

Views allow usage of tokens everywhere they make sense - guess you'll have no problem to use it in a link of a views-footer/header area.

https://api.drupal.org/api/drupal/includes!token.inc/7
> 0 votes

---
Tags: views, tokens
---


title: Callback function on block

text:
# Question
Title: Callback function on block
In order to create a search block with autocomplete, I'm trying to use a callback function. But it doesn't work with my module. This module is implemented on my homepage which is http://mywebsite.com/lastnews

Could you help me?

Here is my code :

```
//my module
function search_city_block_info() {
  $blocks['search_city'] = array(
    'info' => t('Search a city'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

//my block
function search_city_block_view($delta = ''){
    switch ($delta) {
        case 'search_city':
            $block['subject'] = t('Search a city');
            $block['content'] = drupal_get_form('search_city_form');
            break;
    }
    return $block;
}

//just for the callback for autocomplete
function search_city_menu() {
  $items['search_city_page_autocomplete'] = array(
    'page callback' => 'search_city_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

//the form with the search field
function search_city_form($form, &$form_state) {
  $form = array();
  $form['City'] = array(
    '#title' => t('City'),
    '#type' => 'textfield',
    '#maxlength' => 60,
    '#autocomplete_path' => 'search_city_page_autocomplete',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

//the values for autcomplete
function search_city_autocomplete($text) {
  $results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  drupal_json_output($results);
}

```

# Answer
> 0 votes
Try this //the values for autcomplete

```
function search_city_autocomplete($text = NULL) {
$results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  print drupal_json_encode($results);
exit();
}

```

---
Tags: ajax, routes
---


# Question
Title: Node translation syncing problem with entity references
I have a content type with multilingual support (node translation). This content type also has an entity reference (module: `entityreference`) field.

My content is:

```
/node/1 English story 1
/node/2 French  story 1 (translation of #1)
/node/3 English story 2 with reference to #1
/node/4 French  story 2 (translation of #3) **entityreference problem here**

```

I've configured the reference to be synchronized. The problem is that whenever I translate or edit a node, it'll try to sync the reference to other translations.

So I'll always end up with:

```
#3 -> #1 (correct)
#4 -> #1 (wrong)

```

or:

```
#3 -> #2 (wrong)
#4 -> #2 (correct)

```

I can solve this by disabling syncing on the reference field but then I will have to be maintaining the references for all translations manually which is a problem in a website with many translations.

# Answer
You should try module "Synchronize entity references" (`i18n_entityreference`) from project Internationalization contributions (`i18n_contrib`). So far, for me it looks perfect. It even works with inline entity form widgets.

To install and use it:

1. **Install and enable the module.** If you use `drush`:

```
drush dl i18n_contrib && drush en i18n_entityreference

```

(This requires the core module `i18n_sync` and will enable it automatically if not already done. It is needed for synchronizing field values across translations.)
2. **Configure "Synchronize translations"**. Basically go to "Structure → Content Types → \[your content type\]" in the admin menu, switch to tab "Synchronize translations", select your node reference field, and save. See here for details.
3. **Use.** If you have existing content, the node reference field will be synced in a language-aware way when you save any node of a translation set for the next time.
> 3 votes

# Answer
Had the same problem, wrote this little workaround:

```
function YOURMODULE_i18n_sync_translation($entity_type, $translation, $translation_language, $source, $source_language, $field_names) {
  foreach ($field_names as $field_name) {
    $info = field_info_field($field_name);
    if ($info['type'] == 'entityreference') {
      $items = field_get_items($entity_type, $source, $field_name);
      foreach ($items as $delta => $item) {
        $translations = translation_node_get_translations($item['target_id']);
        if (isset($translations[$translation_language])) {
          list($id, $vid, $bundle) = entity_extract_ids($entity_type, (object) $translations[$translation_language]);
          $translation->{$field_name}['und'][$delta]['target_id'] = $id;
        }
      }
    }
  }

```
> 3 votes

# Answer
There's a module for that: https://drupal.org/project/i18n\_node\_reference

> Provides i18n field synchronisation for a node\_reference field.
>
> The referenced nodes are translated into the correct language. If no such language exists, it is ignored. This is the same functionality as is supported by the taxonomy reference translation in i18n\_taxonomy.
> 2 votes

# Answer
The code snippet in the second answer won't work when editing the reference in a translation. That's because `translation_node_get_translations()` accepts a tnid as argument, not a nid. Check the api docs.

Change the call in the above code to something like this and it should work (for nodes only, in this case):

```
$referenced_node = node_load($item['target_id']);
$translations = translation_node_get_translations($referenced_node->tnid);

```

NOTE: I couldn't comment on the other answer, so i'm posting this one.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Image Responsive Carousel like image Gallery
I have created a view of images and I want to display those images in a carousel like display but that needs to be responsive. I came across a jquery plugin for this called "elastislide" but cannot properly figure out how to use it with drupal views I have followed the example here, but nothing is working as such.

# Answer
If you want a fairly simple responsive carousel in views I would recommend checking out Flexslider \- it's pretty simple to setup and does everything you want I believe.
> 1 votes

# Answer
You can check `Nivoslider , Viewslideshow` module.And for responsive you may need to do the css using `mediaquery` in `style.css`
> 0 votes

---
Tags: 7, javascript, theming
---


# Question
Title: Fatal error: Call to undefined function cache_get()
I am getting the following error on the server

```
Fatal error: Call to undefined function cache_get() in includes/module.inc on line 665
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function cache_get() in includes/module.inc, line 665

```

How to fix this?

# Answer
When you type `drush` in the command line you probably reached the right place to solve your problem. This error arises when `drush` is not up-to-date and this occurs when you install `drush` from the official repository in Ubuntu.

The workaround is easy: just install a new version of drush! And to do so, you have to install from the backports package of Ubuntu.
> 2 votes

# Answer
For me, the cause was different: some errors are not caught by Drupal's error handler.

I used a `new DateTime()` in my `settings.php` (probably very rare) It generated an error because the `date.timezone` setting in my CLI `php.ini` wasn't set.

To find the real error (this is the interesting part of the answer for all of you, I think) :

Edit your `module.inc`, line 723.

Add these lines before the `cache_get` call.

```
if (!function_exists('cache_get')){
    debug_print_backtrace();
}
$implementations = cache_get('module_implements', 'cache_bootstrap');

```

It might give you lots of information about the real source of the issue!
> 15 votes

---
Tags: 7, caching, database
---


# Question
Title: Google Analytics configuration setting for Drupal multisite (domain and submain)
I am working on a `Drupal` mulsite project (`using single database`) and using `Google Analytics` module for this.

I have follow the below steps for GA configuration:

1. Created a domain name `example1.com` and a sub-domain name `example2.com`.
2. Create an account on GA and create property for both of this domain name in GA account. Both property give me two different `Tracking ID` (same as below screenshot).

3. Into the configuration setting of GA from drupal admin section I have added `Web Property ID` of `example1.com` and into domain setting added both the domain name `example1.com` and `example2.com` into the section of `List of top-level domains` (a same as attached screenshot).

Now this configuration is only working for `emample1.com`, not for `example2.com`. So can anyone please tell me how can I use `Web Property ID` of domain `exmaple2.php` to get the result?

# Answer
As Kiamlaluno states, this is likely caused by the fact that the module only allows one UA, while you are trying to track two domains. According to the GA module documentation it can be overridden using code like this in settings.php:

```
<?php
// Override Google Analytics Web Property ID per hostname.
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
  case 'www.example.com':
  case 'www.example.net':
  case 'forum.example.net':
    $conf['googleanalytics_account'] = 'UA-123456-2';
    break;

  case 'www.example.org':
    $conf['googleanalytics_account'] = 'UA-123456-3';
    break;

  default:
    $conf['googleanalytics_account'] = 'UA-123456-1';
}
?>

```

Documentation can be found here
> 1 votes

---
Tags: 7, multi-sites, google-analytics, subsites
---


title: Rendering form manually

text:
# Question
Title: Rendering form manually
When making my ticket-system I want managers to be able to reply to tickets when viewing the ticket. On the page to view any ticket I load my form. Because I want it to be a bit more fancier than just the default 'element under element' style *I render each item by item manually*.

```
<?php print drupal_render($form['open']); ?>

```

**Now the problem is, my form doens't work. Clicking on my rendered submit doesn't perform any action.**

My guess is that rendering each item manually doesn't include the 'form container'. How should I include is? Or is my style of working completely wrong?

# Answer
> 3 votes
The best way to implement custom rendering of a form would be to use a custom theme hook for the form:

```
/**
 * Builder function for the ticket form.
 */
function MODULE_ticket_form($form, $form_state) {
  // Build the $form array here...

  // Let the theme API knows that this form use it own theme hook.
  $form['#theme'] = 'ticket_form';
  return $form;
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    // Custom theme hook for the ticket form.
    'ticket_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Default implementation for the ticket_form theme hook.
 */
function theme_ticket_form($variables) {
  $form =& $variables['form'];

  //Custom rendering of forms elements goes here...
  $output = ...;

  // Render every other elements (incl. hidden system ones).
  $output .= drupal_render_children($form);
  return $output;
}

```

Instead of using only a theme function, you can also use a template file. The theme function can also return a render array instead of a string.

# Answer
> -1 votes
Try following will work:

```
<?php $form = drupal_get_form('yourform_id'); ?>

<?php print '<form id="'.$form['#id'].'" accept-charset="UTF-8" method="'.$form['#method'].'" action="'.$form['#action'].'">'; ?>
<?php print drupal_render($form['form_id']);?>
<?php print drupal_render($form['form_build_id']);?>
<?php print drupal_render($form['form_token']);?>
<?php print '</form>'; ?>

```

---
Tags: forms
---


# Question
Title: Multisite: Share users and user roles for existing set up
I have made a Drupal 7 multi-site with 3 sites. Each site is running of the same Drupal install and has a separate database. The database names are `myhost_site1`, `myhost_site2` and `myhost_site 3`. (My hosting provider puts in the `myhost_` automatically).

I need the 3 sites to share the users and user roles. I have read various tutorials and these are the steps I have followed:

1. Created a new database called `myhost_users`.
2. Copied the following tables from `myhost_site1` TO `myhost_users`: `users`, `user_roles`, `authmap` and `sessions`
3. Given the database users for each of 3 main databases access to `myhost_users`.
4. Open the settings.php for each site and insert the following code (replacing the existing $databse definition):

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF DATABASE',
  'username' => 'DATABASE USER',
  'password' => 'DATABASE PASSWORD',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'NAME OF DATABASE',
    'users'     => 'myhost_users',
    'sessions'  => 'myhost_users',
    'role'      => 'myhost_users',
    'authmap'   => 'myhost_users',
  ),
  'collation' => 'utf8_general_ci',

```

);
5. When I go to my site, I get the following error message:

> Uncaught exception thrown in session handler. PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table
6. For the code posted in (4) I have tried using an underscore suffix for the database names (e.g, `myhost_users_`), but I still get an error message.

What am I doing wrong? Do I need any settings in sites/sites.php?

I would be open to using a module to do this.

Bakery is no good as it doesn't share user roles.

Account Sync shares roles, but it doesn't seem to work.

CAS requires phpCAS which I do not have access to.

# Answer
> 2 votes
You don't need additional modules to achieve what you want.

First: Fix you configuration:

```
'prefix' => array(
'default'   => 'default_db.',
'users'     => 'myhost_users.', //
'sessions'  => 'myhost_users.',
'role'      => 'myhost_users.',
'authmap'   => 'myhost_users.',
),

```

The dots on the end of `'users' => 'myhost_users.'` tells Drupal to query the `users` table in `myhost_users` data base (SQL syntax); without dots you'll get an error like "Base table or view not found `myhost_usersusers`/`myhost_users_users` or similar.

Now,

```
'database' => 'db',
'username' => 'db_user',
'password' => 'db_user_pass',

```

are credentials for the default db where Drupal is installed. To query users db you need to add this user with his password (`db_user`, `db_user_pass`) to the `myhost_users` database. in other words, if you have a site with 2 subsites:

* `myhost_site1` \- user of this db
* `myhost_site2` \- user of this db
* `myhost_users` \- (assuming this db stores Drupal users, that you want to share across ites) user of this sb + user of `myhost_site1` and user of `myhost_site2`

To stay logged in on each site it is necessary to share cookies between sites: edit `settings.php` file of each site, uncomment the line with `# $cookie_domain = '.example.com';` and replace `'.example.com'` with your domain. Don't forget the dot at the beginning (`'.mysite.com'`) -- without it both `mysite.com` and `notmysite.com` could be treated as the same domain.

---
Tags: database, multi-sites
---


# Question
Title: Commerce: Diffrent text to add to cart button in product list and in product page
i try to modify the add to cart button text in commerce so i can have diffrent text in product list and diffrent text in product page.

Is it possible to do this with form\_alter?

I tried to use something like node type but no success.

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

    if ((substr($form_id, 0, 30) == 'commerce_cart_add_to_cart_form') && $node->type == 'product_display') {
    $form['submit']['#value'] = t('Buy');
    }
}

```

Thanks

# Answer
> 0 votes
If you try to change text of 'Add to cart' button, you should check add to cart form with it's number.

So apply code like:

```
if(strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0 && $node->type == 'product_display'){
   $form['submit']['#value'] = t('Buy');
  }

```

Thanks!

# Answer
> 0 votes
You should be able to use $node-\>type if you add this first

```
$node = menu_get_object();

```

Remember to check if $node is NULL and $node-\>type is set.

Also if you're wanting to use the "add to cart" hook\_FORM\_ID\_alter() then the function name needs to be something like

```
custom_form_commerce_cart_add_to_cart_form_alter()

```

---
Tags: commerce
---


# Question
Title: Does the cron using Drush must be setup locally or on the server for the production website
I have been reading about the Drush cron and explanation that mentions in this documentation. Wondering do we add that crontab entry for drush locally or on the server where the website is for the production site? This confusion is because the article mentions drush aliases.

This is the crontab entry suggested

> 10 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /usr/local/drush/drush --root=/path/to/your/drupalroot --uri=your.drupalsite.org --quiet cron

Here is the part that is confusing

> Specifying the Drupal site to run
>
> There are many ways to tell Drush which Drupal site to select for the active command, and any may be used here. The example uses the --root and --uri flags, but you could also use an alias record if you defined it in a global location, such as /etc/Drush/aliases.Drushrc.php.

Does it refer to aliases on my local or possible aliases on the server which may have dev, qa and other related sites.

# Answer
> 1 votes
TL;DR You should add it on the server!

Whereas it's possible to add it locally and use a remote alias to run it on the server it would be unreliable (requires your local to be online 24/7) and inefficient.

That said, you can also add "local" aliases on your server for convenience, to avoid adding the `--root` and `--uri` flags to the command in your crontab.

You can add any number of Drush aliases anywhere you want; so on your local machine you can have a "foo.local", "foo.staging" & "foo.prod" aliases for your site. And on your staging and production servers, you can simply add "foo.staging" and "foo.prod" so that you can access all of your environments in a cohesive and consistent manner.

The advantage is that if you define an alias "foo.prod" on the production server, you can replace your crontab command with this: `/usr/local/drush/drush @foo.prod --quiet cron`

It's customary to have the same aliases set up across *all* servers for that very purpose.

---
Tags: 7, drush, cron
---


# Question
Title: Ultimate Cron Background Process Taking a Long Time
I'm having background process on Ultimate Cron process various queue items, but the fastest it usually processes them is at least one minute, and sometimes 3 minutes per item.

This seems incredibly slow to me.

Should I increase the number of threads? I'm not finding much documentation on how to speed up the process - I don't mind if it requires a bit more processing power - this is a required operation for the Drupal install in question, and it has to be run pretty much all the way through every 15 minutes.

There are no errors, just very slow processing.

# Answer
I think we need to check from start to end point. This issue is like some processes which takes more time to execute. So we need to check what is that process and we can find that using Elysia Cron plugin.

This plugin helps you to find which cron process has taken much time and where to take possible actions.

PS: If this stuff helps you please leave me a comment and support :)

Thanks!
> -2 votes

---
Tags: cron
---


# Question
Title: re-triggering hook_user_default_permissions?
I build a module that implements `hook_user_default_permissions` to manage permissions for my site. It's been installed on the site, and its permissions took. But now, a while on, I am making some changes to the permissions, but they aren't taking.

I am trying to figure out how to re-trigger the hook being run. I've tried clearing cache, rebuilding the registry, disabling, uninstalling, and re-installing the module, and rebuilding user perms. None of these have worked. I've looked in the `role_permission` table to verify, and my changes have not been added.

How can I get the hook to run again?

# Answer
It turns out that this hook is a part of features, so I needed to do a `drush fr my_module`.
> 2 votes

---
Tags: hooks, users
---


title: Theming of Entity registration form

text:
# Question
Title: Theming of Entity registration form
I'm using entity registration module on a drupal 7 for events. I managed to enable the registration but I can't find out how to style the registration form.

I tried to modify the form via css but I would prefer have a better control over it, in a template page for example. I'm quite new to drupal so any help would be much appreciated.

# Answer
I use Display Suite to arrange elements and css to style elements. You can create your own template layout in display suite if you need it.
> 1 votes

---
Tags: theming, users, display-suite
---


# Question
Title: Drush cron - how to provide the actual task
Based on this documentation the drush cron can be set up as

> 10 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /usr/local/drush/drush --root=/path/to/your/drupalroot --uri=your.drupalsite.org --quiet cron

Where is the actual task being set here? I would like to invoke a certain url on each cron run. How do I provide that url to be ran in this cron or invoke a function using this drush cron.

Thanks.

# Answer
> 1 votes
From the Drupal perspective, you just need to implement `hook_cron()`:

```
function MYMODULE_cron() {
  drupal_http_request('http://foo.bar');
}

```

That will be invoked on all normal cron runs (there are situations when it won't, e.g. if you have a cron management module installed that limits core cron operations).

But it might make more sense just to wget/curl that URL on a separate single-line cron job. Depends on your use case, but either will probably be fine.

---
Tags: 7, drush, cron
---


title: Create alphabetical pager

text:
# Question
Title: Create alphabetical pager
I want to list all the posts with alphabetical headings like this site:

How can I do this with drupal 7 using views?

# Answer
> 3 votes
You need to try this simple way, just create a view with views module:

1. Advanced-\> Contextual Filters-\> Content: Title. If you click Content: Title, under "More" you will find the option to use upper or lower case when sorting the view. You got half of alphabetical list view just like A | B | C | D | F |......
2. Create a another view for remaining half that group posts under alphabetical letter .
3. Set Footer -\> **Configure Footer: Global: View area** -\> View to insert.
4. Check half and half view on page or block.

# Answer
> 10 votes
Have you looked at the "Glossary" view? It is a sample view included with the views module that lists all site content by letter in a manner similar to the link you listed.

The "Glossary" view is disabled by default, but you can enable it on the views admin page (admin/structure/views).

The settings for sorting the posts in the "Glossary" view can be found on the views edit screen under Advanced-\> Contextual Filters-\> Content: Title. If you click Content: Title, under "More" you will find the option to use upper or lower case when sorting the view.

# Answer
> 1 votes
This new module might be helpful: https://www.drupal.org/project/alpha\_pagination

It uses the glossary functionality that Patrick Kenny mentioned but it extends that in super-powerful and useful ways.

From the module page: The Alpha Pagination for Views module enables you to add an alphabetical menu in the header or footer of a views display.

Dependencies Views

Install Install the Alpha Pagination module.

Copy the alpha\_pagination folder to the modules folder in your installation. Download and enable dependencies (views and views\_ui). Enable the Alpha Pagination for Views module using Administer -\> Modules (/admin/build/modules). Views Integration and Configuration

Build a new view of either users, content (nodes), or comments. Add whatever field you want to use as the basis for the alphabetic grouping (e.g. title, body). You can optionally exclude this field from display if you don't want it to appear in the results shown on the page for some reason. You can only choose a field that is a textfield, textarea or a textarea with a summary.

Add either a header or a footer to your view. Select the new item available in the menu of options for Global: Alpha Pagination.

Configure how you want alpha\_pagination to work and specify where it should appear: set the path to the results view page.

select the field you want to use as the basis for the alphabetic grouping from the options presented in the select list (note: if the field you want to use does not appear, go back and add it to your view and then return to this configuration page to select the field).

add a context that is the same as the field you wish to use as the basis for alphabetic sorting. Be sure to enable Glossary mode and set the character limit to 1. The transform case option on the URL should be set to Upper Case.

by default the alpha pagination will apply to all displays; if you only want the alpha pagination to appear on the current display, use the drop-down menu at the top of the administrative interface to change the setting from "All displays" to "This page (override)".

An optional sample view is included and can be enabled via the alpha\_pagination\_example view. The sample relies on the 'article' default content type. You can create sample content using the devel module or rely on your own data.

This module exists thanks to the support of Highwire Press, Inc. and the Institute for the Arts and Humanities and UNC and was created as part of the Symposiac Conference Platform.

---
Tags: 7, views, routes
---


# Question
Title: Inline Entity Form - start with first new node open
My install is using Inline Entity Forms and I would like it so that when a user visits the create node page, the inline entity form starts already visible but with all fields empty and ready to be created (no need to click "Add Node").

I would like to implement either a module or tpl file in my theme to achieve this. Please can you advise on how to go about it.

I've used this patch https://www.drupal.org/node/2225675 but it only works when editing existing content.

# Answer
I read the codes in the inline\_entity\_form.module, and found the inline\_entity\_form\_single is always displaying a form, so i copied its code to my module and it works:

```
function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  $field = $context['field'];
  if (isset($field['field_name']) && ('FIELD_NAME' == $field['field_name'])) {
    if (empty($element['form']) && empty($element['entities'][0])) {
      $element['actions'] = array();
      $instance = $context['instance'];
      $settings = inline_entity_form_settings($field, $instance);
      $controller = inline_entity_form_get_controller($instance);

      $parents = array_merge($element['#field_parents'], array($element['#field_name'], $element['#language']));
      $parent_langcode = entity_language($element['#entity_type'], $element['#entity']);

      $ief_id = $element['#ief_id'];

      $element['form'] = array (
        '#type' => 'container',
        '#op' => 'add',
        '#parents' => array_merge($parents, array ('form')),
        '#entity_type' => $settings['entity_type'],
        '#parent_language' => $parent_langcode,
        '#ief_id' => $ief_id,
      );
      $bundle = reset($settings['bundles']);

      $form_state['inline_entity_form'][$ief_id]['form settings'] = array (
        'bundle' => $bundle,
      );

      $element['form'] = inline_entity_form_entity_form($controller, $element['form'], $form_state);
    }
  }
}

```
> 2 votes

# Answer
Once again thanks for your help on this user1455180. I managed to get it working by adding

```
$field = $context['field'];

```

to the beginning of the function you gave me and inserting the name of the field acting as the entity reference in the place of "FIELD\_NAME".

```
function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
$field = $context['field'];
  if (isset($field['field_name']) && ('FIELD_NAME' == $field['field_name'])) {
    if (empty($element['form']) && empty($element['entities'][0])) {
      $element['actions'] = array();
      $field = $context['field'];
      $instance = $context['instance'];
      $settings = inline_entity_form_settings($field, $instance);
      $controller = inline_entity_form_get_controller($instance);

      $parents = array_merge($element['#field_parents'], array($element['#field_name'], $element['#language']));
      $parent_langcode = entity_language($element['#entity_type'], $element['#entity']);

      $ief_id = $element['#ief_id'];

      $element['form'] = array (
        '#type' => 'container',
        '#op' => 'add',
        '#parents' => array_merge($parents, array ('form')),
        '#entity_type' => $settings['entity_type'],
        '#parent_language' => $parent_langcode,
        '#ief_id' => $ief_id,
      );
      $bundle = reset($settings['bundles']);

      $form_state['inline_entity_form'][$ief_id]['form settings'] = array (
        'bundle' => $bundle,
      );

      $element['form'] = inline_entity_form_entity_form($controller, $element['form'], $form_state);
    }
  }
}

```
> 2 votes

---
Tags: version-control, entities
---


# Question
Title: How to add alphabetized pager using glossary view?
I have a member's directory that lists the last name, first name of all the users on the site, as well as other custom field values about the members. I created a view, added contextual filter for the user's last name (Provide fixed value = "A", character limit =1), and enabled glossary mode. According to my google search results, I should automagically get an alphabetized pager. This is not happening. I made sure to save my new view. Anyone have any other ideas? What I want is an alphabetized pager that allows the user to choose the first letter of the person's last name, and display the info.

# Answer
> 1 votes
There are a couple of steps, each needs to be followed to get it all geared up right. The explanation at https://stackoverflow.com/questions/7354638/drupal-7-views-3-glossary-mode-where-is-it was short and sweet for this.

> There are 2 view variants you need to create to make this work. First create the page variant and setup your related field as an argument (contextual filters). In the settings for the field, make sure to select the 'more' option and set the argument to behave in glossary mode. I believe you also need to set the default value to 'all' or 'a' or any other letter.
>
> Then create the attachment variant. If you created all your fields in the page, this version should have all of them. Override the argument you selected for the page. Display this in summary mode. You will get different options depending on how you want to display your glossary. The Glossary mode should already be enabled.
>
> The last step is to assign the attachment to the page and turn off the inheriting of contextual filters (i.e. arguments).
>
> The best tip I received for learning how to set this up was from merlinofchaos who said to enable the Glossary view in the list of views. He said to clone it and make your changes. This gave me a thorough understanding of how it works.

# Answer
> 3 votes
There is a module, Views Glossary, which provide different options to glossary views. According to the docs, it provide following features:

> 1. A special kind of layout to glossary view (which is available by default with views) or any view, see in screenshot.
> 2. Providing pager with selectbox and textbox.
> 3. A default view is added for example.
> 4. Making items per pager independent of expose form submit. (A usability improvement)

# Answer
> 0 votes
I struggled and struggled with creating a glossary view for members of an organic group. So when you select a group you can view the details of it. This creates a tab called Members that will show you the members of the group you are viewing. Modules used: OG, views, private message (optional), address field (optional). Just use a different 'name' field than what I have if you don't need/want address field.

**Create a view: OG Members View** i. Add view.... Show 'users'

ii. Create page : path= node/%/members . Menu = tab, title = Members , desc= Group Members, menu= user menu.

iii. Format = grid.

iv. Add 3 fields (or whatever you like), put in this order and remove any others.Just be consistent with whatever 'name' field you use.

a. User uid: exclude, no label. This is so can "private message" the user.

b. User profile pic: no label, thumbnail 50x50, no link.

c. User name and address full name: no label, rewrite results - output field as a link - link path= /messages/new/\[uid\]?destination= node/!1/members/!2. The !1 and !2 are input fields for the gid and user name field. So if you use private message and message the user, the destination parameter will then return you right back to the glossary page you were on.

v. Contextual filter OG membership: Group id. Filter not in url= display no results found, when filter value is in url - validate as group and "action to take if not validate"= show page not found.

vi. Contextual filer: user name and address full name - filter not in url = display all results. Filter is in url validate - basic validation, "action to take if filter not validate"= display no results found. Click on MORE and set glossary mode - char limit = 1, case for both is upper (uppercase is critical otherwise you'll end up having a value of both a and A for admin,Arthur!).

vii. Sort criteria= user name and address full name (asc).

ix. SAVE

**Add an attachment now to this view**

i. 'add' attachment. From here on want to use the "this attachment override" at top of page so hte what you change only affects the attachment on not the page you just created. If you're not careful with this you will alter your PAGE settings and have to undo them.

ii. Set "Attach to" = page, Position= before, under attachment settings. This will be the actual glossary. Turn off inherit filters. When filter is off that enables the contextual filter (which you will set a few steps down) to produce a summary.

iii. (set override) Add header, global text, and place link: show all . To use the !1 you need to turn on the 'use replacement tokens from the first row". This link provides a way 'show all' and undo the letter filter that may be in place. How? In the following link the A at the end tells the page to just show users (for that group) that start with A: http://localhost/pf/node/4/members/A . The link above has no letter at end so the display shows all. As an aside, the "pf" is just my site name, change it for what yours is... the key is to add "node/!1/members".

iv. Contextual filter: og membership group id - (set override) when filter value not available provide default value, type= raw value from url , path component is 2 ( the second one because the first one is 'node' in node/%/members. When filter value is available specify validate, og group, if "filter value not validate" then display no results found.

v. contextual filter: user name and address full name. When filter value not available check "display summary": sort asc, alpha, unformatted. Set display record count, display items inline. When filter value is available validate, basic, if "value not validate" display no results. The MORE at end should have the glossary on , char=1 etc. since it was carried forward from the page. Thus it will only summarize on first letter.

vi. SAVE

For both the attachment and the page do not, under OTHER, set use AJAX =yes. When I had it yes I received ajax log errors and it didn't work. I would click on the glossary letter and the filtering didn't occur.

Hope this helps you.

# Answer
> 0 votes
This new module might be helpful: https://www.drupal.org/project/alpha\_pagination

It uses the glossary functionality that Patrick Kenny mentioned but it extends that in super-powerful and useful ways.

From the module page: The Alpha Pagination for Views module enables you to add an alphabetical menu in the header or footer of a views display.

Dependencies Views

Install Install the Alpha Pagination module.

Copy the alpha\_pagination folder to the modules folder in your installation. Download and enable dependencies (views and views\_ui). Enable the Alpha Pagination for Views module using Administer -\> Modules (/admin/build/modules). Views Integration and Configuration

Build a new view of either users, content (nodes), or comments. Add whatever field you want to use as the basis for the alphabetic grouping (e.g. title, body). You can optionally exclude this field from display if you don't want it to appear in the results shown on the page for some reason. You can only choose a field that is a textfield, textarea or a textarea with a summary.

Add either a header or a footer to your view. Select the new item available in the menu of options for Global: Alpha Pagination.

Configure how you want alpha\_pagination to work and specify where it should appear: set the path to the results view page.

select the field you want to use as the basis for the alphabetic grouping from the options presented in the select list (note: if the field you want to use does not appear, go back and add it to your view and then return to this configuration page to select the field).

add a context that is the same as the field you wish to use as the basis for alphabetic sorting. Be sure to enable Glossary mode and set the character limit to 1. The transform case option on the URL should be set to Upper Case.

by default the alpha pagination will apply to all displays; if you only want the alpha pagination to appear on the current display, use the drop-down menu at the top of the administrative interface to change the setting from "All displays" to "This page (override)".

An optional sample view is included and can be enabled via the alpha\_pagination\_example view. The sample relies on the 'article' default content type. You can create sample content using the devel module or rely on your own data.

This module exists thanks to the support of Highwire Press, Inc. and the Institute for the Arts and Humanities and UNC and was created as part of the Symposiac Conference Platform.

---
Tags: 7, paging, views
---


# Question
Title: Fatal error: Call to undefined function drupal_array_diff_assoc_recursive()
I am getting the below fatal error when i click content type \> content x \> manage fields \> click edit:

"Fatal error: Call to undefined function drupal\_array\_diff\_assoc\_recursive() in /home/content/65/11722765/html/sites/all/modules/token/token.pages.inc on line 23"

Please help.

D

# Answer
`drupal_array_diff_assoc_recursive()` was added in Drupal 7.23, and you have a lower core version than that.

You could try copy/pasting the function somewhere into your current core as a hack, but don't be surprised if it doesn't work.

Or you could try hacking at the Token module to remove its reliance on that function, or install an older version of Token altogether, which doesn't rely on it.

Basically you're in "no warranty" territory; if you update one part of your codebase, but refuse to update the rest of it, you can't expect it to carry on working.

The proper solution is to upgrade your core version ASAP, not just for this, but mostly for https://www.drupal.org/SA-CORE-2014-005.
> 2 votes

---
Tags: debugging
---


# Question
Title: How do I disable a module for the First Sidebar?
I enabled the captcha when someone wants to post a comment, but it's also there when you try to connect to the site...

I don't know how to keep the module enable for the comments but not for the sign-in area.

Thank you for the help !!

# Answer
On the Captcha configuration page (admin/config/people/captcha) you can set which forms should display a Captcha.

By default, all user forms get a Captcha challenge. Set them to "No challenge", add the form ID of your comment form to the list and choose the challenge you want.
> 1 votes

---
Tags: 7
---


title: "Add another item" button before field

text:
# Question
Title: "Add another item" button before field
I'm trying to place "Add new item" button before the unlimited values field. Also two buttons un top and below field will work. In custom module added new button but it brakes AJAX call for both buttons. This is needed for Field collection field but I doubt it matters. This is how I've tried to build second button:

```
    $form['field_fieldname']['add_more2'] = array(
    '#type' => 'submit',
    '#name' => 'field_fieldname_add_more',
    '#value' => t('Add another item'),
    '#submit' => array('field_add_more_submit'),
    '#ajax' => array('callback'=>'field_add_more_js','wrapper'=>'field-fieldname-add-more-wrapper','effect'=>'fade',),
    '#limit_validation_errors' => array(array('field_fieldname','und')),
    '#attributes' => array('class'=>array('field-add-more-submit'))
  );

```

# Answer
> 2 votes
The function theme\_field\_multiple\_value\_form($variables) is used (by default) to generate the HTML for the multi-value field. In this function the 'Add another item' button is hardcoded after the table:

```
$output = '<div class="form-item">';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
$output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
$output .= '</div>';

```

So, what you could do is override the theme function, and print the rendering of '$add\_more\_button' before the rendering of the table.

As a side note: if you want to override the theme function using a custom module, you could use `hook_theme_registry_alter(&$theme_registry)` and set `$theme_registry['field_multiple_value_form']['function']` to your customized "theme" function.

---
Tags: 7, entities
---


# Question
Title: Best way to get module and commit meta data from drupal.org
This is a broader question, but related to: get-more-drupal-org-project-usage-information

**Goal: I'd like to get richer stats about modules.**

Choosing a module has become a very complicated process. Things like recent commits, usage growth/decline, number of maintainers, etc. all factor in but drupal.org has (frankly) lousy tools for finding modules and http://drupalmodules.com/ is basically abandoned.

**Current Approach: Screen-scrape limited available stats like https://www.drupal.org/project/usage**

I've been grabbing some stats to help me make an informed decision but scraping seems archaic given the openness of drupal.

**Ideal Approach: Use published drupal.org API to query in JSON**

Does such a thing exist to harvest module info or is it necessary to scrape? Even better would be to create a database or spreadsheet.

I have seen a thread discussing this, but looking for an implementation or concrete plan to implement.

IMO there is a desperate need to improve module transparency and data to help system builders better select appropriate modules.

# Answer
It took me a while to find but this is what I was looking for:

**https://www.drupal.org/api**

> The following node types currently exist on drupal.org:
>
> book book\_listing casestudy changenotice forum image organization packaging\_whitelist page project\_issue project\_core project\_distribution project\_drupalorg project\_module project\_release project\_theme project\_theme\_engine project\_translation story Of particular interest is interacting with the issue queues. Some of the field values returned by the api are the numeric representations in the database. The following mappings are used for some key fields on project\_issue nodes:
>
> field\_issue\_priority
>
> 400,"Critical” 300,"Major” 200,"Normal” 100,"Minor" field\_issue\_status
>
> 1,active 2,fixed 3,closed (duplicate) 4,postponed 5,closed (won't fix) 6,closed (works as designed) 7,closed (fixed) 8,needs review 13,needs work 14,reviewed & tested by the community 15,patch (to be ported) 16,postponed (maintainer needs more info) 18,closed (cannot reproduce) field\_issue\_category
>
> 1,'Bug report' 2,'Task' 3,'Feature request' 4,'Support request'
>
> Available Taxonomy Vocabularies
>
> 1,Forums 2,Screenshots 3,Module categories 5,Drupal version 6,Core compatibility 7,Release type 9,Issue tags 31,Page status 34,Front page news 38,Audience 44,Maintenance status 46,Development status 48,Services 50,Sectors 52,Locations 54,Keywords 56,Level 58,License 60,Book availability 62,Book format
> 5 votes

---
Tags: community-official-site
---


title: How do I change the site mail address?

text:
# Question
Title: How do I change the site mail address?
I want to change my site-wide email address. To do this, I changed the settings on admin/config/system/site-information. However, when I send an email from rules, it still uses the old email address.

How can I get the new email address to be picked up?

# Answer
> 1 votes
Based on the comments, and narrowing down the problem to the Rules module itself, or its integration with the mail system:

* Tokens work elsewhere
* Tokens within the body of the message work but not the from field
* No templates are used
* Core mail as well as third-party mail are affected
* Clearing the cache, including the rules one, had no effect

It would appear to be a bug in the Rules module or the mail delivery part of it. I would suggest adding an issue to the Rules issue queue and see if they can further explore options for correcting the problem.

---
Tags: rules, emails
---


# Question
Title: Several NFS folders for one Drupal instance
I'm using vagrant & virtualbox to create drupal websites on my Windows local machine. My actual drupal website is under a Windows folder, shared with my guest(ubuntu) by using a Windows NFS server (winnfsd).

After playing with NFS mount caching options, I understood that my website becomes really fast when enabling it.(specially files attributes caching with high actimeo parameter)

The website becomes fast, but it's almost unusable to developp at the same time:

* Changes in my Windows text editor (Sublime Text) are not seen by Linux.
* Sass/compass/gulp also don't see changes made in Windows if actimeo is superior to few seconds.

And when there is no NFS cache at all, I could see that lots of NFS operations are logged by my NFS server logs. Every Drupal files are accessed even several times to get attributes, nslookup, read, access...

So my idea was to make several NFS mounts, with different NFS caching options.

* Drupal core files never changed **=\> really long NFS cache**
* Contrib modules changed rarely **=\> really long NFS cache**
* Custom modules change often **=\> NO CACHE**
* My Themes change often **=\> NO CACHE**

So here is my question, is it good assumptions ? If yes how do we make those kind of multiple NFS shares ? I thought about Symlinks ? Any one tried this approach ?

# Answer
> 1 votes
```
ini_set('opcache.validate_timestamps', FALSE);

```

Then when you want to push a code change out run

```
opcache_reset();

```

or restart the Apache process.

If you're working on a set of files you can use opcache\_invalidate() to check if those files need to be recompiled.

```
// http://stackoverflow.com/questions/24783862/php-recursively-list-all-files-in-directory
function get_dir_contents($dir, &$results = array()){
  $files = scandir($dir);

  foreach($files as $key => $value){
    $path = realpath($dir. DIRECTORY_SEPARATOR. $value);
    if (!is_dir($path)) {
      $results[] = $path;
    }
    elseif (is_dir($path) && $value != "." && $value != "..") {
      get_dir_contents($path, $results);
      $results[] = $path;
    }
  }

  return $results;
}

// https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!OpCodeCache.php/function/OpCodeCache%3A%3Ainvalidate/8
function invalidate_opcodecache($pathname) {
  clearstatcache(TRUE, $pathname);

  // Check if the Zend OPcache is enabled and if so invalidate the file.
  if (function_exists('opcache_invalidate')) {
    opcache_invalidate($pathname, TRUE);
  }
  // If apcu extension is enabled in PHP 5.5 or greater it emulates apc.
  // This is to provide an easy upgrade path if you are using apc's user
  // caching however the emulation does not extend to opcode caching.
  // Therefore we need to check if the function exists as well.
  if (extension_loaded('apc') && function_exists('apc_delete_file')) {
    // apc_delete_file() throws a PHP warning in case the specified file was
    // not compiled yet.
    // @see http://php.net/manual/en/function.apc-delete-file.php
    @apc_delete_file($pathname);
  }
}

$file_path = 'sites/all/modules/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}
$file_path = 'sites/all/themes/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}

```

Put this code in your settings.php file.

If using APC the info for that is located here: Best APC settings to reduce page execution time

And apache: Adding .htaccess within httpd.conf correctly

Also see: First page load/execution slow, login slower Drupal 7

---
Tags: performance, virtual-machine
---


# Question
Title: How do you programmatically hide a field based on another field on a custom content type?
I have built a custom content type that has a boolean field called 'Hide images'. There is also an images field that displays all images at the bottom of the node. I'd like to setup a way so that depending on the 'Hide images' field I can decide whether to display the images field. Is there a way to edit this via a template?

I saw in page--node--contenttype.tpl.php that I could render($page\['content'\]); but I couldn't actually see how I could choose what content to display.

# Answer
> 1 votes
In your template, instead of rendering the entire content array, you can break it down to print each individual item separately. Then, you could wrap the printing of the images in a statement that checks if the boolean value is true/false.

```
<?php if ($content['field_boolean_hide_images'] === FALSE): ?>
  <?php print render($content['field_image']); ?>
<?php endif; ?>

```

This is just an example and shouldn't be used verbatim.

Also, to create a template for your content type, it would be `node--yourContentType.tpl.php` rather than a page template override.

---
Tags: theming, nodes
---


# Question
Title: CSS files defined in .info file are being ignored
Having followed a number of different guides to try and create a Bartik sub theme that allowed me to use the Color module, the following was the last one I attempted that worked: http://drupal.org/node/800510#comment-3277090

However despite this working, none of the CSS files specified in my sub theme are working. Following is my info file:

```
; $Id: bartik.info,v 1.5 2010/11/07 00:27:20 dries Exp $

name = crxtr
description = A bartik sub theme
core = 7.x
base theme = bartik

stylesheets[all][] = css/crxtr.css
stylesheets[all][] = css/colors.css
stylesheets[all][] = css/crxtr-views.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

; Information added by drupal.org packaging script on 2011-01-05
version = "7.0"
project = "drupal"
datestamp = "1294208756"

```

Now the CSS from my front page reads:

```
<style type="text/css" media="all">@import url("http://local.tracker/modules/system/system.base.css?ll8uzr");
@import url("http://local.tracker/modules/system/system.menus.css?ll8uzr");
@import url("http://local.tracker/modules/system/system.messages.css?ll8uzr");
@import url("http://local.tracker/modules/system/system.theme.css?ll8uzr");</style>
<style type="text/css" media="all">@import url("http://local.tracker/misc/ui/jquery.ui.core.css?ll8uzr");
@import url("http://local.tracker/misc/ui/jquery.ui.theme.css?ll8uzr");
@import url("http://local.tracker/modules/overlay/overlay-parent.css?ll8uzr");
@import url("http://local.tracker/modules/contextual/contextual.css?ll8uzr");</style>
<style type="text/css" media="all">@import url("http://local.tracker/modules/comment/comment.css?ll8uzr");
@import url("http://local.tracker/modules/field/theme/field.css?ll8uzr");
@import url("http://local.tracker/modules/node/node.css?ll8uzr");
@import url("http://local.tracker/modules/search/search.css?ll8uzr");
@import url("http://local.tracker/modules/user/user.css?ll8uzr");
@import url("http://local.tracker/sites/all/modules/views/css/views.css?ll8uzr");</style>
<style type="text/css" media="all">@import url("http://local.tracker/sites/all/modules/ctools/css/ctools.css?ll8uzr");
@import url("http://local.tracker/modules/shortcut/shortcut.css?ll8uzr");
@import url("http://local.tracker/modules/toolbar/toolbar.css?ll8uzr");</style>
<style type="text/css" media="all">@import url("http://local.tracker/themes/bartik/css/layout.css?ll8uzr");
@import url("http://local.tracker/themes/bartik/css/style.css?ll8uzr");
@import url("http://local.tracker/sites/default/files/color/crxtr-5fa2c1e5/colors.css?ll8uzr");</style>
<style type="text/css" media="print">@import url("http://local.tracker/themes/bartik/css/print.css?ll8uzr");</style>

```

The 3 CSS files specified in the info file are present and contain rules.

Following is an excerpt also from the head, which shows that at least on some level, the info file is being parsed and the CSS files are being recognized:

```
<!--//--><![CDATA[//><!--...,"sites\/all\/themes\/crxtr\/css\/colors.css":1,"sites\/all\/themes\/crxtr\/css\/crxtr.css":1,"sites\/all\/themes\/crxtr\/css\/crxtr-views.css":1,...//--><!]]>

```

I've tried clearing the cache about a billion times to no effect. I just tried adding the following line to my info file and corresponding CSS file, and the only effect was that it actually removed the bartik/css/style.css from the HEAD, rather than substituting or adding the crxtr/css/style.css:

```
stylesheets[all][] = css/style.css

```

Please let me know if I can provide any more info to diagnose.

Edit: Followed the same process to create a subtheme using NineSixty and have had no problems with it finding and loading my sub-theme CSS files.

# Answer
> 2 votes
Please rename your css file name style.css to blah.css, it will works.

# Answer
> 1 votes
I'm new to Drupal 7, and those days I also had problems subtheming Bartik myself or copying and modifying the whole Bartik folder into my themes folder. At the end, I did using the only 'official' Bartik sub-theme I found (Antonelli) and then changing CSS and stuff in the info of Antonelli instead.

# Answer
> 0 votes
I'd just like to point out that it appears Drupal is quite particular about the location *and/or* name of your css file when including it via a module's **.info** file. This is what worked for me:

**Directory**

```
sites/all/modules/custom/my_module/

```

**Files**

```
my_module.info
my_module.module
css/my_module.css // DOES NOT WORK
css/foo.css

```

**my\_module.info**

```
name = My Module
description = My awesome module
core = 7.x
package = Other
stylesheets[all][] = css/my_module.css // DOES NOT WORK
stylesheets[all][] = css/foo.css

```

For some *reason*, **.css** files included via a module's **.info** file, *cannot have the same filename* as the module itself. This means the **my\_module.css** file will *not* be loaded.

Be sure to *flush all of Drupal's caches* after making changes to a **.info** file.

---
Tags: 7, theming
---


title: Server unable to find existing file

text:
# Question
Title: Server unable to find existing file
I have chosen a hosting provider to put my multi-site system online. I have uploaded the files and databases and have achieved limited functionality. However, a mysterious problem is occurring.

My hosting provider instructed me to implement the sites by creating subdomains of the subdomain they created for my account. So the URL for site1.com at this stage is `site1.newsites.a2hosted.com`.

The site includes an "About" page whose alias is "About\_Site1" and which includes a php call to include a file "about.php".

When I attempt to load the "About" page (via `site1.me.a2hosted.com/About_Site1`), I get this error:

> Fatal error: require\_once(): Failed opening required '/sites/Site1/\_/about.php'

To check if it's looking in the right place, I inserted

```
echo($_SERVER['DOCUMENT_ROOT']);

```

and this immediately before the call to `require_once()`.

So the code is now:

```
echo('doc root: "' . $_SERVER['DOCUMENT_ROOT'] . '"');
require_once('/sites/Site1/_/about.php');

```

and the result is:

> doc root: "/home/newsites/public\_html" Fatal error: require\_once(): Failed opening required '/sites/Site1/\_/about.php' (include\_path='.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/newsites/public\_html/modules/php/php.module(80) : eval()'d code on line 3

The tech support agent at my hosting provider reported: "*I have checked the file and folder permissions, and this file is definitely readable by the system. While this is possibly a development issue related to the way Drupal is handling these subdomains internally, I have opened this ticket to further review the situation and ensure that nothing server-side is causing an issue.*"

The site is set up as a subdomain because that's how my hosting provider told me to implement multi-site on their system.

While they are looking into the problem, does anyone have any insights on what might be going on?

# Answer
> 1 votes
```
echo('doc root: "' . $_SERVER['DOCUMENT_ROOT'] . '"');
require_once('/sites/Site1/_/about.php');

```

Is sort of half-and-half; what you need is

```
require_once DRUPAL_ROOT . '/sites/Site1/_/about.php';

```

Or PHP will be looking in the root of the file system.

---
Tags: 7
---


title: Site maintenance/merge changes

text:
# Question
Title: Site maintenance/merge changes
I set up an account at BlueHost and my unfinished site is now live at columbiablooms.org.

My understanding is that when I make modifications, such as enhancements, that changes are made not only to the file structure, but also the database meaning that from this point forward I need to make all my changes and content additions to this live site. Also, I want to be very careful to backup both the file structure and the database before I make changes in case I mess things up.

At this point my Acquia Dev Desktop is not very useful since there appears to be no way to merge what I've done on my local machine with what's live out there on the web.

# Answer
You aren't required to make changes directly to your live site, it is bad practice to do this for things other than minor content additions/changes.

You should have at a minimum a dev and production environment. Your local environment would be dev obviously and there are many ways to sync the changes between dev and live.

If you have ssh access to your server, the best way would probably be to use drush to sync your changes between environments. There is a good explanation of this method here.

If you don't go the drush route, you could always do it manually by dumping your local db / files and updating the live site.

There is a lot of information on the subject on this site, a good bit of info can be found here.
> 1 votes

---
Tags: migrations, staging
---


title: Contextual filters taxonomy name

text:
# Question
Title: Contextual filters taxonomy name
I'm adding a contextual filter to a view for a custom content type that has a taxonomy field. The contextual filter allows me to filter by the taxonomy tag id but not by the taxonomy tag name. Meaning with the given tags in the taxonomy:

```
1  | test1
2  | another tag
3  | taggy
......
99 | coolness

```

I can generate a contextual filter that will parse a URL like `http://mydrupal/myview/3` to display all content that has been tagged with `taggy` BUT, the URL needs to pass the argument to lookup by tag *name* instead of tag *id*, e.g., `http://mydrupal/myview/taggy` to view all content tagged with `taggy` How can this be accomplished?

# Answer
I assume you've added the `Content: Has taxonomy term ID` contextual filter. You can use taxonomy term names with this filter by adjusting `Specify validation criteria` settings. here's a screenshot:

Make sure `Specify validation criteria` is checked and you should be presented with more options. Under `Validator` choose `Taxonomy term`. You can optionally select with vocabularies to allow. Under `Filter value type` choose `Term name converted to Term ID` and check the `Transform dashes in URL to spaces in term name filter values` checkbox.
> 161 votes

# Answer
Another way to skin the cat:

I needed the actual taxonomy term name query not converting to term ID.

Here is how to query the taxonomy term name that was passed as a contextual filter:

> To get the name you must add a relationship, either on the field or the generic taxonomy relationship. Then you can add any fields for that term as a contextual filter, including the name.
>
> https://www.drupal.org/node/1156022#comment-4469378
> 8 votes

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


# Question
Title: Best way to migrate text field to taxonomy reference field
I want to migrate a text field to taxonomy reference field( the Tags one).

I've 1200 nodes having a field "Organization name". Those creating the content are making mistakes like misspelled company names. I'm using the company name in the views to find all related nodes.

This will help those entering can simply choose the company names or if someone has entered IBM for International Business Machines then I can merge those terms when using taxonomy reference field.

Should I go and create a vocabulary, add all existing values as terms in vocabulary then programmatically assign the text field values to the taxonomy reference field? Then delete the text field and change references in the views etc.

# Answer
> 2 votes
I would:

* Go thorough all values, grouping them by their Levenshtein distance from each other.
* For all set of similar names, I would choose canonical one, and put them in taxonomy as a term.
* Using Computed Field or VBO I would choose the Levenshtein closest term for each node.

Details of implementation would need a bit of polishing, but that's my general approach. Apparently you can use Views Bulk Operations both to create taxonomy terms and to set field's value on node.

# Answer
> 2 votes
niccottrell on Drupal.org provided another solution:

Below `donor` is a source field, `receptor` is a taxonomy field. Loop over your nodes, possibly using Batch API, and for each invoke code like this:

```
$vid = 25; // vocab ID
$edit = array('vid' => $vid, 'name' => $object->field_donor[$object->language][0]['value']);
$terms = taxonomy_get_term_by_name($edit['name']);
if (!empty($terms)) {
  // term already exists
  $first_item = array_shift($terms);
  $tid = $first_item->tid;
}
else {
  // add term and get the tid
  $status = taxonomy_term_save($edit);
  $tid = $edit['tid'];
}
$object->field_receptor[$object->language][0]['tid'] = $tid;
node_save($object);

```

# Answer
> 2 votes
The code that which I wrote in migration\_brand\_type.inc file. This is a file which would create a mapping table for for the text field on the legacy database and Taxonomy on Our Drupal Database.

```
class MigrationBrandType extends Migration {
  public function __construct() {
    parent::__construct();

    $this->description = t('Migrate languages from the source database to taxonomy terms');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'productbrand' => array('type' => 'varchar', // Name of the field which you wish to migrate
        'length' => 255,
        'description' => 'Taxonomy Migration of brand',
        )
      ),
      MigrateDestinationTerm::getKeySchema()
    );
    $query = Database::getConnection('default', 'legacy') // Legacy was the name of the database of mine.
      ->select('names', 'names') // Names was the name of the column from the legacy database from which I was fetching text values.
      ->fields('names', array('productbrand'))
      ->condition('productbrand', 'NULL', '!=');

    // Create a MigrateSource object, which manages retrieving  the input data.
      $this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

    // Set up our destination - terms in the migrate_example_beer_styles vocabulary
    $this->destination = new MigrateDestinationTerm('brands'); // Name of the vocabulary in which I was saying the text values.
    $this->addFieldMapping('name', 'productbrand');

  }
}

```

While creating the field mapping for creating the relationship we do something like:

```
    $this->addFieldMapping('field_brand_type', 'productbrand')
     ->sourceMigration('MigrationBrandType')
     ->arguments(array('source_type' => 'tid'));

```

First, we migrate all the Text to the respective vocabulary and thwn we start the migration of content.

# Answer
> 0 votes
Using the example/suggestion @Molot posted, I created a batch process and packaged it as a module. Thought I would share.

First, create your taxonomy terms and add your entity reference field to your content type, then create and enable your batch module. Be sure to update the `**FIELDS**` below.

```
/**
 * Implements hook_menu().
 */

// Lets add a menu link to initiate the batch process
function convert_field_to_taxonomy_menu() {
    $items = array();
    $items['admin/batch'] = array(
        'title' => 'Convert to Tax Batch',
        'description' => 'Run batch operations.',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('convert_field_to_taxonomy_form'),
        'access arguments' => array('administer site configuration'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
// And a button to click
function convert_field_to_taxonomy_form() {
    $form = array();
    $form['submit'] = array('#type' => 'submit', '#value' => t('Click here to Start'));
    return $form;
}

function convert_field_to_taxonomy_form_submit($form, $form_state) {
    batch_set(convert_field_to_taxonomy_setup_batch());
}

function convert_field_to_taxonomy_setup_batch() {
    drupal_set_message('Updating Nodes');
    // load all the nodes from content type
    $nodes = node_load_multiple(array(), array('type' => "**CONTENT_TYPE**"));
    $node_count = count($nodes);

    // build the list of operation functions and function arguments
    foreach($nodes as $nid => $node) {
        // $operations[] = array(<function name>, <array of arguments to pass to function>);
        $operations[] = array('convert_field_to_taxonomy_method', array($node));
    }

    //put all that information into our batch array
    $batch = array(
        'operations' => $operations,
        'title' => t('Convert to Tax Batch'),
        'init_message' => t('Initializing...'),
        'error_message' => t('An error occurred'),
        'progress_message' => t('Operation @current out of @total.'),
        'finished' => 'convert_field_to_taxonomy_finished_method'
    );
    return $batch;
}

function convert_field_to_taxonomy_method($node, &$context) {
    $context['results'][] = $node->nid.
    ' : '.check_plain($node->title);
    // Optional message displayed under the progressbar.
    $context['message'] = t('Processing snapshot "@title"', array('@title' => $node->title));

    $vid = 38; // vocab ID
    $edit = array('vid' => $vid, 'name' => $node->**SOURCE_FIELD**['und'][0]['value']);
    $terms = taxonomy_get_term_by_name($edit['name']);
    if (!empty($terms)) {
        // term already exists
        $first_item = array_shift($terms);
        $tid = $first_item->tid;
    } else {
        // add term and get the tid
        $status = taxonomy_term_save($edit);
        $tid = $edit['tid'];
    }

    $node->**TARGET_FIELD**['und'][0]['target_id'] = $tid;
    node_save($node);
    $path = drupal_lookup_path("alias", "node/".$node->nid);
    drupal_set_message("<a href='/$path'>".$node->title.
        "</a> updated.");
}

function convert_field_to_taxonomy_finished_method($success, $results, $operations) {
    if ($success) {
        // Here we could do something meaningful with the results.
        // We just display the number of data we processed...
        drupal_set_message(t('@count terms processed.', array('@count' => count($results))));
    } else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
    }
}

```

---
Tags: 7, entities
---


title: Get payment before users create a node

text:
# Question
Title: Get payment before users create a node
When users create a node, they should be redirected to a payment page; if payment is successful, the user can see the node.

Is there any way to achieve this?

# Answer
Although not open source, there is the paid for module called 'pay to publish'.

I've not used this exact module, but have used this companies products before and they worked 100% as advertised...

For some reason my phone will not allow me to paste the URL in here, so just Google 'moneyscripts Drupal pay to publish'.
> 2 votes

# Answer
If you're using Drupal Commerce you could acheive this pretty easy using Rules and a custom defined user role.

Create a user role which is restricted from viewing the content type you want them to pay for. Then configure a Rule which assigns the newly define role to your customer once they have succesfully completed payment. This means that only users who have paid for your product will have access to the content type.
> 1 votes

# Answer
I think you're looking for Commerce Node Checkout.

> Integrate with Commerce in order to allow you to charge users to create nodes. It is possible to have multiple different product offerings for each node type, so the user can pick the product they want to purchase when creating the node. An example use-case would be a classifieds site that charges people to post listings.

The module creates a Paid Posting product type. You created different products for different posting options (e.g. multiple options for how long the posting is published) you then associate those options with a content type you want a user to purchase.

After completing the node creation workflow and selecting the purchase option, a user is redirect to the cart for checkout. Upon checkout the node is published. There is optional functionality to make the node expire after a set amount of time.
> 1 votes

# Answer
You could also use Payment Reference field module of the Payment project.
> 0 votes

---
Tags: nodes
---


# Question
Title: Search with Views not Saving Selected Filters when user tries to go BACK
I've created a search page using Views with exposed filters and the basic search module. The search only returns results for a specific node content type 'resource'. A typical use case would be the following:

User goes to search page, types some text into the exposed search terms block, and also selects some options from the exposed filters that are drop-down menus. They click 'search' and their results are returned on the same page. Pretty standard stuff and I have that all working fine.

A user then clicks a link to a resource node of interest to them and goes to that node's profile page. All fine and dandy.

The problem is when they want to go BACK. I went ahead and added a back button with the following code to my node--resource.tpl.php, which works as you'd expect (it bypasses the browser back button and takes user to main search page again):

```
<input type="button" value="Go Back" onclick="window.history.back()" />

```

**What happens is it displays the search page again, but no longer with the search term they entered OR the exposed filters they selected. I'd like to change that so when they click the 'back' button the search page still shows their search results from before so they don't have to re-select all their options again.**

This seems like pretty basic stuff, but I can't figure out how to do it in Drupal. I imagine it involves session cookies somehow...but how to combine this with Views I do not know.

Thanks for your help!

# Answer
Ok, I solved my own question. To get Views search results to 'stick' you just have to select an option for each filter you want to save and the role that this works for.

In Views \> Filters \> check the box next to 'remember the last selection' and select which roles this applies to.

Easy. Now when a user clicks the 'back' button I've added to the tpl file it takes them back to their selections.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How can i add a page.tpl.php for a page type and a language?
I want to match a page--type-receipe.tpl.php for a page type but it doesn't work. I think the reason is the multi-language.

The page.tpl.php work without any problems.

# Answer
> 1 votes
It doesn't work because **page--type-receipe.tpl.php** isn't a valid template suggestion. If you're looking to theme a page by *node type* & *language*, you can do something like this to create your own theme suggestions inside your theme's **template.php**.

```
function MYTHEME_preprocess_page(&$variables) {
  global $language;

  if(isset($language->language) && isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__'.$variables['node']->language.'__'.$variables['node']->type;
  }
}

```

This will let you make **page--en--recipe.tpl.php** a valid template file for a page showing a *recipe* node in *english*.

---
Tags: theming
---


# Question
Title: How to display a BACK button but ONLY if the user came from somewhere else on my site
I'd like to display a BACK button on my node--resource.tpl.php file but ONLY if the user came to the node from another part of my site. If they copied and pasted the URL for the node directly into their browser's address bar and got to it that way I do NOT want the button to appear.

Here' the button in my tpl:

```
<input type="button" value="Go Back" onclick="history.go(-1)" />

```

Anyone know how to do this with PHP (or another Drupal method)?

# Answer
There are many ways to do this. One of it would be to use $\_SERVER\['HTTP\_REFERER'\] to detect where the user comes from.

Put the following code in your template file.

```
if (strstr($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
     // Facebook brought me to this page.
     print '<a href="javascript: history.go(-1)">Go Back</a>';  }

```
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: amazons3-7-x-2.0, Multiple upload to S3, #upload_location wrong URI
I installed the brand new amazons3-7.x-2.0 published last week, and the process is not straightforward.

I finally managed to have it works, and I have the CCK file field, with a typical remote #upload location URI : s3://\[bucketname\]/\[subdirectory\].

On the node form, the first file I upload works fine. It monitored the file\_managed\_file\_save\_upload($element) function, which is called with the proper argument (remote URI): **$element\['#upload\_location'\]=s3://\[bucketname\]/\[subdirectory\]** .

But when I click on "add new file" and select another file, the file\_managed\_file\_save\_upload function is called with a wrong #upload\_location : **$element\[#upload\_location'\]= s3://\[subdirectory\]**

The upload then failed with the following message : "The file could not be uploaded.".

In order to get amazons3 module to work with this long awaited new release, I had to patch a lot of files with contributed patches fixing the exact same issue of bucketname in the URI.

Is somebody facing the same problem and found a solution ? I will try the plupload module see if it fixes the issue.

# Answer
ok, after spending a few hours debugging the code, I have finally identified the problem and come out with a solution :

Amazons3 implements a amazons3\_field\_widget\_form\_alter that fixes the $element\['#upload\_location'\] :

> function amazons3\_field\_widget\_form\_alter(&$element, &$form\_state, $context) {
>
> $field = $context\['field'\]; $instance = $context\['instance'\]; $delta = $context\['delta'\];
>
> if (in\_array($field\['type'\], amazons3\_file\_like\_field())) { $element\[$delta\]\['#upload\_location'\] = amazons3\_field\_widget\_uri($field, $instance); } }

The problem is that this function is only called once, on $delta=0. Thus, it only fixes the first delta instance of the field, correcting the first upload. But the second upload fails because the bucketname is not in the remote URI.

In order to fix this, I propose the wrote following function in my module :

> function mymodule\_field\_widget\_form\_alter(&$element, &$form\_state, $context){ // On essaie de corriger les settings upload\_location if (!function\_exists('amazons3\_file\_like\_field')) { return; } $field = $context\['field'\]; $instance = $context\['instance'\]; $delta = $context\['delta'\];
>
> ```
> if (in_array($field['type'], amazons3_file_like_field())) {
>     foreach (array_keys($element) as $count => $key) {
>         if (is_numeric($key) && isset($element[$key]['#upload_location']) && !(strpos($element[$key]['#upload_location'],'s3://')===FALSE)) {
>             $element[$key]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
>         }
>     }
> }
> return;
>
> ```
>
> }

It works well, allowing multiple uploads in S3 with the new release of the library. Next step would be to post a patch to the amazons3 module. Which I will do now.
> 0 votes

---
Tags: 7, files
---


title: How many taxonomy terms are too many?

text:
# Question
Title: How many taxonomy terms are too many?
I have a website where I publish book reviews. For each book I publish 2-3 quotes from the book. I'm using the following fields as taxonomy, so that when a user clicks on them he/she can find more content of that category.

* Book name
* Author name
* Publisher

Lets say, over the period of time, I add reviews of about 5000 books, then there will be 5000 taxonomy terms for "book name". Same for the other categories.

My question is, are these too many taxonomy terms for Drupal? Or is there a better way of doing this. All I'm trying to do is, when a user clicks on author's name, he/she can find more content from that author.

# Answer
> 4 votes
Short answers:

* Drupal should have no problem with 5000 terms.
* Using a taxonomy for this is the best solution in Drupal.

You may also want to use Taxonomy manager as suggested by *kala4e4k* in a comment.

What is the upper limit?

Well, taxonomy vocabularies are managed by the database, so this limit is determined by the maximum number of rows you can store in a table in the database you're using.

If you're using MySQL, there is no *built-in* limit to the number of rows per table (just pick a big enough number type to manage the primary key), but there are *other* constraints on table size besides number of rows. If you have a 500 Gbyte hard drive and each record is 1 KB is size, your maximum number of rows will be 500 million (if you dedicate the *entire* drive to this single table, which is not a very realistic scenario). If you buy a 10 Tbyte hard drive, you may run into your operating systems file size limitation (for instance, I believe Ubuntu's maximum is 5 TB, so your limit will be 5 000 million terms instead of 10 000 milion - given the same assumptions about record size).

---
Tags: taxonomy-terms
---


# Question
Title: How to specify a background image in a view so that it doesn't get removed?
I want to output an image as a background-image of a "section"-tag but it doesn't work.

First I added the Image URL Formatter module, so I do not output the image but the url of the file.

In my view I add the image which generated with the contextual filter of the url. In that field I rewrite the output:

```
<section style="background-image: url([field_hintergrundbild])" id="slid-unternehmen">
</section>

```

When I check the site I only get this:

```
<section id="slid-unternehmen"> </section>

```

I tried several times and it seems to me that Drupal will not accept the "style="..."" tag, Drupal will always remove it! And I don't know why?

If I change the `style` to `class`, I get the normal output, as in this example:

```
<section class="background-image: url(http://....)" id="slid-unternehmen"> </section>

```

Does anybody have an idea?

# Answer
> 3 votes
To understand **why** this (= the `style` being removed) is happening, refer to this comment in the views issue queue:

> Rewrite uses filter\_xss\_admin and allows only the tags listed there.

It also includes a **possible solution** for it, which is like so:

> If you need more than this, then you need to use a template where you have complete control. This ensures that data entered via the UI is safe.

For an **alternative solution** (instead of using a template), you may want to consider the Background Images Formatter module. Here is an excerpt from its project page:

> This module provides an image formatter who allows you to set an image in background of a div. The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.

# Answer
> 0 votes
Well if class works then do it using css

```
<section class="haha" id="slid-unternehmen"></section>

```

In **HEADER** click add, and select **Global: Text Area**.

Then on your text field put:

```
<style>
.haha { background-image: url([field_hintergrundbild]);
</style>

```

For Text format select **Full HTML**

**Checkmark** Use replacement tokens from the first row

---
Tags: 7, views, javascript
---


# Question
Title: Display Exposed Filter value of selected exposed filter
I work on drupal 7, and create a page from views used 4 exposed filter. I want to display exposed selected values., and also close button in exposed selected values

I try to selected data in field and excluded it and used in header Global: Unfiltered text. But not work properly.

# Answer
You have a couple of options here Rituraj.

You'd need to use PHP to output the selected values in the header. See the related example here to see how to output view filter values to a template.

```
<?php
$view = views_get_current_view();

if(isset($view->exposed_input['field_release_date_value']['value']['year'])) {
  echo "<h2>Press Releases for ", $view->exposed_input['field_release_date_value']['value']['year']; "</h2>";
}
else {
  echo  "<h2>Press Releases for ", date("Y"); "</h2>";
}
?>

```

This post has an example for using an exposed filter value to override the page title as well.

My preferred method would be to use JQuery to read updates from the exposed filter and inject them into the DOM. That would have the added bonus of making it easy for you to wire up the X links to remove both the value both from the display and from the exposed filter.
> 2 votes

# Answer
It is not the best practice to include PHP in views. Instead override views tpl file to include the code as needed. Consider view page named "Exposed Filter data". "Display output" file can be found under "advanced"-\>"Theme: information" setting of view. Select last name from "Display Output" as the tpl file name. For this example file name is "views-view--exposed-filter-data--page.tpl.php". Clicking on "Display Output", you will get current code of the file. Include following code after $exposed is printed & its condition ends. Here is the code that needs to be done for displaying exposed selected values of all four dropdowns. Considering Lamp, Color Temperature, Luminous Flex & Wattage as Taxonomy Term Reference fields, current view is loaded & current selected values are displayed with a cross anchor link.

Note that here "data-field" value on anchor field are same as id of the select list.

```
<?php
  $lamp = '';
  $color_temperature = '';
  $luminous_flex = '';
  $wattage = '';
  $view = views_get_current_view();
  if (isset ($view->exposed_input['field_lamp_tid'])) {
    $tid = $view->exposed_input['field_lamp_tid'];
    if (is_numeric($tid)) {
      $term_obj = taxonomy_term_load($tid);
      $lamp = '<a href="#" class="reset" data-field="edit-field-lamp-tid">X</a>' . $term_obj->name;
    }
  }
  if (isset ($view->exposed_input['field_color_temperature_tid'])) {
    $tid = $view->exposed_input['field_color_temperature_tid'];
    if (is_numeric($tid)) {
      $term_obj = taxonomy_term_load($tid);
      $color_temperature = '<a href="#" class="reset" data-field="edit-field-color-temperature-tid">X</a>' . $term_obj->name;
    }
  }
  if (isset ($view->exposed_input['field_luminous_flex_tid'])) {
    $tid = $view->exposed_input['field_luminous_flex_tid'];
    if (is_numeric($tid)) {
      $term_obj = taxonomy_term_load($tid);
      $luminous_flex = '<a href="#" class="reset" data-field="edit-field-luminous-flex-tid">X</a>' . $term_obj->name;
    }
  }
  if (isset ($view->exposed_input['field_wattage_tid'])) {
    $tid = $view->exposed_input['field_wattage_tid'];
    if (is_numeric($tid)) {
      $term_obj = taxonomy_term_load($tid);
      $wattage = '<a href="#" class="reset" data-field="edit-field-wattage-tid">X</a>' . $term_obj->name;
    }
  }
  echo $lamp . ' ' . $color_temperature . ' ' . $luminous_flex . ' ' . $wattage;
?>

```

Jquery is used for reseting the value of dropdown & submitting the form, when cross link is clicked. Replace "VIEW\_EXPOSED\_FORM\_ID" with your form id by inspecting element.

```
jQuery(document).ready(function(){
  jQuery('a.reset').live( 'click', function() {
    var datafield = jQuery(this).attr('data-field');
    jQuery('#'+datafield).val('All');
    jQuery( 'VIEW_EXPOSED_FORM_ID' ).submit();
  });
});

```

Hope this helps.

Thanks!
> 2 votes

---
Tags: views
---


# Question
Title: Relationships in Views always 4 results also if no reference for the field
I have two content types :

* meals
* wine

In my content-type "**meals**" I have a entity reference to "**wine**".

Now I wanna create a views to show all **meals**, with a reference to **wine**.

I have create a views with following settings:

> ***FILTER CRITERIA***
>
> = Content Type (= meals)
>
> = (Content entity referenced from field\_wine) Content: Published (Yes)
>
> ***RELATIONSHIPS***
>
> = Entity Reference: Wine

In my view I get all results for that. So if a wine was tagged in 2 meals, I get a view with that two meals.

My Problem now: I always wanna show 4 meals. So I want to show the 2 meals + 2 others.

If i have a wine with 1 meals. So i want so show the 1 meal + 3 others.. and so on.

Do any know how to fill the results if the missing some meals?

# Answer
> 0 votes
I think the best way to do via https://www.drupal.org/project/views\_field\_view . So, below is the steps:-

1. Create a view for the meal which shows all meals and add one more field "nid" as a hidden parameter(just tick exclude from display) so that we will have an available token for nid.
2. Now, create another block of wine and pass meal's nid as a contextual fitler. so, it will give you all wine as per single meals.
3. The next step do the trick. Go back to block #1(meal's view) and and add global:view field and pass "\[nid\]" of the meal as a contextual filter in that field(you will find an option don't worry) and select the view and display of the #2(wine's block).
4. That's it, here you have all the meals with wines. :)

Hope it will solve your problem.

---
Tags: views
---


# Question
Title: Preventing spam registration /url redirect
im getting more and more spam account registrations. what is the simplest way to handle this if one does not need browser based registration? people register the REST/services way via an app.

can this be achieved without additional modules? e.g. server redirect?

# Answer
If you don't need user self-registration then just disable that functionality.

To do this go to :
/admin/config/people/accounts (Admin \> Configuration \> People \> Account Settings)

And for the **Who can register accounts?** setting choose **Administrators only**.

If later on you decide that you need that functionality, you can enable it back and then just add a captcha to your user registration form, or integrate something like honeypot or logintoboggan.
> 0 votes

---
Tags: 7, users, advertising
---


title: What module should I install for php?

text:
# Question
Title: What module should I install for php?
I am trying to import a rule for facebook autopost in Configuration\>Workflow\>Rules, but after I click import button, I receive the error message below. I don't know which php module I have to install. I have searched on drupal site but I don't figure out which module I have to install.

Regards,

# Answer
You should enable PHP Filter modules under *CORE* . Go to /admin/modules and find PHP Filter module and enable

It allows embedded PHP code to be evaluated
> 2 votes

---
Tags: configuration
---


# Question
Title: (hook_menu_alter) override the same path twice
I have created a custom module which implements the hook\_menu\_alter in order to override those two paths and to add my own access control logic:

`$items['taxonomy/term/%taxonomy_term/edit']['access callback']`

`$items['taxonomy/term/%taxonomy_term/edit']['access arguments']`

Looking for an out of the box solution I found this module vppr which overrides the exact same paths adding its own logic.

The point is that if I have both modules enabled - **vppr** module and **my custom module** \- the `['access callback']` from my custom module is never fired. If I disable the **vppr** module my module is working fine.

Is that possible, two different modules can't override the same path or I'm missing something, and why the `['access callback']` from the contrid module is executed over mine?

thanks!

# Answer
> 0 votes
There can only be one set of metadata for a single path. Hooks are invoked sequentially, so yes, if you have another module altering the same path, either yours or theirs will 'win'; never both.

You can control the order hooks are called in using the 'weight' column in the system table, or through the use of `hook_module_implements_alter()`.

---
Tags: 7, routes
---


title: File module not updating field

text:
# Question
Title: File module not updating field
I have a File field for uploading pdfs. When editing the page, I remove the current pdf and upload a new pdf. The new pdf is uploaded to the server and add to the /sites/default/files folder and I can access the new pdf. However, the page still references the previous pdf that was uploaded.

I check the database and noticed that the new pdf was added to the files\_managed and the files\_usage tables but NOT the files table. Any idea why this would be and how I can get the File field to reference the latest uploaded pdf?

In a template, I have a db query for the file id, when I print the fid on the page, it shows the outdated file id instead of the new file id.

# Answer
> 0 votes
Are you clicking Save at the bottom of the edit page after uploading the new PDF?

You need to do this to save the file reference in the node field.

---
Tags: 7, files
---


title: How to re-order user profile form?

text:
# Question
Title: How to re-order user profile form?
I have this code:

```
function mymod_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['#weight'] = 100;
}

```

Which is supposed to push the 'account' section of stuff underneath the rest of the form elements. But the weight seems to be fixed/the order is unchanged?

I've inspected the `$form` array at the point my code runs, and there are all the other fields, with their respective `#weight` values; and `100` is larger than any of those.

# Answer
The weight you set here would be overridden by the weight values you set via Mange Fields.

However...

You can get around this by changing the weight in pre\_render.

E.g.

```
function mymod_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymod_form_alter_weight';
}

function mymod_form_alter_weight($elements) {
  $elements['account']['#weight'] = 100;

  return $elements;
}

```
> 1 votes

---
Tags: 7, forms
---