# Question
Title: Views exposed filter: Upcoming/Past events
I want to implement an exposed filter in the view with a date field. I want to show two choice in select list according to the date value (upcoming events/past events). But I don't know how to achieve this using date field because it allows to choose date only. Is there any way to achieve this feature?

Thank you in advance.

# Answer
Add a date filter.

Expose the date filter.

Select the grouped filters option

Scroll down and define your filters as shown in next image

And you are good to go. You will have an output like this

You can change the options to make it a drop-down too.

To fix for the UI bug in exposed filters groups:

Make sure your date module is at Version: 7.x-2.9 or later, then apply the patch exposed\_grouped\_filter-1876168-71.patch (https://www.drupal.org/node/1876168#comment-10344663)
> 4 votes

# Answer
Remove the 3 default options (hit "Remove" link) and add them manually by using the button "Add another item". The new options will now display the field for relative date.

Hope that helps

Best

EDIT: that seemed to work but actually not... Sorry
> 1 votes

---
Tags: 7, views
---


# Question
Title: Looking to create a taxonomy term path with a query string
I have seen this question asked over on DO and here, but there doesn't seem to be a clear answer.

How to create a path alias with a query string in the target?

I need to able to send a query string when someone clicks on a Taxonomy Tag.

So, I set my tags such as Things-To-Do/All/\[term:name\]/?shs\_term\_node\_tid\_depth=\[term:tid\]

Which encodes the string to /Things-To-Do/All/arts-culture-history/%3Fshs\_term\_node\_tid\_depth%3D612

Which does pull up my view, but of course, doesn't filter.

I have tried creating a custom module, as well as using global redirect, but no luck.

Is this simply not possible? Can I stick something in View Pre-render or something that will unencode the string before it renders.

I have been hitting my head against this problem for a while now and really don't know where to turn.

I should point out that the above answer 'works' but not really with dynamic content.

# Answer
> 0 votes
Well, I finally figured it out.

```
    function cin_rd_init(){

    //first I see if this is a taxonomy page
    if (arg(0) == 'taxonomy') {

    //then I get the termID from the argument
    $termid=arg(2);
        $newterm=taxonomy_term_load($termid);

        if(!empty($newterm)){
        $thetermname=str_replace(' ','-',$newterm->name);
        $thetermid=$newterm->tid;
        $newtermvid=$newterm->vid;

        //Next I check the vocabularyID to see if it should be redirected
        //Important, I also check to see if my parameter string is set already so I don't have an endless redirect.
        if($newtermvid==18 && (!isset($_REQUEST['shs_term_node_tid_depth']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('shs_term_node_tid_depth' => $thetermid)));
        }
        //I can change the destination and query string depending on the vocab I am using
        if($newtermvid==19 && (!isset($_REQUEST['features']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('features[]' => $thetermid)));
        }
} //not empty
} //end if taxonomy
} //end function

```

So now, anyone who goes to a taxonomy term page will either go directly to the term page, unless the term belongs to either of these vocabularies.

If so, then it will redirect those with a query string.

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: How can you hide modules form all listings without deleting them
I have a growing collection of modules on site. My module management page and on my feature management page are starting to get cluttered (even with module filter enabled.) Several of these modules are example modules which are disables and currently only serve to clutter things up. I would like to hide these modules so that they do not appear in any of my module lists. I don't want to delete them (or alter their code if possible.) Is there a way to temporarily hide a module so it does not appear in any of the module lists?

# Answer
Use this module to Hide.

Hide Module

This will hide the module based on role.

> Hide Modules allows selected modules not being listed at the module administration page except for selected roles.
>
> It enables administrators to safely grant 'administer modules' permission to other roles and keeping at the same time some modules out of the list to avoid untrusted users enabling or disabling them.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Cache error on file upload with media, multiform, and plupload
Checkout the log entries for a site I am working on, I found multiple pairs of the following notice/error:

> Error: Form build-id mismatch detected while attempting to store a form in the cache. Notice: Undefined index: #build\_id in form\_set\_cache() (line 564 of /dir/includes/form.inc).

I am using media-2.x with plupload and multiform. The above messages are always logged for all files uploaded through plupload at file/add. Any ideas what is going on here and how to fix it? There will be a lot of file uploads on this site, and I really don't want the database filling up with these log entries.

I am getting these messages with Pantheon and with my local environment, so going to assume it is not a server configuration issue, Core and all modules are up to date. Php is 5.4.

Any help would be very much appreciated!

# Answer
> 5 votes
There is a bug in multiform that was introduced by recent changes to Drupal Core. The bug has been reported in the module's issue queue and a patch has been provided: https://drupal.org/node/2247527

The patch fixed the issue for me, and hopefully will be included in the next release of the module.

---
Tags: 7, media, files
---


title: Schedule appointment form in popup

text:
# Question
Title: Schedule appointment form in popup
I'm looking for a schedule appointment form in Drupal 7 which looks like the below image:

Before I'm going to start building a custom module I'd like to know if there's any other module like this? And I also need to integrate Google Calendar with this.

# Answer
> 1 votes
You can build this without a custom module, and without a specialty contrib module specifically for "appointments".

I would build this using Entityform but you could also just use a basic content type with custom fields. Modules that would go into your recipe would be Date, Date Restrictions, Email field, Page break field, and perhaps Field Group and Display Suite for nailing that layout.

These modules together should allow you to construct an entity (node or entityform) with all of the functions of your screenshot, without custom modules or custom code. Also, you will want Rules to handle the actions that happen when the form is submitted.

You didn't specify if this is just an "Appointment request form" that is later confirmed by a salon employee, or if it is actually to *book* an appointment that is confirmed automatically. The latter would be much more complex as it would require that Drupal knows about all of the existing appointments and have the logic/ability to eliminate conflicts. For this, see Appointment Scheduling

---
Tags: 7
---


title: Link a div to content

text:
# Question
Title: Link a div to content
I have made a 3d Hover effect for a Team Members about page. When you hover over a photo it flips like a box and reveals peoples credentials. I want to be able to make the div link to the team members content (the page that goes further into depth about each individual team member). I have re-written the code like so:

- \[field\_photo\]
```
     <a href="[node:content]"><div class="ch-info-back">
        <br/> <br/>
           <h3> [title] </h3>
              <p> [field_position] </p>
  </div></a>

```

I tried linking it like: . Unfortunately, no luck... I saw that I could make a php function but there must be an easier way !! if anyone could help me out that would be greatly appreciated (=

# Answer
> 0 votes
Add a field to your view of type `Content:Path` and drag it to the top of your field list. Then your href should be:

```
<a href="[path]"><div class="ch-info-back">

```

---
Tags: views, theming, nodes
---


title: Drupal 7 log-in form doesn't react

text:
# Question
Title: Drupal 7 log-in form doesn't react
Out of the blue I'm unable to login into my website: http://karlssonwilker.com/dev\_v2/kw/user

I type my username and my password and upon clicking "log-in" or pressing RETURN nothing happens. Could it be something related with the database? Disabling javascript, css, removing any custom functions, or clearing the cache tables on phpmydamin seems to have no affect.

No idea what the problem is.

I had a test user created before I started having this problem. You can use it if you care to try. user: test pass: test

Anyone came across a similar problem?

Thanks!

# Answer
> 0 votes
I've noticed that your Drupal installation is at http://karlssonwilker.com/dev\_v2/kw/ which is a subdirectory. This can mess up some rewrite rules in .htaccess when using clean urls.

Go to .htaccess and find this line that is greyed out.

```
# RewriteBase /drupal

```

You should uncomment that and replace it with...

```
RewriteBase /dev_v2/kw

```

This will most likely fix your problem. If you are using some sort of CVS and this is a staging site, I would recommend ignoring the .htaccess file. I wouldn't want you to accidentally destroying your live site.

# Answer
> 0 votes
There is something wrong with your HTML:

```
<div id="node_container" <form="" action="/dev_v2/kw/user" method="post" accept-charset="UTF-8"><div><div class="form-item form-type-textfield form-item-name">

```

This is definitely not interpreted as form.

---
Tags: users
---


# Question
Title: How to get the values of an array in the options list (hook_rules_condition_info ()) instead of array index?
```
'example_condition_user' => array(
      'label' => t('User Condition'),
      'arguments' => array(
      ),
      'parameter' => array(
        'username' => array(
          'type'  => 'text',
          'options list' => 'list_all_users',
          'label' => t('Username'),
          'description' => t('user that the conditions apply'),
         ),
        'user_entry' => array(
          'type'  => 'user',
          'label' => t('user'),
        )
      ),
      'group' => t('exemplo'),
      'module' => 'exemplo',
)

function list_all_users(){

  $query = db_select('users', 'u');
  $query->fields('u', array('name'));

  $result = $query->execute()->fetchAll();
  $ret = array();

  foreach($result as $r){
    array_push($ret, $r->name);
  }

  return array_values($ret);

}

```

The list\_all\_users function returns the users (that are in my database) in a array, but the options list does not get the values of the array, but the array index, and this is a problem, because I need the values of the index, and then do the validations rule\_condition\_info (), does anyone have any idea how to fix this?

# Answer
> 0 votes
You just need a reliable array key so you can load the data up again somewhere else; since you're going into the users table, `uid` seems appropriate:

```
function list_all_users() {
  return db_query('SELECT uid, name FROM {users}')->fetchAllKeyed();
}

```

That will turn the options into an array with user IDs as keys and names as values. As far as the front end is concerned, nothing changes.

Now when you receive the selected option value in the validation function, you can just load the user up and get the name from the entity:

```
$account = user_load($the_value);
$name = $account->name;

```

---
Tags: rules, database
---


# Question
Title: Expose Date Filter instead of Start & End Dates
I have a content type event with start and end dates marked. I have create a view with exposed filter, where in users can choose a date and see the event on those days. Right now, view is only allowing me to choose start and end dates. This way if an event is between March 1st - March 10th, there is no way for user to filter and see the events for say March 5th. Technically event being from 1st-10th is also present on March 5th. How can I expose a filter where in user can get events by any date.

Below is what I have now:

But I want like below:

# Answer
I've been trying to solve a similar problem: creating a membership list per a specific date (based on "membership date" field with start and optional end date elements). Here is my current solution - hope it helps!

Environment 1. I use VIEWS, RELATIONS and the PARTIAL DATES module and added a partial dates range field type to the Relation between a person and the organisation. This allows multiple memberships and "fuzzy" start and end dates if exact data is unavailable (i.e. "member since 1995"). You can probably put the date range field directly on your event node, and you may be able to use the standard date field if you don't need to allow for "fuzzy" dates. Note that the Partial date range field automatically calculates timestamp values for "from" and "to" dates.

In the view, I added 2 exposed filters \- "partial\_date\_timestamp\_to" \>= selected date \- "partial\_date" \<= selected date I also added 2 non-exposed filters to allow incomplete nodes to be shown (since membership data is not always perfect) you might not need this if your events always have complete, valid start and end dates. So my filter criteria now reads: (partial\_date\_timestamp \<= selected date OR partial\_date\_timestamp is empty) AND (partial\_date\_timestamp\_to \>= selected date OR partial\_date\_timestamp\_to is empty)

It works, but entering the desired date in timestamp format isn't very user-friendly. Next step is to get desired date from user by a more comfortable method, then convert the result for the view filter.
> 0 votes

# Answer
Look into the Date Picker Module

Once you download it, enable it, and clear your cache you should see a filter field that is called Date (node). From there it's pretty self explanatory.
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: How to use Drush with Apache Directives?
My Drupal installs are set up with apache environment variables/directives (SetEnv DB\_NAME somedb) to store the database name, username and password. It appears that Drush isn't able to use these by default as it fails to recognise the apache directives. Is there another way of doing this or can I use some kind of alias or something else to pass the database credentials directly to Drush?

# Answer
> 0 votes
This is not a Drush function; it is a BASH function. For example, you could do this:

DB\_NAME=mydbestting drush status

Optionally, you could set your DB\_NAME environment variable in your .bashrc file.

However, this is probably not what you want. You would probably prefer to have Drush set the environment variable for you, after you specify the alias. Drush does not have this feature, but there has been some discussion of it in the issue queue on drupal.org:

https://drupal.org/node/1848766

---
Tags: drush
---


title: Pager on Widget Form Query

text:
# Question
Title: Pager on Widget Form Query
The module is a small custom widget for the entity reference field. It creates a list of nodes that allows for multiple selections.

Is it possible to paginate the results of the query even though this is a widget for a field?

```
function outfit_builder_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

///...Additional Code Removed

$query = db_select('node', 'n');
$query->addTag('node_access');
$query->join('field_data_' . $instance['widget']['settings']['image_field_' . $type], 'fd', 'fd.entity_id = n.nid');
$query->fields('n', array('title', 'nid'));
$query->fields('fd', array($instance['widget']['settings']['image_field_' . $type] . '_fid'));
$query->condition('n.type', $type, '=');
$query->condition('fd.delta', 0, '=');
$query->condition('n.status', 1, '=');
$result = $query->extend('PagerDefault')->limit(21)->execute();
foreach ($result as $node) {
  $options[$node->nid] = theme('image_style', array(
      'style_name'  => $instance['widget']['settings']['image_style'],
      'path'        => file_load($node->{$instance['widget']['settings']['image_field_' . $type] . '_fid'})->uri,
      'title'       => check_plain($node->title),
    )
  );
}

$element += array(
'#type'             => 'checkboxes',
'#options'          => $options,
'#attributes'       => array(
  'class' => array('item'),
),

return $element;

```

}

# Answer
I figured it out. After you extend your query:

```
$result = $query->extend('PagerDefault')->limit(21)->execute();

```

You'll need to also include the pager

```
// Attach the pager theme
$element['pager_pager'] = array('#theme' => 'pager',);

```
> 0 votes

---
Tags: forms, database, paging
---


# Question
Title: $drupal_hash_salt is empty in my installations
This is the code in `settings.php`

```
$drupal_hash_salt = '';

```

From what I know it should be a random string and I shouldn't change it at all and it has a direct effect on the website security. But why this variable is empty? Is there any problem and what should I do to assign a string to this variable?

# Answer
The hash is used to salt things one-time links and forms tokens, it filed usually by the installer.

You can add your own salt here, basically any random string or even replace it with the content of a file (see the documentation in the default.settings.php).

If this variable is empty, a hash of the serialized database credentials will be used as a fallback salt (though you have to add it manually if you have a database cluster).

This is function used as a fall back if there is no salt drupal\_hash\_salt

```
function drupal_get_hash_salt() {
  global $drupal_hash_salt, $databases;
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
  // database credentials is used as a fallback salt.
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
}

```
> 3 votes

---
Tags: installation, security, configuration
---


# Question
Title: How do I take out the caching and bandwidth optimizations sections out of the performance window for a user?
How do I take out caching and bandwidth optimizations sections out of the performance window for a user?

# Answer
> 1 votes
You can use the `#access` property to do this. You would just need to wrap things up in your own logic.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  if (user_cant_access_this_stuff()) {
    $form['caching']['#access'] = FALSE;
    $form['bandwidth_optimization']['#access'] = FALSE;
  }
}

```

I am not 100% sure on those `$form` elements (this was taken from something similar I have on a site), so you may need to `dpm()` the `$form`.

---
Tags: routes, hooks, users
---


# Question
Title: How to validate email on webform if the field type is textfield and you have data
by mistake, on a webform, in the field e-mail we selected fieldtype = textfield instead of email type, no problem to change it if you do not have data, but if you have data, when you delete the field all your data is gone. o So the email field is NOT validate to enter just email addresses. How to validate this field without export and migrate the data?

# Answer
After a couple days asking google for the solution, I did this. 1. Install the module https://drupal.org/project/webform\_validation this will add another tab on your webform. 2. select "Regular expression, case-insensitive" 3. add the next regex (regular expresion) ^\[\_a-z0-9-\]+(.\[\_a-z0-9-\]+)*@\[a-z0-9-\]+(.\[a-z0-9-\]+)*(.\[a-z\]{2,3})$ 4. select your email field to validate and add some text to the error message. that's it... from now on all your email will be validate, but the old data must be fixed by hand... the good thing, is you do not need to migrate your data just for fix it..

hopefully this will be helpful to someone... best
> 2 votes

---
Tags: webforms, emails, migrations
---


# Question
Title: Menu Block - stopping displaying children after a specific level
So I am using Menu Block 7.23 and it is working awesome, I have it setup to start at 2nd level to show the children of the active menu, and if no children show active menu with max depth of 1 which has been working great.

I have been asked to make this navigation now, stop displaying the children after the 3rd level and I am not sure how to handle that in Menu Block configurations. I see there is a start level, but not a stop level. Here is an example of my heirarchy:

-Solutions
--Enterprise
---Profile Management
----Online/Offline

So essentially when going to Solutions it would show Enterprise, when going to Enterprise it would show Profile Management, but on Profile Management they do not want Online/Offline to appear, they want Profile Management to remain as the side menu. They want the breadcrumb to show the whole path on Online/Offline so I cannot just disable it from navigation, it needs to be part of the menu structure.

They want to just put reference links to Online/Offline in Profile Management page content, and on Online/Offline it would keep the Profile Management side menu.

Any help would be most appreciated.

# Answer
You could use 'display:none' in the css as a solution. I think using Nth-child would help achieve what you need http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/
> 1 votes

---
Tags: entities, navigation
---


# Question
Title: When you recreate a Feature, do you need to uninstall and re-install it?
When you recreate a Feature, do you need to uninstall and re-install it or is it OK to just delete the feature folder and paste the new on in its place?

# Answer
just delete the feature folder and paste the new folder. You should not get any issues.
> 1 votes

# Answer
Instead of deleting the folder just download the tar.gz file and extract it in the folder where the features folder is there. I would automatically merge the changes.
> 2 votes

---
Tags: 7, features
---


title: Migrate into custom File Type

text:
# Question
Title: Migrate into custom File Type
I am writing the script for a file migration and am using the `MigrateDestinationFile` method. I noticed that when I migrate the files that they default to the `Document` file type. However, I have created custom file types and want the files to be migrated to those file types.

How can I do so?

I was hoping I could do something like this, but it's not working:

```
$this->destination = new MigrateDestinationFile('custom_file_type');

```

# Answer
> 1 votes
I really wish this was better documented. In addition to the above you need to add a field mapping to the type:

```
$this->destination = new MigrateDestinationFile('custom_file_type');
$this->addFieldMapping('type')->defaultValue('custom_file_type');

```

That's it!

---
Tags: files, migrations
---


title: Compile files from URLs in table as zip

text:
# Question
Title: Compile files from URLs in table as zip
I've got a Views table with a column displaying links to files (images, pdf's etc.). I've got a button below the table that exports the entire table. I need another button that should start a .zip download of all images currently shown in the table. The table has a filter on it, so it's important that only the files from the filtered results are downloaded.

I haven't been able to find a module or similar use case, so I hope there's someone here that can point me in the right direction.

Cheers,

# Answer
> 0 votes
Enable the PHP input filter and add a text area to the footer of your view, then use something like the following to build an array of all of your files (taken from this tutorial):

```
<?php
function views_get_current_view_result() {
  $view = views_get_current_view();
  return $view->result;
}
?>

```

And then use that array to build the zip according to download multiple files as zip in php

This would be a lovely idea for a views display handler plugin module, which many would probably find useful.

---
Tags: files, theming, importing-exporting
---


# Question
Title: Transfering a drupal site from localhost to online and viceversa
I am about to finish my first Drupal site and I wish to upload it on the server. However, I am going to add content when the site is online but every time I make a change online I would like to add that change to the site on localhost (changes in content, new module additions, etc.). What is the least time consuming way to achieve this? With .html sites it is very easy because you only need to have the .html file saved offline and online and that it is. What things do I need to consider with a Drupal site? I would like to always have the exact same files, modules, content, configuration on the online version and the offline version of my site.

Thanks in advance.

# Answer
the best way will be to use Git to keep you code updated and Features to keep you configuration up to date.

A good free source code hosting for git is BitBucket. It gives you unlimited private repositories but limited users. Github gives you unlimited users but you pay for private repositories. Anything you change in code can be hosted in one of those code hostings and you can push it from dev (your local) and pull it from your production environment (live). Git keeps track of all your changes.

> Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

For site configurations you can use Features

> the features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.

You can use Features module along with: Strongarm

> Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.
>
> An example of such a variable is site\_frontpage. In Drupal this defaults to node, which ensures that the front page gets content as soon as some exists, but for many Drupal sites this setting is simply wrong. Strongarm gives the site builder a place in the equation - an opportunity to set the site\_frontpage to something that makes sense for their site.

and Features Extras

> Features Extra provides faux exportables (via Features) of several site-building components

This will be a good way to keep your code and your configuration aligned between two environments.

Second option, if you are not familiar with Git, you can just use an FTP software, download or upload files and then use Backup and Migrate

> Back up and restore your Drupal MySQL database and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

For your files folder you can use an FTP software.

To synronize nodes, you can use Deployment.

> The Deploy module is designed to allow developers to easily stage Drupal content from one site to another. Deploy automatically manages dependencies between objects (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of situations.

Here is the documenentation about the module. Create 2 sandboxes and give a try to it. It also works with features.

For code and configuration sync, I strongly suggest you to use Git and Features.
> 2 votes

# Answer
One of the ways to do it is by using Backup Migrate Module with Backup Migrate Files Module for backup of database and files respectively. The steps will consist of taking backup on live server and restoring on localhost, and can be done entirely through the interface.

There are ways by which you can automate it too but that will need configuring some scripts and writing custom code. For that one way to do it is outlined at here (taking backup) and here (restoring backup)
> 0 votes

# Answer
I would suggest using source code management system like git for your code deployment to different servers.

And in order to deploy manual configurations which reside in database, you can use features module with other helping modules like strongarm etc. features will pull all your configurations in code by creating feature module, which is easy to deploy on different instances. While creating features just try to keep them as simple as possible, only pull those configurations which are doing manually and always try to make a feature module to serve independent set of related functionalities.
> 0 votes

# Answer
The solution would depend on what are you planning to do with the local copy

This is not a new problem and the whole industry is trying to move in this direction. CMS based systems like Drupal have a very involved database component, which cannot be satisfied by just a source control repo like Git. You can host your code on a git repo via Github or beanstalk. That can help keep the code in sync.

When it comes to databases, it would depend on whether you are planning to alter the database on your localhost.

* If not, then you can simply point to the server database on your local. Thus you can easily mirror the online copy. Combining this with the git repo approach could help keep your local site in sync with the online site.
* If yes, then there will be need for a manual db update every so often. Here, you can think of your sever db as the "source" whose copy you trust and then you can pull it down at the end of day. There is an easy way do this via rsync commands and a command line insert in to your local db.
* Alternatively you can also use SequelPro which is very handy in pulling down databases from server.

As mentioned before, the correct approach would depend on what you have in mind for your local site.
> 0 votes

---
Tags: database, migrations
---


# Question
Title: Why do I have to enter a recipient after selecting users in the VBO send emails operation?
I'm using VBO module in D7. I created a table view listing users by some filter criteria. I want to send a mass mail to selected users. I'm using the VBO field *bulk operations: user* and selected the *send email* functionality. The view looks like that:

Selecting multiple users and hitting the send email *execute* button brings me to this form:

Why do I have to enter a recipient after selecting users in the view? What does that *send email* operation do if not sending emails to the selected users?

Is it my fault and I messed up the installation or did I miss some settings or configurations?

# Answer
> 5 votes
VBO does not provide the "send email" function. It is provided by core actions and it really doesn't know the context that it is being used in. Therefore, you need to insert a token in the "Recipient" field as mentioned in the help text just below the field e.g. user:mail , node:author:mail etc. I can't tell for sure what the base table your view is using based on your screenshot but it looks like you can use the token \[user:mail\].

If you would like to have this info prepopulated you need to use the views send module. It used to support VBO but it now provides it's own UI. It's a pain if you want to combine it with a VBO view as you get double checkboxes etc...

See http://drupal.org/node/575980 for more info

# Answer
> 1 votes
I think it is so that you can select which address to use. all tokens are available. you probably want to enter \[user:mail\] in most cases. works fine with vbo

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


# Question
Title: Problem: users are logged out automatically without any reason, while navigating to the website
Hi After some time Im having a very serius problem, while logged in users interact with the website they are logged out without any reason.

For example, I log in, then I interact some minutes with the website, then for example I try to access to create an article (or whatever) then I get an access denied because I was logged out automatically, I do not know why...

Any idea?

# Answer
> 2 votes
There are some settings regarding cookie session lifetime in the settings.php file. These settings might not be allowed for overwriting and your server might have its own rules.

```
 ini_set('session.cookie_lifetime', 2000000);
 ini_set('session.gc_maxlifetime', 200000);

```

Check admin/reports/status/php.

---
Tags: 7, users
---


# Question
Title: How can I hide field labels without using any CSS style?
How can I hide field labels from Drupal (without CSS)?

---

```
function clean_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "user_register_form") {
    $form['account']['name']['#title'] = Null;
    $form['account']['name']['#description'] = Null;
    $form['account']['name']['#attributes'] = array('placeholder' => t('Имя пользователя'));

    $form['account']['mail']['#title'] = Null;
    $form['account']['mail']['#description'] = Null;
    $form['account']['mail']['#attributes'] = array('placeholder' => t('mail'));
  }
}

```

I don't know how to write for password and date.

# Answer
Go to "Admin \> Content Type \> Manage Display" and hide the labels as shown in the screenshot.
> 10 votes

# Answer
If you need to hide field labels in a node or nodes of one or more content types, and you want to do it conditionally, you can use `template_preprocess_page()` like so:

```
function mytheme_preprocess_page(&$variables) {
    if($variables['node']->type == 'yourNodeType') {
        // hide what you wish here
    }
}

```
> 1 votes

# Answer
just hide the label by going in content type-\>select the content type-\>manage display..then under the tag LABEL ,select hidden in tha select list options.
> 0 votes

# Answer
If you are using Drupal 6 then the manage display link won't be visible. then you need to manually alter the form using `form_id` and `hook_form_alter` by creating your custom module (The following code works in Drupal 7 too..). For Ex.

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'your_form_id') {
     $form['password_field_name']['#title'] = NULL;
     $form['date_field_name']['#title'] = NULL;
   {
}

```

you need to first debug `$form_id` for which you need to alter the fields in your `mymodule_form_alter()` function and then debug the `$form` for your specific field names of `password_field_name` and `date_field_name`.

Hope this helps.
> 0 votes

# Answer
If you are using default user register form then

```
$form['account']['pass']['#title'] = NULL;

```

If you have added manually by going into content-type then add this line in alter hook

```
$form['field_password'][LANGUAGE_NONE][0]['value']['#title'] = NULL;

```

\['field\_password'\] will change according to you. EX :
If you have created a field with name **Password** then it will have `'field_password'`
Hope this will help you and other
> 0 votes

---
Tags: 7, entities
---


title: show PDF absolute URL in Views table

text:
# Question
Title: show PDF absolute URL in Views table
I've got a column of links to files in a table. They're displayed via file-fields with 'Output this field as a link" enabled in *Rewrite Results*. It's works great with fx images but width pdf's the table only shows the filename, not the path to it.

Any ideas on how to always show the complete path to a file no matter the file type?

# Answer
> 0 votes
1. In views Change the **Formatter** of the field from *Generic file* to *URL to file*.
2. Go to *REWRITE RESULTS* and check 'Output this field as link' and use replacement pattern of the file field.
3. check Use absolute path to get absolute path link of the file

That's it you will get complete path of the file instead of file name at output.

---
Tags: views, uri, files
---


# Question
Title: Why is Views ignoring nid as second argument?
I create a view with two arguments: Taxonomy ID (tid) and Node NID (nid). I leave the default settings for tid and set a default argument for nid to a fixed value (let's say: 1). The tid argument is configured so that all values are shown in case it is not present. This should show all nodes except the one with NID 1.

BUT: This only works if the NID argument is the first argument. If it's the second argument, it is excluded from the query:

Query with nid as first argument:

```
SELECT node.nid AS nid
FROM node node
WHERE node.nid != 1  OR node.nid IS NULL

```

Query with nid as second argument:

```
SELECT node.nid AS nid
FROM node node

```

I'm wondering why that is? What I want to accomplish is actually to exclude the result of one view from another. To do that, I add nid as an argument, get the nids of a different view and tell views to exclude them. That works just fine, but only if nid is the first argument. But I need to have taxonomy as the first argument and I don't understand why that excludes my nid argument.

Although in a different context, I think I had the same problem here: https://stackoverflow.com/questions/20248929/filter-a-drupal-view-displayed-in-a-panel-by-taxonomy-term-depending-on-domain

# Answer
It seems that views ignores the second argument in case the first argument is not present, although the first argument is configured to show all values if it is not present. Setting the following PHP code as default argument for the taxonomy term solves my problem:

```
if (arg(0) != 'taxonomy') {
  return 'all';
} else {
  return arg(2);
}

```
> 2 votes

---
Tags: views
---


# Question
Title: Can't get the authenticated user cookie session to be used when creating a new node via Services 3 endpoint
My application is sending this header to Service 3 endpoint when creating a new node:

```
{
  'Cookie': 'SESS255f42d9a87a0df5bf8959d25909fe8c=St8o29NI9Hx84kPo8NuZbpdHWuRgNSS9qy9cQ-QM4rA; expires=Sun, 15-Jun-2014 00:39:27 GMT; path=/; domain=.mydomain.local; HttpOnly',
  'Content-type': 'application/json'
}

```

Nonetheless, the newly created node user is set to anonymous.

Is there anything wrong with the header I am sending?

# Answer
Solved it.

I should've had checked **Session authentication** at `admin/structure/services/list/MYENDPOINT/edit`
> 0 votes

---
Tags: services, 8, sessions, cookies
---


# Question
Title: rule to remove "Public files directory Not fully protected" in nginx?
I use D7 with nginx and php5-fpm on Linux and get this security warning:

> Public files directory Not fully protected

I see here that one needs to use this snippet in Apache's htaccess to resolve the issue:

```
# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</files>

```

Just wondering what should be the nginx equivalent rule?

**Update**: I already have this in my nginx configs:

```
root   /path/to/drupal;
}

location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
                return 404;
        }
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
}

```

# Answer
> 3 votes
The .htaccess file won't have any effect in Nginx. You'll need to add your own rules to prevent PHP execution in the files directory.

e.g:

```
# Allow access to index.php only
location = /index.php {
  include fastcgi.conf;
  fastcgi_pass    127.0.0.1:9000;
}

# Any other attempt to access PHP files returns a 403.
location ~ \.php$ {
  return 403;
}

```

However, to fix that error message, you can actually just delete the old .htaccess file and Drupal will recreate a new correct one.

Note: the check is in `system_requirements` with the line

```
if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {

```

It only checks for that line, Drupal doesn't currently validate an actual PHP request to the relevant directory to test the handler.

---
Tags: 7
---


# Question
Title: How can I override Drupal\Component\Datetime\DateTimePlus::createFromArray
I have to form datelist field. If user select incorrect date, for example `1970-02-31`, displayed exception Exception:

> The array contains invalid values. in Drupal\Component\Datetime\DateTimePlus::createFromArray() (line 149 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

backtrace:

> 1. Drupal\Component\Datetime\DateTimePlus::createFromArray() called at \[/var/www/drupal8/core/modules/datetime/datetime.module:802\]
> 2. form\_type\_datelist\_value() 2 call\_user\_func\_array() called at \[/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1542\]
> 3. Drupal\Core\Form\FormBuilder-\>handleInputElement() called at \[/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1328\]
> 4. Drupal\Core\Form\FormBuilder-\>doBuildForm() called at \[/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1390\]
> 5. Drupal\Core\Form\FormBuilder-\>doBuildForm() called at \[/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1390\]

I want override exception to return FALSE, and display to user warning about incorrect date.

How do I it?

# Answer
As @Daniel Wehner suggests, this can easily be done by wrapping the *calling code* in a `try` \- `catch` block. That's what it is for.
> 1 votes

---
Tags: 8
---


# Question
Title: Search Form block not displaying in Home Page
I am using drupal 7.9 with the Bartik theme. I have configured 'Search Form' block in header area.

It is displayed on all pages, but not in the home page.

Then I customized the page.tpl.php file with the following snippet:

```
if($page['header']['search_form']):
  print render($page['header']['search_form']);
endif;

```

But this doesn't solve my problem. Does anybody know how to solve this?

# Answer
have you looked at the block settings to see if it has something like "display on these pages" or "don't display on these pages" checked and if so it's saying to not show it on ?
> 1 votes

# Answer
I had the exact same problem crop up. On my site, I have a search\_form block in my header. On the block configuration page (admin/structure/block/manage/search/form/configure), someone tried to be helpful and checked every content type under content type restrictions. So the block was showing for all content types, but not on the front page.
> 1 votes

# Answer
Is your front page a panel page?

If it is panel page, do you have the check-box for "disable drupal blocks regions" checked?

If it is checked, then it will hide all blocks regions
> 0 votes

# Answer
Check for the permissions given to your search form. You might be enabling from Admin with no access to Anonymous user
> 0 votes

---
Tags: blocks, search
---


# Question
Title: Why am I getting this error for the schema I define in my module?
I'm building a module for Drupal 7, but I have troubles with my schema, and I don't understand why.

This is my schema.

```
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'unique keys' => array('id')
    );

```

I get this error.

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL DEFAULT NULL, `end_time` NULL DEFAULT NULL, `duration` INT unsigned NOT ' at line 5: CREATE TABLE {table\_name} ( `id` INT unsigned NOT NULL auto\_increment, `nid` INT unsigned NOT NULL, `oid` INT unsigned NOT NULL, `start_time` NULL DEFAULT NULL, `end_time` NULL DEFAULT NULL, `duration` INT unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `0` () ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8; Array ( ) in db\_create\_table() (line 2717 of /Applications/MAMP/htdocs/project/www/includes/database/database.inc).

How can I fix this error?

# Answer
> 1 votes
I've managed to fix it. I've altered 2 things from my original schema, the first issue was that Drupal 7 no longer supports `'type' => 'datetime'`, instead use `'mysql_type' => 'datetime'`. The second was `'unique keys' => array('id')`, I removed this and everything works correctly.

### Solution...

```
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'mysql_engine' => 'InnoDB'
    );

```

# Answer
> -1 votes
Try this for Drupal7,

```
'pubblish_date' => array(
  'description' => t('The pubblish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),
'unpublish_date' => array(
  'description' => t('The unpublish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

```

---
Tags: 7, database
---


# Question
Title: Services REST API and special characters
I'm using REST Services to communicate between two websites.

Once a node is updated on the website 1, part of the information is sent to the website 2. This works without any problems.

However, all special characters, e.g. apostrophes, are received escaped.

For example: "It's a sample page", will be received as "It\\'s a sample page".

Here is the code I'm using:

```
// $data is just an example. It's more complex and the only relevant part is the
// way node title is passed.
$data = array('title' => $node->title);

$curl = curl_init('http://example.com/rest/node/1');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

```

How can I avoid this? Is there any encoding/decoding I need to do prior to building HTTP query?

Thanks!

# Answer
It looks as though your PHP install might be configured with the deprecated Magic Quotes

> When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically.

More info: Disabling Magic Quotes
> 5 votes

---
Tags: 7, services
---


title: Send user's password in mail

text:
# Question
Title: Send user's password in mail
I want to send a reminder email to the users to log in to my website with their username and password. My mail script is ready with the login ID, but I don't know how to decrypt the user's password.

Can anyone tell me how should I get the password associated with a user account?

# Answer
> 30 votes
You cannot get the user's password from what Drupal saves in the database. Drupal doesn't encrypt the password and saves it in the database, but it saves in database the hash of the password, which is the value returned from a one-way function; this means that is not possible to calculate the value that originated the hash.
That is the reason why hashes are saved instead of the passwords: If somebody access the database used by a Drupal site, it is not possible to retrieve the passwords, and access that site as one of the users registered in that site. (It could still possible to find a word with the exact same hash; so far, collision attacks are shown possible in short time only with MD5.)

Drupal is able to send an email to reset a user's password, which is not what you are asking for, but it could be helpful if you want the users to reset their password after X months. In this case, you could be interested to the code used by \_user\_mail\_notify().

```
  // By default, we always notify except for canceled and blocked.
  $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
  if ($notify) {
    $params['account'] = $account;
    $language = $language ? $language : user_preferred_language($account);
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
    if ($op == 'register_pending_approval') {
      // If a user registered requiring admin approval, notify the admin, too.
      // We use the site default language for this.
      drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
    }
  }

```

# Answer
> 15 votes
Please! Don't do that!

Implementing a login system on a web application is easy. Implementing a ***secure*** login system on a web application is a totally different matter. There are many aspects and details to consider, and Drupal does a fine job of dealing with ***just about all*** of those aspects out of the box.

Adding the feature you ask for would greatly reduce the security of your application. If you can decrypt the passwords, you have just stripped your app of a very important security mesure.

Other answers explain workarounds, BetaRide's answer would do what you ask, but be aware I totally agree with his closing statement.

In a very general way, I would probably tackle this in more or less the following manner:

***In a custom module***

1. Implement hook\_cron, this would builds an array containing all emails that match the criteria of your choice.
2. Loop through the array and send the emails via drupal\_mail. Do look into the function `_user_mail_notify()` kiamlaluno linked to up above.

If user has *never* logged in, you ***may*** need to send a reset password mail (not sure here), possibly using a combination of drupal\_mail and hook\_mail\_alter to customise either the registration or the reset password email to your taste.

Hope that helps, I know it is a bit sketchy as I have not implemented anything similar in my Drupal experience so far, I was just pumping out a few ideas on how one could notify users in a secure manner. There are many alternatives to having a plain-text password in the email.

Good-luck friend, cheers to you & happy new-year!

# Answer
> 8 votes
You can use the AES encryption module to get readable passwords.

However there are very good reasons why passwords are not readable in standard Drupal. IMHO using the built in one way pw-recovery links is much more secure.

# Answer
> 0 votes
You can use Account Password Token Module to send password in mail

> **Experimental Project**
>
> This is a sandbox project, which contains experimental code for developer use only.
>
> This small module provides user account password token for account E-mails settings. Site administrator allowed sending the password to user in bellow settings:-
>
> 1. Welcome (new user created by administrator)
> 2. Welcome (no approval required)
> 3. Account activation
> 4. Welcome (no approval required, password is set)
> 5. Password recovery

---
Tags: 7, users
---


# Question
Title: How to reply to a comment through services in Drupal 7?
I am using Drupal 7 as back-end for a mobile application. I am using comments in my application.

Can anyone help me to reply to comment through web-service?

# Answer
This is how I was able to reply to a comment through web-service.

```
 URL:- example.com/rest/comment
 Method : POST
 Parameters:-
 nid :6
 pid: 4
 comment_body[und][0][value]: Some text

```
> 3 votes

# Answer
Adding this answer just in-case someone finds it useful.

**nid = node id**

**pid = comment id you want to reply to**

```
POST http://example.com/rest/comment

Content-Type: application/json
{
  "nid":28,
  "pid":1,
  "subject":"Comment submitted via JSON REST",
  "comment_body":{
    "und":[
      {
        "value":"This is a great article."
      }
    ]
  }
}

```

--Response--

```
<?xml version="1.0" encoding="utf-8"?>
<result>
    <cid>8</cid>
    <uri>http://example.com/api/comment/8</uri>
</result>

```
> 1 votes

# Answer
I hope you are using Services Module 3.x. So you can have a look at the unit test case file http://cgit.drupalcode.org/services/tree/tests/functional/ServicesResourceCommentTests.test?id=refs/heads;id2=7.x-3.x#l100 There have a look at the method testCommentCreate.

```
public function testCommentCreate()

```

This may solve your problem.
> -1 votes

---
Tags: services
---


# Question
Title: How to set image style for media browser in node edit form?
I am using the media browser that is part of the media module to upload or select images on a node edit form. I an image is already uploaded it is shown in the edit form in it's original size. If the image is large this makes the whole edit form unusable. Where can I set the images style, that is used for the edit form?

# Answer
Once you have chosen the image and clicked save and the overlay is closed, images are display in the "Media thumbnail" image style. Did you perhaps change the settings for that image style under admin/config/media/image-styles?
> 2 votes

---
Tags: media
---


# Question
Title: How to use drupal_get_token() within custom user registration email
I'm in the process of writing a custom user registration module for Drupal 7. I currently have my own custom form which calls the function **user\_save** within it's submit handler to create the new user account. The account is initially created as "disabled", and will only be activated once the user verified their account via a link in a custom welcome email.

I have generated a token to append to the URL query string (contained in the email generated by **hook\_mail()** using **drupal\_get\_token()**):

```
$myToken = drupal_get_token('email_verify_'.$params->uid);

```

Unfortunately I'm always getting an Access Denied message when following the registration link within my custom email. I've checked both values storing the UID within the hook\_mail and page callback and they're indeed correct.

Is there anything I'm missing here? I considered using **user\_pass\_reset\_url()** instead, but we capture the user password on registration so we don't want them to have to re-enter their password twice.

Thanks in advance!

**EDIT #2: adding more code for Pontus**

hook\_menu implementation:

```
//callback to verify user via email link
$items['custom_user/signup/verify/%'] = array(
  'title' => 'Activate your Account',
  'page callback' => 'customer_user_signup_verify_email_page',
  'page arguments' => array(3),
  'file' => 'includes/custom_user_signup.verify.inc',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

Check if valid token within **customer\_user\_signup\_verify\_email\_page()** callback function **drupal\_valid\_token():**

```
if (empty($_GET['tok']) || !drupal_valid_token($_GET['tok'], 'email_verify_' . $user_id)) {
    drupal_access_denied();
}else{
    //enable account now that we know you're a valid user
}

```

URL printed in email:

```
http://mysite.com/custom_user/signup/verify/10?tok=Zh2MmBHLnjvd3Dq9KcDxkwJ0lmk_QmMg5QNZomC7Okw

```

# Answer
> 4 votes
The reason this is failing is because `drupal_get_token()` and `drupal_valid_token()` use the value of `session_id()` to generate and validate the token.

The problem is that `session_id()` will return a different value for anonymous users on each page load. So the token generated by `drupal_valid_token()` is different from the one that is generated in `drupal_get_token()` because the input (`sessoin_id()`) is different.

For form submits where you want to compare a token on the next page load for anonymous users, you can call `drupal_session_start()` on the form page which will start a session and ensure that the results of `session_id()` are the same on the form page and the result page. But in your case, where the user is clicking on a link back to the site from an email, the value of `session_id()` will only be the same if it's the exact next page load. My tests indicate that Drupal destroys the session created by `drupal_session_start()` on the next page load.

---
Tags: users, tokens
---


# Question
Title: why don't set the placeholder attribute for contact field?
this is my `hook_form_alter` function for set the placeholder attribute and other stuff:

```
 function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'contact_site_form':
            $form['tel'] = array(
                '#title' => t('Tél'),
                '#type' => 'textfield',
                '#required' => TRUE,
            );
            if ($form_id == 'contact_site_form') {
                $form['name']['#title'] = t('name/family name');
                $form['name']['#attributes']['placeholder'] = t('Enter your name');
            }
                $order = array(
                '1' => 'name',
                '2' => 'mail',
                '3' => 'tel',
                '4' => 'subject',
                '5' => 'message',
                '6' => 'copy',
            );
            foreach ($order as $key => $field) {
               $form[$field]['#weight'] = $key;
            }
            break;
       }
  }

```

why don't set the placeholder attribute for contact field?

`kpr()` for this element shows:

# Answer
> 0 votes
I added this line to code and the problem was solved:

```
 $form['name']['#default_value'] ='';

```

Edited code is:

```
if ($form_id == 'contact_site_form') {
    $form['name']['#title'] = t('name/family name');
    $form['name']['#default_value'] ='';
    $form['name']['#attributes']['placeholder'] = t('Enter your name');
}

```

# Answer
> 0 votes
edit

```
$form['name']['#attributes']['placeholder'] = array(t('Enter your name'));

```

to

```
$form['name']['#attributes']['placeholder'] = t('Enter your name');

```

then execute "flush all caches"

---
Tags: hooks, forms
---


title: Custom Placeholder Module

text:
# Question
Title: Custom Placeholder Module
I have created a custom module to create a few placeholders in form fields. Unfortunately, I am having a little trouble with getting two of them to work. The code I have in the module is as follows:

```
function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if ($form_id == 'user_account_form') {
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    $form['pass[pass1]']['#attributes']['placeholder'] = t( 'Password' );
    $form['pass[pass2]']['#attributes']['placeholder'] = t( 'Confirm Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount[min]']['#attributes'] = array('placeholder' => array(t('Min Price')));
    $form['commerce_price_amount[max]']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }
}

```

(In order) The search block placeholder texts works perfectly. The login placeholders also work perfectly. The register (user\_account\_form) placeholders are not working at all, and I can not figure out why. And the views\_exposed\_form works for the title and sku, but not for the min and max price range?

I need helping figuring out what I did wrong on the register form, and the min/max view filter price range fields.

EDIT: I have gotten everything to work except the registration passwords. When I uncomment the line for the password fields, they are no longer displayed on the page.

```
    function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount']['#process'][] = 'placeholders_process_commerce_price_amount';
  }
  if ($form_id == 'user_register_form') {
    $form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    //$form['account']['pass']['#process'][] = 'placeholders_process_password_confirm';
  }
}
function placeholders_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}
function placeholders_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}

```

# Answer
The user account form stuff is one level up in the `account` container. For the name and email you can use:

```
$form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
$form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );

```

The password is slightly more complicated, as the 2 inputs are created in a process function. You'll need something like:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'user_account_form') {
    ...
    $form['account']['pass']['#process'][] = 'MYMODULE_process_password_confirm';
  }
  ...
}

function MYMODULE_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}

```

See `form_process_password_confirm()` if you're wondering where 'pass1' and 'pass2' come from (it's one of the default process functions for a `password_confirm` element as set in `system_element_info()`).

It'll be the same sort of thing for the slider, but without knowing where that slider comes from (module, custom code, etc) it's difficult to say what the code should be. At a guess based on the input name's you're trying to target:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'views_exposed_form') {
    ...
    $form['commerce_price_amount']['#process'][] = 'MYMODULE_process_commerce_price_amount';
  }
  ...
}

function MYMODULE_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: Correct format of data to send at services endpoint to create node
I have set up a services endpoint using services module and I am using Mozilla Poster add on to test it. I was able to create a user by sending data from Mozilla Poster in x-www-form-urlencoded format with parameter names "name", "pass" and "mail". Now I am trying to create a node but it is showing the error: "Title field is required".

What should be the parameter name for title field to be sent to the services endpoint? I tried using "title", "field\_title" etc but it is not recognizing it. There is a nice tutorial here to determine data structure to be sent to create a node at remote website. But this tutorial tells how to send data in json format. I want to send data in x-www-form-urlencoded and create a simple node. The HTML code of title field of node create form at my remote website is:

```
<input class="text-full form-text required" id="edit-title-field-und-0-value" name="title_field[und][0][value]" value="" size="60" maxlength="255" type="text">

```

Kindly help me to figure out correct format to send title value in x-www-form-urlencoded format from Mozilla Poster in order to create a node.

# Answer
In the html code of node add form as provided by you, title field has name "title\_field\[und\]\[0\]\[value\]". You have to use exactly this name/key in your POST request. Along with that, you also need to send a value with name/key "title". Both needs to be sent. However the value of "title\_field\[und\]\[0\]\[value\]" will be filled as title in the created node.
> 1 votes

---
Tags: services
---


# Question
Title: After installation of Drupal commons-7.x-3.13 in windows. I got this type of error?
I am using Drupal Commons-7.x-3.13 module to install in windows. After installation I can't logged my site.

Please help anybody. I am in critical situation.

# Answer
You need to allocate more memory. There is not enough for mysql to run. There is an entire handbook page dedicated to this common issue. See https://drupal.org/node/259580
> 2 votes

# Answer
Edit your `my.cnf` file.

In case of linux you need to use : vim /etc/mysql/my.cnf

Tweak/decrease these values as required.

```
wait_timeout = 600
max_allowed_packet=500M

```

and restart mysql

```
sudo /etc/init.d/mysql restart

```
> 1 votes

---
Tags: 7
---


title: Getting the exposed form to show up

text:
# Question
Title: Getting the exposed form to show up
I'm trying to get the exposed form to show up for one of my views, but it doesn't seem to be working.

I've got filters exposed in the "Filter Criteria" section, the "Exposed Form In Block" section is set to "Yes", and the block itself has been activated and placed into one of the sidebars, but its still not showing up.

Am I forgetting to do something here?

Edit: Forgot to add that I'm using Drupal 7

Edit 2: Found a post that says to turn Ajax on to get the form to display, but that doesn't work either.

Edit 3: So turning off the "Exposed Form in Block" option gets the filters to display, but for theming purposes I really need this stuff in a block.

# Answer
Are you filtering your block to only display on certain pages? It could be that the block is not displaying because of your filtering constraints.

Another thing to check is to make sure the region you have placed the block in exists on that particular page.
> 1 votes

# Answer
Check Block is rendering correctly in the region you want to show.
Try to put any other block in that region and see is it visible or not.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: List returned by drush site-alias is correct, but drush @sites finds an incorrect list
I'm using drush 7.x-4.5, Drupal 7.28, Apache 2.2.21, PHP 5.3.8. I have a multi-site installation, with a dozen or so sites, such as:

```
/path/to/drupal/sites/example1.com
/path/to/drupal/sites/example2.com
/path/to/drupal/sites/example3.com

```

Each of these is a symlink to some other location, which is not entirely uniform, e.g.:

```
example1.com -> /home/example1/drupal

```

...but another site might be:

```
example2.com -> /home/example2/www

```

If I run `drush -r /path/to/drupal site-alias`, I get a correct list of sites:

```
example1.com
example2.com
example3.com

```

However, if I then try to do something like `drush -r /path/to-drupal @sites status`, I get something unusable:

```
You are about to execute 'status' on all of the following targets:
  #drupal
  #www
  ...

```

So I can see it's just resolving the symlink and grabbing the last component of the path, then flattening that down to a set of unique last components of paths, which of course does not work at all.

I have tried filling out aliases with `/etc/drush/aliases.drushrc.php`, and while the aliases work in the single-site context (e.g. with `$aliases['e1'] = array('root' => '/path/to/drupal', uri => 'example1.com')`, the command `drush /path/to/drupal@e1 status`). The list that the `@sites` comes up with is unaffected.

Have I just set up this multi-site installation in an unusual way? It seems to otherwise be fine.

For what it's worth, I have a parallel Drupal 6 multi-site installation, and it has essentially the same problem.

# Answer
> 0 votes
The drush maintainers avoid multisite, so there is a possibility that some bugs might exist here. The version of Drush that you are using is very old, though; upgrading to Drush 6 would be advisable. @sites might even work for you then, as some work has been done for multisites and symlinks since Drush 4.

The best thing to do, however, would probably be to make an alias group. Make a file called `/etc/drush/groupname.aliases.drushrc.php`, and define aliases 'e1', etc. as you show above, one for each of your multisites, all in the same alias file. Then, simply:

`drush @e1 status` \- show status on just one site

`drush @groupname status` \- show status on all sites defined in the aliases file 'groupname'

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


# Question
Title: Views: Computing user's age "on the fly"
Is there a way to compute the age of a user *on the fly* in the "rewrite result" section of a date field?

I am trying to avoid computed field and having to use cron on that one. What I would like to achieve is having the age calculated and displayed on the fly in a date field (date of birth) included in a view.

Any and all input on this will be greatly appreciated. Thank you. :)

# Answer
This might help you with the "on the fly" age calculation:

Then use the Views PHP module to implement it in your view. Or if you want to use the SQL method you could use the Views Raw SQL module.
> 1 votes

---
Tags: views, entities, datetime
---


title: Custom status message on a Views page

text:
# Question
Title: Custom status message on a Views page
I have different urls :

* domain.com/blog : a list of articles made with Views module
* domain.com/blog/article-title : article alias
* domain.com/newsletter/confirm/add/xyz/ok : confirmation link sent to new subscribers by email by Simplenews module
* domain.com/blog/ok : page to which subscribers are redirected after they click the confirmation link (simplenews passes the last arg to the redirect page)

For now, domain.com/blog/ok returns the same as /blog or a 404 (if I set the Global:null contextual filter in Views). I'd like new subscribers to be redirected to the blog page **with a custom status message** (for instance "You're now subscribed").

I guess it's something with hook\_menu ? or MYTHEME\_preprocess\_page ?

# Answer
In case someone's interested, I finally got it fixed implementing a simplenews hook :

```
function MY_MODULE_simplenews_subscribe_user() {
  drupal_get_messages('status'); // Flush default simplenews status message
  drupal_set_message(t('My custom message'), 'status'); // Set my own message
}

```
> 0 votes

---
Tags: views, theming, routes, emails
---


# Question
Title: File upload disappears in Web File Manager
I am trying to upload files to our Web File Manager (in Drupal 6.31), and while everything seems to work fine the file does not appear in the directory list afterward. It does not exist on the server either.

I checked the permissions on the default WebFM folder, and it is 775. I am logged in as the first (super admin) user. I am not receiving any error messages. There are no available updates for Drupal Core or WebFM.

What could be going wrong?

Thanks in advance!

# Answer
> 1 votes
This is a critical bug of Web File Manager module that sates "files are being deleted while browsing WebFM with Chrome" (Considering that you have been using chrome to upload files your Web File Maanger) For more reference please refer to this.

---
Tags: files
---


# Question
Title: How do I manage the meta tags 'title', 'description' and 'keywords'?
I enabled the **Panels** module and created a **panel page** for a page in my site.

How do I manage the metatags 'title', 'description' and 'keywords' for a page generated for this panel page?

Any module to do it?

I need it to do it dynamically.

# Answer
Nodewords module will help in this regard. This module will help to add meta tags on nodes and custom pages as well.
> 5 votes

# Answer
Nodewords is for Drupal 6 only. For Drupal 7 use the Metatag module.
> 3 votes

# Answer
If you are in Drupal 6 and you use Nodewords, you must:

* use custom pages configuration by URL to apply to Views.
* use 'node template' page if you use Panels.

Good luck
> 0 votes

---
Tags: panels
---


# Question
Title: How do I alter certain module form output
Some of my node types use fields from extra modules (such as Open Hours or Get Locations). How do I change the way those modules render their fields inside the form? I mean Get Location for example renders fieldset with fields in it. I'd like to change it at all. Also I'd like to change the order of fields and so on. Is there anyway to make it using something like field--field-name.tpl.php for output fields? Sorry if this is a common question but I couldn't find any complete guidance on this.

# Answer
> 1 votes
The form elements for fields (or "Field Widgets" as Drupal calls them) are defined using `hook_field_widget_form()`, e.g.

```
function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return array('value' => $element);
}

```

They use the form API, and don't have associated templates/themes unless one is explicitly set on a contained element.

You can use `hook_field_widget_form_alter()` to manipulate the elements; the simplest example (from the docs) would add a class to a particular element:

```
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

```

But obviously you're only limited by what the form API can do. So if you wanted to provide a specific theme for an element:

```
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'mytype') {
    $element['#theme'] = 'MYMODULE_some_theme';
  }
}

```

Then it would just be a matter of implementing `hook_theme()` and creating the template file to do what you need.

Just for posterity (and because I accidentally answered the question with this first time round); the following relates to formatting the output of a field when its parent entity is displayed:

As listed in Drupal 7 Template (Theme Hook) Suggestions, and originally defined in `template_preprocess_field()`, these are the built-in patterns you can use to override specific field templates:

* field--field-name--content-type.tpl.php
* field--content-type.tpl.php
* field--field-name.tpl.php
* field--field-type.tpl.php

You could also add your own using a template preprocess hook:

```
function MYTHEME_preprocess_field(&$vars) {
  // This will let you use field--foo.tpl.php as the template name for any fields that pass the condition.
  if (some_condition()) {
    $vars['theme_hook_suggestions'][] = 'field__foo';
  }
}

```

As far as changing the order of field output goes, that's usually done through the UI in the "Manage Display" forms available for the various view modes for each entity type.

---
Tags: theming, forms
---


# Question
Title: Is it possible to translate image Title and Alt fields and sync images between tranlations?
Since it would be much easier to manage site with images synchronized. But I have to translate Title fields too.

# Answer
> 0 votes
Assuming you're talking about images uploaded to the site by users and administrators (and *not* static images that are integrated into the site as parts of a theme or a module), *and* you're talking about Drupal's core locale framework for translation and the built-in extensions available through the i18n module, the answer is "no".

Like everything else, it is of course possible to create a custom module to manage translation of image title fields (preferably as a submodule of some popular image management module), but I am not aware of anything like that already exists.

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


title: Form within a block

text:
# Question
Title: Form within a block
I'm using `drupal_get_form('event_signup_form')` to embed my custom form inside a block. The form is being rendered as intended, but submitting the form triggers nothing.

The form function itself is called `event_signup_form($form, &$form_state)` and the submit function is called `event_signup_form_submit($form, &$form_state)` but it's not being called.

I am using hook\_block\_view to show the form:

```
function event_block_view($delta = '') {
$blocks = array();
if ($delta ...) {
$blocks['content'] = drupal_render(drupal_get_form('event_signup_form'));
}
}

```

I managed to get this working - here is how (stub):

```
function hook_block_view($delta = '') {
$blocks['content'] = drupal_render(drupal_get_form('event_signup_form'));
}

function event_signup_form() {
// Register form submit handler, same goes for validation handler
$form['#submit'][] = 'event_signup_form_submit';

return $form;
}

function event_signup_form_submit($form, &$form_state) {
// This is now triggered
}

```

# Answer
> 15 votes
As of Drupal 7, drupal\_get\_form() returns a render array instead of a string, so try using:

`drupal_render(drupal_get_form('event_signup_form'));`

to embed the form in the block. For information, see the section drupal\_get\_form() returns a render array instead of a string in the article Converting 6.x Modules to 7.x

Also, I believe your function `event_signup_form($form, &$form_state)` should just be `event_signup_form()` (without arguments).

# Answer
> 12 votes
My bet is that `$form['#submit'][] = 'event_signup_form_submit';` is the culprit. You set that only if you want an extra submission handler.

This is a working sample code.

```
<?php
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks = array();

  $blocks['MYBLOCK'] = array(
    'info' => t('My block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

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

  switch ($delta) {
    case 'MYBLOCK':
      $block['subject'] = t('My block title');
      $block['content'] = drupal_get_form('MYFORM_form');
    break;
  }
  return $block;
}

/**
 * Custom form.
 */
function MYFORM_form($form, &$form_state) {
  $form['MYFIELD'] = array(
    '#type' => 'textfield',
    '#title' => t('Some Field'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit Button'),
  );

  return $form;
}

/**
 * Custom form submit function.
 */
function MYFORM_form_submit($form, &$form_state) {
  // You need the have Devel module enabled for dpm() to work.
  dpm($form_state);
}

```

---
Tags: 7, blocks, forms
---


# Question
Title: how to combine profiles and content types in a view
I'm trying to filter some content with a view, But view provides access to single entity type. I want to add the fields from `profiles` and `content types`. I'm wondering Is it possible to include both `contents` and `profiles` in a single view. I have spent lot of hours searching on web to find a solution for this, but didn't helped.

In this image I have selected `content` and it allows only to access the elements of `contents`. But I also want to `filter` the result by matching the contents of a `content type` and a `profile`.

Can anyone provide me a better solution to solve this problem....

# Answer
With Content-type view, you can use the "relationship" feature in Views and have access to the profile fields of the author of a certain node that is listed in the view. The same is valid for the Filters of that view.

To do so, edit your view and expand the "Advanced" settings section on the right. Then click on Relationships -\> Add and add the relationship "Content: Author".

Hope that helps.
> 0 votes

---
Tags: nodes, views, users
---


# Question
Title: How can i load a specific CSS file for a specific View?
What's the best way (best practice) to load a specific stylesheet for specific View. i managed to do it like this, in the template.php file but i'm thinking this is pretty awkward and there is a better way.

```
if($variables['theme_hook_suggestions'][0] == 'page__dvd_products') {

drupal_add_css(path_to_theme(). '/css/dvd-product-display-view.css', array('group'=>CSS_THEME));
} else {

drupal_add_css(path_to_theme(). '/css/dvd-product-display.css', array('group'=>CSS_THEME));
}

```

what is a better way to do this? i'm still kind of new at this. any feedback would be greatly appreciated. thanks

# Answer
Looks like you need Code per Views Display module.
> 0 votes

# Answer
I'd avoid installing additional modules when you don't have to. If you have a custom module, you can use hook\_views\_pre\_build(&$view) as in below:

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'NAME_OF_VIEW_HERE') { // put the name of the view here
    drupal_add_css(path_to_theme(). '/css/dvd-product-display-view.css', array('group'=> CSS_THEME));
  }
}

```

See https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_build/7 for more info on hook\_views\_prebuild(&$view).

Also, if you use Views PHP (https://drupal.org/project/views\_php), you can add a PHP area to the header and add the drupal\_add\_css() lines there.
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to place all form buttons on top of the page, before the form, in all forms?
Since these forms can get quite big sometimes, especially with a lot of files attached and default preview for them.

Related, but not the same: How can I display a form button on top of the form?

# Answer
You can do that using `hook_form_alter()` and setting the weight of `$form['actions']` to a very small negative number. Note that this applies only those buttons wrapped in `$form['actions']`. For other buttons that they aren't, you should add them manually.

```
function YOURMODULE_form_alter(&$form, &$form_state) {
  $form['actions']['#weight'] = -1000;
  // a button that is not wrapped in actions.
  // assuming it's id is 'submit'
  $form['submit']['#weight'] = -1000;
}

```
> 2 votes

# Answer
The module for that is part of the Util package and is called, unsurpsingly, Top Buttons.

## Drush:

```
drush dl util
drush en -y top_buttons

```
> 1 votes

# Answer
Adding to the answer above, #weight needs to be accessed with a preceding #. Also, you should check if the form elements exist before modifying them to avoid getting warnings in your logs.

Something like the below might work:

```
function YOURMODULE_form_alter(&$form, &$form_state) {
  if (isset($form['actions'])) {
    $form['actions']['#weight'] = -1000;
  }
  if (isset($form['submit'])) {
    $form['submit']['#weight'] = -1000;
  }
}

```

Also, this solution assumes you have a custom module for your site. If you don't, you'll need to research how to set one up first.
> 1 votes

---
Tags: forms
---


title: Programmatically redirect

text:
# Question
Title: Programmatically redirect
I'm creating an action to trigger on a rule when a user is logged in. I have a field of the user that is a term reference.

I would like to redirect to the url field of the chosen term. This is how I get the chosen url:

```
$tid = $user->field_redirect_field['und'][0]['tid'];
$taxonomy = taxonomy_term_load($tid);
$url = $taxonomy->field_url['und'][0]['safe_value'];

```

I receive a perfect url like **stocklijst/gezocht** (this works ok). Now I would like to redirect to that url. I've tried this:

```
drupal_goto($url);

```

But it doesn't redirect. It always goes to the front-page...

**UPDATE:**

This is what I do now:

I have a rule (When user logged in) that triggers a custom action "Redirect to user url". It's a custom action like this:

```
function redirectonlogin_rules_action_info() {
    $actions = array(
        'redirectonlogin_redirect_login' => array(
            'label' => t('Redirect on login'),
            'group' => t('My custom actions'),
            'parameter' => array(
                // curent user
                'user' => array(
                    'type' => 'user',
                    'label' => t('User'),
                    'description' => t('The current logged in user.'),
                    'save' => FALSE,
                ),
            ),
        ),
    );
    return $actions;
}

function redirectonlogin_redirect_login($user) {
    // REDIRECT TO USER REDIRECT FIELD
    $tid = $user->field_redirect_field['und'][0]['tid'];
    $taxonomy = taxonomy_term_load($tid);
    $url = $taxonomy->field_url['und'][0]['safe_value'];

    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');
    drupal_goto($url);
}

```

The user can select a url in a select list. These are taxonomy terms... .

This works perfectly. But it takes some time, could there be a cleaner way and faster way of doing this?

# Answer
Ideally, you could use hook\_user\_login(&edit, $account). This hook runs after a user logs in and isn't dependent on the Rules module:

```
function redirectonlogin_redirect_user_login(&$edit, $account) {
  $term = taxonomy_term_load($account->field_redirect_field['und'][0]['tid']);

  // These 2 lines may not be required depending on your set up.
  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');

  $edit['redirect'] = $term->field_url['und'][0]['safe_value'];
}

```

But if something is interfering, like a drupal\_goto() in another module that forces a redirect to the normal landing, you might need to replace:

$edit\['redirect'\] = $term-\>field\_url\['und'\]\[0\]\['safe\_value'\];

with:

drupal\_goto($term-\>field\_url\['und'\]\[0\]\['safe\_value'\]);

drupal\_goto() forces a redirect and will ignore anything that comes after it in the page request.
> 1 votes

# Answer
You could use `hook_form_alter`(), In this hook we could redirect with `$form['redirect'] = $url;`
> 2 votes

---
Tags: users, rules, redirection, taxonomy-terms
---


title: Fatal error after disabling ctools

text:
# Question
Title: Fatal error after disabling ctools
I was getting fatal error to do with ctools along the bottom of each page of my site. To try to fix the issue I logged in as admin, and disabled 3 ctools modules in my website:

* Custom Content panes
* Page manager
* Views content pane

This gave me an error page and my site is totally inaccessible or viewable. I turned them back on manually in the database, but now I get this error message:

> Fatal error: Call to undefined function page\_manager\_get\_task() in /var/www/mywebsite.com/httpdocs/sites/all/modules/ctools/page\_manager/plugins/tasks/page.inc on line 266

Does anyone know how to fix this?

# Answer
> 0 votes
Its really hard to figure out a solution for your issue without trying different options; but I hope the following instructions will help you.

1. Backup your current database
2. Open phpMyAdmin or any desirable MySQL administration tool.
3. Delete all **ctools** modules from `system` table or run this query

`DELETE FROM system WHERE name LIKE '%ctool%'`
4. Drop **ctools** tables `ctools_css_cache`, `ctools_custom_content`, `ctools_object_cache` or run these queries

`DROP TABLE ctools_css_cache`

`DROP TABLE ctools_custom_content`

`DROP TABLE ctools_object_cache`
5. truncate all cache tables (**cache** table and all tables with prefix **cache\_**), example of truncate query

`TRUNCATE TABLE cache`

# Answer
> 0 votes
I had the same problem earlier today and this worked for me......

1. run update.php and update your drupal installation like so http://www.example/update.php or localhost/update.php
2. follow the instructions and update all modules as needed

Hope this helps

---
Tags: chaos-tool-suite
---


title: Related content in drupal 7

text:
# Question
Title: Related content in drupal 7
I'm developing a site in drupal 7 that needs a related content block. The problem is that I tried Similar entries and Similar by terms modules but it looks like they are not compatible with views 7.x-3.0 I'm using, yet.

There is an error message when I install both modules and in the bug reports I found posts with errors just like mine but without good solutions.

I was thinking until the modules are ready, maybe, I can, somehow, use views and show random content based on the taxonomy term in the node and not show the current node.

Is there a way to use contextual filters and use arguments from taxonomy in the current node?

If you know some other way or module to achieve something similar please point me in the right direction.

# Answer
> 2 votes
I've achieved this using a view to pull nodes that share the same taxonomy as your current node.

Basically create a view that uses the 'Has taxonomy term' contextual filter. And also include a content NID contextual filter to exclude the current node (in the list appearing in that view).

Follow the example here to create the view ('Views 3' steps at top): http://www.metachunk.com/blog/adding-related-content-view-drupal-7

I've also taken it a bit further and ticked 'Reduce Duplicates' and 'More \> Allow multiple values'. That way you can specify multiple terms from your current node and only get a node once if it appears in more than one term.

Make sure you select the fields you'd want to see in your template.

My view is also filtered to one content type 'news' so i've named it 'related\_news'. I use the following code in my template.php to grab the views content and pass the template an array. Add your custom fields to the $terms array to then use their ID to find related content.

```
/**
 * Return result of Related News view for a specific node.
 * TO-DO: Add default functionality.
 * @param object $node
 * @return array
 */
function [template]_get_related_news($node) {

    $terms = array();

    //Get terms from fields.
    $terms = array_merge($terms, $node->field_field_term_1);
    $terms = array_merge($terms, $node->field_field_term_2);

    //Build array of ids
    $termIDs = array();

    foreach ($terms as $terms){
        $termIDs[] = $terms['raw']['tid'];
    }

    //Load view
    $relatedView = views_get_view('related_news');

    //Execute view with term ids as argument. Include node id to exlude it from results
    $relatedView->set_arguments(array(implode('+', $termIDs), $node->nid));
    $relatedView->execute();

    return $relatedView->result;

}

```

You could also get the view to produce a block and use this to display the content within your theme.

# Answer
> 1 votes
I think you can do this with panels and views.

create a view listing all the nodes with a taxonomy term in advanced set the context to the term you want to view by create a 'content pane' within that view and set arguments input to that term now create a panel for the original node, attach the view pane to it, and pass the taxonomy to the view pan.

This explanation sounds a little confusing, but here is a great video to help

http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics

# Answer
> 0 votes
Have you tried EVA (Entity Views Attachment) ?

You already have existing views. You can extend that view with EVA. EVA will accept a taxonomy term as input and will attach to that node-bundle where you want to display it. Once you have it installed and created there are only four important and select-able properties.

# Answer
> 0 votes
I think what you are looking for is to show nodes which are related to current viewed node based on terms associated to that node. It can be achieved by creating a view with contextual filters “Content: Has taxonomy term ID (with depth)” and “Content: Has taxonomy term ID depth modifier”.

You can view detail instruction in this blog post - Create related content block view based on terms in Drupal 7

---
Tags: views, nodes, 7
---


# Question
Title: How do I include a class in a link inserted in an entitiy's link area?
I want to insert a link to a ctools modal popup with a custom style (class) into the link area at the bottom of an entity (e.g. a node). I do this using `hook_entity_view_alter`. This is how the relevant part of my code looks like:

```
/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  // Set up ctools etc. to use modal omitted for brevity.
  $build['links']['popup']['#links']['mylink']['title'] = 'show popup';
  $build['links']['popup']['#links']['mylink']['href'] = 'mymodule/nojs/modals';
  $build['links']['popup']['#links']['mylink']['html'] = TRUE;
 }

```

The code shown above inserts the following link in the right place:

```
<a href="/mymodule/nojs/modals">show popup</a>

```

However, this leaves out the class required to give the modal a custom style. This what I *really* want to have this link look like:

```
<a href="/mymodule/nojs/modals" class="ctools-use-modal ctools-modal-mymodule-style">show popup</a>

```

Question: How do I get `class="ctools-use-modal ctools-modal-mymodule-style"` included in this link?

# Answer
You can add the html attributes using the `attributes` key which accepts an array of attributes, and add classes using the `class` key, which also accepts an array of classes.

```
/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  // Set up ctools etc. to use modal omitted for brevity.
  $build['links']['popup']['#links']['mylink'] = array(
    'title' => 'show popup',
    'href' => 'mymodule/nojs/modals',
    'html' => TRUE,
    'attributes' => array(
      'class' => array(
        'ctools-use-modal',
        'ctools-modal-mymodule-style',
      ),
    ),
  );
}

```

More information about available keys, refer to `theme_links()` function in Drupal API.
> 1 votes

---
Tags: entities, chaos-tool-suite, javascript
---


# Question
Title: Change background for authenticated user
I'm pleased with my body background for my site; it looks great when not logged in. But when a user is logged in I need a different one. I need to specify a slightly different background because of the fact that my Marinelli-based D7 site's custom body background (2 horizontal bands of green and black) stays in position but all content moves down almost 100px due to the administrative menu at the top.

An authenticated user would not be able to see the navbar due to this color change (green words on a now green background).

Can I specify an alternate background for authenticated users vs. visitors? Or perhaps better: Is there a way to specify that the body background should move down when the user logs in and all the admin menus show up at the top?

Here's my present CSS for body:

```
body.marinelli{
    background: #fff url(../img/backgrounds/body-background.jpg);
    background-repeat:repeat-x;
}

```

# Answer
> 4 votes
I think your solution would be the class "logged-in" and the CSS property "background-position" to move the background image down 100px for logged-in users:

```
body {
  background: #fff url(../img/backgrounds/body-background.jpg);
  background-repeat: repeat-x;
}

body.logged-in {
  background-position: 0 100px;
}

```

# Answer
> 0 votes
you can override “logged-in” class,because it is definded in function template\_preprocess\_html

# Answer
> 0 votes
I have another plan, you can do it in `html.tpl.php` or in 'page.tpl.php'

do something like this

```
<?php  global $user;
       if($user->uid){
      $bodyclass='class-one' ;
     }
     else {
      $bodyclass='class-two' ;
   }
?>
<body  class ="<?php print $bodyclass;" ?>" >

```

make sure after change `tpl` file clear drupal cache .

# Answer
> 0 votes
You can use

```
body.logged-in{
       /* background css */
}

```

in the main stylesheet of the Marinelli template

# Answer
> -1 votes
Drupal adds the ***`logged-in`*** class to the body if the user is logged in.

you can write your css like this

```
body.logged-in {
  /* add custom css here */
}

```

---
Tags: 7, nodes
---