# Question
Title: Unable to upload files. Though the maximum file size limit is 80 MB, can't upload even 50 kb files
I copied a site from localhost to AWS server. I can easily upload files in localhost but when I try uploading in the live site it gives me the error

*`"An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (80 MB) that this server supports."`*

In `php.ini` and .`htaccess` and `settings.php` I have changed `upload_max_filesize` to 80MB and `post_max_size` to 164 MB.

And according to this link, , I also disabled mod\_security module in apache.

Here it says, this could be AJAX/Jquery error.

Is there something else that could be the cause for this error?

# Answer
Some things that can break file uploads:

* upload\_max\_filesize and post\_max\_size ;
* memory\_limit ;
* Unwritable tmp directory.
> 2 votes

# Answer
Try increasing MaxRequestLen to 80MB as well. You will need it done for you by the administrators if you use a shared host environment though.
> 0 votes

---
Tags: ajax, files
---


# Question
Title: How to add Drupal Coupon discount for selected category or item only?
Project: Commerce Coupon Version: 7.x-1.0-beta7

Hi,

We are using drupal percentage coupon module for our websites and its very good.We have a request from customer where they need to exclude coupon discount for selected item/category.Reason they have a category which is having already discounted items.So now they need a feature where they can exclude coupon applying for those items.

Can we do this with existing module?

Thanks

# Answer
> 0 votes
You you can do it by adding new RULES. If you are using Percentage Coupon then you must have a rule in the list of rules list named "Calculate coupon with percentage amount".

Clone this rule & add more conditions according to your need like "Order contains products of particular product types" or "Order contains a particular product".

Its totally upto you to use conditional based discount and disable the default coupon redeem rules.

# Answer
> 0 votes
Yes, add a Reaction Rule for the "Validate a coupon" event.

Check the conditions there and fail validation if it doesn't match.

You can refer to the existing coupon validation rules there for reference.

Alternatively, you could take the approach RajeevK suggested and add the condition to the "Redeem a coupon" rule for the coupon instead.

---
Tags: commerce
---


title: EntityForm custom submit handler

text:
# Question
Title: EntityForm custom submit handler
I've attached an entityform object to content type on my site, the content is an organic group with users and administrators.

I want to extend the current emailing functionality of entityform -which currently emails an administrator, and the user who submitted it- to include the *administrators for the organic group which this instance of the entityform is attached to*.

As far as I can tell, when an entityform is submitted, it doesn't track which node it is connected to, it simply throws all the results for that type of form into a big pool, so I was struggling to try to create a rule that would get all the users from that organic group.

My alternative solution was to simply use `hook_form_FORM_ID_alter`, and add an additional submit handler to the form, and then write the email script out from there, it was mostly a last resort but that's where I'm upto.

However, this is where I'm stuck, for whatever reason, it just does not respond to my submit callback.

```
function mymodule_form_review_entityform_edit_form_alter(&$form, &$form_state) {

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

}

```

I would so hope that I'm just being an idiot and getting the syntax or the code wrong to define my own submit handler, but when I `dpm` out the `$form`, it does acknowledge that there are 2 callbacks in the array. Is this a correct way to amend the callbacks for the form submit?

(Before anyone suggests Webform, I've already been down that route, and in terms of things this form needed to have, Webform couldn't do everything EntityForm can)

# Answer
I managed to figure out that this is how you have to put an additional callback into the entityform submit function, hopefully this will help someone out in the future

```
$form['actions']['submit']['#submit'] = array(
  'entityform_edit_form_submit',
  'mymodule_notifty_review',
);

```
> 4 votes

# Answer
I am currently using entityforms for my projects as well for an HR company.

Have you tried to create view from your entity form and then use relations and contextual filters in that view to relate content. Later on using rules you can send emails containing your views/content. This way you can sideline entityforms' mailing method.
> 1 votes

---
Tags: organic-groups, forms, entities
---


# Question
Title: Number Slider for exposed filter using Drupal 6
I need to expose the number fields in views with the **range slider**, for example : **Min- 421 and Max 780**.

I found this slider Field module, but it support only for Drupal 7. **any idea for Drupal 6 ?**

I don't want to use **Better Exposed Filter** module, because the plugins mentioned in the documentation are not there and hard to configure the options. Looking for any other alternate way.

# Answer
Better Exposed Filters has that functionality built in

> ...
>
> **What else can I do with BEF?**
>
> * Use the jQuery Slider widget for greater-than, less-than or in-between types of filters

I've never used it for D6 but the project page doesn't mention the slider being missing from that version or anything so it should be there.
> 0 votes

---
Tags: 6, views
---


title: A simple field to hold date value

text:
# Question
Title: A simple field to hold date value
For a content type, I need a field holding the value of a certain date in history. The content type will be used to hold some historic events and when the current date matches (September 17th, for example) the node will be displayed.

I know that the date module can handle such things but it is quite comprehensive and I will not be using calendars or event content types. All I need is to hold a date value and compare its day and month part with the current date's.

Is there a simple solution?

# Answer
The Date module will store date time in this format: "2012-05-25 hh:mm:ss" . Using PHP's date\_parse function you can extract all those values. What easier thing do you need?
> 1 votes

# Answer
I think another solution is to create a long text type field and change Text processing to Filtered text (user selects text format) and give Default value (write your logic in PHP (include tags)). And save it. Then edit it one more time and change Text format to PHP code.
> -1 votes

---
Tags: 7, datetime
---


# Question
Title: Drupal Commerce: discount for line items based on user's values?
I need to have different discount rates for every customer.

I added a textfield in the user profile, where I store a Json object with all the discounts (there is a little GUI to manipulate it), so, for example, I can have this situation:

```
{
    'product_B': 20,
    'product_A': 15,
    'product_C': 0
}

```

This means that this customer will have a fixed discount for all `commerce_products` of type A, 15 on type B and 0 on type C.

I got stuck in the `Rules` configuration: I created a rule for the `Subtract an amount from the unit price` event; In the condition, i just check that the user and the line item match few pre-requisites, and it works, but I cant get the `line_item` details in the `action`:

```
// My action
global $user;
$ul = user_load($user->uid);
if(isset($ul->field_discounts))
{
  $user_discounts = field_get_items('user', $ul, 'field_discounts');
  /*
   * Here i have to get few info of the current commerce_product/commerce_line_item
   * in order to calculate the correct $item_discount
   * */
  $discount = ((int)$item_discount * $value) / 100;
  return $discount;
}
return 0;

```

So the question is: inside that PHP block, how to get the current line item?

# Answer
> 2 votes
I don't think the line item will be exposed to the PHP block, and I doubt there'll be anything in scope to get a reference back to it.

You might need to create your own Rules action. It's pretty simple, and you can copy most of what you need from `commerce_line_item_unit_price_subtract()`, which does have access to the line item entity.

`hook_rules_action_info()` would be a good place to start.

# Answer
> 2 votes
HT: Clive for making the initial suggestion. If I were you, I would make an action that "provides" the amount to subtract in a Rules variable and then enter that as a parameter in the "Subtract an amount from the unit price" so you don't have to duplicate the logic that handles price components in your custom code.

Also, I wouldn't use the global $user, because an administrator may cause this order to be refreshed and it would be priced according to that administrator's discount field value. Instead you should be able to traverse from the line item to the order to the order owner. You should always use the order owner when constructing pricing logic, not the current (or global) user.

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


# Question
Title: How to add class in title div for specific block?
I have created a block using Views module in website using drupal 7. My block title's HTML structure is as bellow:

```
<div class="titleHeader clearfix">
   <h3>BLOCK_TITLE</h3>
</div>

```

I want to add a class in `<div>`. Should I create a module for this or any other way? Please guide me how can I do this?

Thank you in advance

# Answer
function themename\_preprocess\_block(&$variables) {

```
if($variables['block']->bid == 'views-front-block') {

     $variables['classes_array'][] = 'container';
 }

```

}

add this function in your template.php file of your theme.
> 1 votes

# Answer
I think the Block Class module will allow you to add classes in blocks. Here is a quote about it (from the module's project page):

> ... allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent `<div class="block ...">` element of a block. Hooray for more powerful block theming!
> 0 votes

# Answer
Your view -\> Edit -\> Expand Advanced Fieldset -\> Theme: Information. Copy the template suggestion from Style output (Display output? I can't really remember) container and create that file (Do not forget to clean the cache). Then copy the default code and modify it. For ex.:

```
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <div class="myClass"><h3><span><?php print $title; ?></span></h3></div>
  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

```
> 0 votes

---
Tags: views, blocks
---


# Question
Title: Node create progrmatically with multiselect
I am creating a node progrmatically.

here is my code..

```
     $node = new stdClass();
      $node->type=$type;
      $node->status = 1;
      $node->uid = $uid;

        foreach($_POST as $field_name=>$field_value) {
          $node->$field_name=array('und'=>array(0=>array('value'=>$field_value)));

        }
node_save($node);

```

this is working fine. if we have a single value for each field.. Now i have a filed having select box with multiple select. How to save them.

Thanks

# Answer
> 1 votes
You just need to keep adding new values underneath the language array, for example:

```
foreach ($_POST as $field_name => $field_value) {
  $node->{$field_name}[LANGUAGE_NONE][]['value'] = $field_value;
}

```

---
Tags: 7
---


# Question
Title: Why field tables are not getting removed when I remove the field?
I have a content type with 20 different fields.

Now the project requirement changed and I dont need 15 fields of them. So I removed all those unwanted 15fields from content type.

But the database is still holding all the 15 tables and also the revision table, Why? What happens if I remove it?

I feel like having these many unused tables in database might impact the performance. Will it really have impact on the performance?

# Answer
> I feel like having these many unused tables in database might impact the performance

That's very unlikely, unless the extra disk space used will somehow affect your server's performance.

Deleted fields and data are cleared up on cron runs (by `field_purge_batch()`), so running cron a few times will probably get rid of them. Exactly how many runs it takes will depend on the number of fields, amount of data in each, etc.

I'd advise against removing it manually unless you're quite familiar with the internals of the field API, and understand the implications.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: PHP error 500 when including a left join on a pager query in db_select()
I've got a query which is causing a PHP error 500 whenever I add a left join:

> PHP Fatal error: Call to a member function orderBy() on a non-object

Here's the query:

```
$query = db_select('my_table', 'mt')
         ->extend('PagerDefault')
         ->fields('mt')
         ->fields('u', array('name')
         ->leftJoin('users', 'u', 'u.uid = mt.user_id')
         ->orderBy('mt.my_table_id', 'DESC')
         ->limit($results_per_page);

$result = $query->execute();

```

The query is to be used with a table + pager. If I remove the `jeftJoin()` and respective `fields()` the query works perfectly. Can anyone shed some light as to why this might be happening?

Many thanks

# Answer
> 5 votes
The documentation says:

> Joins cannot be chained, so they have to be called separately (see Chaining). If you are chaining multiple functions together do it like this:
>
> ```
> $query = db_select('node', 'n');
> $query->join('field_data_body', 'b', 'n.nid = b.entity_id');
> $query
>   ->fields('n', array('nid', 'title'))
>   ->condition('n.type', 'page')
>   ->condition('n.status', '1')
>   ->orderBy('n.created', 'DESC')
>   ->addTag('node_access');
>
> ```

---
Tags: database, wsod
---


# Question
Title: Linked entity references in a content type
I am unsure if this is possible in Drupal 7, but here is my problem: I have 3 content types, A, B and C.

B and C refer to A through a field field\_A (entity reference).

C refer to B through a field field\_B.

When creating/editing B, I want the user to select one node A1 of type A, and then, select some node of type B that refer to the node A1.

For example, let's say I have these nodes:

```
- A1, A2
- B11, B12 referring to A1; B21, ..., B24 referring to A2

```

A user creates new content of type C, and selects A2: I want the user to be able to select items of type B among the list B21, ..., B24.

I started to use an entity reference view to populate the list of B in C, but then was stuck because it is not possible (or I could not manage to do it) to refer to a field of the edited content type.

Thanks for any help!

# Answer
> 0 votes
Actually, while looking at the hierarchical\_select module, I found a module which is (almost) working - the "Dynamic dependent fields" module.

It does not work yet with multiple values though.

# Answer
> 0 votes
When you create node reference you can choose a view to select the nodes which can be selected when creating the content. To be specific you can even pass views arguments:

---
Tags: views, nodes
---


title: Boost and system cache

text:
# Question
Title: Boost and system cache
I'm using the Drupal-7 system caching and i recently installed the Boost module to improve my site performence;
I'm wondering if there's no conflict between the two system caching because i didn't feel any increasing of my site rapidity .
Thank you very much

# Answer
> 2 votes
I use Boost for my company website, and have been pleased with the results.

Did you disable "Cache pages for anonymous users" in the performance settings? Did you add the extra settings required by boost in your .htaccess file? Are you only viewing the site as an anonymous user? Have you made sure the /\[drupal-base\]/cache is readable by Apache, and /\[drupal-base\]/cache/normal is readable and writable by Apache?

If yes to all the above, you likely have other issues slowing down your site, such as too little overall RAM (or too much RAM allocated in the allowed\_memory setting).

# Answer
> 1 votes
The Drupal 7 version of Boost will not function properly while Drupal core cache is enabled. Go to the Performance page (/admin/config/development/performance) and make sure that "Cache pages for anonymous users" is NOT checked.

For a full recipe how to configure and test Boost for D7, along with conditional expiration and a crawler, see this article.

---
Tags: caching
---


# Question
Title: how to add my custom template of heatbeat
d7+heratbeat version = "7.x-1.1"

I have a module named "love.module" in love.module

```
/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'love' && $api == 'love') {
    return array('version' => 1);
  }
}

```

and I have a file name love.heartbeat.inc,

```
    <?php
/**
 * Implements hook_heartbeat_template_info().
 */
function love_heartbeat_template_info() {
  watchdog('-call', 'message', array(), WATCHDOG_NOTICE, 'link');
$heartbeatmessagetemplate = new HeartbeatMessageTemplate();
$heartbeatmessagetemplate->disabled = FALSE; /* Edit this to true to make a default heartbeatmessagetemplate disabled initially */
$heartbeatmessagetemplate->api_version = 1;
$heartbeatmessagetemplate->message_id = 'heartbeat_add_comment2';
$heartbeatmessagetemplate->description = 'user replied on some content';
$heartbeatmessagetemplate->message = '<span>!username replied on !title:</span><blockquote><div>!comment</div></blockquote>';
$heartbeatmessagetemplate->message_concat = '%username% replied on !title.';
$heartbeatmessagetemplate->perms = 2;
$heartbeatmessagetemplate->group_type = 'summary';
$heartbeatmessagetemplate->concat_args = array(
  'group_by' => 'node',
  'group_target' => 'username',
  'group_by_target' => 'title',
  'group_num_max' => '5',
  'merge_separator' => ', ',
  'merge_end_separator' => ' and ',
  'roles' => array(
    1 => 0,
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0,
  ),
);
$heartbeatmessagetemplate->variables = array(
  '!username' => '',
  '!title' => '',
  '!comment' => '',
);
$heartbeatmessagetemplate->attachments = array(
  'buttons' => array(
    'weight' => array(
      'activitycomments' => '-9',
      'flagattachment:like' => '0',
    ),
    'settings' => array(
      'activitycomments' => array(
        'activitycomments_node' => 0,
      ),
    ),
    'enabled' => array(
      'activitycomments' => 0,
      'flagattachment:like' => 0,
    ),
  ),
  'content' => array(
    'weight' => array(
      'activitycomments' => '-9',
      'flagattachment:like' => '0',
    ),
    'enabled' => array(
      'activitycomments' => 0,
      'flagattachment:like' => 0,
    ),
  ),
);

  return $heartbeatmessagetemplate;
}

```

but the hook didn't called.who can help me? did I miss somthing?

# Answer
> 0 votes
I had the same problem and what you should do is replace

```
/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'love' && $api == 'love') {
    return array('version' => 1);
  }
}

```

by

```
/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'heartbeat' && $api == 'heartbeat') {
    return array('version' => 1);
  }
}

```

and after a cache flush, it should appear in heartbeat templates

---
Tags: 7, heartbeat
---


title: translate strings from format_plural

text:
# Question
Title: translate strings from format_plural
How to translate the output of format\_plural which returns a new translatable string every time the count increased.

I put the translation with @count but it returns an array like @count\[NUMBER\] the NUMBER increased and for every NUMBER we have a string that need translation.

The translation work if I put @count\[NUMBER\] and didn't work for NUMBER-1 nor NUMBER+1

How to translate all strings with one translation?

The code comes from download\_count module

And here is the piece of code

```
if (isset($file->downloads) && $file->downloads > 0) {
$output .=     format_plural($file->downloads, 'Downloaded 1 time',     'Downloaded @count times');

```

}

Finally I need to translate plural strings form the translation interface drupal provides and fix the raised number of strings

I have .po files and had changed the plural-forms as that comment then import the file but nothing changed so I need help to fix it.

Thanks in advance

# Answer
Thanks all

I found the solution as that comment form-plural in po

Edited on of the po files after exporting the last state to keep translation.

Import the file using drush (uploading from the interface always fail)

Installed drush\_lang module

Apply that patch langimp relative path in /home/$\_USER/.drush/drush\_language

Clear cache for drupal and drush (drush cache-clear drush)

use the commands that module provides and every thing will be fine
> 1 votes

---
Tags: i18n-l10n
---


title: Display view nodes in lightbox?

text:
# Question
Title: Display view nodes in lightbox?
What would be the best way to show the nodes from a view in a lightbox, triggered by a single image? The idea would be that a nice photo is shown on a frontpage. When users click on it, a view is opened in a lightbox/thickbox/colorbox/\*box. This then shows all nodes in the view.

I currently manage to do this for only images with colorbox, but that's not sufficient as I would like to show captions etc. I would like to use the full colorbox functionality, rather than just the image. I tried using an iframe, however this meant every node is shown with the full site theme (header, logo, footer etc) which is not what I want to do.

# Answer
> 6 votes
I managed in my project by using a custom page template and and an additional get parameter.

Template.php: (In active theme directory)

```
function phptemplate_preprocess_page(&$vars){
    if( isset($_GET['ajax']) && $_GET['ajax']=='true' ){
        $vars['template_files'][] = 'page-overajax'; # For Drupal 6
        $vars['theme_hook_suggestions'][] = 'page-overajax'; # For Drupal 7
    }
}

```

I then created a template file (page-overajax.tpl.php) in theme directory with following content:

```
<div id="overlay-content-wrapper">
   <?php print $content; ?>
</div>

```

After this (Clear all caches) you can use any path (page, view, node) with `?ajax=true` to pass to your \*box to load if it supports for AJAX content.

As using with fancybox:

```
$("a.overajax").fancybox({
    'width': 400,
    'height': 400,
    ajax: {
        type     : "GET",
        cache    : false,
        url      : "user/user-posts?ajax=true",
        success: function(data) {
              $.fancybox(data);
        }
    }
});

```

# Answer
> 2 votes
You can use Colorbox Node module:

> Gives the user the ability to display ANY page inside a colorbox modal without the header and footer.
>
> Your link should look like this: href="blogs/my-example?width=600&height=600"

# Answer
> 0 votes
For D7, I had to follow stricter naming conventions than in Shuaib Nawaz's answer. My code looks like this:

```
function my_theme_preprocess_page(&$variables, $hook){
    if( isset($_GET['ajax']) && $_GET['ajax']=='true' ){
        $variables['theme_hook_suggestions'][] = 'page__ajax';
        // then use page--ajax.tpl.php for page template file.
    }
}

```

Perhaps OP can add this to the comments on accepted answer, my score is too low.

# Answer
> 0 votes
Have you tried the Colorbox node module ? I think that's exactly what you need ;)

---
Tags: 7, views, javascript
---


# Question
Title: EntityFieldQuery for retrieve only 1 field
I'm developing a new rules action that it is called by EntityForm when a Form is submitted.

In this action I want to retrieve 1 field from "noleggiatori" content type, so this is my function:

```
function zbl_rules_send_email_to_noleggiatori($entityForm) {

  $prov = $entityForm->field_provincia[LANGUAGE_NONE][0]['tid'];
  $reg = $entityForm->field_regione[LANGUAGE_NONE][0]['tid'];

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'noleggiatori')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_provincia', 'tid', $prov, '=')
        ->fieldCondition('field_regione', 'tid', $reg, '=')
        ->addMetaData('account', user_load(1)); // Run the query as user 1.

  $result = $query->execute();
  dd($result);

  $articles = $result['node'];
  $fields = field_info_instances('node', 'noleggiatori');
  $field_id = $fields['field_email_per_comunicazoini']['field_id'];
  field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
  dd("articles");
  dd($articles);

  /* Other lines .... */
}

```

But I have a problem: the code is correct (no error), but it does not work correctly because it set ALL content type's fields in `$articles`. I want only "field\_email\_per\_comunicazioni". Is this possible? How?

# Answer
The code looks correct. Note that according to the field\_attach\_load() documentation:

> The field ID that should be loaded, instead of loading all fields, for each entity. Note that returned entities may contain data for other fields, for example if they are read from a cache.

So having other fields than field\_email\_per\_comunicazioni does not mean the code does not work properly.
> 3 votes

---
Tags: 7, database
---


# Question
Title: How to create another html.tpl.php file for logged in users?
I'm using Drupal 7 and I want to create another (different) `html.tpl.php` file for logged in users only.

So, I need to check if user is logged in and set other `html.tpl.php` file if a user is logged.

Is this possible and how to do that?

# Answer
> 12 votes
Implement `hook_preprocess_html()` in your theme (or module, both are equally valid) like so:

```
function MYTHEME_preprocess_html(&$vars) {
  // Determine if the user is auth'd
  if (user_is_logged_in()) {
    // Add a theme hook suggestion.
    $vars['theme_hook_suggestions'][] = 'html__auth';
  }
}

```

Then add a html--auth.tpl.php file to your theme, clear the caches, and you should be good to go.

---
Tags: 7, theming
---


# Question
Title: Assign a submitted Node to a Single User of Role Editor
I am building a content publishing website. There are users with different roles editors, authors, content managers. There are many users with each role. Now what needs to be done is to assign a node to a specific user with a role as an editor or you can say to a specific editor.

I am using workflow module which puts the article to a review state once it is submitted. Now what it does is it allows all of the user with a role as an editors to edit and review the node. But I want that it should only be assigned to one editor and that should be done by the content manager.

I can not get my head around how should this be done. Are there any modules available or I would need to write something myself?

# Answer
I haven't test it, but the module's description seems to match your needs:

https://drupal.org/project/nodeaccess

Otherwise it can be done with a custom module: add a field "authorized editor" of type user reference to your content type, and then use the node\_access function to grant access to the update operation to the user who is currently trying to edit it.
> 0 votes

---
Tags: workflows
---


title: Revision: "per node" version ID

text:
# Question
Title: Revision: "per node" version ID
I have revisions active for a content type, called e.g. "procedures".

When a node of this type is revised, a new vid is assigned, which is a number independent of the number of revisions made on THAT node.

Given the nature of the node, I need to show/store in the node the revision number in a more meaningful way, for example version=1 for the original node, version=2 for the first revision and so on. \[edit\]: I need to store this information in the database, so that it can be queried whenever it's needed. Also, it needs not to change when a old revision is deleted.

How can obtain such result in a easy, clean way?

# Answer
You can add an integer field to your node, and set the default value to 0.

Then in a small module, use hook\_node\_presave to increment its value every time the node is saved (or if you detect a field change). Quick, easy and efficient way.

You can do the same with a computed field, by incremeting the value of the field by 1 when you submit the form, but storing code in the database isn't advised.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Give Role Permission to 1 Admin Configuration area?
Is there a simple way to give access to 1 panel of options within `Administration Configuration`? I made a custom module with settings under `/admin/config/mymodule` and it shows up as a block with links in the admin config area.

But I cant see how to easily say `Role X` can access that -- without giving global `access admin configuration` in Permissions, which lets them see everything there :(.

My example hook\_menu is:

```
function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );
  // Need at least one child item before your section will appear.
  $items['admin/config/eap-predeparture/list'] = array(
    'title' => 'Student Predeparture List',
    'description' => 'Upload, Revise or Rebuild the student perm list to administer access to the predeparture survey.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('predeparture_csv_admin_form'),
    'access arguments' => array('administer site configuration'),
    'weight' => 10,
  );
  $items['admin/config/eap-predeparture/incomplete'] = array(
    'title' => 'Not Yet Completed Orientation Report',
    'description' => 'These students have not completed the Predeparture survey based on those in the CSV file.',
    'page callback' => 'predeparture_incomplete_listing',
    'access arguments' => array('administer site configuration'),
    'weight' => 20,
  );
  return $items;
}

```

# Answer
Create your own permission in your module

```
function predeparture_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```

Then your menu item should have

```
'access arguments' => array('administer my module')

```

And check this permission for the role you want in the permissions page: admin/people/permissions
> 1 votes

# Answer
you can write your own "access callback" function returning TRUE just if the current user have the role you choose. Something like this:

```
function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access callback' => 'my_access_callback',
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );

function my_access_callback() {
  global $user;
  return in_array('the role', $user->roles);
}

```
> 1 votes

---
Tags: users, configuration
---


title: Path alias as arguments in views

text:
# Question
Title: Path alias as arguments in views
I would like to pass **path alias** as **arguments** to a views page. I tried the two methods one and two but unfortunately this doesn't works.

What I want to do is, example.com/box/portfolio link should show the example.com/box/45, 45 is node of portfolio. My views page path is box/% and I used the arguments as Node Id.

# Answer
> 1 votes
Looking into the Views Alias module, it does exactly what you need. Rather than making the change during the Views argument validation, this module will create a path alias to this View for every taxonomy term that can be an argument on the Views you select. Thus, example.com/box/45 can be accessed via example.com/box/portfolio, etc.

# Answer
> 1 votes
It sounds like you need to get the node ID (to pass as the "final" argument) from the URL given that the URL is box/% and the argument is a path alias (i assume this means that your node's has only one level (path-alias instead of path/alias)

You would need to use drupal\_lookup\_path instead of drupal\_get\_path\_alias since the argument is already an alias.

---
Tags: views, 6, path-aliases
---


# Question
Title: warning: number_format() expects parameter 1 to be double, string given in
I have migrated a site from one host to another and I now get the following warning:

> warning: `number_format()` expects parameter 1 to be double, string given in /var/www/vhosts/vinylletters.biz/httpdocs/modules/uc\_font\_attribute/uc\_font\_attribute.module on line 74.

Line 74 is the following.

```
$html .= '<div class="font-block-url-'.$key.'"><span class="font-url">'.$fontValue->fontValue.'</span><span class="preview-url">'.str_replace('.ttf','.png',$fontValue->fontValue).'</span><span class="extra-price">'.number_format($fontValue->price,2,'.','').'</span></div>';

```

I am not sure what I need to do to get this line working.

# Answer
> 1 votes
The `number_format()` function requires a *float* type variable for its first parameter.

Try casting the parameter like this:

```
$html .= '<div class="font-block-url-'.$key.'"><span class="font-url">'.$fontValue->fontValue.'</span><span class="preview-url">'.str_replace('.ttf','.png',$fontValue->fontValue).'</span><span class="extra-price">'.number_format((float)($fontValue->price),2,'.','').'</span></div>';

```

---
Tags: ubercart
---


title: Vallidate exposed filters in View

text:
# Question
Title: Vallidate exposed filters in View
I created a view with Search API.Could you please help how to validate exposed filter(Textbox) with in a view.

I tried using contextual filter it never worked.

# Answer
> 0 votes
I would alter the exposed form and add a validation handler.

If I remember correctly, the form ID is `views_exposed_form`. Just do a check on the view object (which I think is in the `$form_state` variable) to only add the handler to a certain view/view display.

---
Tags: views
---


# Question
Title: Download a backup of the files directory
I've researched this a little bit, but I'm wondering if anyone else has an idea on how to do this. The request is to be able to create a weekly archive of the files uploaded through a document content type, basically downloading all files. The client is a team of non-technical, financial advisors - so the simpler, the better.

Obviously Backup & Migrate doesn't fit the bill since that's database only. The only thing I can really think of is writing a bash script to gzip their document folder, and then have a continually updating URL based on a date that links to that zipped folder.

# Answer
There is actually Backup and Migrate Files too.
> 2 votes

# Answer
Weate using cdn, having the files folder, nor really in the server but linked to it from the server. You could use this idea to have the files in drop box or any similar service, and mounted in your server.

As it is Dropbox, it will be sync directly with any other folder, like your customerfor example.
> 1 votes

---
Tags: 7, files
---


# Question
Title: How do customize settings.php during installation profile
I'm creating an installation profile for my current company internal project.

During the installation process, one of the custom modules crashes during `init()`, since it tries to use one global variable defined on `settings.php` (that's current default behavior of the module)

Using `system_form_install_settings_form_alter()` I changed the settings form, by adding one input textfield for user's input, and on submit the value is appended to `settings.php`, but `settings.php` is rewrited before profile installation starts.

There is any way to prevent cleanup of `settings.php` by the installation process?

# Answer
You may find it easier to use a `settings.common.php`

Often during team projects, we have local `settings.php` with db credentials etc.. and a `settings.common.php` with settings common to the install and deployment environments.

You can add `settings.common.php` with an include / require line in `settings.php`

```
require 'settings.common.php'; // same directory, e.g sites/default/settings.common.php

```

and then write to it as needed during install.
> 3 votes

# Answer
My answer depends on the server using Apache, but I assume any of the other web servers can accomplish this too.

In your virtualhost config, you can set all of the variables for your environment:

```
SetEnv DBUSER datbase_user
SetEnv DBPASS database_pass
SetEnv DBNAME database_name
SetEnv DBHOST localhost

```

And in your settings.php file:

```
$databases = array (
   'default' =>
   array (
     'default' =>
     array (
       'database' => $_SERVER["DBNAME"],
       'username' => $_SERVER["DBUSER"],
       'password' => $_SERVER["DBPASS"],
       'host' => $_SERVER["DBHOST"],
       'port' => '',
       'driver' => 'mysql',
       'prefix' => '',
    ),
   ),
 );

```

You can set any other variables this way as well.

If you are worried about the $\_SERVER array getting into the wrong hands, you can unset all of the important variables at the bottom of settings.php:

```
unset($_SERVER["DBUSER"]);
unset($_SERVER["DBPASS"]);
unset($_SERVER["DBNAME"]);
unset($_SERVER["DBHOST"]);

```

This is how we do it at my office to move sites between our dev environments, staging and even production.
> 3 votes

---
Tags: distributions, configuration
---


title: Editing author of a node Drupal 6

text:
# Question
Title: Editing author of a node Drupal 6
After some painful searching, I think I've deduced a solution (to try) to fix my real problem. That solution involves changing the Author of a node.

The real problem is the Workflow tab showing on a few products for Anonymous users. I've been all through all the permissions, rules and workflows. What I found was that if an Authenticated user who created some content is deleted, that content is assigned to an Anonymous author.

So, I was trying to find the data in phpmyAdmin to edit one there as a test but I haven't found the information.

As the super user, I cannot edit the authorship of a node as I haven't found a tab/setting etc to do so.

Can anybody steer me in the right direction?

# Answer
The node author is usually editable in the 'Authoring Information' tab/section of the node-edit page. If that data isn't available for you (may have been removed by another module or other customization).

If you're comfortable editing the data in the database (via phpMyAdmin or another tool), have a look at the `node` table. You will see that each row contains a value in the `uid` column - this refers to the user id (uid) of the authoring user. User ids can be matched up to the corresponding users in the `users` table. Simply update the `uid` value in the `node` table for the appropriate nodes (likely ones with `uid = 0`) and you should be good to go.
> 0 votes

---
Tags: workflows
---


# Question
Title: manage multiple sites with a single login
My client wants urls site1.com and site2.com that share the same codebase for everything but the theme. They want different node content on each site.

They also want the ability to login to one location site1/user, and be able to update content from both sites there.

Is this possible with a multi-site install or Aegir?

If there are two different databases, it seems that you could not update content from both sites in one Drupal admin panel.

# Answer
> 3 votes
Sounds like you might be looking for the Domain Access module

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.

# Answer
> 0 votes
You can do the old sharing tables thing. It's simple and assuming your hosting everything on the same server it should work fine. Also assuming it's close to drupal in the way it handles SQL.

https://drupal.org/node/22267 \- describes the process fairly well

---
Tags: multi-sites, aegir
---


# Question
Title: Intermittent "Cron already running error"
I get the error every once in a while then Cron completes successfully, then the error crops up again some hours later, and after about 3-4 tries the system completes cron again without a problem, all of this without my intervention. I don't understand it! I've googled and found several posts about how to fix the error once it happens but nothing that I could find tells me how to prevent this error from happening in the first place and why it happens so randomly. I'm running the latest D7 with cron set to run every hour. Any insight would be highly appreciated!

> cron 09/17/2013 - 14:15 Cron run completed. Anonymous (not verified)
> cron 09/17/2013 - 14:15 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 14:15 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 14:15 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 13:14 Cron run completed. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Cron run completed. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Cron run completed. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 13:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Cron run completed. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:12 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 12:11 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 11:59 Attempting to re-run cron while it is already running. Anonymous (not verified)
> cron 09/17/2013 - 10:49 Cron run completed. Anonymous (not verified)

# Answer
> 2 votes
You have a long running, stalled or erroneous cron hook.

To determine where the error is, try the module

cron\_debug

or the temporary core patch listed here:

https://drupal.org/node/1143706

---
Tags: cron
---


# Question
Title: warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'search_form'
I am getting a warning when I use a new theme, I've got error that *search form not found*.

> warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'search\_form' not found or invalid function name in /......./...../includes/form.inc on line 377.
>
> Line 377 $form = call\_user\_func\_array(isset($callback) ? $callback : $form\_id, $args);

I have tried changing some items on line 377.

# Answer
You need to either

1. Enable the core search module or
2. remove the search form block from being rendered in your theme (perhaps in template.php or page.tpl.php)
> 2 votes

---
Tags: theming, debugging
---


title: Output xml feed data into view

text:
# Question
Title: Output xml feed data into view
I have an xml feed and i want to display it with a view. I have created a content type with the fields that are in the feed but how can i tell the view to get the data from this feed. I don't want to insert my feed data into the database. How can this be done programmatically? Maybe from the theme section in views? Maybe with some hooks like hook\_views\_data\_alter? Any help would be much appreciated.

Thanks

# Answer
> 2 votes
So i solved it. In **hook\_views\_pre\_render** i added something like:

```
if($view->name=='property_list'){
// ..got the xml , processed it
// and in the folowing array I added; of course field_address is an item in a content type
$view->result[$i]->field_field_address[0]['rendered']['#markup'] = $child->address;
// if i wanted the field to be a link, then altered this array item
$view->result[$i]->field_field_address[0]['rendered']['#path']['path'] = 'property-detail?id='.$child->ID;
}

```

The link pointed to another view where the detailed property was shown;

---
Tags: views
---


# Question
Title: Is it possible to dynamically set Views' pager settings?
Say for instance, you have a view that displays when viewing a certain node type, but you want the pager settings to be different for each individual node. I was thinking of making a CCK field like "pager setting" and then give it an integer option of x-y. But I don't know if it's possible to somehow dynamically plug that field into the Views' settings. Or is there another way to do this maybe?

# Answer
The views hook that you would want to use is `hook_views_pre_build` which is called before the query is built. Now this is assuming you have some basic module development experience and that you are familiar with the views api.

You should be able to do :

```
/*
 * Implementation of hook_views_pre_build().
 */
function hook_views_pre_build(&$view) {

  // Make sure this is only for the specific view you want to modified
  if ($view->name == "foo_bar") {

    // Get the x-y value from where you're storing it (in your example the node object).
    $pager_count = get_count_for_this_node();

    // Lets also make sure that this is a number so we won't destroy our view.
    if (is_numeric($pager_count)) {

      // Now lets set the pager item to what ever out count is.
      $view->pager['items_per_page'] = $pager_count;
    }
  }
}

```

Above we're using a views hook that's called before the view query is built that way the pager and everything else will reflect the change.

Word of caution: views hooks should only be used if you understand whats going on. The above code is written for views-2.x.

Hope this helps.
> 18 votes

# Answer
For Drupal 7, Only should write the following:

```
$view->items_per_page = $pager_count;

```

In the example:

```
/**
 * Implements hook_views_pre_build().
 */
function module_name_views_pre_build(&$view) {
  if ($view->name == "foo_bar" && $view->current_display == 'foo_display') {
    $pager_count = get_count_for_this_node();
    if (is_numeric($pager_count)) {
      $view->items_per_page = $pager_count;
    }
  }
}

```

I use code example by @ericduran.
> 2 votes

# Answer
You should to use views preprocess function

```
/*
 * Implementation of hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view){
  // $view->name
  // $view->current_display
  // ...
  // look for other variables in $view object
}

```
> 1 votes

# Answer
To update views result and pager in hook\_views\_pre\_render, you can do following:

```
<?php

/**
 * Implementation of hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
    // View result update logic.
    // e.g.
    // $result = array();
    // foreach ($view->result as $k => $row) {
    //   if (whatever is your condition) {
    //     $result[$k] = $row;
    //   }
    // }

    // Assuming $result has data as per your logic.
    // Update the pager according to result.
    $view->query->pager->total_items = count($result);
    $view->query->pager->update_page_info();
    // Add results to view.
    $view->result = $result;
  }
}

```

This should work!! ;)
> 1 votes

# Answer
@tanmayk 's code did the trick for me. In hook\_views\_pre\_render added just these 2 lines of code

```
$view->query->pager->total_items = $nr;
$view->query->pager->update_page_info();

```

But I didn't need to add the results to the view.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I sell points using a new product type?
With the Drupal commerce module, I created a new product type I use for selling points to my customers. The product has a custom field named “points” (field type integer) where I specify the amount of point to sell.

On checkout I want to grant the points to the user (with the Userpoint module). I want to do this with rules.

The problem is that I can’t retrieve the field “points” in action rules. I tried adding the “entity has field” condition, but I am not able to retrieve the field from the commerce order.

The action is *grants points to a user*.

>

How can I achieve this?

# Answer
To answer your question in order to give you a solution. That people can "top" up here is maybe an alternative.

Drupal Userpoint Feature request

> Remember to use dev version.

Commerce Userpoints

What about something like this ?

* 1) Rule

Event: on payment completed Action: loop through the order line-items. Each line-item has an action to call the next component with parameters of order and the line-item.

* 2) Component

Parameters: order, line-item Condition: data comparison line-item:type is Product (to expose line-item:commerce-product) Action: call next component with parameters of order and line-item:commerce-product

* 3) Component

Parameters: order, product Condition: data comparison product:type is Product (to expose the product:field-points-to-add)

* Action: add userpoints, number to add being product:field-points-to-add
> 2 votes

---
Tags: commerce, rules
---


# Question
Title: How to handle the 'Save and edit' form action?
I'm copying code from a module that does more or less what I want. However, the module I'm copying has a bug... The form we're trying to extend has both a 'Save' button and a 'Save and edit' button. The following code only seems to work when the 'Save' button is pressed, not when the 'Save and edit' button is pressed...

```
function x_form_apachesolr_environment_edit_form_alter(&$form, &$form_state, $form_id) {

  $environment = reset($form_state['build_info']['args']);
  $is_external = apachesolr_environment_variable_get($environment['env_id'], 'is_external', FALSE);

  $form['make_external'] = array(
    '#type' => 'checkbox',
    '#title' => t('Make this environment external'),
    '#default_value' => $is_external,
  );

  $form['actions']['save']['#submit'][] = 'x_environment_edit_submit';
}

function x_environment_edit_submit($form, &$form_state) {
  if ($form_state['values']['make_external']) {
    apachesolr_environment_variable_set($form_state['values']['env_id'], 'is_external', TRUE);
  }
  else {
    apachesolr_environment_variable_del($form_state['values']['env_id'], 'is_external');
  }
}

```

# Answer
The way I do it is to add extra parameters, like:

```
$form['actions']['save']['#machine_name'] = 'save';
$form['actions']['save_edit']['#machine_name'] = 'save_edit';

```

Button position in `$form` found here.

Then in submit handler I can use:

```
switch($form_state['triggering_element']['#machine_name']) {
  case 'save_edit':
    // some code
  case 'save':
  default:
    // come other code
}

```

Alternative method:

Note that both buttons have submit handlers attached directly to them:

```
$form['actions']['save'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save'),
);
$form['actions']['save_edit'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save and edit'),
);

```

So, in your own code you can append submit functions separately. Assuming you wish to keep original ones executed, in your form alter use something like:

```
$form['actions']['save']['#submit'][] = 'x_environment_edit_save_submit';
$form['actions']['save_edit']['#submit'][] = 'x_environment_edit_save_edit_submit';

```

and of course create these functions.
> 0 votes

# Answer
Ha, I found the answer by looking in apachesolr.admin.inc, where all the form actions are listed:

```
  $form['actions']['save'] = array(
    '#type' => 'submit',
    '#validate' => array('apachesolr_environment_edit_validate'),
    '#submit' => array('apachesolr_environment_edit_submit'),
    '#value' => t('Save'),
  );
  $form['actions']['save_edit'] = array(
    '#type' => 'submit',
    '#validate' => array('apachesolr_environment_edit_validate'),
    '#submit' => array('apachesolr_environment_edit_submit'),
    '#value' => t('Save and edit'),
  );
  $form['actions']['test'] = array(
    '#type' => 'submit',
    '#validate' => array('apachesolr_environment_edit_validate'),
    '#submit' => array('apachesolr_environment_edit_test_submit'),
    '#value' => t('Test connection'),
  );
  ...

```
> 0 votes

---
Tags: forms, search
---


title: Session cookie prevents pages to load

text:
# Question
Title: Session cookie prevents pages to load
There is a problem with Drupal 6 site. It seems seesion cookie is preventing some pages to load.

Site has approximately 5 to 10 pages (out of 30 000) of difference content types which can't be loaded. No errors returned — browser's wheel turning endlessly. After disabling cookies pages load just normally. After some testing I can say, that the problem in session cookie.

The problem doesn't exist in the development environment. I have made some testing on production (stopped Nginx and restarted Apache as single web-server) to make it similar to to development environment, but nothing changed. Now I have no idea how to debug the problem.

Thanks for any pointers.

\[Solution\]

The problem was in big sessions table (2GB). After truncating the table error has gone.

# Answer
On large sites with many users and many simultaneous connections keeping sessions in database will cause a problems. So there are some tricks that may help you:

* Don't keep unneeded sessions for anonymous users. To do this, choose one of the following, from what I advise most, to what's easiest:
* Move your sessions where they will do less damage:
* Flush sessions every midnight (or other hour with no visitors)
> 0 votes

---
Tags: cookies
---


# Question
Title: Changing the HTML produced by Panels: Is it possible?
I like to use panels, however panels is a pain in the butt to style because of the massive amount of div's it generates. Also the classes it applies to those divs make no sense and are way too bulky as well. Causing confusion among my fellow front-enders.

To show you the output they generate:

The problem is that i'm using 960.gs and panels adds their own classes and bulky div structure, making me have to override their classes. This is something i don't want to do, i want to clean up the divs. Is there any way to do this?

**Edit:**

What i did to clean up some div's that i considered useless:

Starting from line #388 in flexible.inc (panels/plugins/layouts/flexible)

```
$output = '';
//$output = "<div class=\"panel-flexible " . $renderer->base['canvas'] . " clearfix\" $renderer->id_str>\n";
    //  $output .= "<div class=\"panel-flexible-inside " . $renderer->base['canvas'] . "-inside\">\n";

      $output .= panels_flexible_render_items($renderer, $settings['items']['canvas']['children'], $renderer->base['canvas']);

      // Wrap the whole thing up nice and snug
      //$output .= "</div>\n</div>\n";

```

I actually made a copy of the flexible layout and edited that one, but if i had more time on this project, i would create a cleaner plugin for this.

**Note:** This isn't the best solution, this was the fastest possible route to accomplish my goal. Creating you're own small plugin is the best way to go, you can always use one of the existing plugins as a base.

# Answer
> 19 votes
I've looked into this issue before. Here's the issue you want to read. It seems nuts at first, but there are actually good reasons for it being like this.

Bottom line: think of Panels Flexible Layouts as **a prototyping tool**. Use it to try out and draft ideas in development, staging, user-testing etc, then when you've got the perfect layout signed off, implement it for production with clean, crisp, hand-optimised HTML as a *custom Panels layout* (more on those below).

Here's a quick summary of why it is the way it is, based on that issue I linked to:

* Panels' HTML output needs all that crazy markup to be able to accommodate the craziest flexible layouts anyone could want to create - think loads of nested fluid and fixed regions side by side.
* Nothing automatically generated will be good enough for HTML purists, so the Panels guys haven't tried to keep them happy *within the flexible layouts feature*. So there's no HTML optimiser algorithm that tries to pare down the HTML generated by your layout to the bare minimum, because no matter how good it was, it still wouldn't be best-standards HTML.
* Something they don't mention: if there was such an optimiser, certain changes to the layout would cause now-redundant divs and classes to disappear. If you hung CSS off these, you'd need to re-write your CSS most times you make a small change to a Panels flexible layout. This means that if they tried (and failed) to make Panels Flexible Layouts into a best-standards production tool, they would also have weakened it as a prototyping tool.
* You **can get clean, lean Panels HTML output**. The expected workflow, reading between the lines, is I believe something like this:
    + You use Panels Flexible Layouts during early development, while trying out ideas.
    + Once you have settled on a particular layout, if you want clean HTML, you implement it using a custom layout, using only the precise amount of HTML markup that layout needs with just the right classes, semantics etc for your site (how-to below).

While I didn't like it at first, on reflection I think it makes sense. Rather than trying to do the impossible and create one tool that is perfect for both prototyping and for best-standards in a production context - which both have very different needs and could only result in a comprimise that wasn't quite right for either - they've gone with one tool that is ideal for prototyping and another seperate tool (custom layouts) that is ideal for lean production.

This means you can get the best of both, at the cost of a little bit more work implimenting your final layout as a template based on best-standards HTML - but a HTML purist will want to do that little bit of extra work anyway to get their output perfect.

---

**How to create custom panels layouts?** There's a detailed guide in the documentation on how to do so. Here's a quick basic summary:

1. Copy an existing layout from `/sites/all/modules/panels/plugins/layouts` to become `/sites/all/themes/[your_theme_name]/layouts/[new_unique_layout_machine_name]`
2. Rename the files in the new copy to match their new folder name. Note that the `.tpl.php` file should have hyphens instead of underscores.
3. Add a line to the theme info file: `plugins[panels][layouts] = layouts` This tells Panels that you have custom layouts in this theme, and where they are (replace the string `layouts` if it's not the path from your theme to your custom layouts folder)
4. Edit the files with your perfect, sleek, minimal, semantic best-standards HTML and CSS.

* Don't forget to also update the `.inc` file with info about your layout like name, categories, filenames, etc.
    * `theme` in the .inc file should match the `.tpl.php` file's filename, without the extension. Any underscores you enter here in the `theme` value will be converted to hyphens.
    * Also consider editing the `.png` icon to better reflect your actual layout.
5. Clear the cache. Your new layout appears as an option in Panels with the name, category, etc you specified in the `.inc` file. Use it.

# Answer
> 5 votes
You might also consider the Clean Markup Drupal 7 module for controlling markup output for Panels.

I searched this page in the browser and did not find a mention of it already, including in the really good comprehensive answer given by user568458.

---
Tags: 7, theming, panels
---


# Question
Title: Using Static Variables in a Custom Module
I'm trying to define a static variable for use in my custom module. I want it to let me pass a number from function to function. I'm using `drupal_static()` but I can't get it to work. How do I do this?

This is the code I'm using to define my static variable.

```
$var = &drupal_static(__FUNCTION__);
if (!isset($var)) {
  // generate contents of static variable
  $var = '8';
}
return $var;

```

I've tried putting it in a custom module.

```
 function viewusercontact_locateuser($value, $key, &$counter) {
   global $user;

   /**********In here***********/

   if ($value['uid'] == $user->uid) {
      ........
   }
}

```

I can't seem to get it to work. What am I doing wrong?

(I got my code from the following guides)

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal\_static/7 http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 http://erikwebb.net/blog/drupal-design-patterns/static

# Answer
> 8 votes
`drupal_static()` stores variables based on the name of the function they're related to (hence the use of `__FUNCTION__` when you initialise it in the relevant function).

You can pick it up again in any other function by querying `drupal_static()` again, with the name of the originating function. So in your case:

```
function viewusercontact_foo() {
  $static_var = drupal_static('viewusercontact_locateuser');
  ...
}

```

# Answer
> 5 votes
Here's a write up of my final solution.

I solved this problem by avoiding it completely. But the solution to the problem posted is below (as solved by Clive). First you have to define a static variable in a separate function:

```
function myvariable_function() {
  $var = &drupal_static(__FUNCTION__);
      if (!isset($var)) {
        // generate contents of static variable
        $var = '8';
      }
    return $var;
}

```

Then in the first place you use the variable you need it you have to call the function.

```
$var = myvariable_function();

```

From then on you can call it from other functions, by referencing the function.

```
function my_other_function () {
  $dom =  &drupal_static('myvariable_function');
}

```

In order to change that value in another function you can set:

```
$dom = $something_else;

```

And then when you call it again with &drupal\_static, it will be updated:

```
$newvar = &drupal_static('myvariable_function');

```

# Answer
> 0 votes
You can't pass a static variable value from a function to another. The scope of a static variable is the function where it is declared. It keeps its value between all calls to same function in the same request.

---
Tags: 7
---


# Question
Title: which views template controls the field div sections
I have created a view which displays the fields of different node types. Therefore, visually, the user will see apple fields bunched together and orange fields bunched together, and the page makes sense.

However, for each view row, a div is created for EVERY field in the view, orange or apple. For particular reasons, I need to be able to get rid of the divs which don't apply to that row.

I would imagine doing something like:

```
if($row->_field_data['nid']['entity']->type == '[node-type]'):

```

but I can't figure out which template to do this in. I tried in views-view-unformatted.tpl.php and views-view.tpl.php, and in views-view-fields.tpl.php (which are the outer wrappers) but none seemed to do it.

I thought it would be in views-view-fields.tpl.php, but when I tried inserting this into the (overriding) template

```
drupal_set_message("wrapper-prefix:" . $field->wrapper_prefix . " wrapper-label:" . $field->label_html . " wrapper-content:" . $field->content . "  wrapper-suffix:" . $field->wrapper_suffix);

```

the only thing which came back with info was $field-\>content

# Answer
I figured out what I needed to do. It is from the UI - I just needed to set the No Results section to hide the section, and it worked perfectly.
> 0 votes

# Answer
You should be able to accomplish this through the UI from each field settings form:
> 2 votes

---
Tags: views, theming
---


# Question
Title: How to load the current entity object (Profile 2)
**Problem**

I'm trying to load the current entity object, in this case a profile2, profile page.

I've been using Is there a way to load the current entity object?, to try and solve this. Where am I going wrong?

**So Far**

I have the following code running in a custom form inside a block. The block appears on the profile page.

```
function mymodule_form() {
    $node = menu_get_object('profile2', 1);
    dpm($node);
}

```

The path of my page is: `localhost/drupal5/profile-main/154`

I have two kinds of profile 2, machine names `main` and `school`, however the following doesn't work either.

```
$node = menu_get_object('main', 1);

```

# Answer
> 1 votes
I couldn't get `menu_get_object` to work with profile2 so instead I used a combination of profile2\_load\_by\_user and arg suggested by Clive.

```
function mymodule_form() {
   //this arg gets the UID from the URL.
    $testarg = arg(1);

  //The UID is then put into a profile2 defined function which locates and opens the
  //correct profile.
    $currentprofile = profile2_load_by_user($testarg);
}

```

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


title: Make collapsible table rows

text:
# Question
Title: Make collapsible table rows
I'm looking to make a Drupal 7 table with collapsible rows. I'm really looking to do what was asked in https://stackoverflow.com/questions/801082/how-to-implement-collapsible-table-rows-in-javascript

I'm just trying to bend Drupal 7 into shape to do it. Do far, I have created a table which has the extra "section" rows, and I've assigned an HTML class and id to the rows that are to be collapsed. My problem is the Javascript and CSS required to do this.

My rows are created something like this:

```
foreach($results as $row) {
  ...
  if($row_needs_section_header) {
    $section_number++;
    $rows[] = array(
      'data' => array("Section $section_number"),
      'class' => (array('class' => 'collapsitablesection')),
      'id' => "collasitableheader$section_number",
    );
  }
  $rows[] = array(
    'data' => array(
       $column_1,
       $column_2,
       ...
    ),
    'id' => "collapsitable$section_number",
    'class' => array('class' => 'collasitable')),
  );
}

```

This seems to generate suitable HTML, with each of the rows that are to be collapsed being in an "id" with the section number in it, and also having a class of "collapsitable".

I'm now trying to replicate "misc/collapse.js", but instead of working with fieldsets, make it work with my special table rows. I'm at something of a loss with this. Has anyone got any ideas about where to go next?

# Answer
You can use the `nextUntil()` jQuery function like this:

```
(function ($) {
  Drupal.behaviors.collapsibleTable = {
    $('tr.collapsitablesection').toggle(
      function() {
        $(this).nextUntil('tr.collapsitablesection').hide();
      },
      function() {
        $(this).nextUntil('tr.collapsitablesection').show();
      }
    ).click();
  };
})(jQuery);

```

Put this in the script.js of your theme if it has one, if not add a new one, see the documentation: Using the theme's .info file (Drupal 6 & 7).
> 4 votes

# Answer
I revised tostinni's anwer so I don't need a 2nd collapsiblesection row to define the section.

Here I have a main row (class can-collapse-section) that stays in place while clicking it toggles visibility of the subrows below that row (class can-collapse-row).

I also added a font-awesome icon for both states to indicate the row can be expanded / is expanded.

```
(function($, Drupal) {
// Allows collapse of table rows with the can-collapse-row class
// Toggle is provided by the first row above with the can-collapse-section class
Drupal.behaviors.collapsibleTable = {
    attach: function(context, settings) {
        $('tr.can-collapse-section').toggle(
                function() {
                    $(this).nextUntil(':not(tr.can-collapse-row)').hide();
                    $(this).find("i").removeClass('icon-caret-down').addClass('icon-caret-right');
                },
                function() {
                    $(this).nextUntil(':not(tr.can-collapse-row)').show();
                    $(this).find("i").removeClass('icon-caret-right').addClass('icon-caret-down');
                }
        ).click();
    }
};

```

}(jQuery, Drupal));
> 0 votes

---
Tags: 7, javascript, theming
---


# Question
Title: Show 3 different Views displays for same exposed filter block or link Views displays?
So, I have a View which uses exposed filters which has the exposed form style set to block.

In my first view display, I have one page display which shows the content as teaser view for all results. The teaser of the content type is styled with a custom template (**node--my-custom-type.tpl.php**).

I then made 3 tabs using the "Quicktabs" module and put my view page as one of the tabs, and 2 generic PHP blocks as placeholders for the other 2 tabs.

I setup a Page in "Panels" (**Page Admin**) so that I can have the block above and the quicktabs content below. I might change the layout later on but for now it works fine.

My 3 tabs are therefore:

* List
    + This the View Page (Teaser view of the content type)
* Map
    + Currently a block placeholder but should be linked to the same View Page results
* Other
    + Currently a block placeholder but should be linked to the same View Page results

Now, I want to know how can I set the Map and Other tabs to be different View displays for my View that are linked to the same exposed form in my first views display?

Furthermore, the Map and Other tabs would need to just get the custom field: **field\_id** and append the values of all the results to an iFRAME - so I really just need to output PHP and nothing else, no fields or anything.

I suppose I could do this via another custom themed display for the content type... e.g. adding another teaser display type named custom-teaser?

However, how would I "link" all the results between the displays using the same exposed filter block?

# **UPDATE 17/2/13:**

So I tried the "**Attachment**" display, however that just added the **field\_id** to my "List" tab and I don't want the field to appear on that tab.

# **UPDATE 4/6/13:**

I haven't looked into fixing this issue for a while, but getting back to it now.

So I want the end result to be:

* A page with exposed filter and 3 tabs that show each different "view display"
    + Tab 1: Show results as Gallery (custom CSS styling)
    + Tab 2: Show results on a Map (**results have IDs**, would need to get the IDs and pass them to the Map as an array or string as a comma separated list)
    + Tab 3: Show results on another map using different fields

The results should all correspond to the same exposed filter and should be updated when you update the filter. I currently use Quick-Tabs but I can change to something else to make the tab effect.

# Answer
You can use only one exposed form of one of the displays. The other exposed forms should be set "as block", so they are not shown (as you will not set them active in the block configuration). As exposed forms work via GET-params, you simply can use the **same "Filter identifier"** for filters that shall share the **same value**.

An exposed filter in *display2* with identifier `type` will use the same value as the exposed filter in *display1* with the same identifier `type`.

This way you can control all three displays by only using one exposed form.
> 2 votes

# Answer
I think the best options for you is to load the first view in a normal way with the exposed filter, and load your other views programmatically with the correct arguments that you can get from the url.

Get parameter from URL:

`$count = $_GET['count']`

Print view with args :

`print views_embed_view('search', 'page_1', array(23,44,100));`
> 0 votes

---
Tags: 7, views
---


# Question
Title: Views to display different text than field
I have added a field in Article content type,

1. field\_url : contains external URL

I made a view to display the items in table format, Now my problem is to display as small text as possible in table.

I want to display Yes or No for `field_url`. If somebody have filled the field while adding content then instead of displaying whole URL I want to display only **Yes** with a link, if the field was empty I want to display **No**.

# Answer
> 3 votes
Bala's answer is also working... After playing with views for few hours I found another way of implementing **Yes** or **No** in URL with link.

At first I installed link module and changed the `field_url` type from text to Link type.

In Views, I clicked on the URL field, went to **No Result Behaviour** tab and put the text **No** in *No Result Text*.

I opened the **Rewerite Results** tab, **checked** on the *Rewrite the Output of this field* and in the Text, I entered **Yes**

I also **check** on *Output this field as Link*. In the *Link Path* I used the Token `[field_url-url]`. This also gives my desired result of **Yes** with Link and **No** if empty.

# Answer
> 3 votes
**"To display Yes or No for field\_url"** \- I done something similar to this but with Drupal 6 and Views Custom Field.

So for Drupal 7, I think you need to use Views PHP and add Custom Field:PHP field in your view and make conditions.

```
<?php

$static = $this->view->display_handler->get_handlers('field');

$x=$static['tid_1']->last_render;
$y=$static['tid_2']->last_render;

if($x !== null)
{
echo "<a href='#Your link'>"."Yes"."</a>";
}
else
{
echo "NO";
}

?>

```

note: tid\_1, tid\_2 are field tokens, instead change it with your fields token.

# Answer
> 0 votes
you can use display suit module and write some tpl file for your content type in a specific view mode you choose for your view and suggest it to drupal. EDITED : first create view mode,then render your view as a display suit with a view mode you created , and then in for example node--article--\[your view\_mode machine name\].tpl.php write the condition you want based on a field data ! I don't know if I'm clear enough,but do a little research then you understand how it is related

---
Tags: 7, views, uri
---


title: Allow two html tags in node titles

text:
# Question
Title: Allow two html tags in node titles
How I can allow two html tags `<sup>` and `<sub>` in node title of all content types.

Or may be is there some module for BB tags which allow using BB-codes in title?

Or my ba is there some hook for preprocess all titles?

# Answer
```
function template_preprocess_node(&$variables)

```

makes available in your node.tpl the variable $title, so you can wrap this as you like in your node.tpl theme file.
> 1 votes

---
Tags: nodes
---


# Question
Title: page--front.tpl.php not showing up in Zen subtheme
I am developing a subtheme of a Zen-based subtheme. I have created a page--front.tpl.php template but it isn't being recognized. All I see is the page.tpl.php template being used for the front page.

I have cleared the cache multiple times, looked for any other page--front.tpl.php files in the subtheme I am basing mine off of (there are none). I have restarted apache to make sure nothing is being cached, so I am at a loss as to why this is not working. I am using Drupal 7 on a linux server.

Any ideas as to what may be causing this issue? I have googled similar problems but most had to do with clearing the cache (which I have already done).

Using Theme developer, it shows that page--front.tpl.php is not a canditate template to use. In fact it doesn't show any candidate templates that could be used while on the front page of the site.

Thanks.

# Answer
> 1 votes
Found out the problem was caused by the Context Layout module. Apparently this module overrides Drupal's normal template file search order. The solution was to either to disable the Context Layout module or include the templates (like page--front.tpl.php) in the layouts definition in the *themename*.info file. I went with the latter solution.

Here is an example of what should appear in the .info file:

```
; Layout: Landing
layouts[landing][name] = "Landing Page"
layouts[landing][description] = "A layout for landing pages."
layouts[landing][template] = "templates/page--front"
layouts[landing][regions][] = "search"
layouts[landing][regions][] = "highlighted"
layouts[landing][regions][] = "mega_menu"
layouts[landing][regions][] = "slider"
layouts[landing][regions][] = "sidebar_first"
layouts[landing][regions][] = "sidebar_second"
layouts[landing][regions][] = "footer"
layouts[landing][regions][] = "bottom"

```

Notice the layouts\[landing\]\[template\] line where we define where and what template file to use. This is key to getting this to work with Context Layouts.

---
Tags: 7, theming
---


# Question
Title: How to theming attachment views? I don't get nothing when I add elements to the tpl
I'm trying to theming the attachment glossary view

I have create the new tpl files for the elements I want to theming, but I don't get nothing.

I have clear cache several times, and also clean apc.

Any idea how to theming attachements?

Oskar

# Answer
> 0 votes
you can use display suit module and write some tpl file for your element you want to theme in a specific view mode you choose for your view and suggest it to drupal.

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


# Question
Title: How to add a menu tab to a user profile?
I want to create an additional tab (dashboard) on my site's user profile page. There is a Homebox module installed and a dashboard was created for users. The dashboard is accessible by user/dashboard. How can I do this? I tried doing it as below:

1. New module created with name add\_menu\_tab
2. In add\_menu\_tab.module file I wrote as below I want to create an additional tab (dashboard) on my site's user profile page. There is a homebox module installed and a dashboard was created for users. The dashboard is accessible by user/dashboard. How can I do this? I tried doing it as below:
3. New module created with name add\_menu\_tab
4. In add\_menu\_tab.module file I wrote as below:

code :

```
function add_menu_tab_menu() {
     $items['user/dashboard'] = array(
    'title' => 'Dashboard',
      'type' => MENU_LOCAL_TASK,
      'weight' => 7
    );
    return $items;
  }

```

The menu is still not visible in user profile What should I do?

# Answer
You should implement hook\_menu\_alter() instead of hook\_menu.

```
function add_menu_tab_menu_alter(&$items) {
  $items['user/dashboard']['type'] = MENU_LOCAL_TASK;
}

```

Then you should clear the cache, at least the menu cache, as Mołot suggested.

There is also another approach using hook\_menu\_local\_tasks\_alter(). But the first method is better since it is called only once, after the hook\_menu and saved in the database, while the latter is being called each time the local tasks are rendered.
> 2 votes

# Answer
As you said dashboard is created and accessible in `user/dashboard` ,all you need to do is in your custom module altering menu by `hook_menu_alter` (menu alter API) and changing the menu type to `MENU_LOCAL_TASk` .

```
function yourmodule_menu_alter(&$items){
  $items['user/dashboard']['type'] = MENU_LOCAL_TASK;
}

```

**Remember to clear cache afterward ;)**
> 2 votes

---
Tags: 7, users, routes
---


# Question
Title: How do I change my blog title font size and serif typeface in views?
I have tried to changed the title formatting with CSS, without success. I may have done something incorrectly. I also downloaded an module that has the ability to format titles in views, but that also failed.

You can see the list of titles I would like to change here: http://www.thepoliticus.com/

# Answer
> 1 votes
You may need to add a class name to the view to make it easier to specify the view at admin/structure/views/view/\[view-name\]/edit -click-to- advanced click-to- CSS and create a name for the view, this will help to label the CSS.

Then:

1. If your theme has the option to change the font size and typeface, just change it in the theme. Adaptive theme can do this, https://drupal.org/project/adaptivetheme , for instance. If you only want one view to be different, this will not work.
2. Otherwise create a new subtheme and modify CSS as needed to change your view font-face and size. https://drupal.org/node/225125
3. An easier option: using the Sweaver module to interactively change CSS often without having to resort to editing any files, uses a GUI. https://drupal.org/project/sweaver . Be careful to only select that view.
4. Another easy option can use the CSS Injector, to create specific CSS to override existing CSS: https://drupal.org/project/css\_injector and again, select the specific view element for title.

---
Tags: views
---


# Question
Title: How do I access the array of label values?
I can access the value of fields in my template using `$view->style_plugin->rendered_fields`.

How do I access the array of label values in my template file?

```
$datas = $view->style_plugin->rendered_fields;
print_r($datas);

// Response
// Array ( [0] => Array ( [field_company_name] => Google [field_registered_address] => USA ) )

```

# Answer
> 2 votes
The field definitions are in a slightly different place, you can extract all labels with something like this:

```
$labels = array();
foreach ($view->display['NAME_OF_DISPLAY']->display_options['fields'] as $definition) {
  $labels[] = empty($definition['label']) ? 'No label' : $definition['label'];
}

```

---
Tags: views, theming
---


title: Setting commerce sales price with views

text:
# Question
Title: Setting commerce sales price with views
I am trying to set up a sale price on certain products on a drupal site, however from the project page of commerce\_saleprice there is this patch https://drupal.org/files/commerce-views\_precalculated\_price-1020050-5.patch that should be applied but am stack because i dont know to which module this has to be applied as i tried applying it to commerce\_saleprice and it fails.

My requirement is to put some products on sale and then call them in a view... any insight on this, i already have price savings formatters installed.

# Answer
> 0 votes
From the looks of the patch file it needs to be applied to commerce\_price -

cd to /sites/all/modules/commerce (or wherever you have the commerce module) and a command like this should do it:

```
patch -p1 < /path/to/file.patch

```

And then write down what you've done so you don't forget next time you update the commerce module ;)

---
Tags: commerce
---


# Question
Title: How can i insert a comment form between parent comment and comment replies？
i want hide the comment reply，when user click the “2 replies” button will slide the replies，after slide out the replies i also want to show a comment form that people can post a reply easily. anyone can help? Thank you so much.

# Answer
> 0 votes
I don't know if it's correct way but maybe help somebody.

`function theme_preprocess_node(&$variables, $hook) {`

```
$test_pid = array();
$test_cid = array();
$keys = array_keys($variables['elements']['comments']['comments']);

foreach ($keys as $k) {
    if (!is_numeric($k)) {
      continue;
    }
$pid = $variables['elements']['comments']['comments'][$k]['#comment']->pid;
$cid = $variables['elements']['comments']['comments'][$k]['#comment']->cid;
$test_pid[] += $pid;
$test_cid[] += $cid;
$variables['elements']['comments']['comments'][$pid]['#comment']->has_children = TRUE;
$last = $k;
}

// find all last children in comments
$Mcomment_children= array();
foreach($test_pid as $key=>$p){
    if (in_array($p, $test_cid)) {
         $Mcomment_children[$p] = $test_cid[$key];
    }
  }

  foreach($Mcomment_children as $last_children){
    $variables['elements']['comments']['comments'][$last_children]['#comment']->last_children = TRUE;
  }
  $variables['elements']['comments']['comments'][$last]['#comment']->last = TRUE;
}

In comment template file (comment.tpl) you can close div with children last. I used display suite but it's the same.

<?php if($comment->has_children !== true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>
  <?php if($comment->last_children === true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>

```

---
Tags: comments
---


title: How to use cron with views cache?

text:
# Question
Title: How to use cron with views cache?
I have a dashboard with about seven views that are each very expensive. Most of the views can be computed hourly, but I would prefer cron to run them rather than the unfortunate user. How can I have cron refresh the views cache and never a user?

# Answer
> 3 votes
Something like this should work:

1. Set the Views to cache data.
2. Implement `hook_cron()`, and delete the cached data from the `cache_views` and `cache_views_data` tables.
3. Programmatically request the URL which contains the expensive Views to rebuild them (this could be done via CURL, `file_get_contents()`, etc.)

# Answer
> 1 votes
I implement things like that as a drush script, which I think invoke from a crontab. Something like would be a start:

```
$cids = array(...); // the $cid list that you want to nuke

foreach ($cids as $cid) {
  cache_clear_all($cid, 'cache_views'); // may want to also do {cache_views_data}
}

$urls = array(...); // the URLs w/ the views that you just cleared

foreach ($urls as $url) {
  $url = url($url, array('absolute' => TRUE)); // if needed
  cache_clear_all($url, 'cache_page');
  $request = drupal_http_request($url);
}

```

I then call it as

```
0 * * * * /path/to/drush -u 1 scr /path/to/script.php

```

from my crontab.

Doing it from crontab instead of Drupal cron can help eliminate PHP timeouts.

---
Tags: views, caching, cron
---


# Question
Title: Pull data into a list for custom content type?
Hopefully this is a quick question! I'm working on a custom content type for users to create something similar to blog posts. We'll have different authors who will be credited, so I need a drop down list so when a user writes the post, they can select the author.

The trouble is, I need to list to be auto populated from the data that is stored in a different field. We have a content type called (you guessed it) authors. It allows us to fill out name, field of expertise, etc.

So, how can I add an AUTHOR NAME list to my BLOG custom content type?

Thanks! -JB

# Answer
You can use the Entity Reference module to create your 'author name' field, which will reference your `authors` content type.
> 2 votes

---
Tags: nodes
---


# Question
Title: Alter behavior of Next Page > button on a multipage webform page
In a multipage webform (the webform module), there is the Next Page \> button. It has 2 handlers,

```
webform_client_form_pages
webform_client_form_submit

```

How do I add another one? This is because I want to change the behavior of the Next Page \> button. It's behavior should depend on the value of a checkbox on the page. Or should I have to do it in another way?

Thanks,

Eric J.

# Answer
`webform_client_form_submit` handler should be enough to use. Depends what the *'behavior'* exactly is.
> 0 votes

---
Tags: webforms
---


# Question
Title: How can I pass proper querystring when Search from Drupal using my custom search box?
I have this search form in my drupal site.

```
<form id="mysearch" method="get" action="<?php echo $base_url.'/search/node/'; ?>">
   <input type="text" maxlength="150" id="search" name="s" class="input">
   <input type="submit" value="Search" class="button">
</form>

```

I have problem is that when I am submit the form it will pass the query like that

```
http://mysite.com/search/node/?s=xyz

```

Here I would like to change the URL something like this to search in my site.

```
http://mysite.com/search/node/xyz

```

Can anyone help me how can i achieve this thing.

I have put this code for URL Change:

```
$("#adminbarsearch").submit(function(e) {
    $url = $("#adminbarsearch").attr("action") + $( "input:first" ).val();
    e.preventDefault();
    window.location.href = $url;
});

```

Instead of this Can we change the URL by using the `.htaccess`

# Answer
If you use the default search block for Drupal, it will give you the functionality you need.

**EDIT**: Go to Structure \> Blocks and enable your Search Form Block by adding it to a region.

If you perform a search using your default search block, it will redirect to a path in the format /search/node/QUERY where QUERY is what you are searching for.

By default the search form outputs (for example):

```
<div class="block-wrapper">
    <div class="block-container">
        <div class="block">
            <div class="content">
                <form action="/" method="post" id="search-block-form" accept-charset="UTF-8">
                <div>
                    <div class="container-inline">
                        <h2 class="element-invisible">Search form</h2>
                            <div class="form-item form-type-textfield form-item-search-block-form">
                                <label class="element-invisible" for="edit-search-block-form--2">Search</label>
                                <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">
                            </div>
                            <div class="form-actions form-wrapper" id="edit-actions">
                                <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">
                            </div>
                            <input type="hidden" name="form_build_id" value="form-4gEUIDHcVH7lHHH3JpkfkVs9xBmPhHXdDQAMFMF9dHA">
                            <input type="hidden" name="form_token" value="afNo5gRQlaauXmqeZYDf80o5dEwKlg0VP6U-Ir8-p6k">
                            <input type="hidden" name="form_id" value="search_block_form">
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

```

Now if I search for "test", it redirects to /search/node/test
> 1 votes

---
Tags: javascript, uri, search
---


# Question
Title: Drupal 7 module hook_preprocess_page &$vars
In my module I have verified this function is being called, but when I try to edit `page--golfguide--alias.tpl.php` it doesn't have the variables available.

In module:

```
function dc_branding_preprocess_page(&$vars)
{
    $vars['branded_header'] = dc_branding_header_contents();
    $vars['branded_footer'] = dc_branding_footer_contents();
}

```

In template.php for theme:

```
function golfguide_preprocess_page(&$vars, $hook)
{
    global $user, $is_mobile;
    if (isset($vars['node']))
    {
      // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->type;

      // If the node id is "33" the template suggestion will be "page--33.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->nid;
    }
    //Create page suggestion for first part of url-alias
    $url_alias = drupal_get_path_alias($_GET['q']);
    $parts = explode('/', $url_alias);
    $parts[0] = str_replace('-', '', $parts[0]);
    $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__alias';

    if($is_mobile)
    {
        $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__mobile';
    }
}

```

In `page--golfguide--alias.tpl.php`

```
<?php print render($page['branded_footer']); ?>

```

NOTHING outputs and the key `branded_footer` does not exist.

# Answer
> 6 votes
You are trying to render `$page['branded_footer']`, but the module preprocess function is setting `$vars['branded_footer']`, which would be accessible as `$branded_footer` in the template file.

`$page['branded_footer']` would be set if the theme defines a branded\_footer region. In that case, you should follow what How do I create custom regions in a theme? says.

---
Tags: theming
---


title: Add Line Item to "My Order" block

text:
# Question
Title: Add Line Item to "My Order" block
I am using Drupal 7 Ubercart 3. Though I have added line item "Gift Wrapping" successfully using a module, I want to show it as well in the order "My Order" block so that the user immediately sees the fee in the order instead of seeing it on the review page. Please tell me is it possible to show line item in the cart along with other products?

# Answer
Take a look here. This may help you. `hook_line_item`

http://www.ubercart.org/docs/api/hook\_line\_item
> 1 votes

# Answer
```
<?php
function uc_order_line_item() {
  $items[] = array(
    'id' => 'generic',
    'title' => t('Empty Line'),
    'weight' => 2,
    'default' => FALSE,
    'stored' => TRUE,
    'add_list' => TRUE,
    'calculated' => TRUE,
    'callback' => 'uc_line_item_generic',
  );
  return
$items;
}
?>

```
> 0 votes

---
Tags: hooks, ubercart
---


# Question
Title: I want to add functionality into my site that users may be able to sign agreement, pay, and then submit
I want to add functionality into my site that users may be able to sign agreement, pay, and then submit. Also I would like to use this data in the future... Any advice?? EDIT: I want something like web form with payment option on it, I just want a user to be able to pay via Credit card, if the form is filled correctly and all required fields are good... Don't need HIGH-END commerce or online store ??? Please help :(

# Answer
> 0 votes
You can use the Webform module to allow the users to fill it out and then use the Payment for Webform module for payment options.

> This module provides a payment reference Webform component, which allows users to associate payments (made through Payment) with Webform submissions. A possible use case is requiring users to pay before submitting a webform.

***or*** you can do it with Commerce Webform module, by following this tutorial you can easily set up the payment options.

---
Tags: users
---


# Question
Title: how to add the "add content" to menu drupal
I want to add my "Add Content" --\> Products " into my menu bar for a menu link. How can I achieve this? Thanks. I want to add this for ease of access.

# Answer
> 2 votes
Navigate to '`Add Content`" page from admin menu & copy the path after `$base_url`.

Example - If it looks like "`http://example.com/node/add/product`" then copy "`node/add/product`".

Go to your menu and add one more menu item with the **Menu link title** of your choice & put this **node/add/product** in **Path** over there. All the user will have access to this menu item who ever have permission for adding content of this particular content type.

---
Tags: routes, nodes
---


title: Computed value on multipage Webform

text:
# Question
Title: Computed value on multipage Webform
I have multipage webform. I want to compute the value of the component (Hidden -type) which is on the second page based on the data submitted on the first page.

I'm using `hook_form_alter` and added my `client_submit` handler:

```
function mymodule_client_submit(&$form, &$form_state)

```

I can read there submitted data from the first page and I can do the calculation. But I cannot set the value of the component from the second page. I can see the structure of the form in `$form` or `$form_state` parameter. But I do not know how to set the value of the component from the second page as it was not submitted yet.

# Answer
I can suggest you a simple way to do this. You can pass the calculated value stored in a variable to the next `form` function.

Like I had two step form & at first step of the form user select some name from given name(checkboxes), I store them in array & pass them to the next form function like --

```
function MYMODULE_form($names)//Use your module name instead of MYMODULE.
{
  $return_form = drupal_get_form('MYMODULE_get_form', $names);
  return drupal_render($return_form);
}
function MYMODULE_get_form($form, &$form_state, $names)
{
  $form = array();
  $i = 0;
  foreach($names as $name)
  {
    $form['item']['name'.$i] = array(
      '#type' => 'markup',
      '#value' => $name,
    );
    $i++;
  }
}

```

Try something like this, if it solves your problem. Use simple variable if you don't have multiple values.
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: How can i add or set more email tokens in my drupal 6 site
I would like to add more `email token` variables in my `Drupal 6` site.I have found some of the variables like `!username, !temp, !site, !password, !uri, !uri_brief`.Is there any way by which i could add more `tokens` and `assign` these `token variables` in my `custom module`.Could I accomplish this by using some `contributed module` or `programatically`.Hope someone could help me with this.

# Answer
> 0 votes
i guess you want more tokens in the users settings page `admin/user/settings` (D6), according the format of your token (!username)

This page is a bit special because it is a core feature. cf User settings

Token module provides more tokens like \[my-token\] but this cannot be applied in the `admin/user/settings`

If you want more tokens on the users settings, i suggest to use a custom rule (fire on user's creation) with the rules module

---
Tags: 6
---