# Question
Title: Batch API is setup in my module but it does not open batch window progress
I am learning hot to use Drupal for my physics PHD. I was studying how to insert a batch into my custom module. I wrote a simple module which allows to upload a CSV through a form, check the extension and save it into a directory. This is just a try because i want to use batch API for another custom module Here is the code:

```
/**
* Implementation of hook_menu()
*/

function rhmtts_csvimport_menu() {
     $items['rhmtts/csvimport'] = array(
           'title' => 'Import CSV files',
           'page callback' => 'rhmtts_csvimport_page_default',
           'type' => MENU_NORMAL_ITEM,
           'access callback' => TRUE,
           );

     return $items;
}

function rhmtts_csvimport_uploadform() {
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['csvfile'] = array(
           '#type' => 'file',
           '#title' => t("Upload a CSV file"),
           '#size' => 40,
           );
      $form['submit'] = array(
           '#type' => 'submit',
           '#value' => t('Submit'),
           );
  return $form;
 }

           /////// Setup a batch //////////////

  function rhmtts_batch_submit(){

      $batch=array(
          'title' => t('Importing CSV ...'),
          'operations' => array(),
          'init_message' => t('Commencing'),
          'progress_message' => t('Processed @current out of @total.'),
          'error_message' => t('An error occurred during processing'),
          'finished' => 'rhmtts_csvimport_finished',
          );

      batch_set($batch);
      $batch['operations'][] = array('rhmtts_csvimport_uploadform_submit',                    array());

      }

     ////// Define finished function ////////////////////////////

   function rhmtts_csvimport_finished($success, $results, $operations) {

     if ($success) {
        $message = t('All users have had first and last names processed.');
      }
     else {
     $message = t('Finished with error.');
     }
   drupal_set_message($message);
   }

   ///// Methods definition ////

   function rhmtts_csvimport_uploadform_submit($form, &$form_state) {

   // create a csv upload directory in sites/default/files if it doesn't exist
   // yet
   $filepath = 'public://csvuploads';
   file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);

   // save the uploaded file
   $file = file_save_upload('csvfile', array('file_validate_extensions' =>             array('CSV')), $filepath, FILE_EXISTS_REPLACE);
   drupal_set_message('The file you have uploaded is: <pre>'.print_r($file,    TRUE).'</pre>');

  // now read from it
  $realpath = drupal_realpath($file->uri);
  drupal_set_message("The real path of the file is $realpath");
  $fh = fopen($realpath, 'r');

  $table_header = NULL;
  $table = array();
  while(($row = fgetcsv($fh, NULL,';')) !== FALSE){
  if($table_header == NULL) {
  foreach($row as $field) {
    $table_header[] = $field;
    };
    continue;
    };
    $table_row = array();
    for($i = 0; $i < count($table_header) ; $i++) {
    $table_row[$table_header[$i]] = $row[$i];
    };
    $table[] = $table_row;
    }
    fclose($fh);
    drupal_set_message("You have uploaded: <pre>".print_r($table, TRUE)."</pre>");
   }

```

When i choose a file from the form it completed the operation, but the usual page showing batch progression is not showed. Is this because the operation is to fast? Or there are other problems in the code?

Many thanks

Alberto

# Answer
* your menu callback function is `rhmtts_csvimport_page_default`. This does not exist or currently does nothing.
* Your form function `rhmtts_csvimport_uploadform` has this submit handler `rhmtts_csvimport_uploadform_submit` and it never calls or creates your batch function called `rhmtts_batch_submit`.

Your code is more or less all there I would:

* use `drupal_get_form` as my `hook_menu` callback function and give it the name of my form function.
* I would add my batch function onto the form submit handlers for my form as outlined here https://www.drupal.org/node/180528. Then it should all work.
> 0 votes

# Answer
I try to modify a little bit the code, which now is:

```
<?php

 /**
  * @file
  */

 // Implementation of hook_menu()

 function rhmtts_csvimport_menu() {
   $items['rhmtts/csvimport'] = array(
     'title' => 'Import CSV files',
     'page callback' => 'rhmtts_csvimport_uploadform',
     'type' => MENU_NORMAL_ITEM,
     'access callback' => TRUE,
     );

   return $items;
 }

 function rhmtts_csvimport_uploadform($form, &$form_state) {
 $form['#attributes'] = array('enctype' => "multipart/form-data");
   $form['csvfile'] = array(
     '#type' => 'file',
     '#title' => t("Upload a CSV file"),
     '#size' => 40,

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

   );

  $form['#submit'] = array(
    'rhmtts_csvimport_uploadform_submit',
  );

 return $form;

 }

 ////////// Form submission logic ///////////////////////

 function rhmtts_csvimport($form, &$form_state){
   // create a csv upload directory in sites/default/files if it doesn't exist
   // yet
   $filepath = 'public://csvuploads';
   file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
   drupal_set_messagge('Upload directory has been created');

   // save the uploaded file
   $file = file_save_upload('csvfile', array('file_validate_extensions' =>      array('CSV')), $filepath, FILE_EXISTS_REPLACE);
   drupal_set_message('The file you have uploaded is: <pre>'.print_r($file,  TRUE).'</pre>');

   // now read from it
   $realpath = drupal_realpath($file->uri);
   drupal_set_message("The real path of the file is $realpath");
   $fh = fopen($realpath, 'r');

   $table_header = NULL;
   $table = array();
   while(($row = fgetcsv($fh, NULL,';')) !== FALSE){
     if($table_header == NULL) {
      foreach($row as $field) {
        $table_header[] = $field;
     };
  continue;
    };
    $table_row = array();
    for($i = 0; $i < count($table_header) ; $i++) {
       $table_row[$table_header[$i]] = $row[$i];
    };
    $table[] = $table_row;
  }
   fclose($fh);
   drupal_set_message("You have uploaded: <pre>".print_r($table, TRUE)."    </pre>");

 }

 function rhmtts_csvimport_uploadform_submit($form, &$form_state) {

 $batch=array(
   'title' => t('Importing CSV ...'),
   'operations' => array(
    array('rhmtts_csvimport',array($form, &$form_state)),
    ),
    'init_message' => t('Starting process'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
     'finished' => 'rhmtts_finished',
    );

    batch_set($batch);

    }

   function rhmtts_finished($success, $results, $operations){

   if ($success) {
     // Here we do something meaningful with the results.
     $message = count($results) .' processed.';
     drupal_set_message($message);
    }
   else {
      // An error occurred.
   // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with   arguments: @arguments', array('%error_operation' => $error_operation[0],  '@arguments' => print_r($error_operation[1], TRUE)));
     drupal_set_message($message, 'error');
  }
  }

```

When i try to use it the batch page is open correctly, the progress bar is correct, but when the batch has finished it reports than 0 operations have been processed and file directory and file is not uploaded. I cannot understand where is the mistake. Any idea? Thanks
> 0 votes

---
Tags: batch-operations
---


# Question
Title: Simple&efficient slider module for the following purpose
I'm looking for a recommendation of a rather simple, conventional, D7 carousel\rotator\slider module that will let just to replace images (without many advanced techniques).

What I do need this module to have, and doesn't very much compromise about, is these features:

1. Pointers (Left and right) to move between pics.
2. Small dots that reflect the current picture being shown.
3. Text that "comes" into the center of the picture from different directions, and that Ican have full management of it's appearance (Font-Family, size, color, etc).

Thank you very much for your help!

# Answer
> 0 votes
Views Slideshow isn't a bad way to go. It will probably take some working with css/templates/views to get it to display the way you want, but it is the most used module, so if you find yourself up against a wall using it, there's a good chance someone's already has done it and has written a tutorial, or would answer a question.

There are a few other modules out there you could look at. A quick search I found this page, which has a decent list

Also a very in-depth comparison on the different modules out there from drupal.org

---
Tags: 7, javascript
---


title: Getting logged out all the time

text:
# Question
Title: Getting logged out all the time
This has been happening since first started using drupal a year ago and I see others having same problem with no real answer beyond cache.

If you reload it will log you back in but that is no good for users, they will just be confused and frustrated by it and it would seem stupid to put a warning "please keep refreshing your page if you are logged out".

I remember at one stage being told you need to decide between www or no www to stop this from happening but that never really worked, only sometimes.

There must be a logical explanation and definitive way to stop it, surely?

# Answer
> 0 votes
The www is not part of your domain name. It is a web server configuration setting that some servers use and some do not. By default a web server will show your website at both www.mywebsite.com and mywebsite.com.

The sites with www and without www are also cached differently in a browser.

Your current problem can be resolved through the following.

Find the following code in your .htaccess file and remove # hash sign from the last two lines.

```
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

```

If you prefer to use www site with www. prefix you may use the following instead.

```
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

# Answer
> 3 votes
I would imagine that if your users can just refresh the page to become logged back in, that they're almost certainly not being logged out in the first place. Far more likely that they're being served a cached version of the page.

Consider this situation:

1. User visits home page as an unauthenticated user
2. Cache headers tell the browser to keep that page for at least x minutes before refreshing
3. User visits the login page and authenticates.
4. User re-visits the home page
5. The browser cache kicks in, and the user is shown the cached version of the home page they saw the first time round
6. User refreshes the page - the browser cache is cleared, and they now see the index page as an auth'd user

> There must be a logical explanation and definitive way to stop it, surely?

Absolutely there will be - but you need to identify which part of your setup is responsible for the problem. As described above, it's probably a caching issue, so that's where you debugging should concentrate. I've seen this sort of behaviour more often when a reverse proxy is in front of Drupal, so if you have one enabled, start debugging that first.

If you're not comfortable debugging caching issues in that manner, you'll really need to hire someone who is to do the job. It's not something you can do half-heartedly, or without a reasonable knowledge of caching in general (not just in Drupal). If you happen to have a Pantheon account, ask them about it - they plugged the same bug in their Varnish config some time back (I have no idea how though, didn't ask).

I'm not sure that any more specific advice can be really be given, without having access to the server. I'm by no means a caching ninja though, so maybe someone else will be able to offer a specific part of config you can change, test you can do, etc.

# Answer
> 0 votes
Switching from www.example.com to example.com changes subdomains, and this will cause you to not be logged in on one subdomain if you logged in on the other.

To correct this, you can force the use of one domain name in your apache configuration or .htaccess using rewrites or redirects as previously mentioned, or you can edit your site's settings.php file and uncomment out the line $cookie\_domain=".example.com" and it will work regardless of the subdomain.

---
Tags: users
---


# Question
Title: How bad is it to use Node_load in a loop in drupal 7?
Something like:

```
for ($i = 0; $i < 100; $i++) {
    $node = node_load($i);
    print $node->fieldYouWant;
}

```

That is a lot easier to read, gives you access to all the fields etc. However, in a loop, I would imagine Drupal would fall over? Or is the built in caching sufficient to not have to worry about it?

# Answer
You should never need to use `node_load()` in a loop, that's what `node_load_multiple()` is for:

```
$nids = array(1, 2, 3, 4, 5);
foreach (node_load_multiple($nids) as $node) {
  ...
}

```

It's hard to imagine a scenario where loading the nodes individually would be necessary or desirable.
> 7 votes

# Answer
In response to MDP's comment you can use node\_load\_multiple & keep the memory usage low by using node\_load\_multiple in increments of 100 or so & you get the speed benefit of bulk loading. array\_chunk is key

```
// Generate an array 1-1000.
$nids = range(1, 1000);
// Split $nids array into chunks of 100
$nids_chunked = array_chunk($nids, 100, TRUE);
// Only load 100 at a time.
foreach ($nids_chunked as $chunk) {
  $nodes = node_load_multiple($chunk, array(), TRUE);
  if (!empty($nodes)) {
    // Do work on each $node object.
    foreach ($nodes as $node) {
      echo $node->nid . ' ';
    }
  }
}
// Free memory.
unset($nodes);

```

Also I'll plug my sandbox module if you're looking to extract just a field value from a node, EntityFieldQueryExtra. IF you know how to use EFQ, then using EFQE should be fairly straightforward.
> 6 votes

---
Tags: caching
---


# Question
Title: Contextual filter only working on one URL
I've been going through posts such as View block not accepting contextual filter argument, Contextual filter on Views Block file not found, How do I get a block to use a URL to configure a contextual filter?, Contextual filters help, Contextual filter with a block view and more to find the solution or my issue with no luck.

In short my contextual filter only works on 1 of 5 pages I want it to work on (they other 4 pages doesn't return any results). The working page is `label/artists`

I've got a taxonomy vocabulary called `site_sections` and an `artist` content-type. I've got a View Block of `artist` teasers, that I want to filter contextually by a part of the url alias.

I've got a term reference on each artist node to the `site_section` terms which are

* `label`
* `publicity`
* `shop`
* `management`
* `wholesale`

My view is a block showing artist teasers. The block is displayed on these URL aliases:

* `label/artists`
* `publicity/artists`
* `shop/artists`
* `management/artists`
* `wholesale/artists`

My contextual filter:

1. Content: Site section (field\_site\_section)

**WHEN THE FILTER VALUE IS NOT AVAILABLE**

2. Provide default value: Raw value from URL
3. Path component: 1
4. Use path alias: Y

**WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED**

5. Specify validation criteria: Taxonomy term (site section)
6. Filter value type: Term name converted to term ID
7. Transform dashes in URL to spaces in term name filter values: Y

# Answer
> 0 votes
OK, found my error.

On the artist block configuration I'd copy pasted urls except for the label, it said:

```
`label/artists shop/artists/ management/artists/ wholesale/artists/ publicity/artists/`

```

Removing the trailing slashes did the trick.

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


title: Drupal field that get db content

text:
# Question
Title: Drupal field that get db content
How can I make a drupal field that gets a value from a specific database/table, it should be a select list. What I need is to have a drop down select where I can see all entries from a specific content on the drupal system. So I have content type A, and content type B. When I want to create a new content of type B I want a select box where all entries from content A are listed.

# Answer
> 2 votes
This sounds like something you can handle pretty easily with a couple of contrib modules:

1. If you don't already have them install Views and Entity Reference.
2. Add a View of type "Content", filtered by content type B. Call it something like "All type B content".
3. Add an "Entity Reference" display to the new View.
4. Add any sorting/filtering options and change the display field if required.
5. Repeat steps 2-4 for a new view called "All type A content", and filter by content type A instead.
6. Add a new field to content type A of type "Entity Reference".
7. On the field settings page under "Entity Selection" choose *Views: filter by an entity reference view* for the mode, choose the "All type B content" View, and save the rest of the field config as normal.
8. Repeat steps 6-8 for content type B, choosing the "All type A content" View instead.

That should get you exactly what you're looking for, with the added benefit of being able to customise the results easily with Views.

---
Tags: views
---


title: Conditional display of CCK fields

text:
# Question
Title: Conditional display of CCK fields
I was wondering if there is any other way apart from coding (and, possibly, using the rules module) to make the showing of a field dependent on the existance of another field.
Say you have in a node, a video and a photo. You want to show only the video in teaser but if you have not provided a value for the video, then the video field should not be showing, and instead the photo field should be showing. If you have provided a video, then the photo field should not be showing. Any ideas?

# Answer
The only solutions I know except coding it by yourself its Content Templates module. This module allows you to change the template directly from you back office.

The advantage it's that you don't need to deploy your code if you need small change.

You've also Display Suite that seems promising, I never tried but the description sounds good for what you need.
> 3 votes

# Answer
I know this is an old question, but I wanted to update this because it could help someone.

I would try Conditional Fields, it does exactly that. Drupal 6 & 7 only.
> 1 votes

# Answer
You should implement template (or possibly module) preprocess to do the checks and assign the html snippet to be outputted to a variable then just output it like this `<?php print $mytag; ?>` in your `node--[type].tpl.php`
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to do multiple conditions for db_update by using OR condition?
I would like to convert the following UpdateQuery statement to work with multiple conditions by using `OR` instead of the default `AND` condition.

```
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition('name', 'seven') // OR
  ->condition('name', 'rubik')
  ->execute();

```

Is it possible?

# Answer
> 8 votes
### Drupal 7

Yes, it is possible by using db\_or() as in the following example.

```
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition(db_or()
    ->condition('name', 'seven')
    ->condition('name', 'rubik')
  )
  ->execute();

```

For `db_select()`, see the answers given in "OR" condition in db\_select() and Nested OR and AND condition with db\_select.

### Drupal 8

You can still use `db_or()` as in Drupal 7, but it's deprecated in Drupal 8.0.x and removed in Drupal 9.0.0. Instead, a `\Drupal\Core\Database\Query\Condition` object should be created as in the following code, taken from `BooleanOperator::queryOpBoolean()`.

```
if ($this->accept_null) {
  if ($query_operator === self::EQUAL) {
    $condition = (new Condition('OR'))
      ->condition($field, 0, $query_operator)
      ->isNull($field);
  }
  else {
    $condition = (new Condition('AND'))
      ->condition($field, 0, $query_operator)
      ->isNotNull($field);
  }
  $this->query->addWhere($this->options['group'], $condition);
}

```

---
Tags: 7, database
---


# Question
Title: open node-reference links title in popup
I want in my node view pages, node reference links open in popup window or lightbox window. Does anyone have a solution?

# Answer
You can use a theme\_preprocess() function to add attributes to that link, or you can create a custom field template that adds classes or specifies a target.

For a new window/tab, you'd add `target="_blank"` or if you want to use an overlay you would add classes as specified in the module that provides that functionality, such as Lightbox or Colorbox.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How can I automatically add taxonomy terms to a page's <meta> keywords in the HTML?
When Taxonomy is used for "free tagging", it basically becomes keywords for the content. From an SEO perspective, it would be great to automatically include these taxonomy terms in the \<meta\> HTML tag for keywords, letting users help drive your SEO, or giving a non-technical site maintainer the ability to easily edit the keywords used on any given node. How can I do this in Drupal (both 6 and 7)

# Answer
I think you are looking for the Drupal 6 Nodewords module.

The Meta tags module is/was supposed to be the new Drupal 7 version, but it appears to be on hiatus. The Meta tags quick module, however, is an option (currently in dev).

This helpful post has more details.
> 7 votes

# Answer
As mentioned above, the Nodewords module is your best (IMHO) option for Drupal 6; just make sure to use 6.x-1.13 or newer rather than the older (horribly, horribly broken) versions.

For Drupal 7 just go with the Meta tags module; we're actively working on getting it stable and are very close.

Disclaimer: I am the maintainer of the Nodewords module.
> 1 votes

# Answer
I have used Yahoo auto tag module in the past. It worked well for me. Not sure why only 10 people have used it in the past.
> 0 votes

---
Tags: taxonomy-terms
---


title: rule to remove items from Shopping cart

text:
# Question
Title: rule to remove items from Shopping cart
I am having difficulty creating a rule to completely remove items from a Shopping cart. I have tried Before adding a product to the cart

```
{ "rules_prevent_salon_professional_xover" : {
    "LABEL" : "Prevent Salon professional xover",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-18",
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-product" ],
          "op" : "IN",
          "value" : { "value" : [ "97", "98", "99", "100" ] }
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } }
    ]
  }
}

```

as well as After adding a product to the cart

```
{ "rules_prevent_professional_subscription_purchase_cross_over" : {
    "LABEL" : "Prevent Salon professional subscription purchase cross-over",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-18",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "inline_conditions", "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "commerce_product_contains_products" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "sku" : "salon-owner-monthly , salon-owner-3month , salon-owner-6month, salon-owner-yearly "
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "commerce-line-item:commerce-unit-price:amount" ] } },
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } }
    ]
  }
}

```

I tried modifying it, by Removing entity - but still have a product in the Shopping cart

```
{ "rules_prevent_salon_professional_xover" : {
    "LABEL" : "Prevent Salon professional xover",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-10",
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_prepare" : [], "commerce_cart_product_add" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-product" ],
          "op" : "IN",
          "value" : { "value" : [ "97", "98", "99", "100" ] }
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } },
      { "entity_delete" : { "data" : [ "site:current-cart-order" ] } }
    ]
  }
}

```

This Rule does prevent the role from being added to the user, but the product and its normal product price exists in Shopping cart on the Orders page.

# Answer
> 0 votes
I have created a rule that empty cart before adding any new item. So the only latest item will be in the cart. I think thats what you need to do. Any other conditions can be added one by one.

If you want to clear cart totally then you can use `after adding product event`

```
{ "rules_empty_cart_" : {
    "LABEL" : "Empty cart ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart", "rules" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } },
      { "drupal_message" : { "message" : "Cart empty event executed.!!" } }
    ]
  }
}

```

Hope it will help!

---
Tags: rules, commerce
---


# Question
Title: Programmatically changing the global site name?
I'm making a multi-site setup using the same install and the same database, basing it off domains. I'm trying to programmatically alter the site\_name variable so that it displays a different site name based on the domain being used.

I am using 3 different methods to achieve this at the same time, however even that is not bullet-proof. Certain instances (i.e. some administration pages, user login, or user profile edit) still display the default site name in the page title (or elsewhere).

I am doing the following:

* `$conf['site_name'] = $my_title;` in settings.php
* `$vars['site_name'] = $my_title;` in my theme's hook\_preprocess\_page
* using `hook_tokens_alter` in a custom module to change the `[site:name]` token to `$my_title`

Despite all these measures, it seems I did not enforce the site name change in a bulletproof way. Is there a better method I have missed?

Worth mentioning: I am using the Metatag module, which seems to alter page titles on a fundamental level. I am not sure if this is related to my problem.

# Answer
> 1 votes
From PHP code, it's just:

```
variable_set('site_name', 'My Site Name');

```

If it doesn't work, clear you caches, restart your memcached if you're using it or check if you didn't export it into Features or hardcoded into your settings file.

One-time go is via drush:

```
drush -y vset site_name "My Site Name"

```

To check if the value was changed:

```
drush vget site_name

```

# Answer
> 3 votes
What is the value for the `site_name` variable in the `variables` table? (e.g. what's the output of `variable_get('site_name')`?)

If it's overridden from the value that you set in your settings file, reset it like so:

`variable_set('site_name', $my_title)`

---
Tags: tokens, theming, configuration, 7, meta-tags
---


title: pager not working with custom reports

text:
# Question
Title: pager not working with custom reports
I have custom reporting which has few dropdowns. A report is generated in the form of a table with selected dropdown values.

I have tried adding pager to the table.

When I click on next page, all the form values loose their form state and page is reloaded back and table gets disappeared.

Im using 'drupal\_get\_form' in pagecallback in the menu items list.

Here is the code to generate report.

```
/**
 * Method to implement menu for this page
 *
 * @return multitype:multitype:string multitype:string
 */

function dm_reports_menu() {
    return array (
            'dm_reports' => array (
                    'title' => 'Reports',
                    'page callback' => 'drupal_get_form',
                    'page arguments' => array (
                            'dm_reports_form'
                    ),
                    'access callback' => 'user_access',
                    'access arguments' => array (
                            'administer dm_reports'
                    )
            )
    );
}

/**
 * Method to submit the form and generate report
 *
 * @param unknown $form
 * @param unknown $form_state
 */
function dm_reports_form_submit($form, &$form_state) {
    $circle_name = $form_state ['values'] ['circle_name'];
    $report_type = $form_state ['values'] ['choose_report'];
    $system_type = $form_state ['values'] ['system_type'];
    $office_name = $form_state ['values'] ['office_name'];
    $migration_type = $form_state ['values'] ['migration_type'];
    $from_date = get_date_SQL ( $form_state ['input'] ['from_date'] );
    $to_date = get_date_SQL ( $form_state ['input'] ['to_date'] );
    $plan_type = $form_state ['values'] ['plan_type'];
    $phase_type = $form_state ['values'] ['phase'];
    $vendor_name=$form_state ['values'] ['vendor_name'];

    if ($form_state ['values'] ['op'] == 'Generate Report') {

        // Report header
        $header = get_header_data ( $report_type, $system_type );
        $rows = array ();
        // Get rows data
        try {

            $rows = get_row_data ( $report_type, $circle_name, $office_name, $system_type, $migration_type, $from_date, $to_date, $plan_type, $form_state,$phase_type,$vendor_name );
        } catch ( Exception $e ) {
            form_set_error ( '', t ( 'Error occurred. Please try again, or report a problem to administrator.'.$e ) );
            watchdog ( 'atm_status', $e->getMessage (), NULL, WATCHDOG_ERROR );
        }
        $report_name = '';
        if (sizeof ( $rows ) > 0) {
            $report_name = $report_type .'_' . date ( 'd_M_Y_H_i_s', time () ) . '.xls';
    //      generate_xls ( $header, $rows, $report_name);
        }
        $form_state ['report_name'] = $report_name;

        // build the results table
        $form_state['results_table'] = array (
                '#title' => $report_type,
                '#theme' => 'table',
                '#header' => $header,
                '#rows' => $rows,
                '#sticky' => TRUE,
                '#empty' => t ( 'NO DATA FOUND.' )
        // '#prefix' => '<hr><strong>' . $report_type . '</strong><div style="width: 720px; height: 300px; overflow: auto;">',
        // '#suffix' => '</div>'
        );

        $form_state ['rebuild'] = TRUE;
    }

}

function get_dm_issues_data($circle_name,$office_name)
{
$rows = array ();

    $query = db_select('dm_issues', 'di')
    ->extend('PagerDefault')
    ->limit(3)
    ->fields('di');

    $results = $query->execute();

    foreach ( $results as $node ) {
        $rows [] = array (

                $node->de_date,
                $node->po_name,
                //$node->weg_code,
                $node->kvp_duplicates,
                $node->nsc_duplicates,
                $node->duplicate_int_ent,
                $node->no_int,
                $node->nominee_grt_one,
                $node->account_his_na,
                $node->comments

        );
    }
    return $rows;
}

```

Any help would ne appreciated.

# Answer
> 0 votes
```
function dm_reports_form($form, &$form_state) {
    $REPORT_TYPE = array (
            ATM_STATUS_SUMMARY_REPORT => ATM_STATUS_SUMMARY_REPORT,
            ATM_STATUS_DETAILED_REPORT => ATM_STATUS_DETAILED_REPORT,
            BRANCH_HARDWARE_SUMMARY_REPORT => BRANCH_HARDWARE_SUMMARY_REPORT,
            BRANCH_HARDWARE_DETAILED_REPORT => BRANCH_HARDWARE_DETAILED_REPORT,
            CPC_STATUS_REPORT => CPC_STATUS_REPORT,
            DATA_CLEANSING_SUMMARY_REPORT => DATA_CLEANSING_SUMMARY_REPORT,
            DATA_CLEANSING_DETAILED_REPORT => DATA_CLEANSING_DETAILED_REPORT,
            DAILY_STATUS_REPORT => DAILY_STATUS_REPORT,
            DATA_CAPTURE_STATUS_SUMMARY_REPORT => DATA_CAPTURE_STATUS_SUMMARY_REPORT,
            DATA_CAPTURE_STATUS_DETAILED_REPORT => DATA_CAPTURE_STATUS_DETAILED_REPORT,
            DATA_CAPTURE_DETAILED_SUMMARY_REPORT => DATA_CAPTURE_DETAILED_SUMMARY_REPORT,
            DATA_CAPTURE_STATUS_FOR_PAYMENT_REPORT => DATA_CAPTURE_STATUS_FOR_PAYMENT_REPORT,
            POVsVendor_STATUS_SUMMARY_REPORT=>POVsVendor_STATUS_SUMMARY_REPORT,
            PRODUCT_WISE_DATA_CAPTURE_DETAILED_REPORT => PRODUCT_WISE_DATA_CAPTURE_DETAILED_REPORT,
            DATA_MIGRATION_SUMMARY_REPORT => DATA_MIGRATION_SUMMARY_REPORT,
            DATA_MIGRATION_DETAILED_REPORT => DATA_MIGRATION_DETAILED_REPORT,
            PROBLEMS_REPORTED => PROBLEMS_REPORTED,
            ROLLOUT_DASHBOARD => ROLLOUT_DASHBOARD,
            ROLLOUT_PLANNING_REPORT => ROLLOUT_PLANNING_REPORT,
            TRAINING_STATUS_REPORT => TRAINING_STATUS_REPORT,
            DM_SUMMARY_REPORT => DM_SUMMARY_REPORT,
            DM_ISSUES_REPORT => DM_ISSUES_REPORT,
            DE_STATUS_DASHBOARD => DE_STATUS_DASHBOARD
              // GoLiveVsPO_NOT_STARTED => GoLiveVsPO_NOT_STARTED,
             // GoLiveVsPO_COMPLETED => GoLiveVsPO_COMPLETED
    );

$system_types = array (
        CBS => CBS,
        PLI => PLI
);

$migration_types = array (
        MOCK_MIGRATION => MOCK_MIGRATION,
        FINAL_MIGRATION => FINAL_MIGRATION
);

$plan_types = array (
        END_USER_TRAINING_PLAN => END_USER_TRAINING_PLAN,
        USER_CHAMP_TRAINING_PLAN => USER_CHAMP_TRAINING_PLAN,
        DATA_CAPTURE_PLAN => DATA_CAPTURE_PLAN,
        MOCK_MIGRATION_PLAN => MOCK_MIGRATION_PLAN
);

$phase = array (
        ALL=> ALL,
        PHASE_PILOT => PHASE_PILOT,
        "1000 PO" => "1000 PO",
        PHASE_1A => PHASE_1A,
        PHASE_1B => PHASE_1B,
        PHASE_2A => PHASE_2A,
        PHASE_2B => PHASE_2B
);

$form = array ();
$form ['#attributes'] = array (
        'enctype' => 'multipart/form-data'
);

$form ['choose_report'] = array (
        '#type' => 'select',
        '#title' => t ( 'Choose Report' ),
        '#options' => $REPORT_TYPE
);

$form ['phase'] = array (
        '#type' => 'select',
        '#title' => t ( 'Phase' ),
        '#options' => $phase,
        '#states' => array (
                'invisible' => array ( // Making circle name list invisible if report selected is PROBLEMS_REPORTED
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => PROBLEMS_REPORTED
                                ),
                                //array (
                                //      'value' => DM_SUMMARY_REPORT
                                //),
                                //array (
                                //      'value' => DM_ISSUES_REPORT
                                //),
                                array (
                                        'value' => DE_STATUS_DASHBOARD
                                ),
                            )
                        )
                    )
);

$circle_names [ALL] = ALL;
$circle_names = array_merge ( $circle_names, getCircleNames () );

$form ['circle_name'] = array (
        '#type' => 'select',
        '#title' => t ( 'Circle Name' ),
        '#options' => $circle_names,
        '#ajax' => array (
                'callback' => 'reports_populateOfficeName',
                'wrapper' => 'textbox-div',
                'method' => 'replace',
                'effect' => 'fade'
        ),
        '#states' => array (
                'invisible' => array ( // Making circle name list invisible if report selected is PROBLEMS_REPORTED
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => PROBLEMS_REPORTED
                                ),
                                array (
                                        'value' => ROLLOUT_PLANNING_REPORT
                                ),
                                array (
                                        'value' => DE_STATUS_DASHBOARD
                                )
                        )
                )
        )
);

// Populating PO names dynamically
$circle_name = reset ( $circle_names );

if (! empty ( $form_state ['values'] ['circle_name'] )) {
    $circle_name = $form_state ['values'] ['circle_name'];
}

$office_names [ALL] = ALL;

$office_names = array_merge ( $office_names, getPONamesReports ( $circle_name ) );

$form ['office_name'] = array (
        '#type' => 'select',
        '#title' => t ( 'Office Name' ),
        '#options' => $office_names,
        '#prefix' => '<div id="textbox-div">',
        '#suffix' => '</div>',
        '#states' => array (
                'invisible' => array ( // Making circle name list invisible if report selected is PROBLEMS_REPORTED
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => PROBLEMS_REPORTED
                                ),
                                array (
                                        'value' => ROLLOUT_PLANNING_REPORT
                                ),
                                array (
                                        'value' => DE_STATUS_DASHBOARD
                                )
                        )
                )
        )
);

$form ['system_type'] = array (
        '#type' => 'select',
        '#title' => t ( 'System Type' ),
        '#options' => $system_types,
        '#states' => array (
                'visible' => array ( // Making circle name list visible if report selected is TRAINING_STATUS_REPORT
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => TRAINING_STATUS_REPORT
                                ),
                        /*      array (
                                        'value' => CPC_STATUS_REPORT
                                ),
                                array (
                                        'value' => BRANCH_HARDWARE_DETAILED_REPORT
                                ),
                                array (
                                        'value' => BRANCH_HARDWARE_SUMMARY_REPORT
                                )
                        */
                        )
                )
        )
);

$form ['migration_type'] = array (
        '#type' => 'select',
        '#title' => t ( 'Migration Type' ),
        '#options' => $migration_types,
        '#states' => array (
                'visible' => array ( // Making circle name list invisible if report selected is PROBLEMS_REPORTED
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => DATA_MIGRATION_SUMMARY_REPORT
                                ),
                                array (
                                        'value' => DATA_MIGRATION_DETAILED_REPORT
                                )
                        )
                )
        )
);

$form ['plan_type'] = array (
        '#type' => 'select',
        '#title' => t ( 'Plan Type' ),
        '#options' => $plan_types,
        '#states' => array (
                'visible' => array ( // Making circle name list invisible if report selected is PROBLEMS_REPORTED
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => ROLLOUT_PLANNING_REPORT
                                )
                        )
                )
        )
);

$stored_date = get_stored_date_value ( $form_state, 'from_date' );

$form ['from_date'] = array (
        '#type' => 'date',
        '#title' => t ( 'From Date' ),
        '#value' => $stored_date,
        '#process' => array (
                'form_process_date',
                'fix_year_range_current'
        ),
        '#states' => array (
                'visible' => array (
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => ROLLOUT_PLANNING_REPORT
                                ) ,
                                array (
                                        'value' => DE_STATUS_DASHBOARD
                                )
                        )
                )
        )
);

$stored_date = get_stored_date_value ( $form_state, 'to_date' );

$form ['to_date'] = array (
        '#type' => 'date',
        '#title' => t ( 'To Date' ),
        '#value' => $stored_date,
        '#process' => array (
                'form_process_date',
                'fix_year_range_current'
        ),
        '#states' => array (
                'visible' => array (
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => ROLLOUT_PLANNING_REPORT
                                ) ,
                                array (
                                        'value' => DE_STATUS_DASHBOARD
                                )
                        )
                )
        )
);

$Vendor_Name [ALL] = ALL;
$Vendor_Name = array_merge ( $Vendor_Name, getVendorNames_O());

$form ['Vendor_Name'] = array (
        '#type' => 'select',
        '#title' => t ( 'Vendor Name' ),
        '#options' => $Vendor_Name,
        '#prefix' => '<div id="textbox-div">',
        '#suffix' => '</div>',
        '#states' => array (
                'visible' => array ( // Making circle name list visible if report selected is POVsVendor_STATUS_SUMMARY_REPORT
                        ':input[name=choose_report]' => array (
                                array (
                                        'value' => POVsVendor_STATUS_SUMMARY_REPORT
                                )
                        )
                )
        )
);

$form ['submit'] = array (
        '#type' => 'submit',
        '#value' => t ( 'Generate Report' ),
        '#suffix' => '   '
);

if (! empty ( $form_state ['results_table'] )) {
    if (! empty ( $form_state ['report_name'] )) {
        // code to generate link for downloading report
        $base_url = $GLOBALS ['base_url'];
        //$currentDate = date ( 'd-M-Y', time () );
        $currentDate = date ( "d-M-Y H:i:s");
        $form ['download'] = array (
                '#markup' => '<strong><a href="' . $base_url . REPORTS_URL . $form_state ['report_name'] . '">Download Report</a></strong> : As on '.$currentDate
        );
    }

//   Code to display report in table format
$form ['table'] = $form_state ['results_table'];
}

return $form;
}

```

---
Tags: paging
---


# Question
Title: How can I adjust the css within fusion theme based on the size of the screen?
I'm using the Fusion theme for its responsive components but there are some things I want to tweak on the different layouts based on the screen size of the device viewing.

How can I apply style changes to say the phone layout, but not change the desktop and tablet layouts?

As a working example, lets say I wanted to accomplish the following:

```
/* Desktop + Tablet */
h1 {
  color: red;
}

/* Phones */
h1 {
  color: blue;
}

```

Are there selectors I should be using to accomplish this type of fine tuning?

# Answer
You might find this post on media queries and width attributes useful.
> 1 votes

---
Tags: theming
---


# Question
Title: How to add another filter to TVI default page view?
I have the TVI module installed but I wanted to add one more contextual filter

currently: mysite.com/taxonomy/term/\[term of tags vocabulary\]

what I want: mysite.com/taxonomy/term/\[term of tags vocabulary\]/\[other term of another vocabulary\]

How to do this?

# Answer
> 0 votes
You're most of the way there by the look of things, change your page settings -\> path to `taxonomy/term/%/%`

The second `%` will provide your second contextual filter.

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


# Question
Title: How to implement jQuery Accordion for a Menu?
I'm looking to implement something like the Accordion Menu module, but unfortunately that module has issues with Menu Block and other modules... so what's the best way to implement the jQuery Accordion menu with primary and secondary links, from a theming perspective? Should be a simple question for a themer, but I haven't found any specific tutorials that can take me step by step.

Using Drupal 7, Adaptive Theme.

update: thanks for all the responses. I'll look at all of the suggestions and provide another update :-)

---

**Madam Adam's solution: not working correctly yet**

> Only got it to work with this modification; added to js file

```
(function ($) {
//add drupal 7 code
Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
//end drupal calls

//some jquery goodness here...
$( "#accordion" ).accordion( {
  header: "li",
  collapsible: true
} );

}}})
(jQuery);

```

# Answer
> 1 votes
You have to include the accordion library by adding this line to your theme's template.php:

```
drupal_add_library('system', 'ui.accordion');

```

Then you trigger the accordion by adding this to yout template.php or an external js-file:

```
$( "#menu-container" ).accordion( {
  header: "li",
  collapsible: true
} );

```

# Answer
> 1 votes
You can write a simple jQuery script to create accordion like menus

```
<script>
    jQuery(document).ready(function(){

    jQuery('li.expanded').mouseover(function(){

     jQuery(this).find('ul').show(200);
    });
     jQuery('li.expanded').mouseout(function(){

     jQuery(this).find('ul').hide();
    })

    })
    </script>
<style>

 #nav > li{position:relative}
   #nav  li  ul.sf-menu{
    position:absolute;
    height:200px;
    width:150px
    }
    </style>

```

with little adjustment in css. Check classes in the image and how it is used in jQuery

# Answer
> 0 votes
I found flexnav to be extremely useful. There is a module in development that makes most of the installation very easy, can't recommend it enough.

---
Tags: theming, routes, javascript, navigation
---


title: Drupal 7 & jQuery -- the $ dollar sign

text:
# Question
Title: Drupal 7 & jQuery -- the $ dollar sign
If I'm not planning on using any JS libraries other than jQuery, is there any reason to need Drupal's call to jQuery.noConflict() which removes $ as an alias for jQuery?

Assuming there is no need for removing the $ alias, is there a way I can get it back universally without always having to wrap my jQuery code in (function($){...})?

# Answer
The solution I came up with is this:

At the top of the first JS file I include in my custom theme, I simply put the following line:

```
$ = jQuery;

```

Done :)
> 11 votes

# Answer
No, you can not (Well, you probably could, but you shouldn't).

Maybe at some point, your module will be used on another project on another site and then that site will use another JS library (Remember, every drupal module you write is automatically GPL and your client can use it in any way they want).

It's not that complicated to add these two lines to every js file :)
> 6 votes

# Answer
This could also be a possible solution, if you tend to use modules for those kind of questions.

jQuery Dollar

> This module allows developers to use $ to access the jQuery library instead of having to call jQuery explicitly or use special closures in Drupal 7. All you have to do is enable it.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to use a field other than node id or term id as contextual filter?
I have a content type "Person" which has a field called "state". On the node page of any "person", I want to display other nodes of "Person" which has the same value for the "state" field.
For e.g. If a we are on a person node who is from New York, the view block placed on this node should display other persons from New York.

I know how this could be done if it were node id, or term id : using contextual filters and getting content id from URL, etc. However, I'm not sure how do I get this from other text field like "state".

Any pointers would be appreciated.

# Answer
> 0 votes
I think you need use the field type "list" or the field type "Taxonomy term".

# Answer
> 0 votes
I don't know if it is possible with Views UI. But you could always recover your "field\_state" value **manually** by getting the current node (assuming you're running the code in a node page):

```
$node = menu_get_object();
$state = $node->field_state[LANGUAGE_NONE][0]['value'];

```

And then use that value to look for other similar nodes, for example with EntityFieldQuery:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'person')
  ->fieldCondition('field_state', 'value', $state, '=');
$results = $query->execute();

```

And display the results with theme\_table maybe.

---
Tags: 7, views
---


# Question
Title: Commerce Product generate Preview on Add Product page
I want to add a Preview button in Commerce Product Add form. Before adding product, user can see Preview of Product same as Product Display/Detail page.

I am using Rules to create Product Display after saving Product.

I have added below code in form\_alter hook but :

//Add Preview

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'commerce_product_ui_product_form') {
       $form['actions']['preview'] = array(
          '#type' => 'submit',
          '#value' => t('Preview'),
          '#weight' => 10,
          '#submit' => array('product_preview'),
        );

        // Some special stuff when previewing a node.
        if (isset($form_state['node_preview'])) {
          $form['#prefix'] = $form_state['node_preview'];
          $node->in_preview = TRUE;
        }
        else {
          unset($node->in_preview);
        }
  }
}

function product_preview($form, &$form_state, $node) {
  module_load_include('inc', 'node', 'node.pages');
  $node = new stdClass();
  $node->field_product['und'][0]['product_id'] = $productId;
  $node->title = 'test';
  $node->uid = 2;
  $node->type = 'commerceproduct';
  $node->in_preview = TRUE;
  $form_state['node'] = $node;

  node_form_build_preview($form, $form_state);
}

```

Above code displays preview for edit but problem is in node object i am getting $node-\>field\_product\['und'\]\[0\]\['product\_id'\] value not whole Product object. So any updated value of product form fields won't be reflected in preview.

I am not sure how to build whole product object within node object.

Can anyone tell me what is missing here ?

# Answer
You can try rendering the product entity and attaching it to the form.

To render the product entity (see entity\_view):

```
// Extract the referenced product from the node.
$node_wrapper = entity_metadata_wrapper('node', $node);
$product = $node_wrapper->field_product->value();

$product_view_mode = 'full'; // Set the view mode you want to use to display this product.

// This will return a render array.
$rendered_product = entity_view('commerce_product', array($product->product_id => $product), $product_view_mode);

```

Finally, alter the form so that it also contains the rendered product.

```
// Now add the markup to the form.
$form['product_preview'] = array(
  '#markup' => render($rendered_product);
);

```
> 0 votes

---
Tags: commerce, entities
---


# Question
Title: Multi-site installation with shared database but different user table
I need to install drupal multi-site with shared database but just need to create some tables specific to that site like, users table should be different for sub-sites.

I know about full sharing or full different database for different sites, but I need partial different database. I searched for it on google but didn't get exact solution so posting it here if anybody has clue about?

# Answer
You can try editing you sub-sites settings.php file and you just need to provide different prefix for user table (as you need only this table different).

I am providing sample here so that you can implement and see if it works.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
           'users'     => 'abcsite_',
      ),
    ),
  ),
);

```

The above code will tell your installation to use `abcsite_users` (you need to create table first with same structure as of default users table) for entering user details.
> 2 votes

---
Tags: 7, users, database, multi-sites
---


# Question
Title: Where is the entity in code field? [Display suite module]
I create a code field in Display Suite module and I need to insert a `format_plural` in it like

```
print format_plural([node:comment-count],  '1 Comment',  '@count Comments');

```

but token do not work in php block so I tryed:

```
dsm($node);
dsm($entity);
dsm($object);

```

but they do not work because 'Undefined variable' error. Where is the node variable in display suite code field?

How can I achieve this output?

There is the screenshots

# Answer
SOLVED!

I needed to enable 'Display Suite Format' module.
If enable it give me a new text format 'Display Suite code' which give an $entity variable inside a code field!
> 3 votes

---
Tags: display-suite, input-formats
---


# Question
Title: Maintain in-house repository of custom modules?
Whenever a contributed module has a new version, Drupal's update manager will show a notification and allow automatic downloading of the updates. After that, the user is guided through "update.php". Is it possible to get the same automatic treatment for custom modules?

If I develop a few custom modules for a specific site, it would be interesting to get Drupal to look for updates of said custom modules, on a server specified by me, where I'm hosting the modules myself, and treat them like any contributed module. But maybe this goes against good practices?

# Answer
> 4 votes
> maybe this goes against good practices?

Wouldn't have thought so, providing a central repo for your modules can only be a good thing in my opinion. It's the best way to keep multiple sites up-to-date with changes to custom modules.

What you need is a combination of the Feature Server module:

> This module allows you to share features and custom modules on your own website. It lets you create projects and releases, and it produces an update XML feed compatible with the update module in core. In a way it's a highly simplified version of the project module.

And the `project status url` module .info file setting, for your custom modules:

> Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

---
Tags: 7, updating
---


# Question
Title: Is there a drupal 7 module for webform password and password confirmation fields?
Is there any module that I can use for password and password verification field on webform.

I googled the sites and apparently the webform\_password module is for drupal 6 only.

Thanking you in advance

# Answer
Well, actually there's an issue posted for Drupal 7 `webform_password` module.

Checkout the issue here

You can download `webform_password` module for Drupal 7 from here
> 1 votes

# Answer
I've just updated Webform Password Field to Drupal 7 as is, that is, it doesn't do any validation etc. Please feel free to throw in ideas.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: galleria Slideshow images does not display
I have created an eva view, to display a group of gallery albums. Within my content type on manage displays am using a default galleria formatter and in my eva view I have a Grid of different image albums. All I get is the album thumbnails. Tried to clear the cache but still. I went through the galleria read me, and I believe I have done everything that they said one needs to do to get galleria working.

I am using Drupal 7 and have installed the followings:

Initially installed Galleria Jquery plugin(libraries) 1.4.2 Galleria module (7.x-1.0-beta3) but didn't work I then added the following modules Views Slideshow: 7.x-3.1 Views Slideshow: Galleria: 7.x-3.2

Am I missing something?

# Answer
> 0 votes
Thanks for browsing my question. I got it right by simply reverting back to an old version of Galleria Jquery plugin. I used galleria 1.2.9 instead of 1.4.2 and all is well.

I am still puzzled though as to why the new version is not working.

---
Tags: nodes
---


# Question
Title: Online payemnts with commerce: what charges should I expect
I am currently trying to setup a website with a simple online shop. Now for the online payments I'm struggling a bit to gather the information of all the things I'd like to know before making a decision. There are different banks, "externalizers", modules etc. and it seems to me that everywhere they want some money and I am not quite sure what for! So to get things straight - where should I expect charges? And if possible, what is the most economic or even free solution? I do not know if this little web-shop is going to work out. I see this list for example (https://drupalcommerce.org/faq/payment-methods) and do not understand how these things work except that every entity says that they are really awesome :-/. I do not find out how I will get the money transferred (and what countries).

I do not really get how online payment works: I need a bank account and something that transfers the money - so 2 things right?

* Should I expect to pay for a module?
* What should I expect to pay to the bank or entity that is transferring the money?
* What are free/economic solutions?
* Are there any traps/problems what kind of credit cards will be accepted?
* Is there any resource that gives an organized overview of the segment?

Thanks for your help

# Answer
* you shouldn't pay for the module itself, most gateways have free modules, see https://drupalcommerce.org/extensions/module/payment. When you click on each module the CommerceGuys have been so nice to list transaction fees
* I recommend not using a gateway charging more than PayPal. See their fees here: https://www.paypal.com/dk/webapps/mpp/merchant
* Laws on online payments differ from country to country, so there isn't one answer to this. To my knowledge PayPal is the closest thing to free. No-one handles payments for free but some don't take setup fees, only transaction fees.
* Accepting cards directly on your site requires a lot from you, both in terms of subscription to an organization offering merchant accounts (NETS in my case charges around 300€ for this in Denmark - and have a monopoly on the market). Proper gateways like ePay etc. furthermore charges a subscription plus transaction fees (on top of whoever has given you the merchant status). Finally you need to meet certain criteria about how you handle payments. For Example:
    + It's illegal to accept payment for something yet to be delivered in DK, so our gateway has to be able to only reserve the money. We're also obliged to offer our terms and conditions on both english & danish. And the list goes on - and varies locally.
* I recommend you to keep it simple and easy by using PayPal until your sales are high and your knowledge on these matters have increased significantly.
* For your last question I again recommend the drupal commerce module list in my first bullet
> 0 votes

---
Tags: commerce, payment-gateways
---


title: Unable to install drush on mac 10.9.2

text:
# Question
Title: Unable to install drush on mac 10.9.2
Lately I was trying to install drush for the first time. This is what I did..

* Installed the drush tool manually
* Extracted and renamed the tool to `/Library/Drush`
* Gave the `/Library/Drush/drush` tool execution permissions.
* Created an alias for drush in `~/.bashrc`
* Tried to bash drush by entering the alias `drush`, that's when I got the first problem: `Unable to load autoload.php. Drush now requires Composer in order to install its dependencies and autoload classes. Please see README.md`
* After lots of searching I tried way to many things:
    + `which drush` doesn't return anything.
    + Installing the composer (at `/usr/local/bin/composer`) results in this `The requested package drush/drush 1.0.0 could not be found` problem when executing `composer global require drush/drush:dev-master`

Help would be appreciated, because I don't know what I could do to make it work.

Thank you in advance, \`F.

# Answer
I have encountered the same error while installing the drush on MAC, I have tried the following and that worked for me:

```
composer self-update
ln -s /path/to/drush/drush /usr/bin/drush

```

I have downloaded the Drush from this git repository: https://github.com/drush-ops/drush

And followed the method described here for installing the Drush on MAC: https://www.drupal.org/node/1674222

---

For Installing Drush on Mac using Homebrew, check https://www.drupal.org/node/954766
> 1 votes

---
Tags: 7, drush
---


# Question
Title: How to enforce users to input user account's fields after user registeration?
I'm useing D7.

What I want to do is...

Step1: Let users register only by inputting their email address & password on user registration form (http://www.my\_website.com/user/register)

Step2: Redirect them to user account edit page (http://www.my\_website.com/user/user id/edit) after their registration. And then, enforce them to input the rest of fields such as \[first\_name\] & \[hobby\] on the edit page.

The 'step1' was able to be done by using 'Email Registration' & 'User registration password' module. And I think I can redirect users to the edit page. But I don't know how to enforce them to complete the rest of fields in edit page.

I want to do this without using Profile2 module. Does anybody have idea to do that?

I'm really sorry if this is an entry-level question to you. But I'm very new to Drupal and I have been struggling with this for a week, but I couldn't find the way. Please somebody help me!

Thank you!

# Answer
Try using Rules. You could add a new field into the users' accounts that is `Completed Profile Fields` and it could be a single boolean or possabily a `multi-value field`.

Then your rule could check:

* If login, or page load -- has user completed profile fields? If yes, continue to any page -- else show a `profile form page` (not necessarily their account page).
* I'm not sure it would be easy to do this globally, or test the profiles have been filled prior to going to a `/node/add` page for instance.
* After filling in the profile values the Rule could update the user account field `completed profile fields` to `True`.

If you don't want users to see this `completed profile fields` field -- you can install and use Field Permissions.

**EDIT**

If you dont want the user to see this special `completed profile fields` but still want the rule to update the value you may need to set the `uid` of the user updating this field. I do this usually by creating a fake user for the system called like `mysite-system-user` and give him a special role called `system role` for instance.
> 2 votes

---
Tags: users
---


title: Any advice for dynamic radio butons

text:
# Question
Title: Any advice for dynamic radio butons
I need a form that has a radio buton field. The field must not hard coded. Options must created dynamicly. The form will be a block and get radio buton options from given chosed node field.

For example if the form in node 1, radio options comes from node 1's given field, and so on.

Can you give me any advice to accomplish this? (entity form, web forms, custom form etc?)

(Sorry for my poor English)

# Answer
> 0 votes
Personally, I would create a custom module with a custom form and block. You're gonna want to study up on the form api. You can pass variables to your form, which for you would be your node object.

The block is really easy, just use hook\_block\_info() to define your block, hook\_block\_view to define a subject and callback function, and then just define a callback.

Something like this:

```
function mymodule_block_info (){
   $blocks[0] = array(
      'info' => t('radio thing'),
      'cache' => do_stuff
    );
   return $blocks;
}

function do_stuff(){
    //where radio_form is the implementation of your form (make sure it has a param for the node
    drupal_get_form ('radio_form', $node)
    return $stuff
}

```

---
Tags: forms, webforms, entities
---


# Question
Title: How can I make the summary field required?
Is there a way to make the summary field required by default in the node form?

# Answer
It might be easier to create a new field for the summary and just manage it that way, you will then have to remove the summary option from the body field. Otherwise I think you will have to write some code and use hook\_form\_alter.
> 2 votes

# Answer
in a custom module, hook into the the form alter hook

```
MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['body'][LANGUAGE_NONE][0]['summary']['#required'] = TRUE;
}

```

or

```
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id = 'MY_FORM_ID') {
       $form['body'][LANGUAGE_NONE][0]['summary']['#required'] = TRUE;
   }
}

```
> 0 votes

# Answer
Go to admin/structure/types/manage/your\_content\_type\_name/fields; there, you have the option to make this field required.
> -1 votes

---
Tags: entities
---


# Question
Title: Jquery.on method returns undefined is not a function
My goal was to create a simple button which once clicked would hide/show a navigational menu, and change the footer's padding alternatively, I'd have used toggle if not for the latter condition. Before I inserted `.on()` I just had the `.click()` method with a if/else, which only worked for the first click, so I added `.on` to solve the problem. Unfortunately it doesn't work, each time the console prints `'Uncaught TypeError: undefined is not a function'`. Any help, suggestions, or alternatives, will be much appreciated.

```
(function ($, Drupal){
Drupal.behaviors.footerCollapse = {
    attach : function() {
        function collapseOrCondense(event){
            if($('#block-panels-mini-footer-nice-menu:visible')){
            $('#footer').css({'padding-bottom':'2.5%'});
            $('#block-panels-mini-footer-nice-menu').hide();
         }
          else{
            $('#footer').css({'padding-bottom':'5.5%'});
            $('#block-panels-mini-footer-nice-menu').show();
          }
        };
        $('#footer').append('<button type=button class=cbutton>*</button>');
        $('#footer .cbutton').css({'position':'absolute', 'left':'1%', 'top':'1%', 'width':'2%','height':'1.5%'});
PROBLEM: $('#footer .cbutton').on('click',collapseOrCondense);
  }
 }
})(jQuery, Drupal);

```

# Answer
> 1 votes
depending on the version of Drupal you are running, it is likely a jquery version issue. Drupal 7 for example defaults with jQuery 1.4 if memory serves, and .on() was added to jQuery in version 1.7.

You could try jQuery Update module:

> ```
> Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
>
> Drupal 5 to jQuery 1.2.6
>
> Drupal 6 to jQuery 1.3.2
>
> Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
>
> Drupal 8: TBD
>
> ```

---
Tags: javascript
---


# Question
Title: Check to determine if user is member of any group of specific type
Our website has three types of groups: area groups, support groups and member organized groups.

While a member can join several or none of the support groups and member-organized groups, we do want each member to be a part of one (and only one) area group.

I'd like to find a way to use rules to check to see if a member is a member of an area group and if not, display a warning/help message to them to encourage them to join an area group. Ideally, I would like to do this several times shortly after they join and then occasionally after the first couple weeks (some people who are in the process of moving to the area may not want to join a group right away and I don't want the messages to get overwhelming for that small minority).

I've been playing around in the rules module to see what I can do, but I'm not sure exactly how to check to see if they are a member of any group of the area group type -- can anyone help me with determining what conditions I have to apply to get it to check this for me? Also can I put a limit (as suggested above) on the amount of times the message shows?

Or in lieu of that, is there an easier way to accomplish this goal of ensuring that all of our members make it into one area group?

Thanks Heather

# Answer
> 1 votes
I don't think Rules alone will do what you want. You'll want something like

```
// This hook fires whenever a user account is saved.
// If you want to do it at other times, you'll want another hook.
function mymodule_user_presave(&$edit, $account, $category) {
    // This is an organic groups API function for finding out what group a user is in.
    $user_groups = og_get_groups_by_user($account, 'my_group_type');
    if ( [check for group membership] ) { ... }
}

```

---
Tags: rules, organic-groups
---


title: ajaxify content via a callback function

text:
# Question
Title: ajaxify content via a callback function
I am trying to ajaxify my site. I want the **"Main page content"** to be passed via an ajax-command to a custom js-function.

To accomplish this I would do the following:

1. **I need to register a path for my ajax requests**

code:

```
$items['_custom_ajax_'] = array(
  'title' => 'AHAH callback',
  'page callback' => 'ajax_form_callback',
  'delivery callback' => '_custom_ajax_deliver',
  'access callback' => TRUE,
  'theme callback' => 'ajax_base_page_theme',
  'type' => MENU_CALLBACK,
);

```
2. **use a custom delivery callback function `_custom_ajax_deliver` which is the copy of the `ajax_deliver()`**

original code:

```
function ajax_deliver($page_callback_result) {
  // Browsers do not allow JavaScript to read the contents of a user's local
  // files. To work around that, the jQuery Form plugin submits forms containing
  // a file input element to an IFRAME, instead of using XHR. Browsers do not
  // normally expect JSON strings as content within an IFRAME, so the response
  // must be customized accordingly.
  // @see http://malsup.com/jquery/form/#file-upload
  // @see Drupal.ajax.prototype.beforeSend()
  $iframe_upload = !empty($_POST['ajax_iframe_upload']);

  // Emit a Content-Type HTTP header if none has been added by the page callback
  // or by a wrapping delivery callback.
  if (is_null(drupal_get_http_header('Content-Type'))) {
    if (!$iframe_upload) {
      // Standard JSON can be returned to a browser's XHR object, and to
      // non-browser user agents.
      // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
      drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
    }
    else {
      // Browser IFRAMEs expect HTML. With most other content types, Internet
      // Explorer presents the user with a download prompt.
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    }
  }

  // Print the response.
  $commands = ajax_prepare_response($page_callback_result);
  $json = ajax_render($commands);
  if (!$iframe_upload) {
    // Standard JSON can be returned to a browser's XHR object, and to
    // non-browser user agents.
    print $json;
  }
  else {
    // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
    // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
    // links. This corrupts the JSON response. Protect the integrity of the
    // JSON data by making it the value of a textarea.
    // @see http://malsup.com/jquery/form/#file-upload
    // @see http://drupal.org/node/1009382
    print '<textarea>' . $json . '</textarea>';
  }

  // Perform end-of-request tasks.
  ajax_footer();
}

```
3. **create an custom function which do the ajax request like `Drupal.ajax`**
4. **bind the ajax request to some selector e.g. `a.ajaxify`**
5. **add a custom ajax-command**

Im not sure if this is the right way, or if I can extend the core easier somehow. Basicly my approach is simmilar to the module Ajaxify Drupal with JQuery Ajax

Better Ideas?

Update: one more thing – I need an event to be triggered everytime an ajax-link is clicked.

# Answer
> 0 votes
IMHO, I'd like to use Drupal AJAX API instead of jQuery AJAX because it supports many commands, events and content are manageable, error control and event binding for new content, those features are supported by Drupal.

But the disadvantage is it sends too much data, process is more complicated, using POST all the times. But of course, at javascript level, we can override the default behaviors and make it better :)

For example, If you have any ajax errors, like ajax request is running and you change document location, you will see an alert box with error message. That's a bit annoying so I always override it by re-write this function in my theme

```
Drupal.ajax.prototype.error

```

About your working process, I have some comments

* 1 & 2: It's ok for me, but why do you need to use another copy of ajax\_deliver(), why don't you use it directly?
* 3: Are you going to write another thing like Drupal.ajax or just attach new function to Drupal.ajax? something like

```
Drupal.ajax.prototype.commands.log = function (ajax, response) {
    console.log(response);
};

Drupal.ajax.prototype.commands.open_popup = function (ajax, response) {
    var id      = typeof response.id      === 'string' ? response.id : 'gfc';
    var content = typeof response.content === 'string' ? response.content : '';
    var options = typeof response.options === 'object' ? response.options : {};

    Gfc.popup.open(id, content, options);
};

```

I'm ok if you do like that.
* 4: Yes of course
* 5: Errr, are you going to write something new instead if using Drupal.ajax?

---
Tags: 7, ajax
---


# Question
Title: Whats faster db_query, db_select, or EntityFieldQuery
So I'm trying to find out what is faster db\_query, db\_select, or EntityFieldQuery. Currently I'm using EntityFieldQuery. I'm grabbing about 1600 node entries.

I realize this can be taxing on the system so I just want to figure out which is the best option to grab 1600 nodes. Shaving off seconds or even milliseconds would matter a lot with the application I'm building.

Thanks in advance for your answers.

# Answer
> 26 votes
To answer your question in short, db\_query is the fastest! Here are some reasons, facts and figure compiled from different questions, sources:

A simple googling of this question, come up with following results:

```
For simple queries, db_query() is 22% faster than db_select()
For simple queries, db_query() is 124% faster than EFQ
For queries with two joins, db_query() is 29% faster than db_select()

```

and this

```
db_query():

Total Incl. Wall Time (microsec):   796 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 123,352 bytes
Total Incl. PeakMemUse (bytes): 124,248 bytes
Number of Function Calls:   38

db_select()

Total Incl. Wall Time (microsec):   1,118 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 425,216 bytes
Total Incl. PeakMemUse (bytes): 436,392 bytes
Number of Function Calls:   88

```

If you notice above db\_select makes more function calls and utilize more memory than db\_query.

1. See here for reasons on why to use db\_select
2. See here for reasons on why to use EntityFieldQuery over db\_select
3. See here for performance comparison of db\_query and db\_select

I guess the choice should be solely based on your requirements. EntityFieldQuery might be slower but, offers many advantages such as simple syntax, field storage is pluggable, loose coupling and many more.

# Answer
> 1 votes
If you just want the field data from all 1600 nodes, EFQE might be helpful. If you already have the EFQ you should be able to figure out what you need by looking at the sandbox page.

---
Tags: database
---


title: Issue with menu and user token

text:
# Question
Title: Issue with menu and user token
I'm having problems with some links that have a user token in it.

For ex. I have a link like this: `user/[current-user:uid]/edit`. But when I check this in the browser as a user I just see `Edit` instead of my Menu link title. I also get this error:

> Notice: Undefined index: localized\_options in menu\_navigation\_links() (line 1861 of /includes/menu.inc).

When I check this is as an admin I see the correct title and no error.

When I change permissions of `Administer users` and set to all users I can see it as a user to, but that's not the way to do it because now a user can cancel his account and change the role ... .

In my search quest I've found this issue but the solution #2 didn't help much.

I'm using the Menu Token Module and these are my configurations (user is set as you can see):

These are my link configurations:

As you can see I tried the solution from the issue on drupal.org.

# Answer
> 0 votes
I fixed the problem with the following steps:

1. Uncheck "Use token", change the "path" to normal path without using menu token.
2. Save the change.
3. Edit the menu, check "Use token", change the "path" to \[current-user:edit-url\]
4. Save.

---
Tags: users, tokens, navigation, 7
---


title: Themng the grouping fields in Views

text:
# Question
Title: Themng the grouping fields in Views
I have a view which lists dishes by category. Category is a tag ("main", "soup", etc). I use grouping fields, and what i wanted is to make a kind of anchor menu for this view. Is it possible to style the grouping fields?
Right now, grouping fields are in h3 headers, just before the relevant views rows. Is it possible to rewrite them,or alter their structure?

# Answer
> 2 votes
You have to override the view template.

In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As your view is using grouping, you need to override the **'Style output'** theme template as it is the one that contains the h3 tag you want to alter. When you click on the blue 'Style output' link it will open up a dialog with the code you can copy and alter. That code needs to go into a file placed within the template's folder of your theme. The file name must be selected from the list of suggestions in the same line next to the blue 'Style output' link. First in the list is:

```
views-view-list.tpl.php

```

If you override that template it will override it for all views of HTML List format, so you now have to select a more targeted suggestion. Going down the list you will see how different template suggestions target different contexts.

Have a look at this question for more information: Commerce Product Collection View Block: What Determines CSS For Each Header Link?

---
Tags: views, navigation
---


# Question
Title: Why Cant add a class to an element by jquery
In the page.tpl.php I have some elements like

```
<div class="play"></div>

```

I have linked js file to the page and it is correctly works since all functions operate based on click attributes. but I would like to mudify some elements in page.tpl.php page. for example in my JS file I have a code like this:

```
$(".play").attr("id", "myID");

```

I could not make it working. basically it does not add `myID` to `.play`.

Any idea?

# Answer
Going on little information provided its probably because you cannot access jQuery with the $ by default in drupal. This is to prevent other library conflicts (see jQuery.noConflict()) If this is the case you will probably be getting an undefined function error in your console. To fix this you can either use jQuery or wrap it in a function like this:

```
(function($){
  $(".play").attr("id", "myID");
})(jQuery);

```

or can do this:

```
jQuery(".play").attr("id", "myID");

```

By default the version of jQuery that is used on drupal is 1.5. You may consider using jQuery Update module for a newer version.

"Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them."
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: How to save a form inputs in database and retrieve it from database with out form submision
hi can i store form inputs in database and retrieve it from database with validation

I search many sites but neither any documentation or example or any thing i found for drupal7 . I didn't understand why it is not asked before .

I want to save a node form value in database with out form submition and at the time of retrieving i just want to validate those data .

what i achieve is now i can store data without submition or validation but when i was trying to validate those data in listing page (retrieve) page i can't do that.

i have tried node\_validate() drupal\_form\_validate() but neither of it works is i am doing some thing wrong

here is my code

```
function MY_MODULE_list() {
  module_load_include('inc', 'node', 'node.pages');
  $header = array(
    array('data' => t('id')),
    array('data' => t('form_id')),
    array('data' => t('owner')),
    array('data' => t('invalid input')),
  );
  $rows = array();

  $result = db_select('my_table', 'lt')
    ->fields('lt', array('id', 'form_id', 'owner', 'form_state', 'form_state_storage', 'form_state_input', 'form_state_node'))
    ->range(0,30)
    ->execute();

  if (!$result) {
    $rows[] = array(array('data' => t('No Result found.'), 'colspan' => 10));
  }
  else {
    $node_form = new stdClass;
    $node_form->type = 'node_type';
    $node_form->language = LANGUAGE_NONE;
    $form = drupal_get_form('node_type_node_form',$node_form);
    $form['#token'] = FALSE;
    foreach($result as $r){
        $form_state = @unserialize($r->form_state);
        $form_state_node = @unserialize($r->form_state_node);
        $form_state_input = @unserialize($r->form_state_input);
        $form_state_input['form_token'] = FALSE;
        $form_state_input['form_build_id'] = FALSE;
        $form_state['node'] = $form_state_node;
        $form_state['input'] = $form_state_input;
        unset($form['form_token']);
        unset($form['#token']);
        unset($form_state['form_token']);

        node_validate($form_state_node,$form,$form_state);

        $errors = form_get_errors();
        $noOfError = 'empty';
        if (!empty($errors)) {
          $noOfError = count($errors);
        }
        form_clear_error();

      $rows[] = array(
                    array('data' => $r->lid),
                    array('data' => $r->form_id),
                    array('data' => l(t(user_load($r->owner)->name), '/user/'.$r->owner)),
                    array('data' => $noOfError),
                  );
    }
  }

  $build = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('id' => 'MY_MODULE'),
  );
  return $build;
}

```

# Answer
Finally , create a own table for storing formstate and retrive it on my module page . at that time drupal\_validate\_form does the magic.
> 0 votes

---
Tags: nodes, forms, database
---


# Question
Title: mvf field is not working with view dependant filter
mvf field is not working with view dependant filter.

I created a mvf field .

I want its view filter with view dependent filter module .

Its filter is working fine when the field is not in dependant list . But when i inclued it with Dependent filter its not hiding.

# Answer
> 0 votes
finally i have to change the field type .

---
Tags: chaos-tool-suite, views
---


title: Not validating required validation

text:
# Question
Title: Not validating required validation
drupal\_validate\_form is not validating required validation when i was creating a node programatically .

Can any one say, it is design like that or am i doing something wrong .

```
        $node_form = (object) array(
            'type' => 'MY_CONTENT_TYPE',
            'language' => LANGUAGE_NONE,
        );
        $form = drupal_get_form('application_node_form',$node_form);
        $old_fs = @unserialize($r->form_state);
        $form_state = array();
        $form_state['values'] = $old_fs['values'];
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);

```

# Answer
You can check if the form failed validation by calling `form_get_errors`

You could try using `drupal_form_submit` instead, which I think will also validate the form (seen via `form_get_errors`)
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Calculate shipping based on square meters (m2)
I have lengths of material as products in Ubercart, 3 and I need to be able to calculate shipping of them based on their length x width. Plenty of options for shipping based on weight but that's not what is needed here. I've got width and lengths fields in my product type already plus I have created one called "m2" to enter the square meters manually in case that is easier. Just a bit stuck as to what I should do next. Could rules help me? Maybe modifying the flat rate module or would a custom module be needed?

# Answer
I'm struggling with a a similar problem.

From what I can see, the only way to do it with Ubercart is to connect to the API of an appropriate shipping company that supports volumetric shipping calculations. The availability of this (in terms of an existing module) will depend on which country you're working in, plus it will depend on whether there is an existing module that supports the specific carrier you've chosen.

The US is obviously well-served in this regard. Outside the US, support can be patchy, to say the least.
> 0 votes

---
Tags: ubercart
---


# Question
Title: How to add condition in between fields in Profile2 module in drupal 7?
I am using the Profile2 module. Two fields are there in the Registration Form i.e.

**I am** : \[Baby Male, Baby Female, Daddy, Mummy\]

&

**Looking For** : \[Baby Male, Baby Female, Daddy, Mummy\].

if user click on **I am** : \[Baby Male\] then in **Looking For**: \[Baby Female\] is only show.

If select **I am** : \[Baby Female\] then in **Looking For**: \[Baby Male\].

So If **I am** : \[Daddy\] then in **Looking For**: \[Mummy\] & If **I am** : \[Mummy\] then in **Looking For**: \[Daddy\].

How can I do this?. Is there any module in Drupal 7?

# Answer
Yes you can do this also option wise using field conditional state module.

Go through this field\_conditional\_state for details.

Trigger a state when applied to a control field:

```
    empty - Triggers when the control field is empty
    filled - Triggers when the control field is not empty
    checked - Triggers when the control field is checked
    unchecked - Triggers when the control field is not checked
    value - Triggers when the control field's value is equal to a given string
    !value - Triggers when the control field's value is NOT equal to a given string

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to use a separate file for IE responsive.css for version 10/11 in Drupal
I am setting responsive design for only IE (Internet Explorer) in Drupal 7. here is my code its for work lower then IE 10 not for IE 10/11

```
function bootstrap_preprocess_html(&$variables){
  drupal_add_css(path_to_theme() . '/css/ie_10.css',
    array('group' => CSS_THEME,
        'browsers' => array('IE' => 'lte IE 10',
            '!IE' => FALSE),
                 'preprocess' => FALSE)
);
}

```

# Answer
> 0 votes
I suggest customising a pre-built theme template that has already taken care of that such as Zen or Omega.

---
Tags: theming
---


# Question
Title: List of images with checkbox (user registration)
This is what I would like to do:

When a user registers on the website they have to give in if some options like for example if they are politically engaged, professionally engaged, an expert, ... .

I also want a field that contains 3 images. And based on the chosen options of the user I would like to select 1,2 or 3 of them. So the user can contain image 1 & 2 or ... .

So I was thinking of 3 images with 3 checkboxes and cross the checkboxes next to the images (programmatically). But is this a good way to do this? And if yes, how can I implement this?

# Answer
> 1 votes
You can do that by the following.

Go to Configuration » People » Account settings

Add a **Field type :** *List (text)* and **WIDGET:** *Check boxes/radio buttons*

In ***Allowed values list*** textarea add `key|<img src ='/your/path/to/image' />`

Enter one `<img>` per line and set *Number of values* as Unlimited (to appear as checkboxes)

That's it. I tested it and working fine.

Add `key` whatever you want.You may have to make minor CSS changes in order to align checkbox and image.

Hope this helps.

---
Tags: 7, users, entities, media
---


# Question
Title: How to add a path filter to views 3 in Drupal 7?
This question is similar/related to How do you add the NID as a view filter criteria and not contextual filter?

Is it possible to add a filter criterion to a view so that it filters the aliased path for a node?
*Content:Path* is available as a display field but not as a filter.

# Answer
Try the Views URL alias module.

> **The 'Views URL alias' module allows Views to be filtered by path aliases**.
>
> This module is useful if your website uses heirachical paths. It allows you to filter and sort a view by URL aliases. When combined with the Views bulk operation (VBO) module you can apply operations to a specific section of your website based on a URL alias.

Note that Currently, only node aliases are supported.
> 1 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: FeedsHTTPFetcher: how to parse object to get source url?
I've got several content-types based on imported RSS feeds (Feeds import, Simple Pie library).

In a Views pre render, I try to display an information stored in `$row->node_feeds_item__feeds_source_config` that looks like this:

```
a:1:{s:16:"FeedsHTTPFetcher";a:1:{s:6:"source";s:38:"http://www.as-e.be/agendas_rss/rss.xml";}}

```

How can I just get the `http://www.as-e.be/agendas_rss/rss.xml` part of that object? I have no idea how to parse that.

# Answer
Ok, I found out a dirty solution to extract an URL from a random string text!

```
preg_match('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $row->node_feeds_item__feeds_source_config, $match);

```
> 0 votes

---
Tags: 7, views, feeds
---


# Question
Title: How to override Drupal.ajax.prototype.beforeSend?
I need to add my own little if's and checks in 3 functions inside

```
misc/ajax.js (
  Drupal.ajax.prototype.beforeSend,
  Drupal.ajax.prototype.success,
  Drupal.ajax.prototype.error
)

```

How can I override them in my module? I can't find a manual and it's not in Examples for Developers. Sorry if it seems a dumb question, but I'm a php developer - I can work with js, but I'm not so fluent with it.

* Can I simply write it in my module's js file?
* If 2 or 3 modules needs to modify them, how to avoid conflicts?

# Answer
> 3 votes
`Drupal.ajax.prototype.beforeSend` and the others are just variables that happen to have functions assigned to them. As long as your code appears in the page build *after* the original function implementations, you you should be able to just override what's already there:

```
(function($) {
  // In mymodule.js, which appears after ajax.js in the page build
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    // Replacement code.
  }
})(jQuery);

```

# Answer
> 7 votes
This might be a better way:

```
(function ($) {
  // Drupal's core beforeSend function
  var beforeSend = Drupal.ajax.prototype.beforeSend;
  // Add a trigger when beforeSend fires.
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    beforeSend.call(this, xmlhttprequest, options);
    $(document).trigger('beforeSend');
  }
})(jQuery);

```

https://www.drupal.org/node/1372840

---
Tags: ajax, javascript
---


# Question
Title: POST taxonomy item using Services module
I want to POST a new taxonomy item. I'm using Postman in Chrome to test, I'm logged in fine, and I'm posting RAW JSON:

```
{
  "name": "building",
  "description": "",
  "vocabulary" : {
    "id" : 1,
    "resource" : "taxonomy_vocabulary",
    "uri" : "http://site/cms/taxonomy_vocabulary/1"
  }
}

```

And I just get this:

```
<?xml version="1.0" encoding="utf-8"?>
<result>Access denied for user anonymous</result>

```

# Answer
Here is the JSON format to add taxonomy term. I've tested it and works perfect.

```
{
    "vid": "2",
    "name": "Term Name",
    "description": "your description"
}

```

Here vid: vocabulary ID

Make sure the current logged-in user has privileges to add taxonomy term. and make sure to add token in *Headers* like follows

**name:** X-CSRF-Token

**value:** your-token

To know your token access the following path

```
yourdomain/services/session/token

```
> 1 votes

---
Tags: services, 8
---


# Question
Title: Exporting my custom content tables for a module
I've been working on a Drupal 7 module. As I've been going along, I have been adding content types in the database through the Drupal 7 admin.

I now want these content types to be created when my custom module is installed.

Rather than coding this manually in the module, is there any module available that can look at the content types on my site and create the code I need to put in the module install script?

# Answer
> 0 votes
You should look at the Features module. It will generate a module, which you can merge with your custom code.

---
Tags: 7, nodes, installation
---


# Question
Title: Attachment added through hook_mail_alter() is making no effect
I'm trying to add one pdf attachment to the mail sent on webform submission. I'm using `hook_mail_alter()` to add attachments to the mail.

This is the code I am using.

function webfpdf\_mail\_alter(&$message) { $attach = genpdf($message\['params'\]\['message'\]); $message\['params'\]\['attachments'\]\[\] = $attach; dpm($message); return $message; }

The output message shown by `dpm()` shows attachment, but the email doesn't contain attachments.

This is the output of `dpm()`.

```
attachments (Array, 1 element)
0 (String, 568525 characters ) Content-Type: application/pdf; name="Webform-...
Content-Type: application/pdf;
 name="Webform-submission.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="Webform-submission.pdf"

cSA4NS4wNCAwIDAgMzMuNzMgMjguM......
..../****base64data*****/.....
..... ;
body (Array, 1 element)
headers (Array, 7 elements)
MIME-Version (String, 3 characters ) 1.0
Content-Type (String, 24 characters ) text/html; charset=UTF-8
Content-Transfer-Encoding (String, 4 characters ) 8Bit
X-Mailer (String, 27 characters ) Drupal Webform (PHP/5.3.29)
Return-Path (String, 35 characters ) enquires@xxxxxxx.org
Sender (String, 35 characters ) enquires@xxxxxxx.org
From (String, 28 characters ) "LESS" <support@xxxxxx.com>

```

Can anyone help me to fix this?

# Answer
If you're not already using it, I think you need MIME Mail or something similar to handle attachments, and when you do, your attachment needs to be added as an array of arrays rather than an array.
This is what the README file says.

> You can use the following optional parameters to build the e-mail:
>
> * 'plain': Boolean, whether to send messages in plaintext-only (optional, default is FALSE).
> * 'plaintext': Plaintext portion of a multipart e-mail (optional).
> * 'attachments': **Array of arrays** with the path or content, name and MIME type of the file (optional).
> * 'headers': A keyed array with headers (optional).
> 1 votes

---
Tags: webforms, emails
---