# Question
Title: How do I customize the search result page?
I have customized the teaser view of my content types and the page view. Now I need to use the teaser view for the search results page. By default, Drupal displays a full text jumbled mess for each result, I need to be able to customize the look of each one per content type. I don't want to change HOW drupal gets the results, just how it displays them.

# Answer
> 29 votes
You can override theme\_search\_results(), or theme\_search\_result().

The first is the theme function that is invoked for the search result page, while the second is the theme function that is invoked to render a single result. Both the theme functions use a template file (search-results.tpl.php in the first case, search-result.tpl.php in the second case).

search-result.tpl.php would use `$info_split['type']` in Drupal 6, which contains the node type. In the latest Drupal 7 version, `$info_split['type']` is not anymore passed, but search-result.tpl.php still gets `$result['node']`, in the case the search is done for nodes; `$result['node']->type` is then the content type of the node.

To notice that Drupal 7, and higher, allows the modules to implement hook\_search\_page(), but it is a hook used by a module that integrates with the Search module, not from a module that wants to change the result page for results returned by another module.
Also, on Drupal 7, each theme function uses a preprocess function, which in this case would be hook\_preprocess\_search\_results() and hook\_preprocess\_search\_result(). They are helpful in the case you just need to edit the value of what passed to the template file.

# Answer
> 18 votes
In Drupal 7 you use ...

... to tinker with the information displayed in the results.

And you use ...

... to customize the markup of the results.

### Example

This is an example of how to use the content type's teaser as search result. The next snippet goes in the theme's template.php

```
/**
 * Implements template_preprocess_search_result
 * @param type $vars
 */
function MYTHEME_preprocess_search_result(&$vars) {
  $node = $vars['result']['node'];
  if ($node->nid) { // if the result is a node we can load the teaser
    $vars['teaser'] = node_view($node, 'teaser');
  }
}

```

This snippet is the search-result.tpl.php file:

```
<article>
  <?php if ($teaser) : // for nodes we can use the teaser as search result ?>
    <?php print drupal_render($teaser); ?>
  <?php else : // for other results we use the default from core search module ?>
    <?php print render($title_prefix); ?>
    <h3><a href="<?php print $url; ?>"><?php print $title; ?></a></h3>
    <?php print render($title_suffix); ?>
    <?php if ($snippet) : ?>
      <p><?php print $snippet; ?></p>
    <?php endif; ?>
  <?php endif; ?>
  <?php if ($info): ?>
    <footer><?php print $info; ?></footer>
  <?php endif; ?>
</article>

```

# Answer
> 9 votes
I recently spent a good deal of time working with search results on a Drupal 7 architecture website, and settled on using the Display Suite module.

The Display Suite module has a wonderful method for taking control of search results: It will allow you to easily use your teasers in search results. This is a tutorial by the maintainer of the module that focuses on using it for search results.

As always with Drupal, there are a variety of ways to do the same thing. I liked this method because it allowed me to break out the results by content type.

---
Tags: 7, nodes, search
---


title: How to delete node revisions

text:
# Question
Title: How to delete node revisions
I need to delete all node revisions before upgrading to Drupal 7 to save time in migration. Is there any way to do that?

# Answer
> 12 votes
You can use the following code.

```
db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

```

You don't want to delete all the revisions: You want to delete all but the current revision.

Executing only that query is going to leave data about deleted revisions in other database tables, as modules that save information about a revisions are not notified a revision is going to be deleted. I am thinking of the CCK module, for example, which saves information about the node fields in its own database tables. The CCK module executes the following code, when a revision is deleted.

```
/**
 * Implementation of hook_nodeapi 'delete_revision' op.
 *
 * Delete node type fields for a revision.
 */
function content_delete_revision(&$node) {
  _content_field_invoke('delete revision', $node);
  _content_field_invoke_default('delete revision', $node);
  cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());
}

```

A more complete code would be similar to the following one.

```
$query = db_query('SELECT nr.nid, nr.vid FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

while ($revision = db_fetch_object($query)) {
  if ($node = node_load($revision->nid, $revision->vid)) {
    node_invoke_nodeapi($node, 'delete revision');
  }
}

db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

```

Looking at the code of node\_revision\_delete\_confirm\_submit(), I don't see anything else that needs to be done.

The new code I wrote could take much time to be executed, depending on the number of nodes, and revisions. This means the code should be executed:

1. In an implementation of hook\_cron()
2. As a batch operation
3. In a PHP file that bootstraps Drupal, and increases the execution time with `@set_time_limit(240)`
4. With Drush

Considering that the code is only necessary for the migration, I would avoid the first two options, which would require you to write a module you need just in this very specific case. If you have more sites, and all of them need to execute the same code, option 3 is always possible, and that is what is done from Drupal with cron.php.
About option 4, I would first check Drush doesn't have already commands that could be helpful in this case. I would not reinvent the wheel, when it is not strictly necessary. I would also check how to write Drush Shell Scripts.

# Answer
> 1 votes
> We had a website with \>500,000 old revisions in their database. There is a nice module for knocking out small numbers of revisions called http://drupal.org/project/revision\_deletion. But, to quickly remove a large set we wrote this script.
>
> The general idea is to remove all revisions older than a certain date and then do the same for each CCK table. No matter what date limit you pick the current revision is not deleted.
>
> WARNING: it makes assumptions about your table naming conventions -- use only on a backup

```
<?php
// Note - this is for Drupal 6.x
function remove_revisions() {

  // Set limit for revision age
  $days_ago = 30;

  // delete all revisions from node_revisions
  $limit = time() - (60*60*24*$days_ago);
  $sql = "DELETE FROM node_revisions WHERE timestamp < $limit AND vid NOT IN (SELECT vid FROM node)";
  db_query($sql);

  $rows = db_affected_rows();
  drupal_set_message("$rows revisions deleted -- node_revisions");

  $table_types = array('content_field_%%', 'content_type_%%');

  // remove orphaned data from CCK content tables
  foreach($table_types as $table_type) {
    $result= db_query("SHOW TABLES LIKE '$table_type'");
    while ($row = db_fetch_array($result)) {
      $table = current($row);
      $sql = "DELETE FROM $table WHERE vid NOT IN (SELECT vid FROM node_revisions)";
      db_query($sql);
      $rows = db_affected_rows();
      drupal_set_message("$rows revisions deleted -- $table");
    }
  }
}
?>

```

Source: http://fivepaths.com/drupal-revision-removal-and-database-cleanup-by-brute-force

# Answer
> 0 votes
in phpmyadmin

just do :

> DELETE FROM node\_revisions WHERE node\_revisions.vid NOT IN (SELECT node.vid FROM {node} );

Ajay singh rathore. Bangalore

# Answer
> 0 votes
This piece of code takes care of node revisions and all the CCK revisions. It doesn't know about any other possible modules saving revisions but it's fast and you avoid thinking of cron, batch, execution time limit or Drush. It also has a day limit setting as in how many days from today backwards do you *not* want to remove revisions. You have to put the code inside some module and add a hook\_menu. Worked well for me.

http://fivepaths.com/drupal-revision-removal-and-database-cleanup-by-brute-force

Edit Aug 3, 2015: Oops, the page is gone. I can dig this up if someone wants it.

---
Tags: 6, nodes
---


# Question
Title: How can I use a Drupal 6 database in Drupal 7 without upgrading that database?
I am new in Drupal. Currently I am working on one project where I am using Drupal 7.12. My client had one project in Drupal 6 of which database he wants to use in the Drupal 7 project. I can not upgrade the Drupal 6 to 7 as it's a completely different instance but he wants to have same userbase and other things in the new project i.e Drupal 7. As per knowledge DB structure of Drupal 6 and Drupal 7 is very different and hence it's not going to be very easy to use the Drupal 6 DB in 7.

Please suggest me any way to use Drupal 6 DB in 7.

# Answer
> 5 votes
Simply put, you cannot unless you are willing to rewrite a *lot* of Drupal 7 parts.

One thing you can do, is to implement cron jobs to export changes in version-independent format like XML on source site, and import them from XML at target site.

Alternatively, you can use Services module and make one page call the other to perform certain tasks, like user login or article reading.

---
Tags: upgrading
---


title: How can I center a views slideshow?

text:
# Question
Title: How can I center a views slideshow?
I have setup a views slideshow, but is anyone able to help me with centering the images in the middle of the slideshow? Some images are not very wide and they are aligned to the left of the slideshow. I would like all images to be in the center to make it look better.

The site I'm working on is here

I have tried adding the following codes to my css but none of them work:

```
.views-field-field-image-fid img { border-style:solid; border-width:1px; display:block; margin-left: auto; margin-right: auto; position:relative; text-align:center; }

```

and

```
.views-field-field-slideshow-image {
     display:block;
     margin-left:auto;
     margin-right:auto;
}

```

I still cant seem to get it working, I've tried a few other css selectors that I found online as well. Im new to drupal views and quite new to Drupal.

Thank you.

# Answer
> 3 votes
You need to use image styles to get all the images the same size.

From the admin menu, Configuration \> Media \> Image styles.

Create a new image style, with a scale and crop attribute to the exact dimensions for your slideshow. Name it "slideshow-image".

Then go back to the slideshow settings on your views slideshow, and select "slideshow-image" as image style.

Now every image will be the same width and height, regardless of the dimensions you upload them in.

# Answer
> 2 votes
The images in the slideshow are absolute positioned by the script. The easiest way to achieve what you want, is not related to drupal. Just prepare all your images in the same way for the slideshow-size in an image-editor, like e.g. photoshop.

It looks even better... :)

# Answer
> 0 votes
Thank you everyone for your answers. The way I accomplished this was to center the views slideshow main frame in the center of the page. I then did what Chris suggested and applied an image style to the slideshow images. Works perfectly.

---
Tags: theming, media, views
---


# Question
Title: Why drush "assume yes" -y option do not work for some commands
Drush has global option `-y` (or `--yes`) which allow you not to type `y` on every promt during given command execution. (There is also `-n` or `--no` option to which following applies as well.)

This works perfectly when you run something like:

```
drush en i18n -y

```

The propblem arises, for example, when you trying to run `rsync` in that manner:

```
drush rsync @staging:sites/all/themes @production:sites/all/themes -y

```

Drush just don't get the `-y` option, and prompts you for a confirmation.

What is this and how to make use of `-y` option?

# Answer
The solution is to pass all global options like `-y` or `-n` before drush command:

```
drush -y rsync @staging:sites/all/themes @production:sites/all/themes

```

This allows you to pass options to a shell command run with drush without getting in conflict with drush options:

```
drush [global options] command [command options]

```

This will pass `[global options]` to `drush`, and `[command options]` to a shell `command`.

Take a habit of passing `-y` and other global options right after you type `drush`.

Run `drush topic docs-strict-options` to get a help on that case.
> 19 votes

---
Tags: drush
---


# Question
Title: How do I display a content author's userpoints next to the author's name on posts?
I have set up the User Points module and want to show authors' points next to their name.

What is the simplest way to do this?

# Answer
The API function to get the points is userpoints\_get\_current\_points() \*. Just call that function with the uid of the author and display the returned result.

* Note that my API documentation page only lists the Drupal 7 versions, this function works the same way in Drupal 6 and 7 but others might not.
> 2 votes

# Answer
I tried putting that code userpoints\_get\_current\_points() * in comment.tpl.php but it seems that it does not work. I can not program by using PHP. Maybe I had to add something?
> 0 votes

---
Tags: 6, userpoints
---


# Question
Title: Views - Filtering nodes by current user profile field
I have been trying to do this for many days but no luck.

On registration, user has a choice to choose his/her interests - checkboxes with term reference widget. For example - I have made vocabulary 'Interests' with terms sports, computers, painting etc. Every node is related to terms also.

I need to display only the nodes, that users are interested in. For example, if user checked computers on registration, views have to display only nodes with term computer.

I guess there has to be some way to filter only current users profile\_field\_interests. I couldn't find a way in Drupal 7.

Any suggestions?

# Answer
> 2 votes
* You want to use the Views module to create the list – actually a list of users (rather than nodes/content).
* Then you want to use relationships settings to add in the interests.
* Finally, Add a contextual filter on "user: uid" with a default value fetched from the currently logged-in user.

If you haven't used Views before you in for a ride. If you have used Views but not relationships or arguments/contextual filters, then you're also in for a ride.

There's a pretty nice guide for learning Views in the links in my signature – I hope that can be of help. Look especially for the episode on relationships.

# Answer
> 0 votes
This question was asked months ago but i give an alternative answer as a reference (my version is more straightforward but it should perform worse since the filtering occurs in php and not in the SQL):

1) Install and enable the module views\_php 2) In your view add to the displayed fields "Content: Author uid". You can set it not to display 3) Create a php filter field and use the following code: a)in the setup:

```
global $user;
$static=$user->uid;

```

b) in the filter code:

```
if ($static == $data->node_uid )
{return FALSE;} else
{return TRUE;}

```

---
Tags: 7, views
---


# Question
Title: How to programmatically add image from external URL using media module?
I want to programmatically add an image from an external URL and have the module store and display a local copy of the image. How can I do that? Normally, I would click the "select media" button while creating a new node but I want to do it through code.

# Answer
> 0 votes
This is a partial answer to your question, as I'm trying to do something similar but with video material.

You could create the node as a content type, save the media type that you need (have a look through the media code for the relevant mime/type and functions that you need to call). You will probably need to set a multimedia asset field and use the media file selector in the field type.

The bit I'm having an issue with is getting the browser to show it in the created node though, which I'm currently working through.

### UPDATE

Having got a bit further. Once you have saved the media file (using media API), associate the file id with the node ID using file\_usage\_add(). You'll probably also need to associate the file in the field added when you created the media asset field.

# Answer
> 15 votes
Make sure your php.ini allows allow\_url\_fopen. Then you can use something like this in your module:

```
$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);

```

Use php's file\_get\_contents() function

http://www.php.net/manual/en/function.file-get-contents.php

and then use Drupal API's file\_save\_data()

http://api.drupal.org/api/drupal/includes--file.inc/function/file\_save\_data/7

Then you should be able to call it using and save it to a node etc ..

```
$node = new stdClass;
$node->type = 'node_type';
node_object_prepare($node);
$node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid;
node_save($node);

```

---

**Edit:**

As pointed out in the comments, you can use function system\_retrieve\_file See: https://api.drupal.org/api/drupal/modules!system!system.module/function/system\_retrieve\_file/7

# Answer
> 6 votes
Here is my working example.

```
$remoteDocPath = 'http://drupal.org/files/issues/druplicon_2.png';
$doc = system_retrieve_file($remoteDocPath, NULL, FALSE, FILE_EXISTS_REPLACE);
$file = drupal_add_existing_file($doc);

$node = new stdClass;
$node->type = 'node_type';
node_object_prepare($node);
$node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid;
node_save($node);

function drupal_add_existing_file($file_drupal_path, $uid = 1, $status = FILE_STATUS_PERMANENT) {
  $files = file_load_multiple(array(), array('uri' => $file_drupal_path));
  $file = reset($files);

  if (!$file) {
    $file = (object) array(
        'filename' => basename($file_drupal_path),
        'filepath' => $file_drupal_path,
        'filemime' => file_get_mimetype($file_drupal_path),
        'filesize' => filesize($file_drupal_path),
        'uid' => $uid,
        'status' => $status,
        'timestamp' => time(),
        'uri' => $file_drupal_path,
    );
    drupal_write_record('file_managed', $file);
  }
  return $file;
}

```

# Answer
> 1 votes
This isn't a direct answer, but make sure that you already know about the Filefield Sources module, which does this for images in general. It might meet your needs on its own; I don't know if it's useful with Media.

# Answer
> 0 votes
As addition to @tecjam answer: you should use drupal\_http\_request() instead of **file\_get\_contents()**, it gives you more control over process. But in total this method works as expected.

# Answer
> 0 votes
```
// This is a PHP function to get a string representation of the image file.
$image = file_get_contents($path);

// A stream wrapper path where you want this image to reside on your file system including the desired filename.
$destination = 'public://path/to/store/this/image/name.jpg';

$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);

if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
  $file->status = 1;
  $file = file_save($file);
}

return $file;

```

---
Tags: 7, media
---


# Question
Title: Enable fields in manage display programmatically D7
I have just started to use Drupal and I'm trying to add programmatically field in the .install file.

```
 $field = array(
   'field_name' => 'title',
   'cardinality' => 1,
   'type' => 'text',
   'settings'    => array(
     'max_length' => 1024,
   ),
 );

 field_create_field($field);

 $instance = array(
   'field_name'  => 'title',
   'label' => $t('Title'),
   'type' => 'text',
   'widget' => array(
     'type'    => 'text_textfield',
     'weight' => 1.0,
    ),
   'display' => array(
     'default' => array(
       'label' => $t('label'),
       'type' => 'text',
      ),
    ),
 );

$instance['entity_type'] = 'node';
$instance['bundle'] = 'mytype';
field_create_instance($instance);

```

The field is added correctly but it is disabled in the Manage Display. How can I change the region column from 'disabled' to 'content'? I tried to add 'region' =\> 'content' in the instance array but it is not working and I cannot find a good example or documentation about the problem.

Thanks.

# Answer
> 2 votes
I couldn't find any concrete documentation either. However, I'm going out on a limb here and not 100% certain but, I think you just need to specify a correct formatter and the settings since it works that way in the UI.

```
$instance = array(
   'field_name'  => 'title',
   'label' => $t('Title'),
   'type' => 'text',
   'widget' => array(
     'type'    => 'text_textfield',
     'weight' => 1.0,
    ),
   'display' => array(
     'default' => array(
       'label' => $t('label'),
       'type' => 'text', // <-- invalid formatter
      ),
    ),
 );

```

`text` is not a valid formatter type. It should either be `text_default` or `text_plain` or `text_trimmed` or `text_summary_or_trimmed` or `hidden` (which hides the field from display).

---
Tags: 7, entities
---


# Question
Title: What's the use of creating another CKeditor profile
CKeditor comes standard with 2 profiles: one for filtered html, and one for full html. Now I added a third one, but whats the use?

There are only 2 text format.. So why is it possible to create a third ckeditor profile?

# Answer
Because it's also possible to create as many/few text formats as you want...

If you had installed Drupal using a non-standard profile, you might not even have `full_html` and `filtered_html` as text formats, and the CKeditor profiles would be different.

If you don't know why you need to add one...don't add one :)
> 2 votes

---
Tags: wysiwyg
---


title: how to update a field schema

text:
# Question
Title: how to update a field schema
I am trying to add a field (middle name) into the field\_schema of the contrib addressfield module (I initially didn't want to hack it, but was unsucessful in adding a field in from my custom module.). The module has the following hook\_field\_schema()

```
function addressfield_field_schema() {
  $columns = array(
    'country' => array(
      'description' => 'Two letter ISO country code of this address.',
      'type' => 'varchar',
      'length' => 2,
      'not null' => FALSE,
      'default' => '',
    ),
    'administrative_area' => array(
      'description' => 'The administrative area of this address. (i.e. State/Province)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_administrative_area' => array(
      'description' => 'The sub administrative area of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'locality' => array(
      'description' => 'The locality of this address. (i.e. City)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'dependent_locality' => array(
      'description' => 'The dependent locality of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'postal_code' => array(
      'description' => 'The postal code of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'thoroughfare' => array(
      'description' => 'The thoroughfare of this address. (i.e. Street address)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'premise' => array(
      'description' => 'The premise of this address. (i.e. Apartment / Suite number)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_premise' => array(
      'description' => 'The sub_premise of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'organisation_name' => array(
      'description' => 'Contents of a primary OrganisationName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'name_line' => array(
      'description' => 'Contents of a primary NameLine element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'first_name' => array(
      'description' => 'Contents of the FirstName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'data' => array(
      'description' => 'Additional data for this address.',
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
      'serialize' => TRUE,
    ),
  );

  return array(
    'columns' => $columns,
    // TODO Add indexes.
  );
}
```

I found this post online for doing a field\_schema update https://drupal.org/node/150215, but I don't know what the field name or table name is, its not listed in the file. How can I do this? My ultimate goal is to make a standalone plugin file to be used by addressfield, but I needed to update the schema first.

# Answer
The field will be named whatever you named it when you added it. If you can't remember, go to the "Manage fields" UI page for the relevant entity type/bundle and you'll be able to find it there.

The table names will be based on that field name; if the field is called `field_my_field` then the two database tables are:

* field\_data\_field\_my\_field
* field\_revision\_field\_my\_field
> 1 votes

---
Tags: entities, updating
---


# Question
Title: How to hide a form field in hook_node_view()
```
function hook_node_view($node, $view_mode, $langcode) {
// How can I hide a field in the hook_node_view() using $node
// In my case the field is an image file field
}

```

# Answer
You can't. `hook_node_view()` exists only to

> Act on a node that is being assembled before rendering.

It can't be used to alter the node's edit form.

You need to use `hook_form_alter()` or `hook_form_FORM_ID_alter()`, to alter form elements e.g.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && $some_other_condition) {
    $form['some_element']['#access'] = FALSE;
  }
}

```
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How do you add rules to specify zero rate VAT when a VAT number is supplied?
I'm using the **Commerce VAT**, **Commerce EU VAT** and **VAT Number** modules and would like to add a rule so that if someone is within the EU (but not in the UK) and enters a valid VAT number, the VAT rate is set to zero rate.

Our current setup is working so that purchases from within the United Kingdom are being charged VAT, purchases from outside the EU are not, but I've also added the VAT Number module so that people who are in the EU but not in the UK are charged zero rate tax.

I've overwritten the validation function within the VAT Number to bypass the SOAP server for the purposes of testing, but when I get through with a, say, FRXX **** VAT Number, the full 20% is still being added. I'm guess I need to create a rule to work with the VAT Number, but I can't see how or where, as I'm still relatively new to Rules.

How do I create a rule so that the VAT rate on an order changes to zero rated when the customer supplies a valid VAT number, is within the EU and not in the UK?

Any help here would be appreciated.

# Answer
The rules for adding zero-rated VAT to other EU countries when a valid VAT Number is supplied are added when you enable the 'Commerce EU VAT Intra-community Supply' module in the 'COMMERCE EU VAT' module group.
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal 7: Customizing the display of a view
I'm using the latest version of Drupal (7.8). I am using Views to list out all articles with a certain tag in a block. I'm showing the latest 5 articles. No problems so far.

Now I want to customize the display so that the latest article displays with the title as well as the featured image whereas the other 4 articles show up with the title only.

I'm trying to use the suggested templates feature but am not sure how to use it since the HTML comes pre-created in the $rows variable.

Sort of like this:

# Answer
Look into creating your first article display as an attachment. Attachments allow you to group different views together. This is for Drupal 6 and Views 2, but it should give you some idea of what attachments are.

> A Views Attachment is simply a type of Views Display that gets attached to another View Display (usually a page display or a block display).
> 2 votes

# Answer
You should theme your Views and hide it programmatically.
> 0 votes

# Answer
A convenient way to customize the views markup for individual views rows, is to use the Display Suite module.

Where you would choose to display "fields" or the "rendered entity" on your views configuration, you can select "Display Suite". In the configuration for this setting, you can define different view modes to use for row1, row2, row3 etc. However, this only works if you limit the output of the view to *n results* (with or without paging).
> 0 votes

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


# Question
Title: Create a node Automatically when a commerce order is completed
In my site, I am using drupal commerce in order to run a shop.

In my plan, a new node must be created when an order is completed. (paid)

Also in new node creation I want to use the order's field values. (for example order id, or username (and uid ) who ordered , entity values & etc )

Please help me. How can I setup this solution? can I do this process via "Rules" or I have to create a module and use hook functions?

Thanks a lot for your guidance.

# Answer
Yes, its time to create a module, and use these nice hooks Commerce API is offering to interfere to the regular execution of things in your Drupal site.

After getting the big picture, creating a node will be as easy as this first script. So in a hook which is invoked whenever an order is complete, you would add the node creation code.
> 1 votes

---
Tags: hooks, rules, commerce
---


# Question
Title: Voting a post several times by same user
I have a case where authenticated users can **Vote** a content many times.

I want a button at the top of the Node saying **Vote This** and when the users click the button it'll ask for confirmation Do you really want to Vote ?. When confirmed, he'll be redirected back to the same page, and be able to click the button again. However, in the backside, I want to record the time of voting and the user who voted it. Not necessarily the vote count, but just date/time and person.

I tried this with the Flag and Global Flag modules, but the issue is: once flagged, it can only be unflagged.

I also tried Fivestar module, with just one star (which I can change it to a button via CSS), but it doesn't ask for confirmation. It doesn't record the date/time either (I might be wrong here, but playing around with Fivestar, I didn't find a configuration option).

There must be something with VotingAPI which might be useful in my case, but I am unable to identify how to satisfy these conditions. I am seeking guidance.

**Update: *In addition to @Adam Balsam's answer to have confirmation I did***

Use jQuery to add `id` to the link like: (*I only have one vote in node*)

```
$('.plus1-link').attr('id', 'vote-plus');

```

Then added jQuery confirm dialog like:

```
$('#vote-plus').click(function(e) {
               var cnf = confirm('Do you really want to vote?');
               if(cnf === false) {
                   e.preventDefault();
               }
            });

```

It might not be the elegant solution, but this how I solved my confirmation dialog option.

# Answer
Use the Voting API module with the Plus1 module (dev version). Working demo can be found here.

Voting API allows for immediate vote rollover as of 7.x-2.11. You just need a front end module that uses Voting API to allow your users to vote and Plus1 seems to do the trick.

1. Enable Voting API and on the module admin page (/admin/config/search/votingapi -the module maintainers need to update their `hook_menu()` implementation) select immediately for Anon and Registered User vote rollover.
2. Enable the Plus 1 module (requires ctools as a dependency). Use the dev version as the alpha version seems to have some permissions issues.
3. Select the content types you want to allow users to vote on on the Plus1 admin page (admin/config/user-interface/plus1).
4. Give Anonymous and Authenticated users access to the "Vote on nodes" permission.

The Voting API module will take care of recording the time of the vote and the user who cast it. Take a look at Lullabot's votingapi documentation. Specifically `votingapi_select_votes()`.

The Plus 1 module comes with some stock JS and CSS to cast the votes via AJAX and provide some styling. But they also allow you to exclude those files from the admin interface if you want to create your own experience.
> 1 votes

# Answer
Here's something you could try.

Create a content type, Vote. Add an Entity Reference field (to link the vote to the relevant node).

Then, allow users to vote with flags. When a user flags the content, use a Rule that goes something like this:

* Event: Node is flagged
* Action 1: Create an entity, a node of type *vote* (Author: logged-in user, also make sure to set the entity reference field value to the current node)
* Action 2: Unflag the node

This way, the user will be able to flag the node multiple times and each time a vote node will be created that will include the date and time of each vote.
> 2 votes

# Answer
There is a patch for the votingapi module that allows you to control the vote rollover time for both anonymous and authenticated users. You can set the rollover time to zero seconds effectively enabling users to vote as often as they like.

Use the dev version of that module (or apply the patch manually) in conjunction with the Vote Up Down module. This setup will allow you to enable users (authenticated or anon) to vote unlimited times on content.

As far as the "Do you really want to vote?" confirmation, you'll probably have to write a small module or just a JS snippet to intercept the click and execute it on confirmation.

**Update:**
It looks like that patch made it into the 7.x-2.11 module back in March. So as long as you're using that branch, you should have this functionality already. Just se both Anon and Auth rollover to "Immediately" on the module admin page.
> 1 votes

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


# Question
Title: Show markers on gmap from all nodes exposed in view
I'm using gmap module to mark job locations on a map. It now shows all locations of content type: jobs. Is there any way I can only mark the displayed jobs from my view block? I filter the jobs through exposed filters.

EDIT:

Just going to add this code here, might be useful for some. It puts the attachment in a block so you have more control over it.

```
<?php
//Puts gmap attachment in block so it's easier to theme

function gmap_block_block_info() {
  $blocks['gmap_attachment'] = array(
    'info' => t('Gmap Attachment'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function gmap_block_block_view($delta = '') {
  $block = array();
  if ($delta == 'gmap_attachment') {
   // $block['subject'] = t('Gmap Attachment');
    // Load the view.
    $view = views_embed_view('jobs_view_block', 'gmap_attachment');
                        //('machine_name_view', 'machine_name_display)
    if ($view) {
      $block['content'] = $view;
    }
    else {
      $block['content'] = t('The view is empty');
    }
  }
  return $block;
}

```

# Answer
> 1 votes
If you set up the map display as an attachment, you can set it to inherit the exposed filters that you've defined for your job listing. You'll get one set of exposed filters that controls both the listing and the map.

There may be some issues - see this blog post by someone solving what looks like the same problem.

---
Tags: views, location, google-maps
---


# Question
Title: Populate a drop down select list with the results from a view with entity reference relationships
Ok. Perhaps this has been asked before in this site somewhere but for the life of me I can't find an answer.

I have three content types: Client, Contact and Job ticket.

Clients are companies with whom I conduct business. Contacts are contact persons within these companies. The Contact content type has a reference field referencing their company's node. Job tickets are tickets for jobs these companies hire me to do for them. In this content type I have two reference fields: one for the Client and one for the Contact.

What I need is to have the Contact reference field (drop down select list) dynamically populated with the contacts for the client I chose in the Client reference field (another drop down select list). Because if I populate it with ALL the Contact nodes then I get a very big list and I don't know which contact belong to Which company.

I know I can do this with a entity reference view display but I don't know how to configure it.

Thanks in advance for your help.

# Answer
> 3 votes
Reference field option limit

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

I think this link might already be enough.
If not, then I am happy to expand the answer with more specifics.

# Answer
> 0 votes
Another option:
Entity Reference View Widget

You need some custom code and patches to make this depend on another field:

I did not try any of this, so I don't go into too much detail. Still I think this deserves to be a separate answer, to not get mixed up with the other one.

---
Tags: views, entities
---


title: Is Drupal secure?

text:
# Question
Title: Is Drupal secure?
I want to respond to this:

> "Drupal is listed as limited use, not generally available because of the licensing and security issues related to various modules that people want to use."

I have two questions:

1. Is Drupal less secure than other web solutions?
2. Can contributed modules (i.e. modules that are accepted into the Drupal community) make Drupal less secure?

# Answer
> 7 votes
I'll start with your second question, "do contributed modules make Drupal less secure?"

In general, yes, because **contributed modules expand the attack surface of your site**. When a module provides user interaction features it's another point an attacker could probe for exploits on your site. Additionally that module becomes another dependency in your system and that affects site maintenance and agility.

Now, not all contributed modules are the same, they don't all provide user-facing functionality, but the point is that most every additional module has to be balanced with the possible risks that come along, including possible vulnerabilities.

Also, Gareth Parker correctly highlights that contributed modules undergo far less peer-review and testing than Drupal core, so there could be greater likelihood of security risks in the code. Again, it depends on the modules.

As for your first and main question, "is Drupal secure?". As one of the authors of the Drupal Security Report which attempts to answer this question by analyzing Drupal's published Security Advisories as well as describing how Drupal addresses the OWASP Top 10, I would say "yes" :) Full disclosure, I'm also a member of the Drupal security team.

However, there will be vulnerabilities found in Drupal in the future, it's not secure in that it's immune to risk. It's secure in that it's been both professionally reviewed by security firms and peer-reviewed by thousands of contributors during its development. Additionally, core APIs are strong, providing security mitigation techniques and tools, and many of the default configurations are secure.

# Answer
> 1 votes
Drupal Core itself is fairly secure as long as you keep it up to date. There's no way to say that it's perfect, but I wouldn't worry about security

Drupal Modules on the other hand are written by average people who simply want a piece of functionality, create it and then share it. Some projects have many people working on it, some have only one. These modules aren't checked by any kind of Drupal Team for security problems, so it's mainly on the people who make and contribute to them to make sure that it's all secure

Knowing that, it's easy to determine that some modules would be secure, some wouldn't, and it really varies from module to module. So in a long, roundabout way, yes, the modules can make drupal less secure

# Answer
> 0 votes
In my opinion drupal is secure in the general sense but like any other system there are, sometimes, security issues. However, Drupal has a large community and is opensource so the code is examined over and over by a large number of developers. When security issues are found, they're reported and made public so you can take precautionary measures until a patch is available.
You can check the following security advisory to get an idea how often security issues surface. I advise you to bookmark this page.

---
Tags: 7, security
---


title: Update hooks and features_revert

text:
# Question
Title: Update hooks and features_revert
I have a problem in a custom module I can not figure out, I have an update hook like this one:

```
function article_update_7003() {
  features_revert(array('article' => array('field_base')));
}

```

But it does not revert the feature. But if I run that update, and manually change it to:

```
function article_update_7004() {
  features_revert(array('article' => array('field_base')));
}

```

And run it, the feature is reverted. Anyone that knows what is going on? I tried to duplicate it the first time, but that does not help...

```
function article_update_7003() {
  features_revert(array('article' => array('field_base')));
  features_revert(array('article' => array('field_base')));
}

```

# Answer
> 3 votes
It is my understanding that the update hook only runs once per update. The function is `hook_update_n` where 'N' is the instance of the update hook. Each time you want to revert your feature upon a code update you need a new update hook. This is why if you increase the number it works. If you are increasing your version numbers when you regenerate your feature, and also reverting your feature in code with an update hook, those numbers should match, and you will have an update hook for every version increment.

Source: Drupal API.

---
Tags: features, updating
---


title: Drupal 6 with custom OAuth Server

text:
# Question
Title: Drupal 6 with custom OAuth Server
Quick question, Has anyone made their own OAuth server and then tied drupal logins into it?

My boss is asking me if it's possible to run our own internal OAuth server that we can use for multiple things, mobile app, internal app and our website. but they don't want to use the drupal site for the oauth service.

Everything i've found so far is a module that lets you use OAuth in drupal but it makes drupal the OAuth server instead of having Drupal hit an external oAuth service.

Any help would be appreciated.

# Answer
> 0 votes
Drupal 7 has the oauth2\_server module that allows you to run an OAuth2 server. It is well documented and integrates a well known and stable PHP library. OAuth2 is probably a better option for you than OAuth1 because it has grant types optimized for different usage scenarios (mobile app, web app, etc).

If you're limited to Drupal 6, your only option is the OAuth module (also available for D7), but keep in mind that Drupal 6 is basically a deprecated version so when it comes to contrib support and bug fixes you are pretty much on your own.

---
Tags: 7, authentication-authorization
---


# Question
Title: Preprocessor to use a different template for popup window
I'd like to provide the ability to open some content in a new window without all of the headers and sidebars of the normal content window. I tried to do this with a preprocessor, and got close, but still no cigar:

```
function THEME_preprocess_page(&$vars) {
  if (isset($_GET['popup']) && $_GET['popup'] == '1') {
    //error_log( var_export( $vars['theme_hook_suggestions'], true ) );
    // returns as last array item: page__node__3
    $vars['theme_hook_suggestions'][] = 'page__node__3__popup';
  }
}

```

I then have a template with the file name: page--node--3--popup.tpl.php which is just a straight copy of the region--content.tpl.php file, and it actually does hit that template! The problem is that only the title shows up - and when I clear the cache I get a warning message that content is undefined in my popup template. I've also tried naming the file and setting the theme\_hook\_suggestions to 'region--content--popup'/'region\_*content*\_popup' with the same results.

Here is the content of region--content--popup.tpl.php

```
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <a id="main-content"></a>
    <?php if ($title): ?>
    <?php if ($title_hidden): ?><div class="element-invisible"><?php endif; ?>
    <?php print render($title_prefix); ?>
    <h1 class="title" id="page-title"><?php print $title; ?></h1>
    <?php print render($title_suffix); ?>
    <?php if ($title_hidden): ?></div><?php endif; ?>
    <?php endif; ?>
    <?php if ($tabs): ?><div class="tabs clearfix"><?php print render($tabs); ?></div><?php endif; ?>
    <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
    <?php print $content; ?>
    <?php if ($feed_icons): ?><div class="feed-icon clearfix"><?php print $feed_icons; ?></div><?php endif; ?>
  </div>
</div>

```

The H1 page title appears and nothing else.

# Answer
> 1 votes
You probably want:

print render($page\['content'\]);

You can find the variables available to you in the template by printing get\_defined\_vars() using print\_r(), core's debug() function, or one of the extremely handy devel module debugging functions such as kpr() or dpm().

I'd install devel and do this:

kpr(get\_defined\_vars());

Your modal method might not play nicely with page cache so I'd definitely test to make sure it fits your usecase.

---
Tags: 7, theming
---


# Question
Title: Specific number of values in field setting per role
Is there any way to limit user input a field with 1 value in select list, but make it unlimited for admin?

# Answer
Sure. You can manipulate the `multiple` characteristic of the `select` via a `form_alter()` hook. You just have to make sure the field itself is a multiple value field to start with, and then do something along these lines:

```
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if ( /* your user is NOT an admin */ ) {

    if ($form_id == 'YOURNODETYPE_node_form') {

      $form['#field_info']['field_NAMEOFTHEFIELD']['multiple']=FALSE;

    }

  }

  // any other form alters here

}

```

If this doesn't work out of the box for you, a `drupal_set_message()` and `print_r()` of your `$form` will give you a dump of what you have to work with, and you basically just want to find the `multiple` array key for the field in question and change it to `FALSE` for non admins.

But once again, you need to make this field a multiple value field to begin with, but you then don't allow non-admins to enter multiple values into it on the form.

(More information on the Form API can be found here for D7 if this doesn't work as the above is just a quick edit on a D6 testbed here)
> 3 votes

---
Tags: entities, users
---


# Question
Title: Theming user_profile_form (the user edit form)
I am looking for easy ways to theme the user profile form that will allow me to setup a two-column layout for the form and exclude certain elements.

How can I achieve it?

# Answer
Aside from using the Display Suite module, most methods for theming forms require a bit of code to be written. In the following method I define variables from the form that can be outputted in a template file to fit whatever HTML structure you'd like. I put all of my code in template.php, but you can just as easily make a custom module to do this.

1. Add a hook\_theme() implementation

```
function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

```

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
2. Next we'll define some variables to pass into that template in a hook\_preprocess\_HOOK function. We can find the structured array of the form in $variables\['form'\] and assign the form elements to the variables we'd like to throw around our tpl.php file.

```
function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $form_inputs = array(
    'account' => $variables['form']['account'],
    'picture' => $variables['form']['picture'],
    'actions' => $variables['form']['actions'],
  );
  $variables['rendered'] = _YOURTHEME_form_variables_render_all($form_inputs);
}

function _YOURTHEME_form_variables_render_all($elements) {
    //Create array to return, with element name as key and element as value
    $elements_array = array();
    //For each element, render it and add it to the array
    foreach ($elements as $key => $element) {
        $elements_array[$key] = render($element);
    }
    //Return array
    return $elements_array;
}

```

This example will put the general account info fields, the user picture upload field (if pictures are enabled), and the submit actions into a variable called "rendered."
3. Now that we have defined these variables, we can output them in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

```
<div id="new-form">
  <?php echo $rendered['picture']; ?>
  <?php echo $rendered['account']; ?>
  <?php echo $rendered['actions']; ?>
  <input type="hidden" name="form_id" value="<?php print $form['#form_id']; ?>" />
  <input type="hidden" name="form_build_id" value="<?php print $form['#build_id']; ?>" />
  <input type="hidden" name="form_token" value="<?php print $form['form_token']['#default_value']; ?>" />
</div>

```

Notice the hidden form fields at the end; these include vital Drupal tokens that help secure forms from attack. Your form won't work without them.

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.
> 7 votes

# Answer
Display suites can only be used for the display, not for editing. It were great, if it could handle both.
> 1 votes

# Answer
Some fixes for **areynolds's** code:

*Underscore fix in 'render element*

```
function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

```

*Fix preprocess function from data overriding (account-\>picture) and adding action elements (form button).*

```
function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $required_elements[]=$variables['form']['account'];
  $required_elements[]=$variables['form']['picture'];
  $required_elements[]=$variables['form']['actions'];
  $variables['rendered'] = drupal_render($required_elements);
}

```

But all this manipulations give only appearance of the form. But the form won't work properly as it requires other elements such as validate, submit handlers, etc. So I think the best way to hide unrequired elements in $variables\['form'\] array leaving all necessary form metadata.
> 0 votes

# Answer
Panels can fully take over the Profile edit form and with a handful of patches (currently) you can pull in Profile2 info as a Panels relationship.
> 0 votes

---
Tags: 7, theming, users
---


# Question
Title: Menu link to the most recent article with a certain taxonomy term
I am using Drupal 7 and have been trying to figure out following:

How do I make a menu link to the latest article that has been classified with a certain taxonomy term? For example, I want to have a menu link called ‘Lifestyle’ and by clicking that I expect to get the most recent article classified with taxonomy term ‘Lifestyle’. For SEO purposes I prefer if the menu link would contain the title of the article.

I tried to do this using Views module with basic filters, but I have some issues with this approach:

1. As a result I *do* get a latest article with a certain taxonomy term, but the page title is displayed twice (the first one is a link to article itself). How do I remove this properly in a Drupal way (I don’t want to use CSS to hack it).
2. Also, as a result, Views generated URL that looks like this: http://www.mydrupalsite.com/articles/latest/1 (where 1 is a taxonomy term id). I would like it better if the URL would point directly to the node like this: http://www.mydrupalsite.com/articles/the-article-title-here

Any ideas?

Thanks.

# Answer
> 1 votes
For your first question:

As your are displaying "Teaser" view of the node in your view, so you are getting two title of the node. If you want to hide the "Title" of the node and display the override title, then you can follow the below step.

* Go to Administration -\> Structure -\> Views
* Edit your views "latest"
* Click on "Content" in "Show" setion under "Format" section of your views, it will display the popup.
* Select "Fields" from form which is opened in popup and save the form.
* Now, you will see "Title" and "Body" in your "Fields" section.
* You can remove the "Title" from views or Edit "Title" fields and check "Exclude from display" check-box, so it will not display in views.

For Question 2:

If you want to append latest node title with path (latest), then I do not think, there is solution for this.

But, if you install "pathauto" module, then you can create url alias for the same or you can append term name with view path and can get term id for the term name.

---
Tags: views, taxonomy-terms, routes, navigation
---


title: File upload with title

text:
# Question
Title: File upload with title
I want functionality where editor will be able to upload files and name that files whatever he wants, I just want additional field next to file upload field, is there any module which can do that?

Thanks.

# Answer
> 1 votes
This functionality is already provided by Drupal core. Just edit the settings for your image field in content type and enable 'Enable Title field' to have Title field for your image field.

For example, Go to 'Structure » Content types » Article' and 'Edit' the settings for 'Image' field. (admin/structure/types/manage/article/fields/field\_image)

There you will see two checkbox fields 'Enable Alt field' and 'Enable Title field' which can be enabled to provide image related info for each image upload.

# Answer
> 1 votes
I solved it using insert module, it did exactly what I wanted.

When I upload any file for example .pdf, there is a description field for every file.

insert module also integrates with ckeditor, every uploaded file has "Send to textarea" button and you can easily embed links to attachments wherever you want in your editor and title will be the text you entered in file description.

It is not file name, its just title for link but its exactly what I wanted.

UPDATE @amitgoyal's answer is better, so I checked his answer as correct.

---
Tags: files
---


# Question
Title: Send out mails to registered users after certain time period
When a user registers in my site(drupal 6) they will receive a welcome mail.I would like to send out mails to registered users after some time period (say for example,2 months),so the newly registered users will receive mail after two months from their date of registration.I tried Rules module but the users receives mail as soon as they registered.Is there any module to implement this?Anyone could help me?

# Answer
you can use hook\_cron()
to send email using drupal\_mail() and then comparing current date with the published date (timestamp of two dates) in the hook\_node.
If current\_date is equal to (published\_date + 2 months) then send email
> 1 votes

---
Tags: 6
---


# Question
Title: For multilingual sites, where are translated variables for the non-default language stored?
I'm managing deployment using the Features module.

Using Strongarm, I have added the `site_403` (access denied page) variable to my feature. However, this only contains the value for the default language (in my case, English). I also have "translated" this URL into Japanese using the i18n **Variable translation** submodule, but I cannot find where this translated `site_403` variable is stored in order to add it to my feature.

How can I add translated variables (via the i18n module) to a feature?

# Answer
> 2 votes
Please refer to this I18n translation of site\_name not working

You need to enable 'Variable translation', 'Variable store' modules. Then you need to specify which variables you want to translate from Configuration -\> Multilingual settings -\> Variables. With this you would be able to translate your Site Information variables in different languages.

Now in Features, you can export translated variables from the section 'REALM VARIABLES'.

---
Tags: i18n-l10n, features, configuration
---


# Question
Title: Is site safe after a failed module installation?
I was working on a site this morning, and I enabled a whole bunch of modules at the same time. One of the modules threw a PDO exception during the process.

What state is the site in at this point? Assuming the site still loads after the error, is it safe to use, or should I restore from a backup?

For the sake of this question, I am not concerned about the actual error or the module that threw the error (I would report this in the issue queue). I am concerned about the general state of the site, and what may have happened to the installations of the other modules.

To make this more concrete, let's say I tried to enable ModuleA, ModuleB, ModuleC, and ModuleD. After I clicked SUBMIT on the module page, ModuleC threw an uncaught PDO Exception and I didn't get the normal module enabled message. Now, lets say that I can live without ModuleC on the site. What can be said about the state of hpw the installation went for ModuleA, ModuleB, and ModuleD, and also dor Drupal in general?

# Answer
> 1 votes
Generally, it isn't. It may be, but it depends what's in module's `hook_install`.

First, most modules provide schema. The code of `drupal_install_schema` in 7 is currently:

```
function drupal_install_schema($module) {
  $schema = drupal_get_schema_unprocessed($module);
  _drupal_schema_initialize($schema, $module, FALSE);

  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
}

```

As you can see, no call to `db_translation`, and each table is created one at a time. Now, if module only provides own schema, you are left with some garbage in database, but it's a well isolated garbage. But if it implements `hook_schema_alter` it's pretty possible you are left with some tables already altered, bu no code to handle these alterations. Now, in theory installing schema should never fail with PDO error, but due to RDBMS configuration for example, it may happen.

Second problem is that module's author can write pretty much anything in it's install code, and you are not guaranteed it will get rolled back at failed install. If he decides his module needs to change variables provided by core or other modules (for example to allow apparent conditional content, like with translated variables), or if it redefines some fields to provide additional functionality, you may end up with some of your data converted to module's format, and no longer accessible without it, or without running code meant to uninstall it.

---

Note: Situations above from experience. Even if I miss some theoretical part that should make them impossible to happen, they both did happened to me in real life. With -dev versions, but module version depends solely on it's author, so there is no guarantee that it will not happen in stable versions some day, too.

---
Tags: installation
---


# Question
Title: List nodes by term on one page like Drupal 6
I've searched through quite a lot of how to's now and completely stumped, In Drupal 6 with views the relative simple procedure of linking a taxonomy vocabulary to a content type then furthermore displaying it's terms on one page was a dazzle, now however in 7 running views 3+ not so simple.

I don't know if I'm searching for the wrong phase but literally this is what i want:

Content type = Article + Taxonomy vocabulary linked to content type "site content" \> term "blog". Now I want to create a view with path /blog that lists all nodes with the term "blog", further down the line I want to add more entries to the "site content" e.g. "about" and link that to /about for example.

# Answer
> 1 votes
OK, cracked it, here's what I did (sleep worked!):

1. Create taxonomy vocabulary and term (Structure \> Add vocabulary \> Add term (after))
2. Assign to content (Structure \> Content Type \> Article (for example in my case) \> Manage Fields)
3. Type a label \> Field Type "Term Reference" (The vocabulary from step 1) \> Widget "Select List" \> Save
4. Create the view (Structure \> Views \> + Add New View \> Show "Content" \> of type (select the type assigned in step 2) \> Continue and edit
5. Under "Filter Criteria" \> Content: Has taxonomy terms (with depth) \> Apply (All Displays) \> Vocabulary (As created in step 1) \> Apply and continue \> In the field "Operator :: Is one of" \> Type term (As created in step 1), then select from auto complete drop down \> Apply (All Displays)

This will then show in the auto preview. I knew it was simple! - hope this helps someone else in my position.

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


# Question
Title: Multiple views to be displayed on a panels site
So as I've searched through drupal.stackexchange I see this question hasn't been fully answered, I guess it will be asked again and again until good solution is found I will try to summarize the problem and present found solutions.

Imagine a site which uses panels and views. The site has several *areas*, and each of them has its layout, its blocks and design differences. Every *area* can be represented by number of nodes and number of views.

So nodes are displayed by panels - they are wonderful to work with, you just create variant and specify the selection rules. All selected nodes have one variant, they share the same layout and have same blocks. Perfect! Pure pleasure to deal with!

What about **views** as a part of this structure? Since views are also part of the *area*, I want them ideally to appear in the same variant as the above node, but I can't. The out of the box way that is coming from design of the views and panels modules is like this: create view content pane, then create new panel with its own URL, then select it's layout, add the created view content pane, and then add and configure the same blocks, all just like in the previous paragraph.

Since there are a number of views in the same site *area*, this has to be done over and over again. And of course, support: in the case some block needs to be changed, then it has to be changed in all of the panels that present this site area. That's a lot of clicking overhead, prone to errors and.. just doesn't feel right!

There are four solutions that I found in the internet, but all of them are lacking the beauty and cleanliness.

1. **panels everywhere site template** that would provide the required layout and blocks. Result: two variants to support (one in node panel, one in site template panel) and some CSS work since the blocks would be in different html hierarchy.
2. **panels multiple url module** (dont remember the name) that would allow multiple urls to be routed through the same panel. Every view will require adding it's page url into the panel and then adding it to variant. Result: two variants to support, CSS: ok.
3. **special panel for all views**. url of this panel would look like /view/%view\_name/%argument1/%argument2/... After such panel is created, you will need an URL alias to be created too. Result: two variants to support, CSS: ok
4. **nodes acting as selectors** for panels and views. every such "special" node is considered to be a view content and panels variant would remove the node itself and display a view content block instead. This could be the most beautiful way, but since it is a system panel, it lacks arguments that can be passed to view from url. So, no go. Result: one variant to support!! CSS: perfect! Minus: no support for arguments, so views with arguments would have to use another approach. Not perfect again.

Can anyone who has experience with panels/panels\_everywhere in combination with multiple views on their sites shed some light on this? Which of these approaches do you prefer? Are you using any other, more flexible, way to do that (maybe context module or any other, that I haven't started digging yet)?

Update: a simple example. There is a part of site named "corpo pages", which includes several types of content (news, press\_releases, available\_jobs, Q&A and couple of other), and a number of views, listing all this content in different ways. All of them should have same layout and same blocks in the sidebar and below the content. So, viewing content nodes is covered by panels.
Then the issues start when trying to add 5 views. Creating new views with content panes is followed by creating new panels with duplicated everything inside. Which is sort of no problem because it all can be cloned, the hard time starts with support, when the user wants to remove or add a new block, he will have to carefully go through all panels repeating the same action over and over again. I can already see his pain because something will be definitely forgotten.

Mini panels does pretty good job here, reducing such support effort and minimizing the human factor. But it comes with a price of in-place editor not working and overall user experience.

# Answer
If you have a consistent group of content panes that you want to appear in the same order with the same contexts, etc. in every variant, you can use a **Mini panel**, which is provided by the Mini Panel submodule of Panels.

That way, when you need to update one of the content panes, all you have to do is update the mini panel and all of the variants using that mini panel will automatically be updated.
> 1 votes

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


title: Programmatically change the Base URL?

text:
# Question
Title: Programmatically change the Base URL?
Is there any way to programmatically change the Base URL, Just as the "locale" module does..
My Website is multi-lingual which has to recognize 3rd argument, after the language identifier. Some custom code will be triggered when base on the third argument.

Have tried to Find a solution for this but the most of the Solutions suggest settings.php approach.

I am looking for a hook that will allow me to alter the third parameter in the URL for custom functionality.

Sample URL: www.example.com/hi/arg3 Above "hi" is the language identifier and "arg3" will be used for custom functionality. Hence a node to be rendered will have url as www.example.com/hi/arg3/node/1

# Answer
You can do that with:

`hook_url_outbound_alter`

Keep in mind all URLs run through that function so your hook implementation should be as fast as possible.

Example from locale module:

> Rewrite outbound URLs with language based prefixes:`locale_url_outbound_alter`

See also: `Language Negotiation API`
> 4 votes

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


# Question
Title: How do I remove all default styles (such as div.widthMarker) from CKEditor?
I have copied ckeditor.styles.js to /themes/seven/ckeditor.styles.js, and in the configuration page /admin/config/content/ckeditor/edit/Advanced I altered the predefined styles drop down to point to this new file:

```
if(typeof(CKEDITOR) !== 'undefined') {
    CKEDITOR.addStylesSet( 'drupal',
    [
            { name: 'Larger', element: 'span', attributes: {'class': 'size-1'} },
            { name: 'Epic', element: 'span', attributes: {'class': 'size-2'} },
            { name: 'MASSIVE', element: 'span', attributes: {'class': 'size-3'} },
            { name: 'Stupid!', element: 'span', attributes: {'class': 'size-4'} },
    ]);
}

```

Now when I load the WYSIWYG editor I still see other styles in the styles dropdown:

How do I remove the other styles that are not present in my ckeditor.styles.js file?

I have searched through all the code but can't find any reference to div.widthMarker or div.sortableListDiv except for in a .CSS file, but not everything in the CSS file is showing up.

Cheers,
\- Paul

# Answer
> 3 votes
In CKEditor profile settings /admin/config/content/ckeditor
click the edit link on the profile you want to change.

Under "Editor Appearance" uncheck "Stylesheet Parser plugin" and save. This will remove the default classes.

---
Tags: wysiwyg, theming
---


# Question
Title: ctools modal form shows ugly access denied
I have made a modal form using ctools. The form works okay when the user has access rights, but with no access rights an empty modal form is showing and I get a browser error saying

"An AJAX HTTP error occurred. HTTP Result Code 403" (and a lot of debugging information)

Is this a flaw in ctools modal or am I missing something?

In case of access denied I would like to fall back to a standard access denied message.

# Answer
> 1 votes
I will try to answer this myself. There is no mentioning of this issue in the CTools project itself but the issue is mentioned at the CTools Auto-modal project https://drupal.org/node/1450232

There is also a solution:

* implement hook\_page\_delivery\_callback\_alter
* check if callback is made by one of your ajax links
* if so, check is user has access by using menu\_get\_item and inspecting the resulting router item
* if access is ok, do nothing
* if access denied or page not found, render a message

The solution at CTools Auto-modal renders the message in the CTools modal box. But I preferred to kill the CTools modal and just do nothing:

```
$commands[] = ctools_modal_command_dismiss();
print ajax_render($commands);
exit();

```

This way the dreaded drupal ajax error will never appear.

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


title: Discussion forum for each group

text:
# Question
Title: Discussion forum for each group
I need to set up a forum kind of discussion board for each group that is created. Can anyone help me with this.

# Answer
You could use Panels and create a forum looking View (table) thats a copy of the same view that shows your Group content and then add it somewhere on the page. I wouldnt know how to add the 'forum' on a seperate page though.

You could add a select list in the group node form and have 'forum' or 'post' options.
> 0 votes

# Answer
Have you checked Og Forum D7 module?

This module allow to make some forum and their topics owned by an Organic group, just like any other group content.

This is simply done by adding a group audience field to the forum's taxonomy terms and topics and by automating some task (like selecting the same group audience for a topic than its parent forum)
> 0 votes

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


title: Views and Panels URLs

text:
# Question
Title: Views and Panels URLs
I am trying to understand how URLs work in D7 with Views and Panels. When setting up a new view or panel it asks you for a URL.

I am setting up a panel that will embed a few different views. This panel will be for the homepage. I have a view with the URL featured-items. I have successfully embedded it into the front page panel. However, it is also accessible at /featured-items. How do I prevent this from happening?

# Answer
When you select a Views "Page" type display, it must have a URL. And that URL is where this page will be accessed from.

There's a separate views display that's dedicated to be inside Panels, and that one is called "Content Pane" display inside views. This display doesn't take URL, but also has a lot more options for panels configuration such as argument input from panel, settings overrides such as pager, fields, items per page, base URL etc (need to explicitly allow each from the Views display "Pane settings").

So to answer the question, either use Content Pane display, or you can also use a Block display (as suggested by @JayendraKainthola) which is less flexible inside panels.

Once you've created the display Content Pane, it will be available in the "View panes" category when you're adding it to the panel.
> 1 votes

---
Tags: views, panels, uri
---


title: Change block titles from h2 to h3

text:
# Question
Title: Change block titles from h2 to h3
I want that block titles have the h3 tag instead the h2 tag. As I understand I have to change this in the file block.tpl.php. I found 4 block.tpl.php

* root/modules/block/
* sites/all/themes/omega/omega/templates
* sites/all/themes/omega/starterkits/omega-xhtml/templates
* sites/all/themes/omega/alpha/templates/

My question: Which one is the right file to change? I took now the one in the omega folder and it worked (the one in the modules folder did not). But I want to be sure whether this is the correct in order not to have side effects. And what for is the modules/block directory with files?

thanks for any feedback

# Answer
As a rule, we should never make changes in core files. If you will read the readme.md file in omega theme, you will see the following,

> Omega 4.x is a base theme and as such should **never** be used or modified directly. Instead, you should use the sub-theming functionality provided by Drupal.
>
> The easiest way to create a new Omega-based sub-theme is by using Drush. Omega comes with a very easy-to-use Drush command for generating sub-themes through a command-line wizard. You can start the sub-theme creation wizard by invoking `drush omega-wizard` in the command-line.

So you should first create omega sub-theme which is quite easy process and then make changes in sub-theme's block.tpl.php file.
> 6 votes

# Answer
Drupal gives you really easy ways to override core functionality, including themes and modules. In your case, the best thing you can do is to create a sub-theme for your Omega theme.

A sub-theme is basically a theme that inherits functionality from a parent theme. Follow the instructions from here: Creating a sub-theme

Once you've done that, you can manually copy those files from the parent theme into your sub-theme, to override them, and change them as much as you want.
> 0 votes

---
Tags: taxonomy-terms, blocks
---


# Question
Title: How to redirect logged in users accessing /user/login to specific page?
This is a very specific case.

When a user is **already logged in**, and then tries to visit the login page, `/user/login`, they are redirected to their user page, `/user`.

This is a problem for me and I need them redirected elsewhere. To be clear, I'm not asking the much-asked question "how to redirect users after login". I'm already using r3042login and login destination.

## The case explained

My site runs http and https for authenticated users. What's happening is that the user access the http site, then clicks login, logs in on https. Then the user presses Back, or a bookmark to the http site and they are not logged in (because they have a different session). So then they hit log-in, which redirects to the https site, which thinks "ah, you're already logged in!", and presents the user page. The user page is not of any interest to my users.

Ideally I'd have it such that once the https session was started, any access to the http site bounced them over to https again, until they logged out.

# Answer
> 5 votes
> Ideally I'd have it such that once the https session was started, any access to the http site bounced them over to https again, until they logged out.

Maybe it can be done on web server side, but I'm not sure.

> How to redirect logged in users accessing /user/login to specific page?

Don't forget you can alter any `drupal_goto()` calls:

```
/**
 * Implements hook_drupal_goto_alter().
 */
function YOURMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  global $user;

  if (current_path() == 'user/login' && $path == 'user' && user_is_logged_in()) {
    // Redirect to front page.
    $path = '';
    drupal_set_message(t('Welcome back, %username!', array('%username' => $user->name)));
  }
}

```

---
Tags: 7
---


title: Menu block module overrides

text:
# Question
Title: Menu block module overrides
I'm really confused with how to theme menus in Drupal 7 and I've found the Menu block module which is supposed to makes things simpler. Turns out it's not that simple for me.

I've created a Menu block called "*myfooter*" and thanks to the Menu block documentation page I was able to determine that the **mytheme\_menu\_link\__menu\_block\__myfooter()** function seems to be acting on the menu. Huzzah.

But I don't know how to use it at all. It's not as if there was a `$variables` inside and I could `var_dump` the var to try and understand what's in it.

Currently, I'm only doing the following to check that it's actually replacing my menu items by a simple print statement:

```
function mytheme_menu_link__menu_block__myfooter() {
  print 'test string';
}

```

Basically, my problem is that Drupal outputs the menu with an unordered list structure that I don't need.

```
<ul class="menu">
  <li class="lots of classes here"><a href="/" title="" class="blah">Item1</a></li>
  <li class="lots of classes here"><a href="/" title="" class="blah">Item2</a></li>
</ul>

```

How can I wipe it to simply print my items one after another, with a pipe sign or dash or whatever separator I wish? Is **mytheme\_menu\_link\__menu\_block\__myfooter()** even sensible to achieve that?

I've found a bunch of Drupal menu functions in the API but they are all so confusing I feel like I should stick to what Menu block offers.

# Answer
> 1 votes
Documentation for theme\_menu\_link():

```
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

The generated html needs to be returned as a return value.

The $variables argument has all the data.

Instead of var\_dump(), you should install devel and do a dpm($variables). You might have to refresh the page twice to see the result.

# Answer
> 0 votes
Finally discovered that I needed to use `THEME_menu_tree` to theme the parent **ul** and `THEME_menu_link` to theme the **li**. Not straight forward at all...

# Answer
> 0 votes
Another option is to use Menupoly and create your own MenuTheme class in a custom module or theme.

Pro: You can reuse this menu theme for different menus in different blocks, even across sites.

Con: You need code to define the block. And you need a bit of studying.

**How to**

The example module has some inspiration.
Incidentally, it already contains an example MenuTheme that does exactly what you want - a flat menu without ul list.

Next step is to define the block containing the menu.

```
/**
 * Implements hook_menupoly()
 */
function MYMODULE_menupoly() {
  return array(
    'flat_top' => array(
      'menu_name' => 'main-menu',
      'depth' => 1,
      // You can either use the MenuTheme class in menupoly_example, or copy it into your own module.
      'menu_theme' => new menupoly_example_MenuTheme_FlatLinksWithSeparator(' | '),
    ),
  );
}

```

Note: Menupoly uses xautoload to load the MenuTheme classes (and other classes), with the PHP 5.2 compatibility mode.

---
Tags: theming
---


# Question
Title: Unlimited values field - how to hide extra field on node edit
When creating a new node, I have this unlimited values field with the "Add new item" button.

That's OK, wonderful. But when I edit an existing node, I get an **UNDESIRED** empty extra value added for me:

My real case is with a big compound field, but I thought using this small field as an example would be easier to understand.

I there any way to prevent this "extra" field from being intrusively added?

# Answer
This would work for all node edit forms:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'field_YOURFIELD';

  if (empty($form[$field_name])) {
    return;
  }

  $field_language = $form[$field_name]['#language'];
  $max_delta = $form[$field_name][$field_language]['#max_delta'];
  unset($form[$field_name][$field_language][$max_delta]);
}

```
> 11 votes

# Answer
This would work for all node edit forms without even specifying the field names.

```
/**
 * Implements hook_form_NODE_FORM_alter().
 */
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node']->nid) && $form['#node']->nid > 0) {
    $form_fields = array_keys($form);

    foreach ($form_fields as $index => $field_name) {
      if (substr($field_name, 0, 6) == "field_") { // Check if the field is a custom field
        $field_language = $form[$field_name]['#language'];
        if (isset($form[$field_name][$field_language]['#cardinality']) &&
            $form[$field_name][$form[$field_name]['#language']]['#cardinality'] == -1) {

          if (empty($form[$field_name])) {
            continue;
          }

          $max_delta = $form[$field_name][$field_language]['#max_delta'];
          unset($form[$field_name][$field_language][$max_delta]);

        }
      }
    }

  }
}

```
> 3 votes

# Answer
You could write your own module with a hook\_form\_FORM\_ID\_alter to remove the unwanted field. Something like...

```
function my_module_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Do checks here to make sure this is an existing node...

  // Get the index of the last input element in this field
  $last_index = $form['field_field_name'][LANGUAGE_NONE]['#max_delta'];
  // Get rid of the last input element
  unset($form['field_field_name'][LANGUAGE_NONE][$last_index]);
  // Move back the last index so that any new elements are added correctly
  $form['field_field_name'][LANGUAGE_NONE]['#max_delta'] = $last_index-1;
}

```
> 2 votes

# Answer
if from a backend perspective is not possible for now, an alternative could be the following Jquery. This code will remove only the first target when is loaded the page, and only will remove the target when the user will add files, so you will not have problems when you already have files:

```
<script>
if(!$('div.filefield-file-info').length){
$('table#field_test_file_values tr.even:eq(0)').remove();
}
</script>

```

(put before the `body` closing tag of your page.tpl.php)

According my test, the images are uploaded without problems, and when you edit the node, all files are listed.

note: to this example 'field\_test\_file' is the name of the CCK field, so remember to change according the name of your cck field.
> 0 votes

---
Tags: 7, entities
---


title: Lock row in a view

text:
# Question
Title: Lock row in a view
I have a view that displays the most recent articles. However I want to add the option to lock an article on my view so it doesn't move when newer articles are added. Is there any way to do this?

So I would have to add a lock checkbox on the edit form of my article, and when checked, the article can't move on the view

# Answer
> 1 votes
Just use the "Sticky at top of lists" option on the nodes you want to keep at the top.

Then in the sort order of your View, sort by sticky nodes first, and then your normal sort order underneath.

---
Tags: 7, views
---


# Question
Title: how to show a message after a node form is submitted
How do I show a message (notice or alert) **after** the node form is submitted and saved?

I'm writing a module that synchronizes the node content with a remote endpoint. All working good. But, if for any reason the sync fails, I want to show a message on the page the user is redirected to.

My problem is that I don't find the hook or function which is invoked **after** the form is saved to databases but **before** the redirect happens, where I hopefully can set the message I want.

# Answer
You can create an additional submission callback. Not sure if it will run late enough for you. May be worth a shot.

Create a form alter hook using hook\_form\_alter(); Within there add an additional submit function to the #submit array

Example:

```
hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

```

You could try going 1 step further and adding the submit hook to #submit in the #after\_build. This will ensure it is the very last submit callback (unless other higher weighted modules also use the afterbuild)

Example:

```
hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'custom_afterbuild_function';
}

function custom_afterbuild_function($form, &$form_state) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

```

I hope this helps

\[update\] added drupal\_set\_messages to code examples.
> 4 votes

---
Tags: 7, status-messages
---


# Question
Title: Is there a recognized practice for keeping security details in files excluded from version control?
As `settings.php` also contains the database connection details and the site key among others, it is excluded from version control in `.gitignore`.

But there some modules, `APC` for instance that require some of their configuration to be added to `settings.php`.

This means that some settings necessary for the site to run correctly may not be present in a site created from a `git clone`.

Is there a standard practice for dealing with this, ie enabling `settings.php` for source control and `include`-ing the security and other settings from different files, or vice versa?

# Answer
We split our settings.php file into two separate files:

* **settings.php** (for configuration that applies to all environments)
* **local-settings.php** (for configuration that applies specifically to the current environment)

"settings.php" is stored in version control, while "local-settings.php" is excluded. Each environment has its own version of local-settings.php, which contains its database credentials and other configuration that applies only to that environment.

At the bottom of settings.php, we include the local-settings.php file.

```
/**
 * Check for a local-settings.php in this direcory. Include it if one exists.
 */
if (file_exists(dirname(__FILE__) . '/local-settings.php')) {
    include dirname(__FILE__) . '/local-settings.php';
}

```
> 5 votes

---
Tags: 7, security, version-control, configuration
---


# Question
Title: Can a sidebar span two zones in omega 3 theme?
I'm a bit of a newbee with Omega 3. I am having trouble arranging a grid which has a vertical sidebar span two zones. See the attached diagram to understand the design requirements. I need to have a left sidebar and content block both appear under the header, and a right sidebar that spans both the the header and the content.

I would like to know if it is possible to create such a grid within the standard Omega UI, or if not how can this be accomplished.

Thanks!

# Answer
> 0 votes
No, with the way the HTML is built, it goes

* zone-wrapper div (if used)
* + zone dov
* + - region div

In your case, I would leave the Header zone empty (make sure the checkbox for forced rendering is off), and then move all of your regions to the Content zone. In the grand scheme of things, there is nothing special about the Header zone. I am looking at one of my sites now, and I left Header empty.

With the default templates, the Content zone also contains the Breadcrumb and Messages, so you may need to tweak this a bit to output the regions specifically to get these in the proper place.

---
Tags: theming
---


# Question
Title: how to empty the first select option with form api?
I have made two select fields with the form api d7

and i need to make it required and the first option is null to force the user select both

i tried with #REQUIRED #EMPTY\_VALUE OPTION but gives error unsupported operands

i see the validation function may help but my case have an ajax request based on the first select to get the values of the second

so i need to make it required and the first is null

the code answer

```
 $form['gov']=array('#title'=>'Gov','#name'=>'governorate'
,'#type'=>'select','#options'=>$options,'#ajax'=>array('callback'=>'ajax_callback',
'event'=>'change','wrapper'=>'replace'
  ,'method'=>'replace'));

 $form['city']=array("#title"=>'City',
'#name'=>'city','#type'=>'select'
,'#prefix' => '<div id="replace">',
'#suffix' => '</div>','#options'=>$op);

```

also the ajax request only happens one time

# Answer
To make the input required you need to use `#required => TRUE`, and if you wants to add a empty default value you need to add a value to your `#options` like `'' => t('Please select')`

See Form API Reference
> 2 votes

# Answer
Add a empty value setting to the form array:

```
$form[$key] = array(
  ..
  '#empty_value' => '',
  ..
);

```

That will add a `- Select -` option to the list that will not pass a required validation if the user leaves it on `- Select -`.

Don't add an empty value to the #options array `'' => t('Please select')`. That will still pass a required validation if the user leaves that option selected.
> 5 votes

---
Tags: forms
---


# Question
Title: Drush - /usr/bin/drush: line 129: /usr/bin/php: Success
When I run any drush command I am getting this line:

```
/usr/bin/drush: line 129: /usr/bin/php: Success

```

For example:

```
[root@061889 ~]# drush
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush cron
/usr/bin/drush: line 129: /usr/bin/php: Success
[root@061889 ~]# drush help
/usr/bin/drush: line 129: /usr/bin/php: Success

```

I've tried rebooting my VPS but am still getting the same issue. This has been discovered while trying to get past a "Attempting to re-run cron while it is already running" error, in case that has any relevance. But, you've guessed it...

```
[root@061889 ~]# drush vdel cron_semaphore
/usr/bin/drush: line 129: /usr/bin/php: Success

```

Any ideas?

# Answer
> 0 votes
just run

> $ /usr/bin/drush

if it runs it means that your symlink to the drush command is wrong

---
Tags: 6, drush
---


# Question
Title: image_style_url no longer creates images
This started today on a website that has been running for over two months. I have a custom module that creates an image using the following code:

```
$image = image_style_url("catalogue_category_image_size", $product->field_product_image["und"][0]["uri"]);

```

This also did not work, but was the original code from earlier today:

```
$image = image_style_url("catalogue_category_image_size", $product->field_product_image["und"][0]["filename"]);

```

Here is the site, for reference: http://www.boudiccacollection.com/boudicca-catalog

I have no errors at all in the watchdog log or in apache logs. My status report page is green.

The only thing I would note is that the site was recently upgraded to drupal 7.23 from drupal 7.18

I have disabled clean url's to no avail.

**EDIT** I've added `$conf['image_allow_insecure_derivatives'] = TRUE;` to my settings.php and it did not correct the issue, however I now have error messages relating to 2 styles of one image (not all styles...)

Watchdog message: http://www.boudiccacollection.com/sites/default/files/styles/catalogue\_category\_image\_size/public/BR004\_WEB.jpg?itok=hetdMSsA http://www.boudiccacollection.com/boudicca-catalog Unable to generate the derived image located at public://styles/catalogue\_category\_image\_size/public/BR004\_WEB.jpg.

**EDIT** The same image is used in three places and works in one and not the other two.

Place 1 (broken):

Place 2 (broken):

Place 3 (works):

Place 3 has a different URL even though all of the code should be pulling the same image. Maybe this isn't an image\_cache problem...

# Answer
> 0 votes
How I fixed this issue:

1. Removed the image from the node and saved it. This threw an error because it was required, but it still permanently removed the image.
2. Uploaded the same image and saved the node.

I don't know why this broke or why this fixes it. If I get some time someday I may investigate a little more thoroughly.

# Answer
> 2 votes
There was a change on the Image derivative URLs by the Drupal 7.20 update, as the 7.20 release notes also states:

> The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)
>
> As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD\_VaCaD.
>
> In addition, any code which programmatically generates a link to an image derivative without using the standard image\_style\_url() API function will no longer work correctly if the image does not already exist in the file system, since the necessary token will not be present in the URL.

---
Tags: 7, media
---


title: Redirect to Continue Multi Step Form

text:
# Question
Title: Redirect to Continue Multi Step Form
I am building a form that can either begin on the home page or at the '/apply' url. I used this tutorial to build the multi-step form. The form works great if I start from '/apply' and begin at the very beginning of the form process. The form does not work if I start from the home page and get redirected to the second step of the form, then try to submit that second step. This is the error message I receive when I try to submit that second page of the form when I started on the home page:

```
PHP Fatal error:  Cannot create references to/from string offsets nor overloaded objects in /Applications/MAMP/htdocs/drupal/includes/common.inc on line 6548
PHP Stack trace:
PHP   1. {main}() /Applications/MAMP/htdocs/drupal/index.php:0
PHP   2. menu_execute_active_handler() /Applications/MAMP/htdocs/drupal/index.php:21
PHP   3. call_user_func_array() /Applications/MAMP/htdocs/drupal/includes/menu.inc:517
PHP   4. drupal_get_form() /Applications/MAMP/htdocs/drupal/includes/menu.inc:517
PHP   5. drupal_build_form() /Applications/MAMP/htdocs/drupal/includes/form.inc:131
PHP   6. drupal_process_form() /Applications/MAMP/htdocs/drupal/includes/form.inc:374
PHP   7. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:842
PHP   8. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP   9. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP  10. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP  11. _form_builder_handle_input_element() /Applications/MAMP/htdocs/drupal/includes/form.inc:1795
PHP  12. drupal_array_set_nested_value() /Applications/MAMP/htdocs/drupal/includes/form.inc:2003

```

I am attempting to continue the multi-step form from the home page to the '/apply' page by saving the `$form_state['storage']` array in the session, then reading it out of the session in the `custom_module_primary_form` function.

```
//Save form 'storage' in $_SESSION
function custom_module_first_form_submit($form, &$form_state) {
  ...
  if(request_path() == '') {
    $form_state['redirect'] = array('apply');
    $_SESSION['storage'] = $form_state['storage'];
    $form_state['rebuild'] = FALSE;
  }
}

```

This is the modified `custom_module_primary_form` function from the tutorial.

```
//Read form 'storage' out of $_SESSION
function custom_module_primary_form($form, &$form_state) {
  // Check to see if anything has been stored.
  if ($form_state['rebuild']) {
    $form_state['input'] = array();
  }

  if (empty($form_state['storage'])) {
    if(isset($_SESSION['storage'])) {
      $form_state['submitted'] = TRUE;
      $form_state['rebuild'] = TRUE;
      $form_state['storage'] = $_SESSION['storage'];

      unset($_SESSION['storage']);
    } else {
      // No step has been set so start with the first.
      $form_state['storage'] = array(
        'step' => 'custom_module_first_form',
      );
    }
  }

  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state);
  return $form;
}

```

# Answer
I would recommend reviewing the Drupal Contrib examples project:

> This project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.

It has an example in the form's submodule that provides you some working stub / skeleton code that you can learn, modify or apply to your own project.
> 0 votes

---
Tags: forms
---