# Question
Title: related content types - "top 10 best movies" functionality
Been trying to achieve functionality like below. \- Article "Top 10 best movies" when you enter the article it is a landing page with short text and then there are links to all ten movies - 10 through 1 like below:

Tried to do it with two content types - top10(the landing page) and movie(each movie from the top 10 list). Entity reference field on the movie content type pointing to the top10(the landing page). Then made a view listing all movies and filtering by the NID of the main article. But then when I enter the movie content type the links disappear (the nid of the top10 content type is missing). Then tried to make the view to be filtering by the etitiy reference field but then links pointing to other top10 articles appear... Fairly new to drupal and seems like I have meesed it up.

If someone can advise some clean idea would be much appreciated. Thank you in advance.

# Answer
It looks like you need to build functionality to allow users to see movies under different categories where diff categories are top 10, top 9 ....

Assuming we do not have any criteria to put movies under diff categories instead this is being handled while adding them through a content type.

I am not sure if this will be good solution but might help you,

* Create a vocab as movie rating add terms to it as within top 10,within top 9,within top 8... and so far upto top 1st.
* Add this vocab as term reference to content type responsible for generating movie nodes.
* Now every time you add a movie opt the appropriate taoxonomy field.
* Create a view for the same content type and keep the movie rating vocab as exposed filter as type links for this view, which will allow users to select the appropriate category as shared in the image in question.so this filter will automatically filter down the nodes as per the rating added while creating them.
* Allow your view to use ajax for better user experience.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Create destination directory with drush archive-restore?
I'm using this terminal command to restore an archive created on a remote server locally:

```
drush arr archive.tar.gz default --destination ./newdir --db-url=mysql://user:pass@localhost/db

```

The archive was created with drush archive-dump, and the restore is on a Mac running the MAMP stack. The archive is in the current working directory when I run drush arr.

In general, this works fine, but for some reason, the new directory (newdir) isn't created. All files are restored into a folder named "1" (which is created). Drush reports "Archive restored to 1"

Is there some way for me to modify the syntax so that newdir is created, and all files are restored there?

# Answer
> 1 votes
Try `--destination=./newdir`. Drush always uses --flag=value; without a value specified, the default is `1`.

---
Tags: 7, drush
---


title: Improving the "preview" of a node

text:
# Question
Title: Improving the "preview" of a node
I know how to override the preview of a node being edited, but for some reason in the "trimmed" portion it displays a node's title and in the "full" version only the body. I'd like to be able to display the node's title in the "full" version also.

The theme method I'm overriding is `theme_node_preview($variables)`.

I'm actually removing the "trimmed" portion completely, since it's not relevant to my content types. The method looks something like:

```
function theme_node_preview($variables) {
  $node = $variables['node'];

  $output = '<div class="preview">';

  $preview_trimmed_version = FALSE;

  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  $output .= $full;
  $output .= "</div>\n";

  return $output;
}

```

# Answer
> 2 votes
You could also try Page Preview, which shows a simulated full-page preview of a node:

> This module re-implements the Preview area of the node edit form as an IFRAME that renders and displays the full page view of your edited content as the anonymous user would see it, including elements such as blocks that display as a reaction to the page context.

# Answer
> 1 votes
This is my version of previewing the node, could be useful (ctools version):

```
    function foo_preview_node($form, $form_state) {
      $node = clone ctools_object_cache_get('foo', 'node'); // get the latest node object from the cache
      $node->in_preview = TRUE;
      _field_invoke_multiple('load', 'node', array(NULL => $node)); // additional stuff from other modules
      field_attach_prepare_view('node', array(NULL => &$node), 'full'); // lets field types and formatters load additional data needed for display
      $build = @node_view($node, 'full');
      $form['preview'] = array(
          '#type' => 'item',
          // '#title' => 'optional title',
          '#markup' => drupal_render($build),
      );
      return $form;
    }

```

See: http://drupal.org/node/1622952

---
Tags: 7, theming, nodes
---


title: Adding a new variation

text:
# Question
Title: Adding a new variation
I'm building a store using the *commerce kickstart* drupal distribution and I'm a beginner with it, however do possess some alternative Drupal 7 experience. Now, I need to add a different product variation type but when I try to add one, I and I want to add a Images field to it, the default Machine name assigned it field\_images and when I try to store my variation with this field, I get the message *The machine-readable name is already in use. It must be unique.* \- Fair enough you would think, but if I go and check in the existing sample variation types, there's multiple existing variation types that use the exact same machine name, \*field\_images\* this is, why is that? It puzzles me why I should not be able to do the same for a new variation type.

# Answer
> 4 votes
To add `field_images` to your product type, you need to use the "Add existing field" and not "Add a new field" Then the existing machine name is reused. Following that you can configure bundle specific settings under field "instance" settings, as opposed to the shared "global" field settings.

---
Tags: entities, commerce
---


# Question
Title: Why does my user migration ignore most of my source records?
I'm building a migration from d6 to d7. I have roles and taxonomies working, but my user import fails. My user migration class is an extension of DrupalUser6Migration.

drush ma shows:

```
Auditing migrations
ClickUser addFieldMapping: is_new was previously mapped from , overridden                                                                                [warning]
ClickUser
No problems found.

```

drush mi shows:

```
drush mi ClickUser
ClickUser addFieldMapping: is_new was previously mapped from , overridden                                                                                [warning]
Processed 947 (1 created, 0 updated, 0 failed, 946 ignored) in 3.3 sec (18/min) - done with 'ClickUser'

```

There are no messages for this migration. I don't know why only one user is being migrated. That one user is coming over great.

Thanks in advance for any help given.

Adding my implementation to aid in assistance.

```
<?php
/**
* Register all D6->D7 migrations.
*/
require_once('taxonomy.inc');

function clickMigrate_register_migrations() {
/**
 * Each migration being registered takes an array of arguments, some required
 * and some optional. Start with the common arguments required by all - the
 * source_connection (connection key, set up in settings.php, pointing to
 * the Drupal 6 database), source_version (major version of Drupal), and
 * group_name (a.k.a. import job).
 */
$common_arguments = array(
        'source_connection' => 'click2',
        'source_version' => 6,
        'group_name' => 'click',
);

$role_arguments = $common_arguments + array(
    'machine_name' => 'Role',
    'description' => t('Import Drupal 6 roles'),
);
Migration::registerMigration('DrupalRole6Migration', $role_arguments['machine_name'], $role_arguments);

 /*
  * User Picture Migration
  */
  $picture_arguments = $common_arguments + array(
  'machine_name' => 'UserPicture',
  'description' => t('some description'),
  'default_uid' => 1, // The default owner id if owner is not present
  'source_dir' => 'sites/default/files',
  'destination_dir' => 'sites/default/files',
  );
 Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);

// The description and the migration machine name are also required arguments,
// which will be unique for each migration you register.
$user_arguments = $common_arguments + array(
        'description' => t('Migration of users from Drupal 6'),
        'machine_name' => 'ClickUser',
        'role_migration' => 'Role',
        'picture_migration' => 'UserPicture',
);

Migration::registerMigration('ClickUserMigration', $user_arguments['machine_name'],$user_arguments);

global $vocabs;
foreach ($vocabs as $vocab){
    //$vocab['machine_name'] = $vocab['source_machine_name'];
    $vocabulary_arguments[] = $vocab;
}

$common_vocabulary_arguments = $common_arguments + array(
        'class_name' => 'DrupalTerm6Migration',
);
foreach ($vocabulary_arguments as $arguments) {
    $arguments += $common_vocabulary_arguments;
    Migration::registerMigration( $arguments['class_name'], $arguments['machine_name'],$arguments );
}

                      $menu_links_arguments);
}

 <?php
 class ClickUserMigration extends DrupalUser6Migration{
public function __construct(array $arguments) {
    $this->dependencies[] = 'Role';

    $this->sourceFields['field_contact_twitter'] = '';
    $this->sourceFields['field_contact_alternate_phone'] = '';
    $this->sourceFields['field_firstname'] = '';
    $this->sourceFields['field_contact_linkedin'] = '';
    $this->sourceFields['field_phone'] = '';

    $this->sourceFields['field_title'] = '';
    $this->sourceFields['field_department'] = '';
    $this->sourceFields['uid'] = '';
    $this->sourceFields['field_contact_type'] = '';
    $this->sourceFields['field_contact_primary_cont'] = '';
    $this->sourceFields['field_contact_image'] = '';
    $this->sourceFields['field_contact_image:list'] = '';

    parent::__construct($arguments);

    $this->addFieldMapping('is_new')->defaultvalue(TRUE);
    $this->addFieldMapping('uid', 'uid');
    $this->addFieldMapping('field_first_name', 'field_firstname');
    $this->addfieldMapping('field_first_name:language')->defaultValue('en');
    $this->addFieldMapping('field_last_name', 'field_lastname');
    $this->addfieldMapping('field_last_name:language')->defaultValue('en');

    $this->addFieldMapping('field_twitter', 'field_contact_twitter');
    $this->addFieldMapping('field_alternate_phone','field_contact_alternate_phone');
    $this->addfieldMapping('field_alternate_phone:language')->defaultValue('en');
    $this->addFieldMapping('field_user_linkedin','field_contact_linkedin');
    $this->addfieldMapping('field_user_linkedin:title')->defaultValue('');
    $this->addfieldMapping('field_user_linkedin:attributes')->defaultValue('');
    $this->addfieldMapping('field_user_linkedin:language')->defaultValue('en');
    $this->addFieldMapping('field_user_phone','field_phone');
    $this->addfieldMapping('field_user_phone:language')->defaultValue('en');
    $this->addFieldMapping('field_user_title','field_title');
    $this->addfieldMapping('field_user_title:language')->defaultValue('en');
    $this->addFieldMapping('field_user_department','field_department');
    $this->addfieldMapping('field_user_department:language')->defaultValue('en');
    $this->addFieldMapping('field_user_contact_type','field_contact_type');
    $this->addFieldMapping('field_primary_contact','field_contact_primary_cont');

    $this->addUnmigratedSources(array('field_contact_image', 'field_contact_image:list', 'field_contact_member_company','field_contact_linkedin:title','field_contact_linkedin:attributes','field_contact_twitter:title','field_contact_twitter:attributes'), t('Do Not Migrate'));

}
/**
 * Implementation of Migration::prepareRow().
 *
 * @param $row
 */
public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }

    /**
     * Note that the date module adds a timezone_name column to the users table,
     * so if present we can use that directly. Otherwise, we do as the D6->D7
     * upgrade does and just clear it - let users reset their timezones in the
     * D7 site.
     */
    if ($row->uid == 1) {
        return FALSE;
    }
}

}
class FileMigration extends DrupalFile6Migration {
public function __construct(array $arguments) {
    parent::__construct($arguments);
    $this->addFieldMapping('destination_file', 'filename');
}
 }

```

# Answer
> 0 votes
Based on what we discovered in the comments to this question, the migrate\_d2d.module's DrupalUserMigration class does some de-duplication to make sure that it's not creating users with the same email addresses as existing users. It skips source rows if the "mail" value matches that of an existing D7 user.

---
Tags: migrations
---


# Question
Title: In Ubercart Which Hook is reponsible for adding product to the cart page(On clicking add-cart-button)?
In ubercart,While buyer sees a product and clicks on add-to-cart button for buying that product, i want to know which action is responsible for that product being added in to the cart?

I want to edit the sell price, so that only this question. Already tried this hook, but it was not printing anything,

```
    mymodulename_uc_add_to_cart($nid, $qty, $data) {
    print "<pre>";print_r($data);print "</pre>";exit;

    if ($qty > 1) {
        $result[] = array(
                'success' => FALSE,
                'message' => t('Sorry, you can only add one of those at a time.'),
        );
    }
    return $result;
}

```

Which of these hooks

**hook\_uc\_add\_to\_cart
hook\_uc\_add\_to\_cart\_data
hook\_uc\_cart\_checkout\_start
hook\_uc\_cart\_display
hook\_uc\_cart\_item\_delete
hook\_uc\_cart\_item\_insert
hook\_uc\_cart\_item\_presave
hook\_uc\_cart\_item\_update
hook\_uc\_cart\_pane
hook\_uc\_cart\_pane\_alter
hook\_uc\_checkout\_complete
hook\_uc\_checkout\_pane
hook\_uc\_checkout\_pane\_alter
hook\_uc\_update\_cart\_item
uc\_checkout\_pane\_callback**

is responsible for adding quantity and price to cart in the cart page.Or is there any other hook which is doing it ?

Any ideas? Thanks in advance

# Answer
> 2 votes
If you want to alter the cart item, then you can use `hook_uc_cart_alter` of ubercart.

This hook is not in documentation of `ubercart 7` but its still working for `Ubercart 7`.

> This is called every time the cart is rebuild (e.g. when products are added), so it's a good place to alter the cart item.

I have checked `uc_coupon` module and hook `hook_uc_cart_alter` is implemented into that module. So, you can try this hook.

Edit: Code snippets to modify the price of item

```
/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your bid product

    $items[$index]->price = 100;
  }
}

```

For reference:

http://www.ubercart.org/docs/api/hook\_uc\_cart\_alter

# Answer
> 0 votes
with little googling I found this,might be what you are looking for

core add to functionality is handled by

`uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE`)

reference

http://api.ubercart.me/api/drupal/ubercart!uc\_cart!uc\_cart.module/function/uc\_cart\_add\_item/7

But if you are looking for a hook which allows you to penetrate your codes,

```
hook_uc_add_to_cart($nid, $qty, $data)

```

reference

http://api.ubercart.me/api/drupal/ubercart!uc\_cart!uc\_cart.api.php/function/hook\_uc\_add\_to\_cart/7

Also check the following links for more info about different API's

http://api.ubercart.me/api/drupal/ubercart!uc\_cart!uc\_cart.api.php/7

http://api.ubercart.me/api/drupal/functions/7

**Updates:**

Checkout already being discussed thread for custom alteration of prices here.

---
Tags: 7, ubercart
---


# Question
Title: How to use hook_node_presave to change field's value
Basically, I want to put first name & surname together into $node-\>field\_par\_contact\_name

But it gives me warning. (See below)

```
function partnership_node_presave($node) {
  if($node->type == 'partnership') {
    $first_name = $node->field_par_contact_first_name['und'][0]['name'];
    $surname = $node->field_par_contact_surname['und'][0]['name'];

    // https://drupal.org/project/field_hidden
    // Hidden variable
    $node->field_par_contact_name['und'][0]['value'] = $first_name. ' '. $surname;

    // Warning after save: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of .../drupal-7.23/includes/entity.inc
  }
}

```

**Updated**, please see image:

# Answer
For starters, you're probably using the wrong array key for the field value that you're saving; 'name' should be 'value' there.

```
$node->field_par_contact_name['und'][0]['value'];

```

Second, you're actually using Taxonomy Term Reference fields for your "first name" and "surname" fields. One important point about Reference fields is that you can't always assume that the referenced entities have been fully loaded and are available in your object. By default, when the node object is loaded, that field only looks like this:

```
$node->field_par_contact_first_name (Array)
  'und' (Array)
    0 (Array)
      'tid' => 284

```

Only the 'tid' key is definitely there. 'name' is a property of the referenced term, and isn't usually automatically available. (Subsequent code may actually load the referenced term and make it available within the $node object, but that's just happenstance if so.)

**You would have a much easier time of it if your "First Name" and "Surname" fields were text fields instead of references.** Then, those values would belong directly to the node itself, rather than to a separate taxonomy term being referenced.

If you're stuck using taxonomy term references, though, then you should make a point in your code to load the referenced term, then get the values you need from the $term-\>name property itself.
> 6 votes

---
Tags: hooks
---


# Question
Title: Drupal 7 Migrate: How do I migrate a mult-field key into a single taxonomy term
**Background: <br>** I am doing a migration on Drupal 7 using Migrate 7.x-2.5. And I am migration a Sql table into a Drupal taxonomy. The key to my source SQL table is comprised of three fields: element\_id, scale\_id, and category.

The taxonomy term name must be element\_id-scale\_id-category so that I can properly reference the taxonomy. Here is some sample data:

3.A.1 RW 1 None
3.A.1 RW 2 Up to and including 1 month
3.A.1 RW 3 Over 1 month, up to and including 3 months

So the taxonomy name for the first line above will be "3.1.1-RW-1" and the description will be none.

Here is my code so far:

````
$query = Database::getConnection('default', 'external_db')
         ->select('ete_categories', 'ete')
         ->fields('ete', array('element_id', 'scale_id', 'category', 'category_description'))
         ->orderBy('element_id', 'ASC');

// Create the source data feed using the variable $query

$this->source = new MigrateSourceSQL($query);

//       D E F I N E       T H E       D E S T I N A T I O N

$this->destination = new MigrateDestinationTerm('ete_categories');

//       D E F I N E       T H E       K E Y S

$this->map = new MigrateSQLMap(
  //  We have to tell migrate what the source key is
  $this->machineName,
  array(
    'element_id' => array(
      'type' => 'varchar',
      'length' => 20,
      'not null' => TRUE,
      'description' => 'Element Id',
    ),
    'scale_id' => array(
      'type' => 'varchar',
      'length' => 3,
      'not null' => TRUE,
      'description' => 'Scale Id',
    ),
    'category' => array(
      'type' => 'decimal',
      'length' => 3,
      'not null' => TRUE,
      'description' => 'category',
    ),
  ),

  MigrateDestinationTerm::getKeySchema()
);

//       M A P       T H E       F I E L D S

//  So let's map the fields

$this->addFieldMapping('name', CONCAT(`element_id`,'-',`scale_id`,'-',`category`));
$this->addFieldMapping('description', 'category_description');

````

**My Question**
I can concatenate the three fields into one using command line SQL. However, I do not know how to do this within the confine of the migration modules.(I realize that the code **"CONCAT(`element_id`,'-',`scale_id`,'-',`category`))"** is not valid migration code.)

So how do I concatenate the three fields together into a single field and set the destination field "name" equal to the concatenated fields?

Thanks

# Answer
> 1 votes
In your migration class, you can override the `Migration::prepareRow()` method to add a new name field to your rows:

```
  public function prepareRow($row) {
    $row->name = "{$row->element_id}-{$row->scale_id}-{$row->category}";
    return parent::prepareRow($row);
  }

```

And then simply map that field:

```
    $this->addFieldMapping('name', 'name');

```

But for simple concatenation, you can also use `SelectQuery::addExpression()` to add the `CONCAT(...)` to your SQL query:

```
    $name_alias = $query->addExpression(
      "CONCAT(element_id,'-',scale_id,'-',category)",
      'name'
    );

```

And then simply map the expression to the `name` field:

```
    $this->addFieldMapping('name', $name_alias);

```

# Answer
> 0 votes
I get two different results with the about two pieces of code. There are 41 rows to migrate.

When I use the first piece of code using the prepareRow, it worked great. I migrated 41 rows with the correct data in the name fields.

The second approach (addExpression) also worked, but it only migrated 4 rows, which is the number of unique Element Id there are. However, the names did contain the element\_id-scale\_id-category.

Also, I believe the following code has one to many ")"

````
$name_alias = $query->addExpression(
  "CONCAT(element_id,'-',scale_id,'-',category)",
  'name'
);

````

---
Tags: migrations
---


title: Panopoly add content panel

text:
# Question
Title: Panopoly add content panel
I have seen this Panel on Panopoly distribution where you can add different elements from the left side, add content to them and also have a preview.

I was wondering if this is powered by Panel (or its related contributed modules) or is only available if you install Panopoly?

Many thanks,

Luca

# Answer
> 1 votes
I just tested installing panopoly distribution and a series of module needed to build same functionality on standard drupal profile installation

Here are my findings

* The functionality you are asking does not seem to achieve with one contrib module instead its a result of lots of modules
* Check this link. This links lists the feature list or the main modules list.
* lets take panopoly\_pages contrib module, this module allows user to add content or landing page
* but again this module depends on several other modules to work in desired way
* Here is the link for complete list of all required modules.

**My findings**
* Installing all required modules I found it almost become the complete panopoly profile,so in my views it will be better to use panopoly distribution instead of separately installing the modules

How you can add this to existing site ?

Check out more on panopoly here.

---
Tags: panels
---


# Question
Title: Must an admin theme be enabled to be used?
I've created a sub-theme of the admin theme, Seven, in order to override some CSS used to display date combo inputs on a node edit form. The info file lists a new style sheet and the regions that are defined in the original Seven info file.

Everything seems to work fine if I select this sub theme as the Admin without even enabling it. I can easily override the CSS.

However, if I also *enable* the sub theme, blocks suddenly appear inside the admin theme whenever it's invoked\*. I believe this is because the new sub theme has different (default?) settings for active blocks in the block table. (rfay has a solution for this problem here: http://randyfay.com/content/changing-theme-name-or-adding-subtheme-without-losing-block-and-theme-settings)

My question: Is it necessary to enable a theme/sub theme that will only be used as an Admin theme? If so, is there any way to avoid the block problem, or is that just the way it goes?

* Edit: A lot of blocks appear in the new admin theme when it is enabled. Below is a visualization of the blocks table. Before the custom theme is enabled, it does not appear in the block table, so there are no blocks at all. After it is it enabled, the 12 blocks from the main theme ("custom" in the table) are all placed into the content area. Blocks might end up in the Content region because regions in the enabled theme don't exist in the customized seven theme? In any case, it's just a nuisance really, and can be easily fixed using the SQL at the link above. However, if there is no downside in using an admin theme that is not enabled, the block clean up wouldn't be needed.

# Answer
No, it's not needed to enable theme to use it as an admin theme. You only need to enable it if you want to alter it's settings, both the ones in "appearance" section, and blocks. Just go to http://example.org/admin/structure/block/list/seven and http://example.org/admin/structure/block/list/your-seven-subtheme and set up the blocks the way you want them, that's all.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Adding variation types and sub variation types
I'm new to *commerce kickstart* and am wondering how I can create variation types and "sub" variation types? I would like to create an architecture that allows me to have a variation type `fruits` and then sub types `apples` and `oranges` e.g. - how can I do this?

# Answer
> 2 votes
You can create `fruits` as taxonomy and assign this to your product type.

Creating Taxonomy:

* Go to Administration -\> Structure -\> Taxonomy.
* Click on "Add vocabulary" link to create new taxonomy and it will redirect you to taxonomy form.
* Add `name(fruits)` for `vocabulary` and save the form and it will redirect you to list of `taxonomy`.
* Click on `list terms` in row of `fruits` taxonomy.
* Click on 'Add Term' link to add new term for `fruits` taxonomy.

Assign `Taxonomy` to product type:

* Go to Administration -\> Store -\> Product
* Click on `Product types` link in top of page and it will redirect you to list of `Product types`.
* Click on `Manage fields` link in row of `Product`.
* Add `Term Reference` field and select `fruits` as vocabulary and save the form.

Selecting taxonomy as menu:

If you want to display taxonomy as menu, you can use 'Taxonomy menu' module.

> Transform any of your taxonomy vocabularies into existing menus easily!

`Taxonomy menu` will create your `Taxonomy Term` as menu item.

Configuration of Menu:

* Edit your taxonomy in admin and select Menu location for `taxonomy menu`.

---
Tags: nodes, commerce
---


# Question
Title: User name who flagged in Global Node flag
I have a global node flag where editors can flag the Node article as famous. There are more than 10 editors, so, I want to display in the node who flagged it and when. I used Views Relationships to get the flag data, I could easily get the flagged time but couldn't get flagged user. I tried with flag users relationship but it results in Anonymous user instead of the user who flagged.

Is there any way I can display the user who flagged it ?

# Answer
For those who are in similar situation, I'd like to inform that at the time of writing, **This is Not Possible with Flag**. Flag module is just ***Boolean*** true/false.

I changed the ***flag*** to ***Vote*** using VotingAPI and Plus One modules. The VotingAPI has Views integration and via views ***Relationship***, I could get the ***User information*** and ***Vote Timestamp*** to display in the page.
> 2 votes

---
Tags: views, flags
---


title: Custom Filter in Views using Drupal 7

text:
# Question
Title: Custom Filter in Views using Drupal 7
i have a content type having two major fields.

A and B

Now i want to get all resutls of those nodes .

if A having value of 1 or B having value of 2.

if anyof node matched with one field i need to show result.

How to do this in views ?

Thanks.

# Answer
You can follow this using below step:

* Go to Administration -\> Structure -\> Views
* Edit your existing view or create new new.
* Add Filter 'A' and B in your view
* Click on "Rearrange" filter icon in Filter section
* Click on "Create new filter group" and move filter "A" and "B" in new filter group.
* Select Operator as "Or" in new filter group and save the form.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to insert an image into a drupal form
Is it possible in drupal7 to insert a photo in drupal form? I have a start interface that contains two buttons leading to two athors interfaces and I would like to insert a photo above the two buttons. I have tryed the next but it didnt work

```
function my_module_start_form($form, &$form_state) {
  $image_options = array(
    'path' => 'path/to/img.jpg',
    'alt' => 'Test alt',
    'title' => 'Test title',
    'width' => '50%',
    'height' => '50%',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
  );

  $image = theme('image', $image_options);

  $form['start']['image'] = array(
    '#markup' => $image,
  );

  $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );

  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );

  return $form;
}

```

# Answer
> -2 votes
May be this will help..

```
 function my_module_start_form($form, &$form_state) {
 $image_options = array(
'path' => 'path/to/img.jpg',
'alt' => 'Test alt',
'title' => 'Test title',
'width' => '50%',
'height' => '50%',
'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

 /*$image = theme('image', $image_options);
  $form['start']['image'] = array(
    '#markup' => $image,
  );*/
    print theme_image($image_options);//print the image

    $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );
  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );
    return $form;
}

```

---
Tags: 7, forms
---


# Question
Title: In hook_node_insert drupal_goto with alias name not working
In hook\_node\_insert() i have used drupal\_goto(), to go to the newly created node with alias name of it, but id doesn't work.

**I have already created url alias with patterns for that content type.**

```
$alias = drupal_get_path_alias('node/'.$node->nid);
drupal_goto($alias);

```

If i give drupal\_goto() with nid it works.

```
drupal_goto('node/'.$node->nid);

```

What is the issue with respect to alias name not working or how to get alias of newly created node and get it redirected to view page of it with alias name as url.

Any ideas or suggestions? Thanks in advance.

**\[Updated code\]**

This is the code which i am trying

```
function hook_node_insert($node)
{
    if($node->type == 'product')
    {

        $_SESSION['product_node_nid'] = $node->nid;
        $banner = $_SESSION['banner'];
        $theme = $_SESSION['theme'];
        $params = array();
        $params['node'] = $node;
        $site_email = variable_get('site_mail', '');
        if(($banner || $theme) || ($banner && $theme)) {
            drupal_goto('payment-approval');
        }
        else {
            //$alias = drupal_get_path_alias('node/'.$node->nid);
            module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module
            pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $language->language); // Language is optional
            $alias = drupal_get_path_alias('node/'.$node->nid);
            //$alias = drupal_get_path_alias('node/'.$node->nid); print_r($alias); exit();
            drupal_goto($alias);
        }
    }
}

```

# Answer
> 2 votes
Third variable for `module_load_include()` function is missing in your code.

You should use code `module_load_include('inc', 'pathauto', 'pathauto');` instead of `module_load_include('inc', 'pathauto');`

There is another method for your problem that you can use `hook_form_alter` instead of `hook_node_insert` hook in your module.

`hook_node_insert` will execute if you will insert node using any other method like importing node using `feeds` module.

**Update Code:**

```
function custom_feature_node_insert($node) {

  $options = array('language' => pathauto_entity_language('node', $node));

  //$alias = drupal_get_path_alias('node/'.$node->nid);
  module_load_include('inc', 'pathauto', 'pathauto'); // include the inc file for Pathauto module

  pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $options['language']); // Language is optional
  $alias = drupal_get_path_alias('node/'.$node->nid);

  drupal_goto($alias);

}

```

# Answer
> 2 votes
I checked the drupal\_goto and found out that you must provide the path for parameter. You can't use alias for drupal\_goto. So i think you can solve your problem like that:

1. While you create node. You will also create the alias for that node. The reference for create the alias for node here. In your code just normally redirect like that

```
drupal_goto('node/'.$node->nid);

```
2. After that you will install Global redirect module. This module will have responsibility to redirect your node/nid to your node's alias

**\[Updated\]**

Can you try to generate the alias by using the Pathauto. So can you put these code in hook\_insert()

```
function yourmodule_node_insert($node){
  module_load_include('inc', 'pathauto');
  pathauto_cleanstring($node->title);
  $node->path = array('pathauto' => TRUE );
  drupal_goto('node/'.$node->nid);
}

```

# Answer
> 1 votes
drupal\_get\_path\_alias() expects a full internal Drupal path, like this:

```
drupal_get_path_alias('node/23');

```

However, you're only giving it an NID, which is being evaluated like this:

```
drupal_get_path_alias(23);

```

---
Tags: 7, nodes, path-aliases
---


title: Multiple exposed search filters

text:
# Question
Title: Multiple exposed search filters
Maybe I am trying to do something simple and I am just blind, but after a day of hard work I am desperate...:

1. I have view, created using Views 3 module, with source in index of Search API module
2. I have Profile two custom fields on User Entity, named "Name" and "Surname".
3. I am using two "Search: Fulltext search" exposed filters in View, grouped using AND. The first with "Contains all of these words" and the second with "Contains none of these words".
4. I have user with "Name" = Vysakh, "Surname" = Babu

Now:

* When is in first "Search: Fulltext search" exposed filter with rule "Contains all of these words" written "Babu" (without speech marks), it founds his profile. Great.

But:

* When is in second "Search: Fulltext search" exposed filter with rule "Contains none of these words" concurrently written "Vysakh" (without speech marks), instead of excluding his profile as well (thus showing empty result), view shows all the profiles, except Babu Vysakh...

Any ideas why and what can I do?

I tried all combinations of exposed filters, put them to different groups, switch from "Search keys" to "Search filter"... No luck.

# Answer
> 1 votes
There is actually a bug in Search API 7.x-1.8.

The full-text views' filters handler is able to use only one exposed filter (the last one in stack, the previous instances are overwritten).

While it was a LOT of hacking in the Search API module, the simple answer is: you can use only one exposed Search filter in Views with Search API 7.x-1.8 without extensive PHP coding.

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


# Question
Title: Poll Listing, Where admin can rate and user and rate a poll?
I need to develop a page, where we need to display a list of polls which are published.

and

Need to create a content by admin where user and admin, both can rate it.

Does anybody suggest a contributed module or Do i need create custom Module for it?

# Answer
> 0 votes
You could use the Advanced Poll Module.

> > Advanced Poll is a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.

For more details you could go through the README.txt of this module.

---
Tags: 7, polls, rating
---


# Question
Title: How to load node with AJAX on a Calendar click?
I want functionality like this: when user clicks a node link in a calendar view, the details of the node should be loaded tu another region with AJAX. How to achieve this?

# Answer
> 1 votes
You can take help of Drupal hook\_menu with Json object output and a Drupal JS beahvior to handle click event.

Idea : In the click event call an ajax function to your menu callback that gets you a JSON object of required content. Load the content in your desired DOM element.

code for hook\_menu; considering your module name 'mymodule'

```
function mymodule_menu() {
  $items['mymodule/%node/load-content'] = array(
      'page callback' => 'mymodule_ajax_node_load_content',
      'page arguments' => array(1),
      'access arguments' => array('access content'),
  );
  return $items;
}

```

code for Page callback :

```
function mymodule_ajax_node_load_content($node) {
  // The variable holds complete node object for you.

  $data = array();

  $data['body'] = $node->body['0']['value'];
  // Consider providing any other node details if required.

  $output = array('status' => 'ok', 'data' => $data);

  return drupal_json_output($output);
}

```

JS code for attaching a behavior to Drupal,

```
Drupal.behaviors.nodeLinkClick = {
  attach: function(context, settings) {
    // sort by click.
    $("a.node-link").click(function(e){
      e.preventDefault();
      $.ajax({
        url: Drupal.settings.basePath + 'mymodule/' + nid + '/load-content',
        type: 'GET',
        data: data,
        dataType: 'json',
        success: function(response) {
          $(".dom_to_load_content").html(response.data.body);
        },
        error: function() {
          // show error in any DOM.
        },
      });
    });
  }
}

```

NOTE : The above code not tested; a small snippet cut-out from my project. Hope this helps you. Let me know if you still facing any problem.

---
Tags: ajax, datetime
---


# Question
Title: how to enable comments only to subscribed users
I'm creating a site for events where people can subscribe themselves to a single one. Now, I'm using Node Registration module to allow users to subscribe. I would like to know if it is possible to enable comments of a particular event only to users who are members of it. Is there a module to do this? I tried with rules module but i couldn't...

# Answer
Here is a programmatic way to do this, add this code to your custom module

**NOTE:**

In the following code my content type name is article, change it to yours.

Also this code can not handle functionality for anonymous user as I couldn find a way to track if anonymous user is already registered or not.

```
/**
  * Helper function to check if user is registered to a given event node or node.
 */
function check_if_user_is_registered($node, $uid) {
   $return = FALSE;
   $registrations = node_registration_load_multiple(FALSE, array(
      'uid' => $uid,
      'nid' => $node->nid,
      'cancelled' => 0,
    ));
  if(is_array($registrations)) {
    foreach($registrations as $registration) {
      if($registration->author_uid == $uid) {
        $return = TRUE;
      }
    }
  }
  return $return;
}

/**
  *  Implements hook_node_load().
 */
function MYMODULENAME_node_load($nodes, $types) {
  global $user;
  foreach ($nodes as $node) {
    if($node->type == "article") {
      $access = check_if_user_is_registered($node,$user->uid);
      if(!$access) {
       $node->comment = 0; // to close comments
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, comments, notifications, nodes
---


# Question
Title: How to modify attributes of fieldset-wrapper?
It's similar and connected to How to modify attributes of \<label\> in form definition function? \- This time I want to ask how to modify attributes of a `<div class="fieldset-wrapper">`. HTML structure of a fieldset is:

```
<fieldset id="some-id" class="well-small form-wrapper vertical-tabs-pane">
  <legend>
    <span class="fieldset-legend">
      Lorem Ipsum
    </span>
  </legend>
  <div class="fieldset-wrapper">
    <span class="some-field">
      <!-- Irrelevant -->
    </span>
  </div>
</fieldset>

```

I need class `well-small` directly on a fieldset-wrapper div. But if I apply it to a fieldset itself, it appears when you see it in sample above. When I move it one level down, well, there are only fields there, so it's one level too far instead of one level too close to the document root. Is there a way to conditionally add classes and other attributes directly from form building functions?

CSS and JS workarounds are out of the scope for me. I know how to work around it. Now I'm asking to know how to do it directly in PHP.

# Answer
Looking at `theme_fieldset` the `fieldset-wrapper` class is hardcoded and that div doesn't take any additional classes from the `$variables` array.

So looks like the only option is to override `theme_fieldset` in your `template.php` of the active theme. If your conditional variables are present in `$variables` then you could do the logic straight in the `theme_fieldset` override function (replace `mythemename` with the name of your theme)

```
function mythemename_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  }

  // Condition/logic here
  $class = '';
  if($variables['....'] == '....') {
    $class = ' well-small';
  }

  $output .= '<div class="fieldset-wrapper'.$class.'">';
  if (!empty($element['#description'])) {
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '</div>';
  $output .= "</fieldset>\n";
  return $output;
}

```

Otherwise, a more elegant solution (by @Mołot) would be to supply use `drupal_attributes` like so:

```
mythemename_fieldset(&$variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  }

  $element['#wrapper-attributes']['class'][] = 'fieldset-wrapper';

  $output .= '<div' . drupal_attributes($element['#wrapper-attributes']) . '">';
  if (!empty($element['#description'])) {
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '</div>';
  $output .= "</fieldset>\n";
  return $output;
}

```
> 5 votes

---
Tags: theming, forms
---


title: httpd.conf clean urls issue

text:
# Question
Title: httpd.conf clean urls issue
As I have multiple Drupal sites on my server, I am attempting to enable clean urls via the httpd.conf file.

I am using the following code:

```
<Directory /var/www>
   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

```

However, when I visit check the **Enable clean URLs** box and click the save button, my website just reloads as my **index.php** file showing the phpinfo() data.

Can anyone tell me where I'm going wrong, please?

# Answer
> 1 votes
It is hard to tell what your exact problem is, but the default .htaccess does more than just redirect requests to index.php. It

* Protects certain directories and files from being accessed
* Set up safe PHP defaults for those with old configurations
* Sets up some baseline cache rules
* Redirects directory/file not found to index.php

In addition, the catch-all rules that you are using is not the correct one for Drupal 7.

Unless you really know what you are doing, you should keep the .htaccess in each Drupal site's DOCROOT, and then configure your server to support multiple sites using the normal methods. You really shouldn't have to do any configuration specifically for Drupal, other than potentially needing `AllowOverride All`. Personally, I use virtual hosts on all of my servers. The Apache config for each site essentially looks like:

```
<VirtualHost *:80>
  ServerName www.example.com
  ServerAlias example.com *.example.com

  DocumentRoot /var/www/example/docroot

  <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
  </IfModule>

  <Directory /var/www/example/docroot>
    AllowOverride All
  </Directory>
</VirtualHost>

```

That could run just about any site on the planet, Drupal, PHP, or otherwise.

On high volume sites, it sometimes makes sense to avoid .hatccess files (they are scanned every request), and place *everything* in your apache config (where it will be parsed/stored upon startup).

---
Tags: 7, uri
---


title: Problems with Services and CSRF token

text:
# Question
Title: Problems with Services and CSRF token
I've been trying to create a user via webservice without doing any custom coding or curl.
This post got me 75% there: How to create test\_endpoint?

I finally got it working, but only by passing in my creds with each request. CSRF token header is ignored.

I'm using the Services and Services basic authentication modules.

I do an initial GET request to services/session/token with Basic auth headers with my username/password and get the token as expected. In the next call, POST to rest/user, I have the CSRF token (HTTP\_X\_CSRF\_TOKEN) and Content-type (application/json) and json encoded user data in the body. Instead of authenticating with the token, I get a login popup.

If instead I send the Basic auth headers with my username/password along with the create user request and json data, it works. I don't understand why CSRF is being ignored.

Thoughts?

Edit: One other note. In testing I used both the FF RestClient and FF Poster plugins. I have not tested on Chrome.

# Answer
> 3 votes
For future users, there's a bunch of confusing examples out there. Based on the above link example this is my working setup:

URL: /rest/user.json

Headers:

```
"X-CSRF-Token":"fsddfhbusoibdfbdsbfoubewbfw"
"Content-Type":"application/json"

```

Body:

```
{
 "name":"username",
 "pass":"password",
 "mail":"email",
 "field_user_full_name":{"und":[{"value":"CHECK1 n CHECK2"}]},
 "roles":[4],
 "status":"1",
 "language":"und"
}

```

---
Tags: 7, users, services, csrf
---


# Question
Title: Do not send registration mail to fake users, who haven't specified their gender in registration form
Since several years I run a Drupal 7 web site \- as a frontend to a multi-player card game.

I have the following SPAM protection at my web site: the new users should specify their gender at the registration (it should be "Male" or "Female", but not the default "Robot") and then they have to play the card game:

Every night I run a cronjob, which deletes users who have wrong gender or who have registered 10 days ago and still haven't played:

```
delete from drupal_users
where uid <> 0 and
to_timestamp(created) < (now() - interval '10 day') and
uid not in (select distinct id from pref_money); /* haven't played the game */

```

This does work well, BUT recently the amount of registering fake users has increased to hundreds per hour and my site keeps sending lots of registering mails (which bounce then to my poor mailbox) every minute.

**So my question is:** how NOT to send the registration mail to users who have their gender set to "Robot"?

Here is what I have found sofar:

1) The gender (an additional field at my reg. form) can be found the following way:

```
        $result = db_query('select field_gender_value from {field_data_field_gender} where entity_id=:id', array(':id' => array($viewer_id)));
        $gender = $result->fetchField();
        if ('Robot' == $gender) {
           ....
        }

```

2) And I probably should provide a `hook_mail_alter` in my custom module:

```
function MY_CUSTOM_MODULE_mail_alter(&$message) {
  # XXX how to find gender here?
  if ('Robot' == $gender) {
      # XXX how to abort mailing for registration only?
      $message['send'] = FALSE;
      return;
  }
}

```

But in 2) I don't know 2 things - how to find the gender value there and how to cancel the registration mails only?

Any suggestions please?

*Please do not suggest the Mollom module or any standard Drupal anti-spam measures, because my question is very specific.*

# Answer
> 2 votes
I suggest you implement hook\_form\_id\_alter to either add a new validation function to the registration form, or replace the submit callback.

In a validation function, you have access to the form values, and you can do whatever checks you want, and fail the submission. This will reject the form all together.

If you replace the submit callback instead, you could override only the sending of the e-mail. but otherwise let the form pass through, which seems closer to what is being asked for.

---
Tags: emails, advertising, users
---


title: commerce_customer_address

text:
# Question
Title: commerce_customer_address
I am using Commerce Kirckstart installation.

I would like to change a field in `commerce_customer_address`. I only want a new field, like `telephone` and I would like to remove State. Some one knows how to do without code. thanks

# Answer
> 1 votes
Commerce customer profile uses an address field, whose columns are defined by the addressfield module.

It's not possible to alter those columns without writing code, so you're out of luck.

Also, I'd imagine that removing the state field would incur quite a bit of extra work, as existing validation/submission functionality would need to be overridden.

The easiest thing you can do is add the telephone number field to the profile type entity itself, and use a form alter or CSS to remove/hide the state field.

---
Tags: commerce, entities
---


# Question
Title: How can I make a usable backup of the site on CD?
The client would like to archive off a copy of their drupal 7 site every 6 months or so. By archiving, they are referring to copying the site (in a usable format) onto a cd.

What are some of the options for doing this?

# Answer
> 0 votes
The Backup and Upgrade module can be used to schedule automated database backups. One of those backups, combined with the codebase, gives you a full backup of the site. If this is to be burned to a disc every 6 months, I wouldn't bother automating anything - the time investment won't be worth the future time savings.

# Answer
> 0 votes
You should just use this: http://drupal.org/project/backup\_migrate\_dropbox as it will backup directly to your dropbox account or straight into your clients computer. From there you can just burn the CD or do whatever you want with the files. You have have it automated and it can backup every couple of days or months if you like. Just set and forget it kind of thing.

# Answer
> -1 votes
@kine456 : Some years ago, after a client request, I used Server2Go (http://www.server2go-web.de/) and it works pretty well with a small Wordpress site. Stunnix may works as well (http://stunnix.com/prod/aws/). But it is not, in both case, the way to a store a backup.

---
Tags: backups
---


# Question
Title: How do I modify the attributes of <label>?
I need to be able to change attributes (like `class`, `data-toggle`, `data-direction`) of the label itself, at a PHP level, in a way that will support conditions in form definition function.

The solution given in How can I add a class to a label? doesn't work for my problem, as they are only workarounds that will not work with the theming JavaScript I need to expose my data to. Also, they are pretty much limited to styling, and that's only one of the attributes that may be needed.

I'm OK with only having limited, predefined sets of attributes, as long as I can select one at the time of form building.

# Answer
> 2 votes
Solution is to implement `theme_form_element_label`.

Changing one line from:

```
$attributes = array();

```

to:

```
$attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

```

in your implementation makes it possible to use '#label\_attributes' just the way you would use normal `#attributes`.

**NOTE:** If your parent theme defines this function already, then you need to copy function from parent theme, not from `form.inc`.

---

Full implementation, to put in template.php:

```
function mymodule_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  // NOTE: CHANGED LINE BELOW!
  // If there are attributes already, use them. If not, create empty array.
  $attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

```

---
Tags: 7, forms
---


title: drupal_goto() usage

text:
# Question
Title: drupal_goto() usage
I did some research about using `drupal_goto('page')`, and I noticed that the parameters of the function can be only the path of the destination page.

I want to use this function in a form submission handler. Can I take the submitted values and use them with `drupal_goto()` as in the following code?

```
function my_module_form_submit($form, &$form_state) {
  $database_name = $form_state['values']['databasename'];
  drupal_goto('page', $database_name);
}

```

# Answer
> 4 votes
In a form submission handler, there is no need to use `drupal_goto()`, and it should be avoided, since it stops the other form submission handlers from being called.

If you need to redirect the users to a page, you should use `$form_state['redirect']`, which accepts the same parameters used by `drupal_goto()`. In particular, the following code will redirect the users to node/123?foo=bar#baz, if other modules don't alter the redirection, and other conditions are met.

```
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

```

As for passing the values contained in the array `$array` to the redirection URL, that is easily done with the following code.

```
$form_state['redirect'] = array(
  // Se the values you need.
);

$form_state['redirect']['query'] = drupal_get_query_parameters($array, array());

```

If then the need is just to pass data from a page to another, there are better solutions, such as passing the data into the session data. I would rather use that, since theoretically there isn't a limit to that data stored as session data, while a URL cannot be longer than X characters.

### Reference

---
Tags: forms
---


# Question
Title: How to hide rating field when adding comment to own node?
On my website, users can rate nodes with the Fivestar module while adding a comment. In other words, the rating field (called 'stars') is part of the comment. Now, I'd like to hide the rating field for users when they comment on their own nodes *(or when they already have commented before - see: How to hide Fivestar rating field after first comment?)*.

How can I do that?

---

**Edit 1:** I applied this patch (patch 97 on https://drupal.org/node/189527), but my problem still isn't solved. I now have the following option at *Administration \> Structure \> Content types \> MyArticle \> Comment fields*:

But after clearing caches and creating new content, the rating field is still displayed when I add a new comment.

---

**Edit 2:** I sent an e-mail to the patch's author and he answered this:

> The purpose of the patch I created is to prevent a user from rating their own node. I believe the problem you are having with this patch is that, since the fivestar field is on the comment, that the patch I wrote would probably reference the comment itself (as the entity id) instead of the node - freely allowing someone to vote.

---

**Edit 3:** I tried to solve my problem with a custom module called 'hiderating'. This is the code I'm using:

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      $form['field_stars']['#access'] = 0;
      }
      else {
      $form['field_stars']['#required'] = 1;
      }
    }
}

```

I made the 'Stars' field not required from the interface. The code is nearly working: the 'Stars' field isn't displayed when one comments on his/her own node, but unfortunately, it isn't turned to 'Required' when one comments on someone else's node. In other words, my code's `else` part doesn't work properly.

How can this be fixed?

# Answer
You should use `unset($form['field_stars']);` instead of `$form['field_stars']['#access'] = 0;`

You can keep the fields as required and also remove the else condition.

So your final code would be something like this

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
      }
    }
}

```
> 1 votes

---
Tags: 7, entities, comments, rating
---


title: hide collapsible fieldsets on node edit

text:
# Question
Title: hide collapsible fieldsets on node edit
I understand how to edit a specific content type with form\_alter

```
my_module_form_node_form_alter(&$form, $form_state) {

  $type = $form['#node']->type;

  if ($type == 'my_content_type') {

  }
}

```

I would like to hide all collapsible fieldsets EXCEPT scheduling. How do I only target these other fieldsets to hide?

http://screencast.com/t/ozHu5esPGc

# Answer
Dull ax approach would be to cycle through your `$form` looking for fieldsets and unsetting (now setting `#access` to `FALSE`) all but the one you want to keep, eg, something along the lines of...

```
// drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');
foreach($form as $key => $field) {
  if ($key != 'field_FIELDNAME' && is_array($field)  && $field['#type']=='fieldset' && $field['#collapsible']) {
    // unset($form[$key]);          // ADDITION/EDIT: '#access' below is a better/working approach
    $form[$key]['#access'] = FALSE; // than unset if required fields are in the fieldset :)
  }
}

```

...with the `drupal_set_message()` helping to get the `field_FIELDNAME` for your scheduling fieldset.

Just realize that without further logic, you would never be able to edit any fields inside these fieldsets again.

Another option might be to check out the nodeformcols module that makes lengthy node forms a bit nicer and does contain this functionality out of the box for both fields as well as fieldsets.
> 1 votes

# Answer
by using #attached property you can add js to this form in this form alter only. And using jQuery .hide() function you can hide the divs of those fieldsets that you don't require. This way entire fieldset will get hidden
> 0 votes

---
Tags: 6
---


# Question
Title: Views contextual filter navigation links?
Assuming a view with a contextual filter based on a field "category" that is a select list with a limited number of values: what is the best approach to *dynamically* generate a simple list of links (based on available values) at the top of the view to allow a user to navigate the categories? I want to expose the values as links and keep the clean url structure that contextual filters create. See screen below for reference.

In the past, I've hacked together a basic hard-coded solution using hook\_views\_pre\_render and the l() function, but I'm wondering what the best practice would be.

# Answer
> 1 votes
Take a look at the quicktabs module. It should let you define "tabs" for these filters.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery.

Additionaly, there is this in-depth blog post not written by me showing filtering/sorting a complex view + filters page using quicktabs. The left side of this view page has "tabbed" items like what you want in your example. CSS tweaks will make the tabs "look" how you want.

---
Tags: 7, views
---


# Question
Title: Is it possible to hook_form_alter by path?
I have a basic `hook_form_alter` working but the issue is I cannot do it by form id as the id might be different in various environments, i.e. local, dev, production. So the usual method of altering by targeting a form ID is not ideal then.

I figured I could do this by path (as that won't change) but none of the usual methods work. I'd like to keep this in code so that's why I'm not simply changing the UI for this setting.

Here's my basic alter which works:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
}

```

However, if I do this, it does not work:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'];
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}

```

I'm guessing what I'm trying to do is not even possible and therefore I'll try to figure out a different method.

# Answer
I think you should use $\_SERVER\['HTTP\_HOST'\] . request\_uri();

This will give you the complete path.

So your code should be

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'] . request_uri();
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}

```
> 2 votes

---
Tags: 6, forms
---


# Question
Title: Adding Content to Drupal 7 through a remote PHP script
In our system, the content is generated by a standalone PHP script that runs from command line. Is there a way to add this content programmatically to a remote Drupal 7 CMS from this standalone PHP script?

I am not able to find such information on drupal.org. I have found the following code:

```
$node = new stdClass();

// Set content type
$node->type = 'article';

// Prepare defaults
node_object_prepare($node);

// Define language (currently language neutral)
$node->language = LANGUAGE_NONE;

// Basic content
$node->title = 'Test';
$node->body[$node->language][0]['value'] = 'Body text';

// Example if using custom fields
$node->field_CUSTOM_FIELD[$node->language][0]['value'] = 'Value';
// Example if using fields that are taxonomy type
$node->field_CUSTOM_FIELD_TAXONOMY[$node->language][0]['tid'] = 1;

// Save node
node_save($node);

```

But this code has to run from Drupal 7 server process only. This code cannot be used in a standalone PHP script that runs remotely. Another option is Entity API but that code too has to run on Drupal Server only. Do I need to create my own module and code my standalone PHP script to connect to API exposed by this module?

# Answer
> 1 votes
Services module can be used to allow to create node remotely

Check out some reference links as below

# Answer
> 0 votes
You are right that the script cannot run as a standalone script - it must be bootstrapped within Drupal before you can use the Drupal API to make changes to the site. The simplest way to do this is to run your script through drush using the `php-script` command which will allow you to run a bootstrapped script.

For this however your script needs access to the site's database and the site's code-base (you could do this on a copy of the code base if your script doesn't need/affect files - though that could be risky unless you know exactly what you are doing).

If this is not available (your script is running on a remote server without access to the database/code base of the site) then you need a solution with two components: one that generates some data on the remote server, and one that imports the data on the Drupal side.

One way to import external data within Drupal is to use the Feeds Module. It already has a number of possible formats (such as importing from formatted CSV files) and also allows you to write your own importers quite easily.

---
Tags: nodes
---


# Question
Title: 3 reset button with auto submit for each and reset all
I created a view page with exposed filters in a block. I have three exposed filters in a view, with apply and reset button for each one.

It shows results based on the filters. It is working fine. But I need these filters each having its own reset button and reset all button resetting all three.

Can it be done through views? Should I handle through code? If so where I need to write the code?

# Answer
> 0 votes
This following post has a nice hook\_alter function that adds a reset button to exposed filters on views. It lists both code for 6 and 7.

http://fleetthought.com/blog-post/adding-reset-button-exposed-views-filters

---
Tags: views
---


# Question
Title: What should be the optimum values for Minimum cache lifetime and Expiration of cached pages
i am working on a mobile app. Using **drupal json views** i am parsing the data and displaying on the device. It takes nearly **10 sec to load 10 records on the device**. Initially i thought this might be due to slow internet, but that is not the issue. Later i came to know this is something related to **cache**. So can any one help me to **minimize the loading time by suggesting minimum cache lifetime and expiration of cached pages** .

# Answer
> 0 votes
The values of minimum cache lifetime and expiration of cached pages depends on how frequently the content on your site changes and for how long the external caches can show stale data from your site.

To get more info about these check https://drupal.stackexchange.com/a/83342/4876

However in your case I am not sure if these will matter. You should probably consider looking at Views Content Cache That might improve the performance in your case.

---
Tags: views, caching
---


# Question
Title: Filter Criteria "Workbench Moderation: Current" only works on published revisions?
I added the following filter criteria to a View:

Workbench Moderation: Current

However, after not seeing the output I expected, I realized that this filter only displays a revision if the revision is both current **AND** published. If a draft is currently current, then it is ignored by the filter.

Is that a bug?

Thanks,

Stephen Gilson

# Answer
I found the answer in this post: https://drupal.org/node/1947732

From that post:

"The key is when you create the view, you need to set it to show content revisions rather than content. They mysql query used when showing content revisions is different than when showing content. One pulls data from the node table, the other pulls from the revisions table. The latter is what you want when dealing with revisions. In my testing so far, the Workbench Moderation: Current filter works fine in a content revision view."
> 1 votes

---
Tags: views
---


# Question
Title: Is there a module to conditionally set a fields value depending another field?
is there a module that can set a value of a field which depends on the value of another field first? I know i can do it via js, but was wondering if something was out there already. conditional field module doesnt work in my case as it dosent set the value depending on the result of another.

example: I am creating a basic page and I have a select box field with the following: white/black/red. when i select red, i want the body to be filled in with 'yes' and if its black i want the body to be filled in with 'no'.

# Answer
I guess you need to check on the fields you set as dependant and dependee! In your case the body field should be the dependant and the selection field should be dependee.

Hope it helps!
> 0 votes

# Answer
No other module available apart from conditional field, you need to create your own module with hook form\_alter() and use some code like

```
<?php
function wishlist_status_form($form_state) {
$form['status'] = array(
    '#type' => 'textfield',
    '#title' => 'Status',
    '#suffix' => '<div id="my-wrapper"></div>',
  );

$form['ajax-submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'wishlist_status_change',
        'wrapper' => 'my-wrapper',
    ),
    '#value' => t('Save'),
  );
return $form;
}

function wishlist_status_change($form, $form_state) {
    dpm($form_state, 'state callback');
    return 'test';
}
?>

```
> 1 votes

# Answer
It might be difficult to change the value of a field without some coding. But it if you just want to store the value based on the value of some other field you should take a look at Computed Field
> 0 votes

# Answer
Perhaps you can use the Rules module and create 2 rules.

* **Event:** After saving new content.
* **Condition:**

1. Entity has field. Parameter: Entity: `[node]`, Field: field\_colours (*Or whatever your field is called.*)
    2. Data comparison. Parameter: Data to compare: `[node:field-colours]`, Data value: Red
* **Actions:** Set a data value. Parameter: Data: `[node:field-body]`, Value: Yes

You can create a similar rule for 'black'.
> 0 votes

---
Tags: 7, entities
---


title: Base migration class?

text:
# Question
Title: Base migration class?
What's the procedure for including a base migration class that some of my migrations extend? I have some common functionality across multiple migrations class and would not like to repeat the code in all classes.

My question is how do I "register" my base class with Migrate? I need it to get autoloaded. Perhaps if I just include it in the module's list of files?

# Answer
> 1 votes
Take a look at the example migration for beer and wine that ships with Migrate in the 'migrate\_example' folder.

You will need to register your your migration and handler classes explicitly with hook\_migrate\_api(). See 'migrate\_example.migrate.inc' inside 'migrate\_example'.

However, you don't need to explicitly register abstract intermediate classes that hold common info for other migrations you're implementing. See the abstract class 'BasicExampleMigration', inside 'beer.inc' as an example.

---
Tags: migrations
---


# Question
Title: What do I put in the drupal 7 commerce Checkout Completed Rules: Send Email field to display all of the order data?
Currently I have the following below in my completed checkout send email settings. But when i receive the emails on a completed order, I'm still missing some data even though I have it set there. Would someone please paste their completed order send email setup?

See below as it only shows the SKU reference #'s.

One main issue I'm having is for these tokens:

\[commerce-order:commerce-line-items\] -- Only gives the Product ID number and nothing else

\[commerce-order:commerce\_line\_items\] -- Displays "No line items found".

# Answer
I think this is a permissions issue related to line items and anonymous users. See https://drupal.org/node/1811972, and https://drupal.org/node/1333174.

This does not answer your exact question, but what I've done recently is install Commerce Invoice Receipt (https://drupal.org/project/commerce\_invoice\_receipt) as a solution. Here's the basic checklist I followed:

1. install commerce invoice receipt (dev version has support for logo)
2. set visibility of fields at admin/commerce/config/order/display/invoice
3. disable SQL query rewriting on on Line items view - needed for line items to appear when emailed to customer (security issue, but I'm not sure how serious)
4. create a new rule with Send Invoice Receipt action - for customers
5. create a new rule with Send Invoice Receipt action - for admins
6. disable rule: Send an order notification e-mail
> 1 votes

---
Tags: 7, rules, commerce
---


# Question
Title: Create Taxonomy with Hierarchy from an Array
How might I create a vocabulary full of taxonomy with a hierarchy from an array such as this:

```
$vocab = array(
  'level1-1' => array(
    'level2-1' => array(
      'level3' => array(),
    ),
    'level2-2' => array(
       'level3' => array(
         'level4' => array(),
       ),
    ),
  ),
);

```

# Answer
> 2 votes
Here is a solution ...

```
// First create your array of terms
$terms = array(
  'level1-1' => array(
    'level2-1' => array(
      'level3' => array(),
    ),
    'level2-2' => array(
      'level3' => array(
        'level4' => array(),
      ),
    ),
  ),
);

// Create your vocabulary.
// First check if the vocabulary exists otherwise an error will be thrown when trying to create it.
$vocabs = taxonomy_get_vocabularies(NULL);
$vocab = new stdClass();
foreach ($vocabs as $vocab_object) {
    if ($vocab_object->machine_name == 'vocab_short_name') {
        // Vocab found.  Grab the object.
        $vocab = $vocab_object;
        break;
    }
}
// If the vid is not set then create the vocab.
if(!isset($vocab->vid)) {
    $vocab = new stdClass();
    $vocab->name = 'Vocabulary Name';
    $vocab->machine_name = 'vocab_short_name';
    taxonomy_vocabulary_save($vocab);
}
// Recursive function that will create the hierarchical terms.
mymodule_add_hierarchical_terms($terms, $vocab->vid);

function mymodule_add_hierarchical_terms($vocab, $vid, $parent = null) {

  foreach($vocab as $term_name => $term) {
    // Create the term
    $term_object = new stdClass();
    $term_object->vid = $vid;
    $term_object->name = $term_name;
    if(isset($parent)) {
        $term_object->parent = $parent;
    }
    taxonomy_term_save($term_object);

    if(is_array($term)) {
      // Recursively call the function, passing the term id of the parent.
      mymodule_add_hierarchical_terms($term, $vid, $term_object->tid);
    }
  }
}

```

---
Tags: 7, taxonomy-terms, importing-exporting, migrations
---


# Question
Title: Can't set PHP block visibility programatically
Heres my code:

```
$blocks['membership_package_information'] = array(
    'info' => "Membership Package Information",
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => membership_block_visibility(),
  );

function membership_block_visibility() {
  if(arg(0) == 'checkout' && arg(2) == null) {
    return true;
  }
  else {
    return false;
  }
}
```

I'm trying to limit the block to only show on the first page of the drupal commerce checkout page (checkout/\[order-id\]) and not the second (checkout/\[order-id\]/review) but its not working. When I put this code in the PHP visibility section of the block UI page, it works. I'd rather it be in my module, why wont it work? It seems that the UI settings are being picked up and not whats in my block.

# Answer
Re: https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook\_block\_info/7 you have to put the actual PHP code "in" the `pages` array key...

> For BLOCK\_VISIBILITY\_PHP, the PHP code's return value should be TRUE if the block is to be made visible or FALSE if the block should not be visible.

...not set it to the return of a function, eg, something along these lines:

```
$blocks['membership_package_information'] = array(
    'info' => "Membership Package Information",
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => '<?php return membership_block_visibility(); ?>' // ADDITION: you need the <?php ?> brackets :)
);

// make sure this function is in a module file that is always loaded...

function membership_block_visibility() {
  if(arg(0) == 'checkout' && arg(2) == null) {
    return true;
  }
  else {
    return false;
  }
}

```

Do also note the caveat off the api page:

> Most modules do not provide an initial value for 'visibility' or 'pages', and any value provided can be modified by a user on the block configuration screen.
> 3 votes

---
Tags: blocks
---


# Question
Title: How To Remove Menu Tabs From Custom User Dashboard
I'm working on creating some custom user dashboards but cannot seem to find how to remove certain menu items. I intend to use a combination primarily of Panels with Context and Views (but I haven't ruled out simply using Homebox) but at this early stage learning D7 I've created a custom Variant in the system Panels template, created a rule set in the Variant which will set each user dashboard to load based on their subscription (Ubercart Role). Because of the nature of the Roles, different DBs are required. As you can see in the attached screenshot, the menu tabs are showing left to right (View, Affiliate Center, Bookmarks etc), I've tried going through all the backend and cannot for the life of me find what controls them to show, could somebody please tell me what causes them to show, so I can either 'hack it' or delete it.

I know it maybe a theme influence and for my current testing I'm using Bartik, but I intend to use an HTML5 theme based on either AT Theme or Boilerplate, but haven't got to that stage as yet (or that maybe my next 'hack' learning lesson today!). Ultimately, I intend to use a Less framework, but for now I merely want to get the functionality working BEFORE I do CSS.

So, what's influencing the menus in my basic User DB as shown here?

https://dl.dropbox.com/u/55172207/screen\_shot\_cp.png

Thanks in advance to anyone for the help.

# Answer
> 0 votes
I solved this by removing the $vars \['tabs'\] by commented out // in my template.php file (as seen below). This appears to solve my problem of Tabs appearing. I'm not sure it's correct, but it seems to have solved my issue. FYI, I was using a Bootstrap theme.

// Provide additional variables to theme. $vars\['brand'\] = theme('brand', array( 'name' =\> $vars\['site\_name'\], 'href' =\> $vars\['front\_page'\], 'logo' =\> $vars\['logo'\], )); $vars\['preface'\] = theme('preface', array( 'breadcrumb' =\> $vars\['breadcrumb'\], 'title\_prefix' =\> $vars\['title\_prefix'\], 'title' =\> $vars\['title'\], 'title\_suffix' =\> $vars\['title\_suffix'\], 'messages' =\> $vars\['messages'\], 'help' =\> $page\['help'\], 'actions' =\> $vars\['action\_links'\], ));

// remove Tabs from var above // 'tabs' =\> $vars\['tabs'\],

# Answer
> 0 votes
You can do that from your theme's `template.php` file by implementing the `theme_menu_local_task()`.

Using this function you can also rename specific tabs.

Code for both actions is below.
It is taken from this file of our Ultima theme.

```
<?php

/**
 * @file
 * Theme local task function.
 *
 * Created by: Topsitemakers
 * http://www.topsitemakers.com/
 */

/**
 * Implements theme_menu_local_task().
 */
function YOURTHEME_menu_local_task(&$vars) {

  $link = $vars['element']['#link'];

  // List of tab names to be excluded; t() function will ensure that the
  // tab name will be matched and excluded on multilingual sites as well.
  // This is useful in case you have many modules installed on the site and
  // large number of tabs break the layout of the theme.
  $excluded_links = array(
    t('View'),
  );
  if (in_array($link['title'], $excluded_links)) {
    // Skip all further processing.
    return;
  }

  // Uncomment code below to rename the "View" tab for certain node types
  /*
  // Check if the link title is "View"
  if ($link['title'] == t('View')) {
    // Make sure we are on single node page
    if (arg(0) == 'node' && arg(1)) {
      $node = node_load(arg(1));
      // Do this for specific content types
      if ($node->type == 'page') {
        $link['title'] = t('View full page');
      }
    }
  }
  */

  // Continue building the local task link
  $link_text = $link['title'];

  if (!empty($vars['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '<li' . (!empty($vars['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";

}

```

---
Tags: theming, panels
---


# Question
Title: Is there an example OAuth2 client module anywhere?
Similar to this post and this request, I'm creating a OAuth client in Drupal 7 but using OAuth2.0. There's an OAuth2 module with an unpublished Drupal 7 version that I've toyed with, but it's geared pretty exclusively for servers or proxies, not clients. I've started writing a skeleton module for an OAuth2 client implementation, but before I go any further I wanted to make sure I'm not just spinning my wheels. Are there are any good modules that either implement a web services client using the OAuth2 standard, or a template module that I've missed?

# Answer
A year later, there is OAuth2 Server which provides the server part only, but has tests which are a good demonstration of client code in Drupal (using drupal\_http\_request()), so that code can at least be used as an example. The module documentation also tries to explain basic OAuth2 concepts and potential pitfalls.
> 1 votes

# Answer
Several months later from OAuth2 Server I still couldn't find any suitable OAuth2 Client (especially one that works with OAuth2 Server). So I developed an OAuth2 Client myself.

It is also on drupal.org, but it is a sandbox and needs some review and support in order to be promoted as a full project: https://drupal.org/node/2138549
> 1 votes

---
Tags: services, authentication-authorization
---


# Question
Title: /admin/modules and Views Edit pages take forever to load
I recently noticed that two specific sections of my site are taking forever to load, `/admin/modules` and `/admin/structure/views/view/{any-view}/edit`. Before I disabled the PHP max\_execution\_time (only temporarily), it kept timing out at 5 minutes.

Now that the timeout is disabled, the mysql server is going away. I've seen a lot of suggestions that `max_allowed_packet` should be 100M+, so I set it to 500M for some ridiculously high value. Last time I hit that page had to have been ~15-20 minutes ago, and it's still just sitting there.

The only thing I have done recently to it was moving a TON of images into sites/default/files from another web server. (~ 25Gb)

Does anyone know *why* `admin/modules` and the View Edit pages are taking forever? It's only those two sections. The public side of the site is fine, the other admin parts are fine, it's just those two places.

# Answer
> 1 votes
I found more information on this and have fixed it.

I guess that when Drupal has enabled modules that are missing from the filesystem (this happened as we're using Capistrano to deploy and I didn't sync the two sites correctly), it recursively keeps calling `file_scan_directory()` trying to find the missing modules, and that causes the site to timeout.

References:

Avoid re-scanning module directory when multiple modules are missing

Drupal 7 speed issue: file\_scan\_directory called \> 1000 times per page load

Used XHProf to see what the call stack looked like over the course of loading `/admin/modules` and found over 5,000,000 function calls. By contrast, any other page had about 30,000 ~ 50,000 function calls.

---
Tags: views, 7, database
---


# Question
Title: Can I run Drush in a situation where the database is on one server and the remainder of the Drupal installation is on another?
I have a setup (out of necessity not choice) where my drupal installation is on server a, and the database on which it relies is on server b. The site is working fine, however when I run most Drush commands I get the good old:

Drush was not able to start (bootstrap) the Drupal database.

On the server where everything except the database is stored, there is no mysql. If drush isn't an option for me that's perfectly fine but I've been tearing my hair out on this one.

Many thanks in advance for any ideas.

# Answer
I've never run a Drupal site like this, but Drush should take your database settings from your settings.php file; if the database is remote for Drupal, then it should be remote for Drush as well. Note that most Drush commands (with the notable exception of the sql-\* commands, which you will not be able to use without a local mysql installation) just call through to the corresponding Drupal code, after first bootstrapping. If your bootstrapping is failing, check to see if there is anything in your settings.php that depends on the site's URI to select the database. If so, make sure that you use the --uri= flag, or set the 'uri' element in your Drush site alias when using Drush. If that doesn't get you going, post the output of a failing Drush command with the --debug flag specified.
> 3 votes

---
Tags: drush
---


# Question
Title: How to make user profiles searchable and filterable by multiple fields in the context of a job site
I'm currently in the process of developing a job search site hopefully with these abilities for users of the site:

Job seekers can search for and filter jobs. I'm on my way with this so no problem here.

However what I would like to do is create users searchable for employers. So users can sign up and fill in a number of fields, expertise, CV, skills or whatever else...

Then I want users with paid employer accounts to be able to search and filter employees by these fields.

I'm fairly new to Drupal and I was wondering how I would go about doing this?

# Answer
I think you're going to need to use views here.

When you create your view, make sure you use Users and not Content. See screenshot. Once you do this you can set up and expose all the filters you need to allow searching, etc.
> 0 votes

---
Tags: users, search
---


# Question
Title: Receive the error PDOException: SQLSTATE[23000] when trying to update some content text
I get the following error when I try to update a static page's content as an Administrator:

"The website encountered an unexpected error. Please try again later."

In the logs, there is an error for type 'node' and type 'php':

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY': INSERT INTO {pinit} (nid, description, image, pincount) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3); Array ( \[:db\_insert\_placeholder\_0\] =\> 3 \[:db\_insert\_placeholder\_1\] =\> \[:db\_insert\_placeholder\_2\] =\> /sites/default/files/Steve155.jpg \[:db\_insert\_placeholder\_3\] =\> horizontal ) in drupal\_write\_record() (line 7166 of /home/diversif/public\_html/includes/common.inc).

I just updated to the latest version of Drupal, and ran the update script on the database. I also created an authenticated user, and confirmed that they are experiencing the same issue.

I'm not modifying anything in the content other than some text. Are there other logs that I can look into to find the source of the problem, or the solution.?

# Answer
> 0 votes
Looks like an error with the module

pinit

It's inserting a duplicate row for nid into it's database table.

It should probably use `db_merge` instead.

You may need to raise a bug report with the module maintainer.

---
Tags: nodes
---


# Question
Title: Why do I get Call to undefined function updatedb()
I am attempting to wrap my head around some of the advance features of drush. i am using **Drush User's Guide** and it's example code and ran into this error \[`Fatal error: Call to undefined function updatedb() in /home/trakz/.drush/user_blocker.drush.inc on line 68`\]from the code below.

**Line 68** is: \[`$query= updatedb('users')`\]

Can anyone tell me what is wrong? I have checked the Drush guide and updatedb() is valid. Googling around did not help.

drupal 6.28 drush 5.7

**any assistance woudl be greatly appreciated.** Thank you.

```
/**
 * Callback implementation for user-blocker command
 */
function drush_user_blocker() {
  // Grab all languages given. If any.
  $languages = func_get_args();

  // See if we received a date from which we should filter
  $since = strtotime(drush_get_option('since', '2 years ago'));

  // Perform the update over the users table
  $query= updatedb('users')
  ->fields(array('status' => 0,))
  ->condition('uid', array(0, 1), 'NOT IN')
  ->condition('access', array(1, $since), 'BETWEEN');

  // Add the condition to filter by language
  if (count($languages)) {
    $query->condition('language', $languages, 'IN');
  }

  $total_blocked = $query->execute();
  drush_log(dt("Blocked !total_blocked users", array('!total_blocked' => $total_blocked)), 'success');
}

```

# Answer
`drush updatedb` is a valid command.

`updatedb (updb) Apply any database updates required (as with running update.php).`

However, I'm not sure about using it in place of `db_query`.

In D7 you would use `db_update` there.

In D6, you're stuck with `db_query`

It looks like a syntax error in the module code, it probably needs to use D6 style `db_query`
> 3 votes

---
Tags: 7, drush
---


# Question
Title: Drupal running behind a proxy send emails with links to the wrong domain/IP
So I have a public site http://www.mysite.com with the following vhost entry:

```
ProxyPass /press http://123.45.67.89/press
ProxyPassReverse /press http://123.45.67.89/press

```

And I have a Drupal site running at `http://123.45.67.89/press` ready to receive requests.

All works fine except emails sent from the Drupal site come through as:

```
http://123.45.67.89/press/user/reset/1/1384468691/3WY1S7QUJK8Wdp78U9Itu2ygw-KenVLY_9mgBZeTOy8

```

Which is not accessible to the general public, and instead needs to output:

```
http://www.mysite.com/press/user/reset/1/1384468691/3WY1S7QUJK8Wdp78U9Itu2ygw-KenVLY_9mgBZeTOy8

```

How can I trick Drupal to think it's being accessed on the desired domain? Thanks for any advice.

# Answer
Silly me, forgot all about setting `$base_url` in `settings.php`. By default it is commented out, but I've now set it to:

```
$base_url = 'http://www.mysite.com/press';

```
> 0 votes

---
Tags: 7
---


title: Get node url to other fields

text:
# Question
Title: Get node url to other fields
The above image is from Views Table. The values inside **Name** is title field so it is clickable by default and links to its Node. I want to make the values inside **Nick Name** and **Age** clickable link too, which will go to the same Node as its title.

I went to **Nick Name** field and did ***Rewrite Result*** and ***Output this field as a link***, but in ***Replacement Patterns*** there is no **Token** for link, still I tried with `[title]`, `[title:url]`, `[path]`, `[view_node]`, etc. but it cannot be linked to its Node.

# Answer
> 1 votes
You should add a nid field and then select the option to exclude from display. Arrange it so that the nid field is at the top in the list. (This is needed so that the rest of the fields can use this field in replacement patterns.)

Next when you are rewriting the result give the link as `node/[nid]`

That should do it.

# Answer
> 5 votes
You need to first add a path field to your view, and then exclude from display:

1. Add the field "Content:path" to your view as the first field in the list
2. Exclude "Content:path" from display
3. Under "Rewrite results", enable "Use absolute link (begins with "http://")"
4. For Nick name, choose "Output this field as a link"
5. For "Link path", use the \[path\] token

Repeat #4 and #5 for age if you like

It's important that the path field be listed first (or at least before Nick Name and age) or it won't be available as a token.

Also note that you must use an absolute link for Content:path under Rewrite Results. It's a little counter-intuitive, since the field is being excluded from display, but the setting is still used in the \[path\] token.

---
Tags: 7, views
---


# Question
Title: How does an entity get printed into a page after going though the page callback function?
This following code snippet is the value of `page callback` from `hook_menu()`. However, I cannot connect `entity_view` and the page template. How can I print or access the `entity_view` returned in this code from my page template?

```
function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}

```

# Answer
You should pass the array of fully-loaded entity objects to the entity\_view function, not only the id.

For example:

```
...
$entity = entity_load('example_task', array($task);
return entity_view('example_task', $entity, 'full');

```
> 1 votes

---
Tags: routes
---


# Question
Title: Show a Display Suite view mode depending on a field value in the profile of the viewing user
I'm not looking to use Views for this challenge here but simply to add a check for a value of a field on the viewing user's profile and then to select the correct view mode from Display Suite for that node depending on that value. What would I have to do to accomplish this?

# Answer
Are you looking for code or just the approach? One approach would would be to use HOOK\_entity\_view\_mode\_alter(&$view\_mode, $context) in a custom module:

1. Check that the user is logged in
2. Check that the user is viewing the right kind of node
3. Load the user and get the profile field value
4. Based on the field value, set the view mode ($view\_mode = 'custom')
> 0 votes

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


title: "Add to cart" minimum order quantity

text:
# Question
Title: "Add to cart" minimum order quantity
I am using Ubercart 2 on Drupal 6 with http://drupal.org/project/uc\_product\_minmax. It works well, except for the fact that the default catalog only provides an 'Add to cart' button with no quantity field, and the quantity it adds is 1, which makes it useless as the minimum order quantity in this particular case is 2.

I have tried implementing `hook_add_to_cart()` to forcefully change `$qty` to 2 if it's lower only to find that I cannot manipulate it before uc\_product\_minmax implements the hook, so I'm in need of an alternative.

Maybe this isn't even fixable without modifying uc\_product\_minmax itself, but I'm up for trying any other ideas.

# Answer
> 1 votes
If you want to alter the cart item, then you can use `hook_uc_cart_alter` of ubercart.

> This is called every time the cart is rebuild (e.g. when products are added), so it's a good place to alter the cart item.

Code snippets to modify the qty of the item

```
/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your product

    $items[$index]->qty = 2;
  }
}

```

For reference:

http://www.ubercart.org/docs/api/hook\_uc\_cart\_alter

# Answer
> 0 votes
Here you see this.we have default option for quantity when we add product in drupal .we make this is 2.

---
Tags: 6, ubercart
---


# Question
Title: Fatal error - Class 'context_condition_node' in date_context module
I'm debugging a site that has completely broken - not finding too much out there and hoping for some help. The error I see is:

Fatal error: Class 'context\_condition\_node' not found /sites/all/modules/contrib/date/date\_context/date\_context.module on line 56

Anyone seen this before?

# Answer
It means this module is missing or registry is broken.

Can you check if the date module does exist?

If not you may try to download a copy of date module and put it in the exactly the folder.

Use Drush `drush cc all` to clear the cache.

In Drupal 7 you can also go to admin performance page to clear the cache. Sometimes this is still available by admin/config/development/performance.

If it still does not work, you may want to have a go with registry\_rebuild module to rebuild the registry totally.
> 0 votes

---
Tags: wsod
---