# Question
Title: Why might the user's email address not show up in Views Send or as a Token?
I have set up a User view, with User: Email as one of the fields (the others are username and some text fields) . The email address of each user shows correctly in the view, either formatted as text, or as a link.

I was hoping to use Views Send to send an email from that view. When I tick the Views Send tickbox and click 'send email' the dropdown displayed against 'Field used for recipient's e-mail' shows all the fields in the view apart from the email field.

I tried pulling in another text field and rewriting that to show \[user:mail\] or \[mail\] as a Token, but the rewritten field is empty.

I've been all around the houses trying to work out why that field is not showing in the dropdown and I'm stumped. Any help would be greatly appreciated.

# Answer
YAY!

I finally managed to find out why this was happening by comparing against two other Drupal sites where Views Send behaved as expected.

The issue was with the Views Contact Form module : https://www.drupal.org/project/issues/views\_contact\_form

If you have that enabled, it breaks Views Send by hiding the main user email address, even if you have the format of the field set to plain text.
> 1 votes

---
Tags: tokens, views
---


title: View and grouping

text:
# Question
Title: View and grouping
I've view with first column as a group (there are screens below where you can see how I do grouping).

I wish to group my list ignoring 'case sensitive'. How would I do it properly?

Thanks!

Here is how my view is built.

# Answer
> 1 votes
You can achieve this using `hook_views_pre_render()` as shown in example below:

```
function MODULE_NAME_views_pre_render(&$view) {
    if ($view->name !== 'view_name') {
        return;
    }

    $view->field['title_1']->field_alias = 'title_uppercase';
    foreach ($view->result as $result) {
        $result->title_uppercase = strtoupper($result->node_title);
    }
}

```

---
Tags: views
---


# Question
Title: Sorting non-english characters in multilingual website
> I'm having an issue with finding good approach to make sorting works in a Drupal Views.
>
> I've multilingual website (1 database for all languages). Few languages are sorted wrong.
>
> I've read that the real issue is on database layer, however I can't set any specific encoding there, since database contains many different languages.
>
> What would be the most correct approach to make sorting works? The minimum I need atm is a sorting in a Drupal Views.

Any good approach of solving such issues?

# Answer
It may help to somebody.

I end up with doing a simple module (which I'm gonna improve later) that inject COLLATE while doing query to Database so it sort everything properly.

Please feel free to comment this solution :)

```
<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}

```
> 0 votes

---
Tags: i18n-l10n, views
---


title: Drush not working after restart

text:
# Question
Title: Drush not working after restart
I had Drush working yesterday and was able to use it to download a copy of Drupal. After shutting down my machine last night it now won't work.

`which drush` does nothing today. `drush help` gives: `-bash: drush: command not found`

I guess that when I installed it yesterday, some setting was live in the terminal allowing it to work, but this wasn't saved or stored so after restarting it doesn't work. On the day drupal was installed I closed and reopened the terminal window several times and Drush kept working.

I can still see my copy of 6.5.0 in $Trotter/.composer/vendor/drush/drush/

The installation instructions say:

> Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash\_profile (Mac OS users)

I followed these instructions on creating a bash profile and have saved my bash profile with the single line in it: `export PATH="$Trotter/.composer/vendor/bin:$PATH"`

Following the instruction below in terminal didn't do anything for me:

> Type ". .bash\_profile" to reload .bash\_profile and update any functions you add

Please suggest what I need to do to get Drush working again, and keep working after restarting the machine.

Here is the location of composer inside my home directory:

# Answer
> 1 votes
The use of $username in the path looks a bit suspect. You should use .bash\_profile for mac as as .bashrc seems not to be auto loaded. There usually isn't a /username/ directory, its usually /home/username/ so your path should probably be:

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

then execute this to load the file:

```
source .bash_profile

```

or open a new terminal

---
Tags: drush
---


# Question
Title: How do I programatically attach fields to a node defined in hook_node_info()
I've got a module which defines a node type. I also need to attach a few fields to this node.

I'm defining the node in hook\_node\_info(), and I'm creating fields in hook\_install(). However, isn't this going to create the fields before the node? Isn't hook\_install() executed before hook\_node\_info(), meaning that I'll be attempting to attach the fields to a non-existing node type at that point?

How do I define a node type programatically, and also attach fields to the node type programatically upon module installation?

# Answer
> 0 votes
If you have familiarize with features module. It will be easy. You can get more idea about content type creation and it is related with field. Follow the steps to get a working example.

1. Create content type and related field in you site.
2. Enable features module and export this content type as a new module.
3. The system generated module, you can find the content type creation and field relateion code. You can find documentation for creating content type and field via code in drupal.

# Answer
> 0 votes
I eventually found a question which is more or less identical to this question. The accepted answer suggests that `node_types_rebuild()` gets invoked as the very first in `hook_install()`, and from there fields may be attached to defined node types.

---
Tags: entities, installation, nodes
---


# Question
Title: Omega theme not rendering correctly when css aggregation is disabled
I have tried clearing the drupal caches and manually deleting the aggregated files. Also tried clearing the browser cache.

Anyone seen this problem before?

# Answer
> 1 votes
Can be because it needs polyfills which are only loaded with aggregation turned on.

Try with a CSS3 standards compliant browser (ie. latest version of Chrome) which would not need the polyfills at all.

Omega 4 comes with these polyfills:

* Selectivizr.js
* CSS3 Media Queries JS
* Respond.js
* CSS3 PIE
* HTML5 shiv

---
Tags: css-js-aggregation
---


# Question
Title: can i register using same email id for a 3 different profile types
This project is related to add social service work details into my website. I used profile2 module to create a 3 profile types and its create successfully. we have 3 profile types, 1) Single User 2) Comapny 3) NGO

Can i register on above 3 profile types using same email Id because if single user is chairman of company and they wants to register as comany using same email id so it is possible. same like if single user is chairman of NGO and also they wants to register NGO using same email Id then it is possible or not.

How i can manage this situation.please help me

# Answer
You may need Shared Email module for this. It allows multiple email accounts with same email address.
> 0 votes

# Answer
A lot more depends on the scope of functionality and how will it grow, which can not be answered here I believe.

Profile 2 module separates user account from user profile i.e. account properties i.e. email password will be shared across all profile types.

Now different profile type create/edit/view permission can be handled by setting up user roles. So with your example it will go like User with chairman role(assuming we have chairman as drupal user role) can create/update/ profiles as company/single user/ngo.

Again there will not be separate registration process for building profiles.
> 0 votes

---
Tags: users
---


title: Disable the /blog route

text:
# Question
Title: Disable the /blog route
I'm using Drupal 6.16. I would like to permanently disable the /blog path (and all its sub-paths, but not the Blog module.

Is this possible?

# Answer
You can do this with `hook_menu_alter()` in a custom module or theme, for example using the following code.

```
function custom_module_menu_alter(&$items) {
  unset($items['blog']);
  unset($items['blog/%user_uid_optional']);
  unset($items['blog/%user/feed']);
  unset($items['blog/feed']);
  return $items;
}

```

Make sure to clear the cache.
> 8 votes

# Answer
The path redirect module will allow you to send users from 1 URL to another. https://drupal.org/project/path\_redirect

In your case: \- Download and install this module \- Visit the modules admin page \- Add a redirect from 'blog' to 'node/1' (as an example)

People attempting to go to '/blog' would then be redirected to your entered location

Not sure you can wildcard the URL, but you can add certain URLs as above. To stop content being created under 'blog/blog-a' you could setup an auto path alias for created blogs. \- visit /admin/build/path/pathauto \- Create an auto path for node of type blogs

Blogs will then be created with your chosen alias.

I hope this helps.
> 2 votes

# Answer
REDIRECT ACCORDING TO THE GEOLOCATON

```
  function geo_redirect_init() {
  $geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );

   if ($geoPlugin_array['geoplugin_countryCode'] != "GB" && (!isset($_SESSION['non_uk_redirect']) || $_SESSION['non_uk_redirect'] === false)) {
     $_SESSION['non_uk_redirect'] = true;
     drupal_goto("/blog");
   }
  }

```
> -1 votes

---
Tags: routes
---


# Question
Title: Exclude exposed filter for one content type in my view
I use leaflet map for displaying markers, like that :

My actual view - filter criteria :

```
- Content published
AND
- Content - Has taxonomy term AND
- Content - Has taxonomy term AND
AND
Content type = 1 OR
Content type = 2

```

But now, I want display vectors with a third content type. It works without filters (taxonomy), and add all taxonomy terms to my third content, it's an ugly solution.

Do you have a solution ?

edit : drupal doesn't understand this setup

# Answer
It looks like you want to make more distinct and/or groups. If using Drupal 7, here is a clear explanation of how to do it (see the accepted answer): How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6?

If using Drupal 6, the Views Or module can do the same thing.

If I understand your problem, the solution would be to put the first 2 Content Types in a group with the Taxonomy Term filters, then use a separate OR group for your 3rd Content Type.
> 0 votes

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


title: Dependency fields on add people page

text:
# Question
Title: Dependency fields on add people page
For a project I need to register new customers. That customer belongs to a store chain, and that store chain is connected with a store.

I only want to display the store's which are linked to the storechain on the add people page.

What is the best way to fix this? Conditional fields module doesn't work for this :(

Thanks in advance!

# Answer
> 0 votes
perhaps the Profile module create a profile per store and then show the right store profile fields on the registration page, if needed to work with your logic you could place specific stores on specific registration paths with Profile2 Registration Path.

**EDIT**

> What is the best way to fix this? ... big changes like this aren't possible ...

You asked a problem, I offered a solution. My opinion on the best way to fix your problem is to do some re-engineering of your site. If you disagree that's fine -- best of luck on finding a solution to your problem.

Modules such as views bulk operations, Rules, Node Convert are examples of modules which exist to make sweeping changes of a website feasible (although not without coordination on your behalf). What you say isn't possible -- I say is merely difficult.

---
Tags: entities
---


title: How could I do a FULL OUTER JOIN?

text:
# Question
Title: How could I do a FULL OUTER JOIN?
What code should I use to execute the following SQL query?

```
SELECT column_name(s)
  FROM table1
  FULL OUTER JOIN table2
  ON table1.column_name = table2.column_name;

```

# Answer
> 2 votes
Dynamically it would look like this:

```
$q = db_select('table1')
  ->fields('table1', array('column_name'));

$q->addJoin('FULL OUTER', 'table2', NULL, 'table1.column_name = table2.column_name');

```

Which will give you

```
SELECT table1.column_name AS column_name
FROM
{table1} table1
FULL OUTER JOIN {table2} table2 ON table1.column_name = table2.column_name

```

Or you can run any SQL string with `db_query()`:

```
$sql = <<<SQL
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
SQL;

$result = db_query($sql);

```

---
Tags: database
---


# Question
Title: How to compare a field value with each title values?
I need to compare two field values.

Let's say I have a content type named "Specimen". The content title is the accepted name of that specimen. A second field, named Synonyms, can be filled by users to suggest synonyms for the accepted name.

What I need is a field validation with that kind of test : If the synonym matches any title of that content type, then display a message (That synonym is actually an accepted name already entered in the database) and invalidate the value entered. Else, the synonym is valid and can be entered in the form.

I know Uniqueness which is a great module to compare titles between them but not between a CCK Field and each title (unless I missed something?)

I have tried to configure a test with the module Field validation but did not manage to get a nice result, even with the test "Match against a field". Maybe it was not set properly.

I guess that Rules can be my friend too but for now, I have always created very simple rules. So I would appreciate any help to build this test.

# Answer
Finally, I found a solution with the module Field Validation and a PHP Code validation rule associated to my field Synonyms:

```
$args=array(':type'=>'specimen');
$titles=db_query('SELECT title FROM {node} WHERE type = :type',$args)->fetchCol();
foreach ($titles AS $title){
if ($this->value==$title){$this->set_error();}
}

```

It works like a charm.
> 0 votes

---
Tags: forms, rules
---


# Question
Title: The drush command 'rets-import' could not be found
I believe I have all the pieces of the Drupal RETS Real Estate Framework installed in my drupal 7 site.

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

But when I run:

```
drush -u=admin -d rets-import

```

I get:

```
The drush command 'rets-import' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.

```

What step might I have missed in my install of this framework?

# Answer
> 3 votes
The file that integrates DRealty with Drush `drealty.drush.inc` is kind of in an odd place within a `drush` folder of the module.

http://cgit.drupalcode.org/drealty/tree/drush/drealty.drush.inc

Drush will scan the root level of a module folder or your `.drush` directory for drush include files but I dont think it will randomly scan deeply into module directories. I recommend moving this file into your `.drush` folder and clearing the cache, then trying from your site folder again. Eg,

* cp ./drealty/drush/drealty.drush.inc ~/.drush
* drush cc drush
* cd YOUR\_DRUPAL\_PROJECT/sites/all/modules
* drush -u=admin -d rets-import

---
Tags: drush
---


# Question
Title: views_row_selector module - capturing a form submission
I am using the views\_row\_selector module to add checkboxes to a table created in Views

The hook\_menu $item looks like this

```
$items['admin/structure/account'] = array(
    'title' => 'Accounts',
    'description' => 'Names and addresses',
    'page callback' => 'views_embed_view',
    'page arguments' => array('accounts_view'),
    'access arguments' => array('administer booking'),
);

```

Everything works perfectly, but how do I capture the form submission?

# Answer
> 0 votes
When using this module you need to write custom code to include a submit handler and use the results. See my inline Issue Queue links where the module maintainer describes this. This is code from a toy example i have sitting around:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // As per this issue responded to by the module author, we need to add our
  // own submit button and handler to make use of the data
  // selected in views row selector.
  //
  // https://www.drupal.org/node/1898842#comment-6984976
  if ($form_id === 'views_form_identity_search_page') {

    $search_had_results =
            count($form_state['build_info']['args'][0]->result) > 0;
    if ($search_had_results) {
      // some custom tasks I make up that could use the results as
      // arguments. Ideally these paths are Rules, Views or hook_menu stuff.
      $my_tasks = array(
        '/foo/bar' => 'report 1',
        '/foo/baz' => 'report 2',
        '/foo/bak' => 'report 3',
      );

      #$form['views_row_selector']['#required'] = TRUE;

      // Some magic to make horizontal form elements.
      // http://drupal.stackexchange.com/questions/7954/horizontal-form-elements
      $form['actions']['#attributes']['class'][] = 'container-inline';
      $form['actions']['my-task'] = array(
        '#type' => 'select',
        '#title' => t('Task to Perform'),
        '#options' => $my_tasks,
        '#weight' => -5,
        '#required' => TRUE,
      );

      $form['actions']['submit']['#value'] = t('Perform Action');
      $form['actions']['submit']['#submit'][] = 'ucsb_identity_selection_form_submit';
    } else {
      $form['actions']['#access'] = FALSE;
    }
  }
}

function MY_FORM_ID_form_submit($form, &$form_state) {
#  dpm($form_state, __FUNCTION__);
  $ids = array_filter($form_state['values']['views_row_selector']);
  // take the results, compact them as "1,2,3" for example and perhaps
  // redirect to a new Views page setup to use Contextual Filters
  // with arguments.
  $ids = @implode(',', $ids);
  $options = array('query' => array('identity_results' => $ids));
  drupal_goto('custom-user-diagnostics', $options);
}

```

good luck!

---
Tags: views, forms
---


# Question
Title: Updating from 7.34 to 7.35 after successfull update, drush status shows version 7.34?
Recently i tried to upgrade my site from 7.34 to 7.35 everything when successfully but when i go to status report or executing drush status command it shows that im still on drupal 7.34.

These are following screenshots: Result of drush up --security-only (same with drush up drupal)

And this screenshot shows drush status just after the update:

Any suggestions whats wrong?

Thanks in Advance Tee

# Answer
This is a file permissions issue. See:

Can't update drupal core to 7.27

Drush should give an error message here, instead of pretending to work.
> 0 votes

---
Tags: drush, updating, security
---


title: features issues not overriding

text:
# Question
Title: features issues not overriding
I have a feature that I copied from site A to site B. Site B is created using a profile install based on site A. Now I have to enabled a feature that I copied from A to B but whenever I enable this feature I always "overrides". I revert to the feature but it's always overriding. It's usually the field\_base portion that has overrides. I have more than one feature that does this. I dont want to recreate using DB settings. I want the feature settings. Any help would be appreciated. Thanks.

# Answer
> 0 votes
it was the actual features module itself. The latest version removed foreign keys which caused the overridden to be permanent.

---
Tags: features
---


# Question
Title: Drupal 7 get user by Profile2 field value
I have Profile2 field name uid\_intranet which is unique. And in one of my module, I want to get $user object by uid\_intranet. The API is kinda like:

```
$users = profile2_get_users('uid_intranet', 100)

```

But no such API. So any solutions?

Thanks!

UPDATE 01, my complete code:

```
// Helper
function _mymodule_get_profiles_by_profile2field($field_name, $field_value) {
  $table = "field_data_{$field_name}";
  $column = "{$field_name}_value";

  // Profile IDs
  $pids = db_select($table, 'ui')
    ->fields('ui', array('entity_id'))
    ->condition($column, $field_value, '=')
    ->execute()
    ->fetchAllKeyed(0,0);
  if (is_array($pids) && count($pids) > 0) {
    $profiles = profile2_load_multiple($pids);
  }
  return $profiles;
}

```

# Answer
> 2 votes
Why not adding your helper function to query the database, something like below

```
function mydmoulename_get_user_by_prfoile2field($field_value) {
    $user = new stdClass();
    $user_id = db_select('field_data_field_uid_intranet', 'ui')
        ->fields('ui', array('entity_id'))
        ->condition('field_uid_intranet_value', $field_value, '=')
        ->execute()
        ->fetchAllKeyed(0,0);
    if (is_array($user_id) && count($user_id) > 0) {
        $user = user_load_multiple($user_id);
    }
    return $user;
}

```

**NOTE:**

When you add a field to profile, a custom table is created in database,so check your database and get the table name, in above example I am using table name as "field\_data\_field\_uid\_intranet". When you browse the table you will find column where it wil be storing the field value against the user who added the fied, you need to check the column name which is holding the field value in above exampe I am using "field\_uid\_intranet\_value" as column name change it according to your requirement.

Once done, now you have your own function simply call it passing the field value as argument like

```
$user = mymodulename_get_user_by_prfoile2field(100);

```

you will get the complete user object as return value.

# Answer
> 0 votes
The above answer is quite wrong, the entity\_id is not the user id its the profile ID. You must join the above table with profile in order to get the user id.

for instance

```
$result = db_query('
SELECT p.uid FROM {field_data_field_fb_id} fb join {profile} p
on p.pid = fb.entity_id
WHERE fb.field_fb_id_value = :fb_id', array(':fb_id' => $user_fb_id));

$user_id = $result->fetchCol();

```

The entity\_id is just a reference to the profile table.

---
Tags: 7, users
---


# Question
Title: How to disallow commerce checkout if no payment method is available?
With Drupal Commerce and Commerce Payment, when no payment method is available on the checkout, it displays this message: `Payment is not required to complete your order.` and the customer is still able to finish the checkout.

It's probably trivial, but I can't find a solution that doesn't involve calling a hook in a custom module.

The best solution would to actually display a webform when no payment method is available.

# Answer
The core payment module offers this option in the checkout pane's settings form.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How can I apply different templates based on taxonomy hierarchy?
I'm new to Drupal and I don't have extensive knowledge so I'm hoping I can get this question answered. I want the taxonomy pages of lower hierarchy to be displayed differently from the higher by applying a different tmeplate. Is there a way in Drupal 8 to do this other than giving each term its own template?

# Answer
> 0 votes
What template exactly? taxonomy-term.html.twig, I guess?

You're looking for template suggestions. See Working with template suggestions on Drupal 8 for a similar question.

You can implement `hook_template_suggestions_TEMPLATE()` and then provide alternative file names for whatever condition you can think of.

# Answer
> 0 votes
Thanks to @Berdir 's answer I was able to come up with this hook, which does it for me.

```
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
   $weight = \Drupal::entityManager()->getStorage('taxonomy_term')->load($tid)->getWeight();
   if ($weight == 0) {
      $suggestions[] = 'page--taxonomy--term--product';
   }
}

```

The only downside is that the whole term entity has to be loaded just to get the weight. As this entity is rendered later its possible, that its persistent at the time the hook function is triggered. But due to my lag of drupal knowledge i don't know where it might be.

---
Tags: taxonomy-terms, theming, 8
---


# Question
Title: How do I display taxonomy content from taxonomy category?
I have fields in taxonomy under category taxonomy. Attempted views but couldn't find taxonomy fields to add as fields :(

Do not want node fields.

What I did is: 1. Create taxonomy, category 2. Add terms, dog, cat, etc 3. Add fields such as image, description, etc

So on view, all terms under category taxonomies appear in a view with description, images and more.

How do I display all taxonomy terms' content under category?

**Updated**

Vocabulary: Categories Taxonomy: Body Contouring for example. Inside, it has the description and image.

So wanted to list taxonomies with their details in grid layout. Attempted views, but it is only all content type related to taxonomies' id.

I only need content from taxonomies. How do I display taxonomies' content?

# Answer
> 2 votes
Not sure of your full requirements as it is a bit confusing but it sounds like you are trying to output all the fields of a specific Taxonomy.

If you are using Drupal 7, just create a view of 'Show' Taxonomy Terms.

Then from there add the taxonomy fields that you require by searching from the 'add field' dropdown.

Finally create a filter for taxonomy term 'category'.

Hopefully that is what you are after.

Do you not see this filter when creating your view. What version of Drupal are you using?

# Answer
> 0 votes
Option 1: In views, you first set up a relationship to your taxonomy (under advanced). You can then use fields and filters from related taxonomy. Here's how:

1. Create a view of your content.
2. Under Advanced-\>Relationship, click Add, then choose the taxonomy field (Content:field-name)

3. Under fields, find "Taxonomy Term:" items. Here you can add individual fields with a relationship to your term.

Option 2: install display suite module, define a custom view mode and use this view mode in views. Here's how:

1. Install Display Suite.
2. Create a custom view mode for a taxonomy and set it up as you want it to appear:

3. Repeat for the node, but this time use the new view mode to render the taxonomy in the node.

4. Set up a view, but this time instead of fields, choose to output full content and select the correct view mode.

Now if you ever choose to change how your taxonomy or your node are displayed, the view will automatically adapt to the changes. You may not see it with one view, but trust me, when you have dozens of views and thousands of products, those view modes are life-savers, so you may as well do it right from the start.

---
Tags: theming
---


title: Redirect to page before login

text:
# Question
Title: Redirect to page before login
Now i know there are some ways that a redirect on login can be setup, ie using views etc, but i think my issue maybe a bit more complicated.

When a user accesses a node for example where they are prompted to login, from here they are directed over to the /user/login page.

I want the user to be redirected back to the page they were before they came to the /user/login page, with a few exceptions of course.

How can i get the user journey to be...Node -\> user/login -\> redirect back to Node?

# Answer
> 1 votes
One of the ways to do this (if you are able to build the links manually) is to add the destination parameter to the URL.

/user/login?destination=node/xxxx

After login, you will automatically be redirected to node/xxxx.

# Answer
> 1 votes
There is a module that takes care of this called Login Destination.

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

Also available for Drupal 8

# Answer
> 1 votes
Here's another way with Rules:

Event - Drupal initialize

Condition - site current user does not have a role authenticated Condition - site current page url does not contain 'user/'

Action - Site-redirect to user/login, append original destination.

Not the most efficient of ways, but no coding is required.

---
Tags: rules, sessions
---


# Question
Title: How can I load a block's subject and body, programmatically, for use in a module?
I need to create an array in my custom module that contains data from multiple blocks. something like this:

```
array(
  'block_1' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),

  'custom_module_block' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),

  'another_block_machinename' => array(
    'subject'=>'Block Subject Here',
    'body'=>'Full block body html here',
  ),
);

```

In order to do this, i need to be able to programmatically load block content, being able to access and handle each block's subject and body in order to populate my array.

Imagine the node equivalent being a simple node\_load(); where you can easily access $node-\>title and $node-\>body from within the loaded node.

I'm not able to find any functions that make loading this block data possible. Neither block\_load() nor module\_invoke() get me all the data I need (specifically the block subject).

So, how do I load a block's subject and body programmatically so I can use it in my custom module?

# Answer
Contrary to a statement in my initial question, module\_invoke() **DOES** return the subject of the block...but ONLY if there's block content *($block\['content'\])*! This means if you're trying to load a block with empty content *(for example a Views block without results)*, the block subject returned from module\_invoke will always be empty.

So, as long as the block has content, this will return both block subject and block content (turn this into a loop to load multiple blocks);

```
$block_array = array();
$loaded_block = module_invoke('module_name', 'block_view', 'block_delta');
$block_array[]['title'] = $loaded_block['subject'];
$block_array[]['content'] = $loaded_block['content']['#markup'];

```
> 0 votes

# Answer
```
/**
 * Implements hook_block_view().
 */
function hook_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'block_1':

      $block['subject'] = NULL;
      $block['content'] = 'Full block body html here';
      break;

    case 'block_2':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

    case 'block_3':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

  }
  return $block;
}

```

Based on https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_view/7
> 0 votes

# Answer
Use following code to get list:

```
$result = db_select('block', 'b')
            ->fields('b')
            ->execute()
            ->fetchAll();
$arr = array();
    foreach ($result as $key => $row){
        $block = module_invoke($row->module, 'block_view', $row->delta);
        $arr[$key]['content'] = render($block['content']);
        $arr[$key]['subject'] = $block['subject'];
    }

```
> 0 votes

# Answer
Given the assumption that you know what blocks you want to load, and you just want the arrays back that would be displayed (for your own purposes, as you said,) I think you can just "view" the blocks to create the array.

```
$blocks = array();
$blocks[] = block_block_view(1);
$blocks[] = views_block_view('viewname-blockname');
$blocks[] = custom_module_block_view('delta');
return $blocks;

```

Wouldn't that work?

**Edited to add:**

This returns an array like this:

```
Array
(
    [0] => Array
        (
            [subject] => Simple Block Title
            [content] => <p>This is block(1).</p>
        )
    [1] => Array
        (
            [subject] => View title
            [content] => <div class="view">All the view content, probably as markup.</div>
        )
    [2] => Array
        (
            [subject] => Title of my custom block
            [content] => Array
                (
                    [#theme] => item_list
                    [#items] => Array
                        (
                            [0] => My custom block returns a render array
                            [1] => Markup is for theme layer
                            [2] => This is a silly example
                        )
                )
        )
)

```

Of course, you can specify array keys when you add $blocks\[\] items if you need more than just numeric. Either way, as you can see, this returns the subject and content separately, not all mixed together.
> 0 votes

---
Tags: blocks
---


title: Remove "Submitted by" on search results

text:
# Question
Title: Remove "Submitted by" on search results
How can I modify the search results on drupal 7 so that the submitted by author and date doesn't appear?

# Answer
I installed the "Custom search " module and it was the easiest way. https://www.drupal.org/project/custom\_search
> 2 votes

# Answer
Try below code in your template.php

```
<?php
  function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
  }
?>

```

Or create a template file for search results if not there named "search-result.tpl.php" and add this

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
 <h3 class="title"<?php print $title_attributes; ?>>
   <a href="<?php print $url; ?>"><?php print $title; ?></a>
 </h3>
 <?php print render($title_suffix); ?>
   <div class="search-snippet-info">
  <?php if ($snippet): ?>
    <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
<?php endif; ?>
<?php if ($info): ?>
  <p class="search-info"><?php print $info; ?></p>
<?php endif; ?>
</div>
</li>

```

and To remove the author, date and comments count remove or comment out the following lines:

```
<?php if ($info): ?>
  <p class="search-info"><?php print $info; ?></p>
<?php endif; ?>

```

and in css

```
.search-info {
display: none;
}

```

Taken answer from this link
> 3 votes

# Answer
You can also completely remove those items instead of just setting display to none, template\_preprocess\_search\_result function processes variables for search-result.tpl.php . So by modifying the `template_preprocess_search_result` you can limit the varibles sent to `search-result.tpl.php`. It is the function, use the modified version in `template.php`

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

    $result = $variables['result'];
    $variables['url'] = check_url($result['link']);
    $variables['title'] = check_plain($result['title']);
    if (isset($result['language']) && $result['language'] != $language->language && $result['language'] != LANGUAGE_NONE) {
        $variables['title_attributes_array']['xml:lang'] = $result['language'];
        $variables['content_attributes_array']['xml:lang'] = $result['language'];
    }

    $info = array();
    if (!empty($result['module'])) {
        $info['module'] = check_plain($result['module']);
    }

    if (!empty($result['user'])) {
        $info['user'] = $result['user'];
    }
    if (!empty($result['date'])) {
        $info['date'] = format_date($result['date'], 'short');
    }

    if (isset($result['extra']) && is_array($result['extra'])) {
        $info = array_merge($info, $result['extra']);
    }
    // Check for existence. User search does not include snippets.
    $variables['snippet'] = isset($result['snippet']) ? $result['snippet'] : '';
    // Provide separated and grouped meta information..
    $variables['info_split'] = $info;
    $variables['info'] = implode(' - ', $info);
    $variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'];
}

```

by removing the `if (!empty($result['user'])) {` and `if (!empty($result['date'])) {` lines the user and date will be removed.
> 2 votes

# Answer
You can theme it, change code as you wish, place following code in template.php in your theme root folder.

```
function YOURTHEME_preprocess_node(&$vars) {

```

$vars\['submitted'\] = t('Author: !username, created: !datetime', array('!username' =\> $vars\['name'\], '!datetime' =\> format\_date($vars\['node'\]-\>created, 'custom', 'M d, Y'))); }
> 0 votes

---
Tags: 7, search
---


title: db_query variable substitution

text:
# Question
Title: db_query variable substitution
I'm trying to substitute a variable in a db\_query but keep on getting this error:

```
Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, string given

```

It's a single item string that I'm trying to insert:

```
$primary_key = db_query("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'mydatabase') AND (`TABLE_NAME` = '%s') AND (`COLUMN_KEY` = 'PRI')",$mytable)->fetchAll(PDO::FETCH_ASSOC);

```

I've tried wrapping the variable in an array but then I get no results. **How do I substitute my variable here?**

# Answer
Drupal 7 doesn't use the '%' place holders. Try this:

```
$primary_key = db_query("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'mydatabase') AND (`TABLE_NAME` = :tbl_name) AND (`COLUMN_KEY` = 'PRI')", array(':tbl_name' => $mytable));

```
> 1 votes

---
Tags: database
---


title: Form is still trying to do validation

text:
# Question
Title: Form is still trying to do validation
I have heavily modified an Ubercart form.

I have tried to remove the initial validation placed on this because I'm using a whole host of different fields.

For some reason, however, the validation is still getting executed.

Why would this be the case? Am I removing all sources of validation correctly?

```
  array_unshift($form['#submit'], 'client_mod_uc_cart_checkout_handler');
  $form['#validate'][] = 'client_mod_uc_cart_checkout_validate';

```

I have also tried setting $form\['#validate'\] to array();

However, upon submission, I get:

```
First name field is required.
Last name field is required.
Street address field is required.
City field is required.
Postal code field is required.
First name field is required.
Last name field is required.
Street address field is required.
City field is required.
Postal code field is required.

```

Why would this be the case?

# Answer
```
$form['#validate'][] = 'client_mod_uc_cart_checkout_validate';

```

Will only append your function to the list of functions in the validation array.

I'm fairly certain using `= array()` won't work because that's how you define an array, not how you empty one.

Modified answer from Stack Overflow:

> Use unset, if you need the array later on just instantiate it again.
>
> ```
> unset($form['#validate']);
> $form['#validate'] = array();
>
> ```
> 1 votes

---
Tags: 7, forms
---


title: how to make big menu in drupal 7

text:
# Question
Title: how to make big menu in drupal 7
How to make the menu like this in drupal 7. There are many customer module in drupal.org, but I don't know much about which module will suit with this. I would to drop down product category when user puts cursor on product menu item.

Thanks

# Answer
> 1 votes
You can do this by using any of below modules :

1. Megamenu

> Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs.

2. Bigmenu

> THIS MODULE attempts to replace the all-in-one global tree view with a similar interface, but sub-trees are "collapsed" below a certain level, and can be expanded as needed.

3. TB Mega Menu

> TB Mega Menu allows you to create a mega menu with an innovative back-end user interface and synchronized with Drupal core menu.

4. OM Maximenu

> That is now possible by using OM Maximenu which can create menus with all other module blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.

5. Superfish

> Superfish integrates jQuery Superfish plugin with your Drupal menus.

6. Menu Views

> Allows menu items to render views instead of links. This is useful for creating "mega-menus".

7. MuchoMenu

> This module allows users to create mega menus that have mini panels as their flyout content. The benefit is that ANY type of content or UI can be added to the menu flyouts.

# Answer
> 0 votes
You may want to look at Maximenu . This allows you to build complex menus and also allows you to use blocks as menu items.

However you might need to some research if the menu is expected to be fully responsive.

---
Tags: routes, navigation
---


# Question
Title: Not saving data after upgrading from 7.26 to 7.35
I recently update my Drupal site and is working fine on my local machine ie: localhost. After uploading the site to the hosting it is not saving the form/data. I'm not even able login to system on first attempt, it is not showing any error as well.

1 - I make sure that .htaccess files is moved to the server.

2 - I clear Drupal and browser cache several times.

3 - No javascript/jquery error on console.

4 - Check on different browsers.

I'm lost what else can be doing problem, Please guide me to the right path.

PHP info = http://worldstogethertravel.com/info.php

TIA :)

# Answer
> 1 votes
This worked for me:

1. Apply the patch from here: https://www.drupal.org/node/1313912

cd sites/all/modules/contrib/taxonomy\_access

wget https://www.drupal.org/files/1313912-5.patch

cat 1313912-5.patch | patch -p1
2. go here and rebuild permissions. /admin/reports/status/rebuild
3. Clear the cache

---
Tags: 7
---


# Question
Title: combining messages and content types in views
I am using the Message module to tell people when nodes are created, deleted or edited. Is there a way to combine the messages module with my nodes in views.

What I want to do is show a message of a node being deleted or edited, and then show some fields of this node. I tried using tokens inside the message module, but that does not seem to do the trick.

# Answer
> 0 votes
Workaround:

Use Drupal hooks on create/edit/delete of node, then create a custom message type that just takes text field (no entity reference).

Then in your hooks create the new message type and add for its field value the message text constructed from the node fields. Embed links to node if node is still available.

```
$message = message_create('general_alert');
$wrapper = entity_metadata_wrapper('message', $message); // populate with node data

// Set necessary fields to use with tokens.
$wrapper->field_message_text->set(array('value' => $text));
$message->save();

```

Or even better, include both an entity reference field for your message and a text field. Add the entity reference when creating/updating the node, and populate the text field when deleting the node.

---
Tags: views, nodes, message-subscribe
---


# Question
Title: Using Drupal Commerce, how do you render the "add to cart" button?
I have created a custom node.tpl.php file for the product\_display content type. I have everything worked out except I have no ideal how to isolate the "add to cart" button, actually the "add to cart" form, and render it within the template wherever I need it.

# Answer
> 3 votes
The product reference itself renders as the button. In your product display content type, make sure the product reference has the "Add to Cart form" format, then render it thus:

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

```

# Answer
> 1 votes
For future reference, you can add the "Add to Cart" button to your D7 taxonomy or front page view by visiting Structure -\> Content Types -\> \[Product Type\] / Manage Display -\> Teaser.

# Answer
> 1 votes
To add the "Add to cart" button, go to the manage display of the product reference field and set "Add to Cart form" in Format column.

---
Tags: 7, forms, theming, commerce
---


title: add site language to XML

text:
# Question
Title: add site language to XML
i'm trying to get a extra element in our XML that show the site langues where te customer is working in. However i can not get is to work....

Here is the code:

```
if ($submission->nid == 315) {
$destination['path'] = 'private://export/account/';
$destination['filename'] = 'request_password_' . $submission->sid . '.xml';
$wrapper = 'request_password';

// when content is supplied, generate XML file
if (isset($destination['path'], $destination['filename'], $wrapper)) {
$source = array();
$source['data'] = $submission->data;
$source['node'] = $node->webform['components'];

$xml = new XmlWebformGenerate();
$xml->setXmlHeader('1.0', 'utf-8');
$xml->setXmlWrapper($wrapper);
$xml->source = (new XmlSource($source))->getSource();

```

What this does is; create a XML from a webform. When the user submit the webform then it will create a XML file with te field of the webform. However what i would like to add is a tag that displays the language the user is viewing. however i cannot find a way to insert it to the XML, because it's already receiving the source from the node.

Could some one help me out with this? Many thanks! :)

# Answer
You can get the current language through the global $language var:

```
$current_lang_code = $GLOBALS['language']->language;

```

With that in mind you just need to make whatever changes are necessary to your PHP classes (`XmlWebformGenerate/XmlSource/etc`), to add that data to the document.
> 0 votes

---
Tags: webforms, i18n-l10n
---


title: Want to rename contact form fields name

text:
# Question
Title: Want to rename contact form fields name
I am using drupal 7 contact form in my site and I want to rename some field names, like "Subject" to "Emne" etc..

# Answer
> 0 votes
Use `hook_form_FORM_ID_alter()` as shown below:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULENAME_form_contact_site_form_alter(&$form, &$form_state) {
    $form['subject']['#title'] = t('New Title');
}

```

## Update #1

For Page Title use `drupal_set_title()` as shown below:

```
drupal_set_title('kontakt'); // Add this line in above function MODULENAME_form_contact_site_form_alter

```

---
Tags: 7, emails
---


title: Drupal and apache rewrites

text:
# Question
Title: Drupal and apache rewrites
I'm just migrating a site that has a proxy pass in the vhost config like the following.

```
ProxyPass /n/ http://xxx.xxx.xxx.xx:80/n/
ProxyPassReverse /n/ http://xxx.xxx.xxx.xx:80/n/

```

I need to replicate that in the drupal .htaccess file as I don't have direct access to the hosting as we're using a fully managed drupal solution. I have tried the following but it does not work, when I navigate to the drupal site /n I just get a 404.

```
RewriteRule /n/?$ http://xxx.xxx.xxx.xx:80/n/ [P]

```

# Answer
Be aware that \[P\] requires mod\_proxy to be enabled:

```
RewriteEngine on
RewriteRule /n/(.*)$ http://xxx.xxx.xxx.xx:80/n/$1 [P]

```
> 0 votes

---
Tags: .htaccess, proxies
---


# Question
Title: How to set the first option as the selected in the SELECT form via hook_form_alter
I have created a Views with an exposed filter and I tried to use hook\_form\_alter to convert it to a select list. Now, I need to set the default value as the first option whatever output in the select list. I DONT'T need to have '-Any-' as the default value which usually do. I wonder how can I achieve this. The page keep showing the below message when first visit the page not until one of the option is selected and applied.

> An illegal choice has been detected. Please contact the site administrator.

Here the code in my template.php. Hope you can help me out. Thanks!

```
if($form_id == 'views_exposed_form' && $form['#id']=='views-exposed-form-news-page') {

     //Query
     $query = db_select('node', 'n');
     $query->fields('n', array('title'));
     $query->condition('n.type', 'news');
     $query->orderby('n.title', 'ASC');
     $result = $query->execute();

     // Get Select options
     $options = array();

     foreach( $result as $node ){
       $options[$node->title] = $node->title;
     }

    // Alter the form
        $form['title_1'] = array(
         '#type' => 'select',
         //'#default_value' => ??
         '#options' => $options,
         '#title' => t('Filter By'),
    );
 }

```

# Answer
You need to add the following code to your implementation of hook\_form\_alter():

```
if (empty($form_state['input']['title_1'])) {
  // set the first element as default value
  $form_state['input']['title_1'] = reset($options);
}

```
> 2 votes

---
Tags: forms
---


title: How to implement a custom hook

text:
# Question
Title: How to implement a custom hook
I have implemented a custom login module and I want to keep it on general purpose state.

This module have been developed because users can be authenticate against an internal LDAP Server (Sun Microsystems' LDAP directory server). So in this module I want to keep only the authentication and retrieve data from the LDAP directory. That's fine, I have it, within the PHP API (LDAPc) we have available.

There are situations where the link to log into the application comes with extra querystring parameters, and I have the thought to add a hook to my custom login module, so from other module I can implement that custom hook, retrieve these querystring and do whatever we need to do... add them in an extra table linked with the user table, for example.

I could do this inside the custom login module, but if so, my module will not be valid for other drupal sites with other needs.

My first thought, following this post: http://tylerfrankenstein.com/code/drupal-create-custom-hook-for-other-modules

has been to add the lines:

```
    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

```

to my current development state

```
/**
 * Implements hook_menu().
 */
function psaldaplogin_menu()
{
    $items = array();
    // Login Page to authenticate against PSA Ldap directory
    $items['user/psaldaplogin'] = array(
            // Every user can access to this page
            'access callback' => TRUE,
            // Define the function where implement the generation of the page
            'page callback' => '_psaldaplogin_view',
    );
    return $items;
}

/**
 * Authentication procedure
 *
 * TODO:
 *     Allow other modules implement this process as a hook,
 *     so more complex process on login step
 *     could be implemented outside this module
 *
 */
function _psaldaplogin_view()
{
    // Clear messages queue
    drupal_get_messages();

    // Check if the user is already logged
    if (user_is_logged_in()) {
        drupal_goto('home');
    }

    // Allow other modules process the querystring parameters
    // --> DOESN'T WORK
    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

    // Authorized the user
    if ($username = _getAuthorizedUser()) {
        // Get the user information from PSA Ldap directory
        $userData = _getLdapUserInformation($username);
        // Register the user into Drupal
        if (_registerExternalUser($userData)) {
            // Redirecto to home
            drupal_goto('home');
        } else {
            // If the registration failed show access denied message
            drupal_access_denied();
        }
    } else {
        // If the authentication failed show access denied message
        drupal_access_denied();
    }
}

```

Figuring out I will be able from other module implement something like:

```
function slider_retrieve_login_extra_params($params)
{
    // check $params since they are unsafe data

    // test if the querystring params could be retrieve here
    file_put_contents('/tmp/genius/genius.log',
        "\n" . print_r($params, true) . "\n",
        FILE_APPEND);
}

```

But this chunk of code is never executed, so it is clear I have a miss understanding on how to allow other modules to implement a custom hook.

I'll appreciate if someone could point me to the right direction to achieve this solution. Otherwise I will have the module as template since for each development the login needs could be different.

Thanks for the reading.

Regards.

# Answer
Putting aside the general design of your application, you are right to use `drupal_alter` to provide a hook.

However, you are missing the correct hook implementation function name.

It should be:

```
drupal_alter('retrieve_login_extra_params', $params);
// ...
function MODULE_retrieve_login_extra_params_alter(&$params){
// ...
}

```

You may also be interested in:

1. LDAP Integration
2. `user_external_login_register`
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Why the ETAG always change of my D7 site
ETAG should not change if the page not changed.

But when I refresh the web page after login, the ETAG always change.

# Answer
> 0 votes
In my setup, if I am logged into the CMS, then the Etag seems to be written as a unix timestamp, which is clearly being done to force caching off. So this may be the reason you see the Etag constantly changing.

However, even when not logged in, in my case the Etag seems to change when the associated page cache expires, even if the content in the resource doesn't change at all. I don't know why this is happening.

---
Tags: 7
---


# Question
Title: How to target specific sites with Drush when using Multisites?
I have a Drupal Multisite set up. It contains two sites, but the core Drupal install has no site.

With Drush, I can use @sites to target all sites. For example:

* `drush @sites -y cc all` \- Updates all multi-sites
* `drush @sites -y en jqmulti` \- Install Jquery in all Multi-Sites

However, because I have no site installed in the core folder, I always get an error message stating that the core site is missing. Is there any to use Drush to only update the sub-multisites and skip the core one?

I know I can run Drush from the sites directory of the sub-sites, but that isn't very convenient when I want to target all sites.

The reason I am using Multisites is because both sites share themes and user-logins.

# Answer
When you say "core site", do you mean the site in `sites/default`? Is it an option to just delete the settings.php file at `sites/default/settings.php`?

If you'd like to manage your aliases in an alias file, create a file `~/.drush/mysite.aliases.drushrc.php`:

```
$root = '/path/to/root';

$aliases['site1'] = array(
  'root' => $root,
  'uri' => 'site1.com',
);

$aliases['site2'] = array(
  'root' => $root,
  'uri' => 'site2.com',
);

```

See this link for an example.

Then, to refer to one site:

`drush @site1 status`

* or -

`drush @mysite.site1 status`

To refer to all sites:

`drush @mysite status`

Maybe you want to get more fancy than this, though. If you have more aliases in your alias file (e.g. for 'dev' and 'live' sites, you can make your own lists:

```
$aliases['dev'] = array(
  'site-list' => array('site1', 'site2'),
);

```

Then:

`drush @mysite.dev status`

If you want, you may also store your alias file in `/path/to/root/drush` or `/path/to/root/sites/all/drush`, but if you do this, Drush won't be able to find your alias file unless you specify --root on the commandline, or change your working directory to be somewhere inside of `/path/to/root`.
> 8 votes

# Answer
You need to setup a new Drush alias file for running the command on the remote site. Typically you name the file as `<project_name>.drushrc.php`.
You then need to place this file in the `.drush` directory in the home directory of your logged in user.

See this link for a sample Drush alias file.

After setting up the file, do a `drush cc drush` to clear the Drush cache and let it allow picking up the new alias files (Note: This might not be required on some environments)

**UPDATE:** If you are hosting your remote site on Acquia or Pantheon, you get to download the alias file directly.

To download the alias file for

1. Acquia, go to `https://accounts.acquia.com/account/<login_id>/security?site=insight` and you download the alias from the link:
2. For Pantheon go to `https://dashboard.pantheon.io/users/<user_id>#sites/list` and download the alias file
> 1 votes

---
Tags: 7, drush, multi-sites
---


# Question
Title: Drush doesn't download module version specified as dependency
My module has a dependency to specific version of Media module *(7.x-2.0-alpha4)* and I have specified that in my *info* file as documented in Writing module .info files (Drupal 7.x) documentation, just like this:

```
name = mymodule
description = MyModule description.
package = Media

dependencies[] = file_entity
dependencies[] = media (7.x-2.0-alpha4)
dependencies[] = media_internet
dependencies[] = views

```

When I try to enable my module with it's dependencies `drush en -y mymodule`, Drush downloads current stable version of `media` module *(7.x-1.5)* instead of the specified one and then enabling my module fails because of unmet dependency. I'm doing this on plain Drupal installation v7.34, DevDesktop stack v 2 RC build Mar 18 2015, Drush v7.0.0-alpha9 (from DevDesktop).

I have also tried to specify the version as `(2.0-alpha4)` and `(2.x)` \- without success.

What am I doing wrong? Thanks for any hints!

# Answer
> 3 votes
The Drush download code actually pre-dates this feature; as you have observed, it is not supported.

I have posted a feature request in the Drush issue queue, here:

https://github.com/drush-ops/drush/issues/1285

# Answer
> 1 votes
As @greg\_1\_anderson says, this feature is not supported yet, so such a dependency has to be downloaded and enabled in two steps

```
drush dl media-7.x-2.0-alpha4
....
drush en mymodule

```

Just running `drush en -y mymodule` will fail on unmet dependency.

---
Tags: 7, drush
---


# Question
Title: Can I add to an existing Entity schema from my own custom module
I'm extending a the Quiz module; by having taking extra data regarding the test . For this I have a custom module that redirects using a custom form .

It all works fine but as its only a single value I'd like to just add it to the existing 'Quiz result' entity. I know how to do this by hacking the 'contrib' module OPEN 'quiz.install' and adding it to the $schema\['quiz\_node\_results'\] array.

Once its added here I can then see it in Views as needed. But obviously this solution isn't good enough. Is there a way to add to an existing Entity schema from my own custom module; rather making a separate table in SQL for this info.

I've tried hook\_schema\_alter as well, but can't seem to get that to work either.

Here's what I had in my my\_module.install file

```
 function my_module_schema_alter() {
  $schema = array();
  // Create the quiz node results table
  $schema['quiz_node_results']['fields']['time_taken'] = array(
    'type' => 'int',
    'size' => '10',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Stores the user inputted estimated time.',
  );
}

function my_module_install() {
  $ret = array();
  $schema['quiz_node_results'] = array();
  rcni_saq_extended_schema_alter($schema);
   foreach ($schema['quiz_node_results']['fields'] as $name => $spec) {
    db_add_field($ret, 'quiz_node_results', $name, $spec);
  }
}

```

Many thanks for any help.

# Answer
your my\_module\_schema\_alter is missing a schema parameter.

fixed:

```
function my_module_schema_alter(&$schema) {
  $schema = array();
  // Create the quiz node results table
  $schema['quiz_node_results']['fields']['time_taken'] = array(
    'type' => 'int',
    'size' => '10',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Stores the user inputted estimated time.',
  );
}

```
> 1 votes

# Answer
Additional to the above answer the main thing to remember when testing the code you're writing here is that your module doesn't just have to disabled but 'uninstalled' EVERY time you run your code. I emphasise the 'everytime' as I was running breakpoints in my code\>

In the following example I'd made a Hello World module that has a schema for a 'hello world' table and this code extends that in a .install file

```
/**
 * Implements hook_install().
 */
function hello_worlds_install() {
  $schema['helloworld'] = array();
  hello_worlds_schema_alter($schema);
    foreach($schema['helloworld']['fields'] as $field => $spec) {
     if (db_field_exists('helloworld', $field)) {
      watchdog('system', 'Module install: Attempt to recreate field: "%field",   when it already exists.', array('%field' => $field), WATCHDOG_WARNING);
    }
    else {
      db_add_field('helloworld', $field, $spec);
    }
  }
}

/**
 * Implements hook_uninstall().
 */
function hello_worlds_uninstall() {
  $schema['helloworld'] = array();
  hello_worlds_schema_alter($schema);
  foreach($schema['helloworld']['fields'] as $field => $specs) {
    db_drop_field('helloworld', $field);
  }
}

/**
 * Implements hook_schema_alter().
 *
 * Other modules, such as i18n_helloworld also modify the helloworld database table.
 */
function hello_worlds_schema_alter(&$schema) {
  if (isset($schema['helloworld'])) {
    $schema['helloworld']['fields']['notes'] = array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => 'none',
      'description' => 'String containing the notes',
     );
    $schema['helloworld']['fields']['background_image'] = array(
       'type' => 'varchar',
       'length' => 255,
       'not null' => TRUE,
       'default' => 'none',
       'description' => 'String containing the background image name for the helloworld',
    );

    return $schema;
  }
 }

```
> 0 votes

---
Tags: entities
---


title: Array and Select Options

text:
# Question
Title: Array and Select Options
I have the following code working together with a script that populates fields on autocomplete.

What I would like to do is instead of having an autocomplete text box - use the city field in a drop down / select option field so instead of the user typing the city they select from the drop down.

```

$cities = array(
    array('city'=>'New York', state=>'NY', zip=>'10001'),
    array('city'=>'Los Angeles', state=>'CA', zip=>'90001'),
    array('city'=>'Chicago', state=>'IL', zip=>'60601'),
    array('city'=>'Houston', state=>'TX', zip=>'77001'),
    array('city'=>'Phoenix', state=>'AZ', zip=>'85001'),
    array('city'=>'Philadelphia', state=>'PA', zip=>'19019'),
    array('city'=>'San Antonio', state=>'TX', zip=>'78201'),
    array('city'=>'Dallas', state=>'TX', zip=>'75201'),
    array('city'=>'San Diego', state=>'CA', zip=>'92101'),
    array('city'=>'San Jose', state=>'CA', zip=>'95101'),
    array('city'=>'Detroit', state=>'MI', zip=>'48201'),
    array('city'=>'San Francisco', state=>'CA', zip=>'94101'),
    array('city'=>'Jacksonville', state=>'FL', zip=>'32099'),
    array('city'=>'Indianapolis', state=>'IN', zip=>'46201'),
    array('city'=>'Austin', state=>'TX', zip=>'73301'),
    array('city'=>'Columbus', state=>'OH', zip=>'43085'),
    array('city'=>'Fort Worth', state=>'TX', zip=>'76101'),
    array('city'=>'Charlotte', state=>'NC', zip=>'28201'),
    array('city'=>'Memphis', state=>'TN', zip=>'37501'),
    array('city'=>'Baltimore', state=>'MD', zip=>'21201'),
);

// Cleaning up the term
$term = trim(strip_tags($_GET['term']));

// Rudimentary search
$matches = array();
foreach($cities as $city){
    if(stripos($city['city'], $term) !== false){
        // Add the necessary "value" and "label" fields and append to result set
        $city['value'] = $city['city'];
        $city['label'] = "{$city['city']}, {$city['state']} {$city['zip']}";
        $matches[] = $city;
    }
}

// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);

```

And the following is my script:

```

  Drupal.behaviors.mywebform = {
attach: function (context, settings) {
    var ac_config = {
        source: "/devtest/sites/democities.php",
        select: function(event, ui){
            $("#edit-submitted-info-city").val(ui.item.city);
            $("#edit-submitted-info-state").val(ui.item.state);
            $("#edit-submitted-info-zip").val(ui.item.zip);
        },
        minLength:1
    };
    $("#edit-submitted-info-city").autocomplete(ac_config);
  }};

```

Any suggestions?

# Answer
> 0 votes
probably not really drupal realated. But here you go:

```
Drupal.behaviors.mywebform = {
  attach: function (context, settings) {
    $.ajax({
        url:'/devtest/sites/democities.php',
        type:'POST',
        dataType: 'json',
        success: function( json ) {
            // if #edit-submitted-info-city is not a select you will have to make it one, or take the select that is in, or create one select in it.
            $('#edit-submitted-info-city').append('<select>').attr('id', 'stackexchangeExample');

            $.each(json, function(i, value) {
                $('#stackexchangeExample').append($('<option>').text(value.city).attr('value', value.city));
            });
        }
    });
}};

```

you might want to make sure that you run this only once, adjust the creation of the select element accordingly. or add a once() implementation

---
Tags: javascript
---


# Question
Title: Install a custom empty module break my custom style
On Drupal 8, I have a style and a **empty** module :

/modules/kyna/nature/

/modules/kyna/nature/nature.info.yml

```
name: 'Nature Theme Structure and configuration'
type: module
description: 'Example Module description'
package: Kyna
version: VERSION
core: 8.x

```

When my module is installed and the cache clear, my custom theme is broken:

Why my custom and empty module break my custom theme please ? Without the addon all is OK:

Thanks.

# Answer
> 4 votes
Is your custom theme called nature?

That's not allowed, you can't have modules and themes with the same name.

---
Tags: 8
---


title: How to make a slideshow of Views?

text:
# Question
Title: How to make a slideshow of Views?
i want to make a slideshow block of two views.

view 1 is 'most popular blog posts', showing 10 titles with date and no. of times viewed. view 2 is 'most commented blog posts', showing 10 titles with date and no. of comments.

I'll put the slideshow block on the front page, it will show view 1 first then after 5 seconds, it will show view 2.

How?

# Answer
By using the Views slideshow module.

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

# Answer
Use this and all your problem get solved: https://www.drupal.org/project/views\_slideshow\_jcarousel
> 1 votes

# Answer
You can do this by using jCarousel module.

> This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

1. Enable the module
2. Goto View -\> Select Format of type jCarousel
3. Configure the settings
> 0 votes

# Answer
You can use Views Slideshow module for views sliding.

click here for module installation SlideShow Module

and Click Here and follow those steps to how to install slideshow module and configure the module in your site.
> 0 votes

---
Tags: javascript, views
---


# Question
Title: How do I use print to generate a PDF of all entities referencing a specific node?
I'm trying to use the Print module to generate pdf's and epubs of the stories on my site. However, I need to get Print to generate these files from the story page and then generate the pdf with ALL nodes that reference the story, the chapters. I'm not sure how to do this as I've never really done tpl.php's before. I need some help here.

Can print be made to work with a panels layout that shows what I want in it? I have a panels layout working mostly for an example of what I'm trying to achieve.

http://fanbards.net/print/stories/13008

How do I make the tpl.php file I need to make that end up as my print selections for Stories?

# Answer
> 0 votes
Seeing the url for print layout works fine, my first suggestion would be, that you can actually do it simply by activating the pdf module and changing the path to trigger the 'pdf-generator':

print-path: http://fanbards.net/print/stories/13008

printpdf-path: http://fanbards.net/printpdf/stories/13008

…you may find further useful info about this on the documentation page for Print.

# Answer
> 0 votes
Well, I managed to create a content type based template for print. I'm not sure if it's the best way but it's what I came up with. Any improvments would be appreciated.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>">
<head>
    <?php print $head; ?>
    <base href='<?php print $url ?>' />
    <title><?php print $print_title; ?></title>
    <?php print $scripts; ?>
    <?php if (isset($sendtoprinter)) print $sendtoprinter; ?>
    <?php print $robots_meta; ?>
    <?php if (theme_get_setting('toggle_favicon')): ?>
      <link rel='shortcut icon' href='<?php print theme_get_setting('favicon') ?>' type='image/x-icon' />
    <?php endif; ?>
    <?php print $css; ?>
  </head>
<body>
<?php if (!empty($message)): ?>
      <div class="print-message"><?php print $message; ?></div><p />
    <?php endif; ?>
    <?php if ($print_logo): ?>
      <div class="print-logo"><?php print $print_logo; ?></div>
    <?php endif; ?>
    <div class="print-site_name"><?php print theme('print_published'); ?></div>
    <p />
    <div class="print-breadcrumb"><?php print theme('print_breadcrumb', array('node' => $node)); ?></div>
    <hr class="print-hr" />
    <?php if (!isset($node->type)): ?>
      <h2 class="print-title"><?php print $print_title; ?></h2>
    <?php endif; ?>
    <div class="print-content"><?php print views_embed_view ('story_summary','print_story_pane', $node->nid); ?></div>
    <div class="print-content"><?php print views_embed_view('print_views','print_chapter_pane', $node->nid); ?></div>
    <div class="print-content"><?php print views_embed_view('print_views','print_authors_note_pane', $node->nid); ?></div>
<div class="print-footer"><?php print theme('print_footer'); ?></div>
    <hr class="print-hr" />
    <?php if ($sourceurl_enabled): ?>
      <div class="print-source_url">
        <?php print theme('print_sourceurl', array('url' => $source_url, 'node' => $node, 'cid' => $cid)); ?>
      </div>
    <?php endif; ?>
    <div class="print-links"><?php print theme('print_url_list'); ?></div>
    <?php print $footer_scripts; ?>

```

---
Tags: entities, files
---


# Question
Title: How include hash (#) in drupal_goto path?
Is there any way to include a # in drupal\_goto?

i want something like this

```
function MYMODULE_preprocess_node(&$variables) {
  $node = $variables['node'];
  switch ($node->type) {
    case 'product':
      drupal_goto("products#".$node->nid);
  }
}

```

# Answer
For Drupal 6,

It should be 3rd parameter

```
drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

drupal_goto("products", NULL, $node->nid);

```

For Drupal 7

```
drupal_goto($path = '', array $options = array(), $http_response_code = 302)
drupal_goto("products", array('fragment' => $node->nid));

```
> 18 votes

# Answer
In Drupal 6 drupal\_goto use its third parameter for the fragmentation. If you wants to make the url like products#345 you should pass its fragment as third argument in drupal\_goto function.

```
drupal_goto("products", NULL, $node->nid); // where $node->nid is the fragment.

```

In Drupal 7 you should pass fragment as key value pair of array on second parameter of drupal\_goto function.

```
drupal_goto('products', array('fragment' => $node->nid)) ; // where $node->nid is the fragment.

```

Both of above will produce an url like products#123, where 123 is the value of $node-\>nid variable.
> 7 votes

# Answer
This also worked for me in Drupal 7

```
 drupal_goto( '/products/' . 'section', array( 'fragment' =>  'subsection', 'alias' => TRUE ) );

```
> 2 votes

# Answer
drupal\_goto loses #zzz if there is a ?destination=foobar#zzz, as this is never returned by $\_SERVER, remove this line as does nothing apart from breaking stuff:

```
//$options['fragment'] = $destination['fragment'];  // removed
is the same as
$options['fragment']='';

```
> 0 votes

---
Tags: redirection
---


title: How to create a hook?

text:
# Question
Title: How to create a hook?
How can I create my own hook (similar to the ones Drupal core creates) for other Drupal modules to utilize?

# Answer
> 20 votes
You don't actually create hooks. You use helper functions such as `module_invoke_all()`, `module_invoke()` or `drupal_alter()` to invoke all functions matching the expected name pattern. The invoked functions are usually found with `module_implements()`.

Even if it is not needed for the hooks to work, the best practice is to document them in `MODULE.api.php` by creating empty *stubs* `hook_NAME` functions with documentation comments.

# Answer
> 0 votes
You can also create hook, using hook\_trigger\_info you can create new hook, and in your module you need to implement it. As an example, suppose you want to create an archive of nodes and put old nodes in it. You also want to trigger a hook when the archive operation is done. it is going to be some thing like this

```
function hook_trigger_info() {
    return array(
            'node' => array(
                    'archive_nodes' => array(
                        'label' => t('Archive old nodes'),
                    )
            )
    );
}

```

After defining the hook, your module is responsible for implementing the hook and actions using module\_invoke() or module\_invoke\_all() .

You can enable the `trigger` module to see this new hook under the node tab.

---
Tags: 7, hooks
---


# Question
Title: Add body class to both Node add and Node Edit Page
I want to add a Body class to my Node Add pages and my Node Edit Pages.

How can I do this?

I know that I need use the following in `template.php` to add a class to Node Edit:

```
function MYTHEME_preprocess_html(&$variables) {
     if (arg(0)=='node' && arg(2)=='edit') {
      $variables['classes_array'][] = 'node-edit-page';
    }
}

```

But how can I modify the code to work with node add?

Note: Node Add is when you create a node (e.g. yousite.com/node/add/page).

Node Edit is when you edit an existing page (e.g. yousite.com/node/1/edit)

# Answer
> 1 votes
Did you try :

```
function MYTHEME_preprocess_html(&$variables) {
  if ((arg(0)=='node' && arg(2)=='edit') || (arg(0) == 'node') && (arg(1) == 'add')) {
    $variables['classes_array'][] = 'node-edit-page';
  }
}

```

---
Tags: nodes, theming
---


# Question
Title: Prepopulate a field in a Reference Dialog Box
I have 2 content types named Incident and Migrant. Both of them have fields that reference each other. My question is how to prepopulate a field in a reference dialog box while the node is being edited?

How am I going to prepopulate Incident field with Incident 36 nid. When the popup/dialog loads? Assuming that Incident field is a Autocomplete Text Field?

Here's what I tried, I have tried Entity Reference Prepopulate but, I figured that that the Reference Dialog is displayed via iframe so getting the nid from the URL wont work.

I'm very new to drupal and still in the learning curve so if possible answer me in a detailed fashion.

Modules i used

Entityreference prepopulate Reference Dialog

# Answer
> 0 votes
Yes, you can. What you need for this? 1) references\_dialog 2) entityreference\_prepopulate 3) your custom\_module. For example field that you want to make with prepopulated field in url is entityreference. Here is link to youtube how to use entityreference\_prepopulate and URL https://www.youtube.com/watch?v=z9C4Uf6euLY.

After this you should override your "Create ..." link. How to do this? Easy. Just implement hook\_references\_dialog\_widgets\_alter in your custom module and change name of function that generate add link

```
/**
 * Implements hook_references_dialog_widgets()
 */
function mymodule_references_dialog_widgets_alter(&$widgets) {
  $widgets['entityreference_autocomplete']['operations']['add']['function']
    = 'mymodule_references_dialog_entityreference_add_link';
}

```

And than you can define your add link function:

```
function mymodule_references_dialog_entityreference_add_link($element, $widget_settings, $field, $instance) {
// blah blah from original function
// Here you can catch field what you need and define url with $_GET parameters for it.
}

```

That's all. Enjoy reference dialog with get params in url.

---
Tags: entities, nodes
---


title: Drupal database loading slow

text:
# Question
Title: Drupal database loading slow
I'm making a website (don't open in IE) where I use Ajax to load a view. I now want to use BOOST to cache the view as HTML.

These pages should be "BOOSTED":

http://www.spanjevakantiewinkel.nl/regio/ajax/8 http://www.spanjevakantiewinkel.nl/regio/ajax/9 ...

Should I use JSON instead of my way to load the view? Any idea how?

The ID (8,9,...) is given by hovering a small image beneath the large header image. Then the view will be loaded, but always within the database, I want HTML pages made with BOOST.

```
function dynamic_regio_menu() {
  $items = array();

  $items['regio/ajax'] = array(
    'title' => 'Dynamic Regio',
    'page callback' => 'dynamic_regio_get_by_category_id',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function dynamic_regio_get_by_category_id($cat_id){
    $viewName = 'regio_submenu'; // The name of the view we are going to load

    $args = array($cat_id);  // Array of arguments we set for the view.
    $displayId = 'block'; // The display id of for the view.

    // Call the views_embed_view function to returned themed view output
    $html = views_embed_view($viewName, $displayId, $args);
    echo $html;
}

```

```
xhr = $.ajax({
  type: 'POST',
  url: '/regio/ajax/' + this.parentNode.getAttribute('tid'),
  success: updateData, dataType: 'html',
});

```

# Answer
I think the problem is how your views are cached - if you say it is sometimes slow, it is most probably because those times the cache is beeing saved. If the content doesnt change often, you might just prolongue the interval. Another option is to use Views content cache. But basically if you have enough visitors (and enough people hovering the images :), they will only wait from time to time ...
> 1 votes

# Answer
The Query time is simply the time it took for the DB to send the result of the query to be returned. The page execution takes into account all of the processing of those results.

This is why it's so important to have Caching enabled.

This may explain more of Views caching: Are views cached through the core caching mechanisms or should I be setting the caching directly in each view?
> 1 votes

# Answer
I am not sure if it can help or not but when I try to make ajax I have to call drupal\_exit() I don't want drupal to get all page element just this string

```
function dynamic_regio_get_by_category_id($cat_id){
    $viewName = 'regio_submenu'; // The name of the view we are going to load

    $args = array($cat_id);  // Array of arguments we set for the view.
    $displayId = 'block'; // The display id of for the view.

    // Call the views_embed_view function to returned themed view output
    $html = views_embed_view($viewName, $displayId, $args);
    echo $html;
    drupal_exit();
}

```
> 0 votes

# Answer
I would definitely advise to check if you have removed modules that are still enabled. This is a real performance killer because Drupal is searching for the module files.

The behavior that you describe looks like this issue.
> 0 votes

# Answer
OK, I know this is an old thread, however, I just went through quite a bit of trouble with this and thought I should post here so others will know what my problem was.

first and foremost, verify that your view is not trying to render every single node and comment in the content type if there is a lot of content! It will dismally slow the site doen even if you are using caching, etc. The problem only manifested itself after migrating 56000 or so comments onto 30000 nodes.

The pager count evidently counts nodes and comments and my view had a contextual filter for the logged in user that was not working as it should. Once I got it working, the views are fast and everything is good so I hope this helps someone down the road.
> 0 votes

---
Tags: 7, views, ajax, database, javascript
---


# Question
Title: How do I add additional view modes for a node?
I am creating a custom content type. By default, nodes support only two view modes (`full` and `teaser`):

```
function mymodule_view($node, $view_mode)
{
    if ($view_mode == 'full') {
         $node->content['#theme']= 'my_full_node_view_theme';
    }

    if ($view_mode == 'teaser') {
          $node->content['#theme']= 'my_teaser_node_view_theme';
    }
    return $node;
}

```

I want to add some other view modes for this node type, like:

* `small_box`
* `small_box_with_user_pic`
* `big_box`

and want to render the node with code like this:

```
$node = node_load($my_nid);
$output = drupal_render(node_view($node, 'big_box'));

```

Any suggestions?

# Answer
> 24 votes
first we have to add additional view modes with hook\_entity\_info\_alter

```
function customuserblog_entity_info_alter(&$entity_info) {
     $entity_info['node']['view modes']['blog_post_big'] = array(
        'label' => t('simple big  teaser'),
        'custom settings' => TRUE,
      );
    }

```

// we may attach additional theme functions or templates and add variables with hook\_view

```
function customuserblog_view($node, $view_mode) {
  if ($view_mode == 'blog_post_big') {
   // add some additional variables for template
    $node->content['#theme'] = 'custom_blog_big_teaser_view';
  }
}

```

// in our hook theme

```
customuserblog_theme(){
    return array(
      'custom_blog_big_teaser_view'= array(
          'render element' => 'form',
          'template' => 'custom-blog-big-teaser-view',
       ),

    );
}

```

# Answer
> 10 votes
If *all* you want is custom view modes, then Entity View Mode can help. Display Suite also makes it easy to create custom view modes, to create new pseudo-fields, and have a nice drag & drop interface for laying out different elements in the various view modes.

If you want to do this all in code, then entity\_example from the Examples module has a view mode IIRC. Drupal Commerce also has a number of custom entities with custom view modes.

# Answer
> 1 votes
If you are using Display Suite, make sure that ds\_ui module is enabled and go to admin/structure/ds/view\_modes to get a list of existing and create new view modes.

# Answer
> 1 votes
I know this is an older topic, but I have found the following method to work just fine for most use cases.

These simple steps will take you through creating your own module with the new view mode. It's fairly simple. I would love to provide attribution, but I can't remember where I found the basis for this. It does follow the same logic as werqious's answer though.

File 1 : my\_module\_view\_modes.module

```
<?php
//Add more view modes for content type displays, in addition to default and teaser.
function almagest_view_modes_entity_info_alter(&$entity_info) {

//NB: media_ prefix required.
//You can repeat the following section for any view modes you'd like to create.

// First View Mode
// tag 1 references the entity type, ex. node or file
// tag 3 provides a machine name for your mode
  $entity_info['node']['view modes']['my_view_mode'] = array(
    'label' => t('My View Mode'), // This is what you'll see in your "Manage Display" tab.
    'custom settings' => TRUE,
  );

// Another View Mode
  $entity_info['file']['view modes']['my_other_view_mode'] = array(
    'label' => t('Another View Mode'),
    'custom settings' => TRUE,
  );
}

```

File 2 : my\_module\_view\_modes.info

```
name = My Module View Modes
description = Add additional "View Modes" for entities in this module. Helpful for additional displays in views or node rendering.
package = My Modules
version = 7.x - 0.1
core = 7.x

```

Save these two files in your my\_module\_view\_mode folder in your modules folder and enable. Clear your cache and now you'll see the new view modes in their respective entities.

---
Tags: 7, nodes
---


# Question
Title: queries with db_select don't respect integers
When I check "SHOW PROCESSLIST" in phpMyAdmin I can see lots of queries where argument-integers are being inserted as strings (with single quotation marks).

I'm wondering if this is due to the way phpmyadmin reports the queries (if it puts every argument between quotation marks) of if it is db\_select that puts every argument between quotation marks.

An example of my code where integers are being used as arguments:

```
$select->join('taxonomy_index', 't_'.$key, 't_'.$key.'.nid = n.nid AND t_'.$key.'.tid = :tid_' . $key, array(':tid_'.$key => (int)$tid));
$select->condition('t_'.$key.'.tid', (int)$tid);

```

As you can see I explicitly write (int)$tid but in my query log I can see the following:

```
... WHERE (t_0.tid = '10') ...

```

The big question is: How can I be sure that integers are being treated as integers in my queries? I don't want MySQL having to transform strings to integers.

# Answer
Drupal doesn't alter the arguments you give it (apart from expanding arrays), but because they're passed directly to `PDOStatement::execute`, in which

> All values are treated as PDO::PARAM\_STR.

the quotes are inevitably added.

Assuming a recent-ish version of MySQL you can try disabling prepared statement emulation to let MySQL sort them out instead. In settings.php:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver1',
  'pdo' => array(PDO::ATTR_EMULATE_PREPARES => FALSE),
);

```
> 3 votes

# Answer
it's my understanding that Drupal's doing that when it sanitizes vars for database input.

I believe you can wrestle control over this if you use db\_query() like so, but I've never tried this:

```
$vals = array('tid', 10);
$result = db_query("SELECT * FROM taxonomy_index WHERE tid = :type", $vals)->fetchCol();

```
> 0 votes

---
Tags: 7, database
---


title: Drupal Backup and Migrate Error

text:
# Question
Title: Drupal Backup and Migrate Error
I'm looking to use Backup and Migrate modules to port over my website. However, even when I go and install a fresh install, update all the modules and activate them accordingly, and finally restore my database, I come out with a white page with the error below. I've done some searching around online here and elsewhere looking for a solution to the following error, and while I've found similar things none have been able to help me resolve this error:

```
Fatal error: require_once(): Failed opening required '/var/www/html/profiles/acquia/modules/ctools/plugins/export_ui/ctools_export_ui.class.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/includes/bootstrap.inc on line 3168

```

From what I've read thus far, I am getting that this is basically telling me the something doesn't exist and needs to be added into the PHP. That's where things have begun to get foggy as I continue to push through.

Thanks in advance!

# Answer
The issue was while I had imported all of the past module information, I was missing the profile files.
> 1 votes

---
Tags: backups
---


# Question
Title: Hide status messages generated from Commerce - Not required with use of Ajax add to cart module
I am using a nice little module Commerce Ajax Cart which adds products to the cart without a refresh.

However, my only little issue is that when then navigating to the checkout page, it displays all the status messages for the products that have been added to cart.

I could hide these with CSS using the status class, however, this could also hide any important status messages with it.

So my question is, how can I hide the status messages from commerce, or if anyone knows where these status messages are being generated from within the commerce modules.

Thanks

# Answer
> 1 votes
I believe you're referencing the "Display an Add to Cart Message" Rule. Looks like:

To disable this go to: Configuration \> Workflow \> Rules \> Disable - Display an Add To Cart Message.

---
Tags: commerce, status-messages
---


# Question
Title: Inserting space/gap between two main menu links
In my main menu, I have the following links: Home, About Us, Blog, Log In and Sign Up. I want the Log In and Sign Up links to float to the right such that there will be space/gap between the 'Blog' and 'Log In' links.

Please how can I achieve this?

# Answer
> 0 votes
You can use menu attributes module to specify ids for those both menu then you try

# Answer
> 0 votes
If you're ok with wading into code, you can use \_menu\_item\_alter() in your template.php to add CSS classes to just the menu items you want.

---
Tags: routes
---


# Question
Title: Creating a Views Search Page AND Block (not just a search block and results page)
I have a site with a box on the home page (only) that has a search box. I also have a 'search' link available on all pages of the site, in the navigation. The search link takes the user to a page called 'Search' where the search box appears (again) and allows them to do searches there. I've built the search for that page so the search box appears and the results display only after the user types in a search.

The main question I have is this: how do I create a block for the home page that ONLY displays the search box (results of such search still showing on the results page I've created in Views)?

I know how to expose the View as a block but this doesn't solve my issue because I want the search box itself to still show on the results page too.

# Answer
> 1 votes
Consider using a block with php filter to display the exposed search box in a block.

Example below is based on Search API with blocks exposed. I'm taking a guess you're using Search API based on your description.

For Search API:

`$view = views_get_view('your_view_here');
$view->set_display('Page');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);`

For Drupal's Core Search:

`$block = module_invoke('search', 'block_view');
print render($block['content']);`

---
Tags: views
---


# Question
Title: VBO Pass Argument to Custom Action Function
I have a view that list entities. It has a VBO field on it for executing a few custom actions.

I can get the actions working, but I need to add a field to the operations form on the view which lets the user select a date field. I then need to pass that date value on the VBO form submit, to the custom action, so that I can use it to manipulate some entity data.

I am able to add the date field via this method:

```
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo){
    $form['vbo_set_close_date'] = array (
        '#type' => 'date_popup',
        '#title' => t ('Set Close Date'),
        '#date_format' => 'm/d/Y',
        '#date_label_position' => 'within',
        '#weight' => 1000,
    );
}

```

Now I am stuck because that data doesn't get passed to my custom action, and I'm not sure what the correct method would be to accomplish that. I've though of adding a custom form submit handler, but still not sure if that's working because I can't seem to get it to trigger.

# Answer
> 2 votes
Awhile back I did come up with a work around for this. Basically you can create a custom submission handler for the VBO form, then have that custom handler perform the code you need.

```
/**
* Implements hook_views_bulk_operations_form_alter().
*
* This is the function that alters our VBO form
*
* @param $form
* @param $form_state
* @param $vbo
*/
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo){

  // Here I added a date popup to the form
  $form['vbo_set_close_date'] = array (
        '#type' => 'date_popup',
        '#title' => t ('Set Close Date'),
        '#date_format' => 'm/d/Y',
        '#date_label_position' => 'within',
        '#weight' => -10000,
  );

  // Here is where I added the custom submission handler. This calls the "mymodule_set_close_dates" method
  $form['select']['submit']['#submit'][] = "mymodule_set_close_dates";

}

/**
 * Callback function for VBO form
 *
 * @param $form
 * @param $form_state
 */
function mymodule_set_close_dates($form, &$form_state){

  $date = $form_state['values']['vbo_set_close_date'];
  $action = $form_state['operation']->operationId;
  if(!is_null($date) && $action == 'action::mymodule_close_job'){ // <------- custom action
      $value = strtotime($date);
      $relations = $form_state['build_info']['args'][0]->result;
      foreach ($relations as $relation){
        $rid = $relation->rid;
        $wrapper = entity_metadata_wrapper('relation', $rid);
        $wrapper->field_ended->set($value);
        $wrapper->save();
    }
}

```

---
Tags: 7, forms, views, actions
---


# Question
Title: Deleted content returns over and over again
I have a situation where I can delete (update options \> delete selected content) in admin \> content...and it says it deletes all the selected records.

But then later on all those records will return again. After I delete them they are not showing at all in (admin \> content). But then later, they will show up again there and the links will be clickable etc. It will be like I never deleted them. I can do this over and over again and they keep re-appearing. We're talking about 50 nodes here.

I haven't updated the database otherwise. I've gone to a page (such as search) where those used to appear and they appear again there...and sometimes it seems like maybe that has something to do with it. But I still don't understand what or why.

Is there a better way to delete content to ensure its completely gone?

# Answer
Did you check the error log? is there any warning or error in there?

If not then you should manually delete it from database. just look for their ID and remove them from DB
> 1 votes

---
Tags: nodes, database
---


# Question
Title: Custom template file for custom view mode on site front page
I'm trying to style a view a certain way on the front page (using a custom front page, page--front.tpl.php) of my site, and here are the steps I've taken using Entity View Types and Views modules:

1.) Created content type called 'Recipe' 2.) Created View Mode called 'Front Small' 3.) Created a view and called it 'Front Feature One' 4.) In the view settings, I've set the format to 'Content', and selected 'Front Small' view mode for display 5.) In my template.tpl.php file I've put in the following:

```
if ($variables['view_mode'] == 'front_small') {
    $variables['theme_hook_suggestions'] = 'node__' . $variables['type'] . $variables['view_mode'];
}

```

6.) I tried creating a file called node--recipe--front-small.tpl.php to style the node in a custom way but it never gets used. The standard node.tpl.php file is being used instead.

Can anyone tell me if I'm naming the file incorrectly or if something else might be wrong? When I spit out the $view\_mode variable in my node file it shows "front\_small" only. I've also tried removing 'recipe' from that file name to see if it would make a difference, but to no avail.

Note: I am using a custom front page styled in the page--front.tpl.php file. The view mode above that I'm trying to style should be appearing on this front page, so I'm not sure if there are other things I am missing.

Any help is greatly appreciated. Thanks in advance!

# Answer
First of all, tell me where do you put that code? what is its function? `node_preprocess`? besides that It doesn't make any sense to define a specific view mode for your view then trying to theme it using views! I recommend you to define fields as view mode, select your fields and theme it in the theme hook suggestion.
> 0 votes

# Answer
> template.tpl.php

wrong file I guess, theme hook suggestions go in template.php, you'll have to implement hook\_preprocess\_node(). See How to provide template for particular view mode? for an example.

The rest looks all fine for now. Also try using 'rendered entity' instead of 'content' as a format in views at least once.
> 0 votes

---
Tags: theming, nodes
---