# Question
Title: What could happen if cache_form is stored in Memcache?
I have been tuning cache settings for a large site. I updated memcahed settings and set cache\_form to be stored in the Database, cache\_form started growing and the amount of transactions along with mysql bin logs, and replicator logs started to eat disk space enormously (I have a database about that is ~ 300GB ). Also, the cron is running fine. So I switched back to Memcache. I need to understand what happens when I have cache forms in a volatile cache?
Also, If this is not an ideal solution, what could I do?

# Answer
Memcache will drop cache content to make room for new cache objects.

That may be a problem if using a single memcache server instance for several cache bins.

`cache_form` needs to be more persistent to avoid losing form build validation data.

You could have a dedicated memcache server instance/port for `cache_form` and that would work ok, provided the service isn't restarted. However, in practice, servers need occasional reboot which could cause loss of user form data.

Usually `cache_form` is stored in the database as it provides the semi-persistent storage required there.

If `cache_form` isn't working properly, your users will experience "This form has been outdated" and other form validation errors.
> 8 votes

# Answer
Usually, you can store cache safely in Memcache.

If memcache has enough memory to work with, it should work much faster and it should be reliable enough for production sites (I have deployed memcache many times before).

Since form cache is always temporary and it is required for multistep forms, ajax forms, etc to work, it is possible that if any data gets corrupted in-between actions your users may experience loss of data on the forms they are filling.

I have never seen that happen, though.
> 0 votes

---
Tags: caching
---


title: Breadcrumbs aren't working at all

text:
# Question
Title: Breadcrumbs aren't working at all
I'm trying to get my breadcrumbs to display in a default site template with panels, but they aren't showing up when I go to view my pages, although everything else is. It also says that they are there in layout designer. I downloaded custom\_breadcrumb module in hopes that it might right something with panels, but no luck.

This is how I'm adding them to my panels; Add Content \> Page Elements \> Breadcrumb \> save & update

No other settings. It may also be worth mentioning that I'm using Bear and Aurora base theme.

What can I do to get these back up?

# Answer
This problem is related to using blockify, which is a requirement for Aurora. It is fixable with a patch.

There is a full explanation along with the patch here: https://drupal.org/node/2074249

If you're new to drupal like me and haven't installed a patch before here is a guide with links to a video that explains how to go about doing this: https://drupal.org/patch/apply
> 0 votes

---
Tags: panels, breadcrumbs, theming
---


# Question
Title: How can I dynamically refresh the price on product page when changing quantity based on price table
I'm currently building a web store with Drupal commerce and would like to get to price shown on a product page to asynchronously refresh when the user increases the amount in the quantity field, such as here.

How can I achieve this?

# Answer
Commerce Cart Ajax

> **Features**
>
> 1. The “remove” button on cart view removes the item from the cart immediately, without a page refresh. The row is removed from the table.
> 2. The “Qty” is updated when the "update" button is clicked. The totals are recalculated. No page refresh.
> 2 votes

# Answer
You can show the price in the add to cart form using this approach:

```
/**
* Implements hook_form_FORM_ID_alter
*/
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){
  // Add read only price field to add to cart form
  if (isset($form_state['default_product']->commerce_price)){
    $price = commerce_product_calculate_sell_price($form_state['default_product']);
    $form['display_price'] = array(
      '#title' => t('Price'),
      '#type' => 'item',
      '#markup' => commerce_currency_format($price['amount'], $price['currency_code']),
      '#prefix' => '<div class="display-price">',
      '#suffix' => '</div>',
    );
  }
}

```

It may need adjusting to include the quantity multiplier, but should provide a good starting point there.
> 1 votes

---
Tags: ajax, commerce
---


# Question
Title: Display one time message to user upon logging in
I'm looking for a module (or another way) of displaying a message to all users only once after they login. Basically, a client wants to add a newsletter on their site, and would like to give the change to all the users with accounts once they login to signup to the newsletter. They just want the message to appear once, the user can dismiss it, and then it will never display again. Ideally it would be possible to generate more messages at future dates for other reasons (changes to privacy policy, offers, etc).

I've looked at a few modules, including LoginToboggan, Rules, Flag, Absolute Messages and EU Cookie Compliance but none seem to do what I need.

Anyone know of a module or a method of implementing this with the above modules?

# Answer
You can try the Splashify module

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.
> 3 votes

# Answer
Do you have the Rules module installed?

You can try creating a rule with the following settings:

* Event: User has logged in
* Elements: User has role (set it to authenticated users)
* Actions: Show a message on the site (set your welcome message here)

Drupal will show your welcome message as a system message. There you go!
> 3 votes

---
Tags: 7, javascript
---


title: pass cck email value to webform block

text:
# Question
Title: pass cck email value to webform block
I currently have 2 webforms displayed on a page - these are inserted dynamically from a node.tpl.php file.

However, I also have a cck field on the current node for an email address - I would like to be able to pass this email value directly to the "Email To" field of the webform.

This would create a new email recipient depending on which node you were viewing. For example:

The "About Us" page contained the field "email: hello@mydomain.com" - therefore the webform loaded in the sidebar would be sent to this address.

The "Location" page contains the field "email: location@mydomain.com" - now this would be the email address that receives any submissions from that page.

The idea is to have 1 webform and dynamically change the email its sent to based on a cck field. Is this possible at all?

Thanks, Garry.

# Answer
> 0 votes
1. In your webform add an "email field" for the recipient (say `email_recipient`).
2. Go to `node/123/webform/emails` to set the recipient to be your previously created field.
3. Create a hook\_form\_alter to put the email address you your webform field.

```
<?php
function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  //you need to set up a CUSTOM module to store this.
  //use devel with dsm($form); to figure the name of each field
  if ($form['#id'] == 'webform-client-form-123') {
    //load the node from the url
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node_email = node_load(arg(1));
      //set your webform field to your email
      $form['submitted']['con_email_recipient']['#default_value']
           = $node_email->field_email_recipient[0]['value'];
    }
  }
}
?>

```

Add some CSS to hide the field, and it should work, code untested but I'm pretty confident about the steps, also have a look at Working with Default Values.

# Answer
> 0 votes
I know this is old, but in case anyone else comes up with this problem, the problem is this line:

```
if (arg(0) = 'node' && is_numeric(arg(1))) {

```

should be

```
    if (arg(0) == 'node' && is_numeric(arg(1))) {

```

---
Tags: nodes, entities, webforms
---


# Question
Title: Custom VBO action to print selected nodes
I would like to use views bulk operations to select and then print a large amount of nodes at once. I only want the print dialog box to open one time for the whole batch. Any ideas on how to approach this process?

# Answer
> 0 votes
In your hook\_action\_info() implementation, you should set `'aggregate'` to `TRUE`. For example:

```
function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_your_custom_print_action' => array(
      'type' => 'node',
      'label' => t('Print nodes'),
      'aggregate' => TRUE,
    ),
  );
}

```

---
Tags: views
---


title: Use rules on custom content fields

text:
# Question
Title: Use rules on custom content fields
I am trying to apply a rule to a certain content type with a taxonomy term selected from a list, this term is from a select list that selects the terms from a certain vocabulary that lists the terms from the vocabulary. I want the rule to only apply when international is selected......I have been at if now for four days, nothing doing. Tried a search but the results I found were not helping. I would really appreciate the help.

# Answer
> 1 votes
Your can probably add a rule of this kind :

The event is : `Before saving content` Restrict by type : `your content type`

Then add a condition : `Text comparaison` then select your field with the Data selection like this `node:field-example:0:name` and match the `International` value. The rules will fire if all theses conditions passes

---
Tags: taxonomy-terms, rules
---


# Question
Title: How to disable and enable all contributed modules in Mysql?
I am trying to perform core update to site that was installed from backup of another Drupal 6.16 website with content and modules. Guides suggest to disable all contributed modules during update and enable them after. (Can this be skipped?) I know that modules can be disabled by changing their "status" in system table. I was thinking that contributed modules has different path value so they might be filtered somehow. Is it a good idea to export status column of the system table, set their status to 0, and import after?

# Answer
> 6 votes
It is not necessary to disable all contrib modules during a minor update of Drupal. If you are planning on exporting and importing your database anyway, I would recommend using Drush to do the update on a local development copy of your site. That way, you can test the result of the update before moving it back to the live site. It is not advisable to update your live site directly.

You might also want to give serious consideration to finding a better hosting service. If you had ssh access, you could migrate your database from live to dev with drush sql-sync, which is a great time-saver.

**Edit:** If you *do* want to disable all of your modules via Drush, here is a shell alias that will do it (from examples/example.drushrc.php in Drush-5):

```
# $options['shell-aliases']['dis-all'] = '!drush -y dis $(drush pml --status=enabled --type=module --no-core --pipe)';

```

If you want to enable all of the contrib modules from the live site on the dev site, you could do something like this:

```
drush @dev -y en $(drush @live pml --status=enabled --type=module --no-core --pipe)

```

I don't recommend disabling modules by manipulating the SQL directly; it's much more reliable to use Drush.

# Answer
> 5 votes
I would suggest using Drush to do the update. Specifically, the `drush up` command. In general, Drush will be a huge time saver for you.

# Answer
> 1 votes
If you don't have drush installed on the server you can run this on the database:

`UPDATE system SET status=0 WHERE filename LIKE '%sites%'`

Remember that this will only disable the modules, it won't uninstall them.

---
Tags: 6, updating
---


# Question
Title: External URL Redirect Breaking Image Links
I was recently hired to manage an existing Drupal 7 site (built with an Omega subtheme) and am doing my best to ramp up quickly. Unfortunately, I do have some fires to put out immediately and could really use some help. The website has redirects coming in from another hosting provider/domain manager. For example, www.oldsite.com is being redirected to www.currentdrupalsite.com (currentdrupalsite.com being the site that I am managing) from a different host than the one that the current Drupal site is being hosted on. This redirect is breaking my image links, specifically the logo.

So, the img src path is `http://oldsite.com/sites/all/themes/themename/logo.png` instead of `http://currentdrupalsite.com/sites/all/themes/themename/logo.png`.

Can I fix this through the Drupal interface?

# Answer
A redirect from the old site to the new should not affect how the page is rendered on the new unless some absolute paths are hardcoded in the template files.

First check the value of `$base_url` in the settings.php. If that is correct (or just commented out) check the code of your theme's template files.
> 0 votes

---
Tags: 7, media, uri
---


# Question
Title: Views taxonomy terms page with two content types
This is the structure:

* menu1 - taxonomy/term1
* menu2 - taxonomy/term2
* menu3 - taxonomy/term3
* menu4 - taxonomy/term4

The custom content type is using taxonomy terms and with enabled Views Taxonomy term that comes with the module, every content is displaying very well in categories. I can see that uses path /taxonomy/term/%

I'm displaying the nodes as a grid style with specific fields.

Now I want to add a second content type that will use the same category from the first content type and will be displayed over the first content type nodes.

EDIT: I've tried to clone the view and change only one field, but it didn't work. The result is only the content from the fist view. I've used the same path like the default view taxonomy term, but I guess it's not possible to do like that.

EDIT2: So I can see that it's not possible to achieve with adding block and use the same url like the default view taxonomy term.

I've checked the taxonomy display module and I can see that I can associate only one view.

# Answer
Directly modifying the default "`taxonomy/term/%`" view is not a good option, you can clone the default view and can make the required changes to the cloned view.

The better solution for the above problem is the Taxonomy Display module. Taxonomy display lets you associate a vocabulary with a particular view. Now, when I click on particular term link, which is an alias for taxonomy/term/%, the view takes over and this is actually rendered correctly maintaining the integrity of the field structure.

The detailed documentation of taxonomy display module is available here.
> 1 votes

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


# Question
Title: search results page in custom layout using Display Suite
I'm pretty new in drupal. I'm using Drupal's core search module for search functionality in my website. Now. I need to customize search results display page to my website theme. For this I've googled and find that this can be done if you change tpl.php files, but I don't want to change any template files for this. I've also found that Display Suite is most appropriate for this so I go fot it.
I found display suite search page under `admin/structure/pages`. (Image 1)
I've edit this page layout and create variant as per my page layout requirement. search form and search results taken from widgets. (Image 2)

Now the problem is I cannot see search results in search results block. How can I display search results in that block. Or is there any other way to achieve this as per my theme layout. Any suggestions or tutorial links will be appreciate..

Thanks in advance...

# Answer
In configuration search setting I "Active search modules" set display suite search and set Default search module as "display suite".
> 1 votes

---
Tags: search, display-suite
---


title: Adding additional fields to panels

text:
# Question
Title: Adding additional fields to panels
I'm working with Page Manager and Panels. I'm adding content (panels) to each custom page layout, and every panel has a title by default. Is there any way to add additional information, common to every panel, like a subtitle?

In other words, is there a way to add fields to the Panel entity?

Thanks!

# Answer
> 1 votes
Yes. You can do that with Fieldable Panels Panes (FPP). Here is a quote about it (from the module's project page):

> ... creates an entity that may be used in panel panes to create fieldable entity panes. These panes can be created either directly in the Panels UI or in a separate administrative UI and later added.
>
> Once added, they can appear in the "Add content" dialog to be easily reused. Since they are fieldable entities, they can contain any kind of data that field API can provide.
>
> Each entity supports revisions, and any revision can be made current without having to make a new revision.
>
> Access control is provided by the CTools access method, for both view and edit access.
>
> Bundles are supported and can be added via the UI or hook\_entity\_info\_alter().
>
> A Trello board is being used to help coordinate development.

---
Tags: panels, chaos-tool-suite
---


title: Refer to value in field in body

text:
# Question
Title: Refer to value in field in body
UPDATE: Although the answers below were correct, I ended up resolving the issue by editing the stylesheet to refer to those specific locations.

---

If I create a custom field and set it to hidden, is there any way I can call the values from those specific fields in the body?

For example if a field called color in an article is set to red, is there any way I can make the background of a div red.

# Answer
Try what I suggested here: Getting a field's value from an entity

Replace `field_get_items('entityform', $entityform, 'field_myfieldname')`

with

`field_get_items('node', $node, 'field_myfieldname')`
> 1 votes

# Answer
Two methods I can think of. One is to use hook\_nodeapi and catch the events of getting saved or viewed. Change the body field accordingly. You can also use hook\_node\_view.

I assume you want to change the bg of body field. Second easier way is to a use Computed Field. Now add two computed fields named "pre" and "post". Set "pre" to before body and "post" after body in the content "Manage Display"( pl. see the attachment).

In the condtional field "pre" insert the PHP code to take out color field value and print something like: "print ".

In the "post" field close the div tag: "print ""

I suggest you go through any simple Drupal book to get you started with the basics or do a course at Lynda.com.

You can always come back here and ask any question in case you have any query or need help in coding etc.
> 1 votes

---
Tags: entities
---


# Question
Title: translation_node_get_translations() bug?
I have a multilingual site and I need to know which nodes are the translation of the current one; I use `translation_node_get_translations()`, but it seems it doesn't work.

I have 2 nodes (node/17 and node/670) where the latter is the translation of the former.

If I call `translation_node_get_translations(17)`, I get an array with 2 elements referring to the nodes with ID equal to 17 and 670; if I call `translation_node_get_translations(670)`, I get an empty array.

Is that a bug, or do I have to differently retry this information?

# Answer
I found the solution: Calling `translation_node_get_translations()`, I have to provide the **tnid** (the node ID of the original node) as parameter, not **nid**, as nodes are translated by the node ID of the original node.

```
function _azzurra_get_translations_nids($node){
  $nodes = translation_node_get_translations($node->tnid);

  $nids = array();
  foreach($nodes as $value){
    $nids[] = $value->nid;
  }

  return $nids;
}

```

I wrote this function who return a list of all nids related to the argument node \[included the nid of the argument node.. \]
> 5 votes

---
Tags: i18n-l10n
---


# Question
Title: How to remove "site email address on behalf of" and just keep the sender email address in "from:" part of a mail from drupal 7
I am getting from part of a mail sent from my drupal 7 website like below

From: (site mail address) **On Behalf Of** (sender mail address)

Here I want to remove everything except sender email address, how can I do this?

I have found following url but it is expired

http://www.fosspedia.com/drupal-remove-on-behalf-of-from-the-sent-mails/

Any help???

Thanks

# Answer
> 1 votes
Well you can write a simple module, and in your module insert this function. Here is where i got the idea

```
function yourmodule_mail_alter(&$message)
{
    $message['headers']['Sender'] = $message['headers']['From'];
}

```

If you want to go with quick sketch comment, in the link to completely get rid of the headers use

```
<?php
function mymodule_mail_alter(&$message) {
  unset($message['headers']['Sender']);
  unset($message['headers']['Errors-To']);
  unset($message['headers']['Return-Path']);
}
?>

```

There is also a module that can help out with this mail headers

> Control and modify any (almost any) mail header. Mail Headers allows you to:

---
Tags: emails
---


# Question
Title: Why node export:import link is not displayed?
I want to export drupal 7 nodes with node export. I have downloaded and enabled the node export module. The node export option has been added in the content tabs next to view,edit,translate. I exporte the nodes in a file however I cannot find the import link in order to import them! Is there something else to configure?

# Answer
Go to `node/add/node_export` (Content \> add content \> Node export: import) and paste the code or load from file.
> 3 votes

# Answer
Go to `node/add/node_export` and then select the Import tab, Paste the exported code and then select the **content type** you want to import from the list.

> For **advanced imports** if you are familiar with the Feeds module, enable Node export feeds module to use with the Feeds import interface http://drupal.org/project/feeds
> 1 votes

---
Tags: importing-exporting
---


# Question
Title: How to add a placeholder field to Entity Forms
I am trying to add a placeholder field, but I seem to only be able to add a text field above the form input,

Is it possible to add through the manage fields section in entity form ?

# Answer
You should use Field placeholder module.

> Field Placeholder module gives support to add HTML5 placeholder attribute to field widget forms.
>
> By default, this module integrates text, number and mail modules, but any other widget type can be added through hook\_field\_placeholder\_info().
>
> Field placeholder adds a new option in field settings page to enter the placeholder value, which is included automatically when the widget is rendered.
> 4 votes

---
Tags: forms, entities
---


title: view to show content with future date

text:
# Question
Title: view to show content with future date
I am creating a view which shows nodes of content type Movies. Movie content type has fields name, description,rating, and release date. Fields the view displays are name ,description and release date. What I want to display those nodes only that have release date set to some future value. I googled a lot but did not find anything. How to do it?

# Answer
Hopefully you actually used a date field for "release date". If so, just create a view and you normally would then in your filters add your release date field. Set it to a relative date text. Make it "greater or equal to" and insert " now" into the relative date.
> 7 votes

---
Tags: views, datetime
---


# Question
Title: Upload large file to azure storage and link it in Drupal
I have some large Files (\>3GB) to upload to a Drupal (running on azure). Because of the size of the files, I think i need to upload it to the azure storage (with Azure Storage Explorer) and then use the file in Drupal. This all works fine so far.

But: When I create the content page, I can't find a way to browse the azure storage instead of the local File system?

I use Windows Azure Integration. But this just gives me the possibility to upload a file to a azure storage blob. When I try this with a large File in the Drupal installation, it takes forever (ok, I didn't wait until the end). I am looking for the other way around: upload file to azure storage. Use this file in Drupal.

Does anyone have a solution? Or how would you solve the problem?

---

Using the proposed Remote File Source worked for me when I choose "File Attach". I have to upload the file to the web-server though and not to the azure storage. But doing this with filezilla does the job.

# Answer
> 1 votes
How about the Remote File Source module?

> Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.

I haven't tried it, but it looks stable with only a couple of bugs

---
Tags: 7, files
---


# Question
Title: Making new variable for a theme function shows an error notice
I am trying to make a new variable for a theme whose name is ntheme. I have defined the following function in template.php.

```
function ntheme_gnu_preprocess(&$variables) {
  $variables['disclaimer'] = t('Comments are unaythorized. The views expressed are those of the comment author.');
}

```

I used `$disclaimer` in the comment-wrapper.tpl.php template file.

```
<div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if ($content['comments'] && $node->type != 'forum'): ?>
    <?php print render($title_prefix); ?>
    <h2 class="title"><?php print t('Comments'); ?></h2>
    <?php print render($title_suffix); ?>
  <?php endif; ?>
  <?php print render($content['comments']); ?>
  <?php if ($content['comment_form']): ?>
    <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
    <?php print render($content['comment_form']); ?>
  <?php endif; ?>
  <p><?php print $disclaimer; ?></p>
</div>

```

I get the following warning.

> Notice: Undefined variable: disclaimer in include() (line 39 of C:\wamp\www\drupal\sites\all\themes\ntheme\templates\comment-wrapper.tpl.php).

What am I doing wrong?

# Answer
You should use `THEME_preprocess_comment_wrapper(&$variables)` to alter comment wrapper variables.
> 0 votes

# Answer
Each template file has its own preprocess/process functions. If `<theme>` is the theme identifier for the theme function, then `<module_name>_preprocess_<theme>()`, `<theme_name>_preprocess_<theme>()`, `<module_name>_process_<theme>()`, and `<theme_name>_process_<theme>()` are the function names for the preprocess/process functions.

In this case, `ntheme_gnu_preprocess()` would not be a preprocess function, since it doesn't follow the schema Drupal adoptes for preprocess/process functions: ntheme\_gnu is not the short name of the theme.

`ntheme_preprocess(&$variables, $hook)` would be invoked, but for every theme function / theme template used from Drupal; if you need to use the preprocess function just for the comment-wrapper.tpl.php template file, then you should use `ntheme_preprocess_comment_wrapper()`.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Context module not triggering Delta snapshot
I am using the Omega theme, and have the Delta and Context modules enabled. I created a Delta snapshot, and then created a Context to load that snapshot on the front page.

I created the context `Condition -> path -> <front>` and `Reaction -> Delta -> Select Custom theme settings template`. However, when I load the front page, the new snapshot doesn't load - it reverts back to the 'standard' Omega layout that I created.

I've tried deleting and recreating both context and snapshot, and clearing cache. I can't figure out what I'm missing.

Thanks for the help

# Answer
ok...so I'm dumb. I guess this is for anyone else who is going too fast, like I was - I created the delta module for another theme. I didn't realize that the delta snapshots are per theme, which makes sense.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to change drupal commerce status message?
I have created a custom cart and checkout. When product is added to cart, drupal displays a message "The product XYZ has been added to your cart" through rules which links to default cart. How can I change the message to link to my custom cart? Note: I checked the other questions but none is related to changing links to carts or DC etc.

Thanks in advance.

# Answer
> 2 votes
You need to find the rule called 'Display an Add to Cart message' and edit it.

You'll see there is a related action in there called 'Display a translatable Add to Cart message'. In mine, I've even added a **second** action that takes folks to my cart immediately after adding an item:

In any case, what I would do is delete that specific action and then Add a new action instead. From the '**System**' section, choose '**Show a message on the site**'.

Then, in the 'Value' field of that action, you can add whatever message you want and you can add html in it as well. So you can add something like:

```
Ready to <a href="/your_custom_cart_url">checkout</a>?

```

Let us know if this worked for you...

---
Tags: commerce
---


# Question
Title: How do I limit the maximum height of an image in signatures?
Is there a way to automatically set the maximum allowed height of images in the Signatures for Forums module for Drupal 6? This will greatly help to have a tidy forum.

# Answer
> 0 votes
Under Home \>\> Administration \>\> Site Configuration Go to **Signatures for Forums** Inside template for signature you can set the height inside the div as follows :

```
<div style= "height : 100px;">%s</div>

```

Home \>\> Administer \>\> User Management

Go to Picture Support option and enable it

After that you will find a field **Picture maximum dimensions:** where you can set your image maximum height and width check the image link

---
Tags: 6
---


title: Views Template Field Rendering

text:
# Question
Title: Views Template Field Rendering
I have a view which is a block on a page and I want to style the view. I tried using the rewrite output however I ran into a problem with it removing the `style=""` tag. So I had to resort to a .tpl.php to modify the display as I please.

Currently I am using

```
$d = $view->result;

    // Loop through it
    foreach($d as $r) {
        // Get values
        $position = $r->_field_data['nid']['entity']->field_position['und']['0']['value'];

        $name = $r->_field_data['nid']['entity']->title;

        $image = file_create_url($r->_field_data['nid']['entity']->field_picture['und']['0']['uri']);

        $path = drupal_lookup_path('alias',"node/".$r->nid);

        print "<div class='e'><a href='/".$path."' class='colorbox-load'><div class='tb' style='background-image:url(".$image.");'></div></a><strong>".$name."</strong><span>".$position."</span></div>";
    }

```

And as you see this is extremely ugly and I am dependent on 'und' not changing... which it does.

Is there another way to get the view field data besides having to go through the array and find it? I tried render() and that didn't work. I also tried using `entity_metadata_wrapper('node', $view);` and that didn't work (the fields where not attached to the array).

I can't figure out how to do it without the hacking code... Help!

# Answer
> -1 votes
There did not appear to be any way to do this easier, so I did it manually/hacky.

---
Tags: 7, views
---


# Question
Title: Prorgrammatically generated quicktab does not display content
I have programmatically created a quicktab but the contents of the tab do not display. I have followed the instructions and have looked at this related question but it does not work for me. I suspect I must be missing something simple. Here is the code for creating the quicktab:

```
function create_quicktabs() {

  $block_ids = array(
    'Books & Journals' => 'books_journals_search',
    'Articles' => 'articles_search',
    'Archives' => 'archives_search',
    'Databases' => 'databases_search',
    'Course Reserves' => 'course_reserves_search',
    'Institution Repository' => 'repository_search',
  );

  $tabs = array();
  foreach ($block_ids as $title => $block_delta) {
    $block = block_load('catalogue_search', $block_delta);
    $tabs[] = array(
      'title' => t($title),
      'type' => 'block',
      'bid' => $block->bid,
      'hide_title' => TRUE,
    );
  }

  // Configure the QuickTabs options
  $quicktabs_options = array(
    'style' => 'Bullets',
    'ajax' => FALSE,
    'sorted' => FALSE,
  );

  $quicktabs_name = 'catalogue_search';
  $quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
  return $quicktabs;
}

```

I get no errors when this is run, but it seems as though quicktabs can't find the block to display. I have verified that the blocks do exist and the block ids are valid. I have also tried using block\_delta for the bid value - again same result. This is for Drupal 7 by the way. What am I doing wrong?

# Answer
> 0 votes
I have found the solution to the problem through some experimentation. It appears that the value for bid must take the form of: module\_name\_delta\_block\_delta. To illustrate this, here is an example:

```
$tabs[] = array(
  'title' => t($title),
  'type' => 'block',
  'bid' => 'catalogue_search_delta_books_journals_search',
  'hide_title' => TRUE,
);

```

The module name is: catalogue\_search. Then you need the text: *delta* Finally the block delta name: books\_journals\_search.

I did not see this documented anywhere so hopefully this will help others with the same problem.

---
Tags: 7, blocks
---


# Question
Title: Dynamic site title based on role and/or content type
I need to dynamically change the Drupal site title to match the role the current use has, or as an alternative option I need to be able to change it based on the content type that is being viewed (on my installation, each role has it's own content). How can i do that? I'm using Drupal 6

# Answer
As much as I know the site name is being output with `$site_name` in a basic Drupal 6 page.tpl.php file and is also part of the `$head_title` variable. To change them dynamically you could use template\_preprocess\_page() in your template.php file. Assuming you want to change one or both of those variables based on the user role you could use the following example:

```
function mytheme_preprocess_page(&$variables) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    $head_title = explode(' | ', $variables['head_title']);
    $head_title[1] = 'Title for admin';
    $variables['head_title'] = implode(' | ', $head_title);
    $variables['site_name'] = 'Site name for admin';
  }
}

```

Both the head title and site name variables are modified for the 'administrator' role in this case. It should be relatively simple to make this work for all roles the way you want if writing some custom code is not an issue.
> 1 votes

# Answer
The Page Title Module along with Token Module might help you achieve that.
> 0 votes

# Answer
I wanted to do something similar but append text to the Site Name

```
function mytheme_preprocess_page(&$variables) {
  global $user;
  $sitename = variable_get('site_name', '');

  if (in_array('administrator', $user->roles)) {
    $variables['site_name'] = t('!sitename for Admins', array('!sitename' => $sitename));
  }
}

```
> 0 votes

---
Tags: views, 6, nodes
---


# Question
Title: Drupal 7 Commerce: How to change cart page title?
Have changed everything else for the cart in the settings file but the page title doesnt work. Page title is 'Shopping cart' so would expect it to be basket as its set below however this is changing the title of 'basket' link (which is good) but not the page title. Suggestions please?

```
$conf['locale_custom_strings_en'][''] = array(
  'Shopping cart' => 'Basket',
  'Shopping cart (@count items)' => 'Basket (@count items)',
  'Shopping cart (1 item)' => 'Basket (@count item)',
  'Your shopping cart has been updated.' => 'Your shopping basket has been updated.',
  'Your shopping cart is empty.' => 'Your shopping basket is empty.',
  '%title removed from your cart.' => '%title removed from your shopping basket.',
  '%title could not be added to your cart.' => '%title could not be added to your shopping basket.',
  'Add to cart' => 'Add to Basket',
  'Update cart' => 'Update Basket',
  'View cart' => 'View basket',
  'Shopping cart contents' => 'Shopping basket contents'
);

```

# Answer
> 5 votes
There are probably a dozen different places you could do this, personally I'd go for `hook_page_alter()` in a custom module:

```
function MYMODULE_page_alter(&$page) {
  // Make sure you're on the right page
  if ($_GET['q'] == 'cart') {
    drupal_set_title('New title');
  }
}

```

You would probably get away with doing the same thing in your theme's template.php file (maybe in `hook_preprocess_page()`) if you're not keen on writing a custom module just for this functionality.

The alternative to this is to install the String Overrides module. I've used this module in the past to override the title for exactly the same page (/cart) and it works great. It also means you can take your translation strings out of the settings.php file, which in my opinion isn't necessarily the best place to have them (even though it's absolutely a 'Drupal' way to solve the problem).

# Answer
> 3 votes
Another flavor using `hook_menu_alter`

```
function mymodule_menu_alter(&$items) {
    $items['cart']['title'] = 'Order Confirmation';
}

```

---
Tags: commerce
---


title: How to create an list in Drupal 7

text:
# Question
Title: How to create an list in Drupal 7
I am creating a form and I would like to create an unordered list of links. My problem is that I don't know how to go about this. I didn't see anything in the forms API about accomplishing this. What is the correct procedure to produce an unordered list?

Thanks.

# Answer
There's no single correct procedure to output HTML - as Ankit mentioned in his answer, one way is to add the raw HTML to the `#markup` property of an element in the form. Nothing wrong with that at all.

You could also use `theme_item_list()` which produces a simple HTML list with configurable attributes, and a bunch of default classes so you can target certain elements easily (see the docs for full details).

```
$items = array('First item', 'Second item', '...');
$form['some_element'] = array(
  '#theme' => 'item_list',
  '#items' => $items,
);

```

will output

```
<div class="item-list">
  <ul>
    <li class="first">First item</li>
    <li>Second item</li>
    <li class="last">...</li>
  </ul>
</div>

```

it will probably inherit some of Drupal's core or your custom styles because of "item-list" class on the wrapper. That may or may not be what you want, so for this case I guess what you use will likely depend on that styling.
> 3 votes

# Answer
You can use the `#markup` of the form api to create the unordered list of links, the documentation of #markup explains it well. Any valid html content can be added to the form using the #markup.
> 2 votes

---
Tags: 7, theming, forms
---


# Question
Title: Insert block content into the $content variable to be indexed by search
I have a block that is generated by a view. It brings in the author's name and other information for the specific node that is being viewed. The problem is that the **block data is not indexed by drupal since it is not in the "content" of the page**. How can I get around this? I tried moving the region to the node.tpl.php but that didn't help. Any suggestions would be great.

# Answer
> 1 votes
You can use Nodeblock or one of it's competitors:

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page.

Side effect of managing blocks' content like that is exactly what you want: they can be indexed in search, as they are, in fact, nodes.

If you have dynamically created blocks, you could try to use API provided by Bean module \- it works the other way around, exposes blocks as entities, instead of entities as blocks. And if it will not work, well, at least you could use it as an example code for entity \<-\> block mapping.

# Answer
> 1 votes
You can use the Search by page module but according to this post, the only way to do it is to move your blocks into your theme rather than use the GUI - not really a glamorous solution at all, more of a hack.

But, if you're interested:

```
$block = block_load('block', 'ID');
    print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

```

where ID is the if of the block you want to output.

---
Tags: 7, views, theming, nodes, search
---


# Question
Title: Add a field programmatically to a custom entity
I am defining a new entity following the steps related here: http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

My question is how I can add a field programmatically to the Entity when I define it. I have read some links but I can't get it work.

My code:

```
function generador_examenes_entity_info() {
  $return['question_section'] = array(
    'label' => 'Apartado',
    'controller class' => 'SectionController',
    'base table' => 'question_section',
    'uri callback' => 'section_uri',
    'fieldable' => TRUE,
    'entity_keys' => array(
      'id' => 'sid',
    ),
    'static cache' => TRUE,
    'bundles' => array(
      'question_section'=> array(
        'label' => 'Question Section',
        'admin' => array(
          'path' => 'admin/structure/question-section/manage',
          'access arguments' => array('administer'),
        ),
      ),
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full Content'),
        'custom settings' => FALSE,
      )
    ),
    'access callback' => 'section_access',
  );
  return $return;
}

```

Thanks

# Answer
You'll need to define a field and an field instance in your module's .install file. The function can either be in hook\_enable() or hook\_install(). The field will provide the name of the field and some default settings. The field instance can be seen as the link between the field and the entity you want to place the field on.

The format of the settings differs per field type (a text field has a maximum length, an entity reference field can define the selectable bundle(s), etc). Often the available settings are explained in the module's hook\_field\_info implementation. For core fields these can be found on the following page: 7 functions implement hook\_field\_info(). For non-core fields the settings are likely to be explained in the hook\_field\_info implementation as well, for example entityreference\_field\_info().

The process Drupal follows when registering a field is as follows:

The field is registered in the field api first, with it's default settings (the settings as defined in hook\_field\_info()). But your module can override them in the settings array of your field\_create\_field function. So that the field with your name will have by default your settings. Other values such as cardinality (how many values can the field hold) and translatability can be defined as well. See the detailed information on field\_create\_field() for all values.

From there the field is attached to the entity and it's bundle by means of a field instance. This instance defines which field should be attached to which entity and bundle. Here the settings can be overridden once more for this specific fields implementation on this specific entity. You can also select the widget here; the way the field is to be selected. Modules define their widgets in hook\_field\_widget\_info(), available widgets for core fields can be found here: 7 functions implement hook\_field\_widget\_info(). For a textfield you would use the widget `text_textfield`, for an image you can use `image_image`, for a non-core module you'll need to lookup the available widgets yourself in the hook\_field\_widget\_info() implementation. For a full lis tof all properties you can set on field instances, see field\_create\_instance().

Image field example

```
function mymodule_enable() {
  // Check if our field is not already created.
  if (!field_info_field('my_image')) {
    $field = array(
      'field_name' => 'my_image',
      'type' => 'image',
      'locked' => TRUE, // Settings can not be changed
      'settings' => array(
        'no_ui' => TRUE, // Field is not visible in field UI and can only be instantiated programmatically.
      ),
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'my_image',
      'entity_type' => 'my_entity',
      'bundle' => 'my_entity_bundle', // If your entity does not have bundles, this is the same as the entity type.
      'label' => 'Featured image',
      'required' => TRUE, // Field must have a value.
      'widget' => array(
        'type' => 'image_image',
      ),
    );
    field_create_instance($instance);
  }
}

```

Entity reference example

```
function mymodule_enable() {

  // Create an entityreference field.
  $field = array(
    'field_name' => 'my_entityreference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'my_other_entitytype',
    ),
    'cardinality' => 1, // Field may only have one value.
    'translatable' => FALSE,
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'my_entityreference',
    'entity_type' => 'my_entitytype',
    'bundle' => 'my_entitytype_bundle',
    'label' => 'Reference to my_other_entitytype',
    'required' => TRUE,
    'widget' => array(
      'type' => 'options_select',
    ),
  );
  field_create_instance($instance);
}

```
> 17 votes

---
Tags: 7, entities
---


# Question
Title: Allow the user to permit per role to view of any/all profile2 fields
I have a Drupal 7.0 social site with three roles, each with a profile they may or may not want other roles to see all/part of. I'm not sure how to allow the user to specify which fields can be viewed by each role, but this is my current idea:

* Create an on/off checkbox to signal view permission for each role per profile field
* Use the views module to present profile, filters allowed view of each profile field
* Similarly, when editing a profile, it will be presented with a view module so that corresponding role permission checkboxes can show next to it.

I imagine 'edit profile' could look similar to Drupal permissions (except under permissions would be the profile fields instead of module/feature list):

I'm clear on how to set up the view such that any given role can see each profile field that has been checked.

But is this possible to make it so when the user is setting up their profile, they see a view to add/edit profile2 with inline permission boxes instead of the default profile form that hasn't any such checkboxes?

Perhaps I would need customize adding in hook\_form\_alter or can this all be done in the UI?

# Answer
Instead you can try Profile2 Privacy module, It will do your requirement exactly.

> This module extends Profile 2 by allowing administrators to create ***privacy levels*** as predefined groups or sets of profile fields on a per role basis. Users can then select from among the privacy levels to apply access control to their profile.
>
> For each role, select the profile fields that are visible to users in that role, when the profile owner has selected this role. For example, if you created an “authenticated users only” privacy level, you might ***set the anonymous role to view first and last name fields***, the authenticated role to see first name, last name and contact fields and an admin role to see all fields.
> 0 votes

---
Tags: views, users
---


# Question
Title: How to create product bundle or similar to that?
I have a plan to create a e-commerece website for Computer Assembling. I have exp in Prestatshop and few other CMS (e-commerce) framework. In that i found Drupal 7 is having the best one like durpalecommerece. So I selected Drupal 7 as CMS framework. I download few modules ubercart and tried e-commerce module also.

But its not meeting my requirements. My requirement is

1. Homepage - User can see All default PC set (Monitor, CPU, Keyboard and Mouse) with price.
2. Select PC, Next page description will display.
3. Defualt Product piece is 1, but the user can increase more.
4. Based on the increase Rate will be changed.

Above steps are working fine. Below steps are not working.

1. Homepage - If user doesn't happy with default PC set, User can build there own PC
2. Select "Build own PC".
3. List of Monitor companies and inches will display.
4. User selects one monitor and click,
5. It will redirect to CPU Parts.
6. User will select Mother board, ram, hardisk ... one by one
7. On click "NEXT" redirect to shopping cart....

How to achive Product bundle here to get calculate amount in cart

# Answer
> 1 votes
For building a e-commerce website you should try the drupal commerce module or commerce\_kickstart (If you are novice with drupal then commerce\_kickstart is the option). **Drupal Commerce**

> Core Features
>
> Create product types with custom attributes
> Dynamic product displays
> Order management, line item
> Payment method API, allowing many different payment gateways
> Tax calculation / VAT support
> Discount pricing rules
> Deep integration with systems like D7's Fields, Views,Rules and Entity API.

**Commerce Kickstart**

> Commerce Kickstart is the quickest way to get up and running with Drupal Commerce. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. It also gives you a set of options to create a fully-featured demo store out of the box complete with an attractive theme, catalog and search configuration, and a custom back office interface. Who should use Commerce Kickstart? Anyone who wants to skip weeks of configuration to build a commerce site on the Drupal Commerce framework.

---
Tags: commerce
---


# Question
Title: Sending an email blast only goes to certain users
A little background on the problem: I have been tasked with figuring out a problem in a Drupal site that I have no experience with. I have done Web Development using PHP, etc. but never used Drupal. I have a parent site with 3 sites underneath, and roles for each user (can be members of all sites or just one). I have a rule that sends an email out to these users after certain content is submitted. However, not all of the users receive the emails (about 150-180 users per email blast).

Does anyone have suggestions as to how I can go about debugging and figuring out this problem? I have to fix this by tomorrow. Here is what I have done so far:

-Made sure users were assigned to the role in the email rule. -Unchecked the box "send only to active users"

Any help is appreciated!

# Answer
> 1 votes
Default PHP mailer has a lot of issues, and sometimes mails are not received or accepted by the servers as this a common method for sending spam.

A good practice is to use the SMTP module (https://drupal.org/project/smtp) for sending emails. You need to connect it to a server (eg. google) for authentification and then it replaces the default drupal php mailer.

---
Tags: rules, emails, users
---


# Question
Title: How to add data to Drupal.settings without drupal_add_js
Is there any way to add some variables to `Drupal.settings` without `drupal_add_js` (with `setting` argument).

I'm creating a site that has a custom ctools popup style but I'm not feeling good with `drupal_add_js`. How can I add this JavaScript snippet to the page using the theme's `.info` page ? I'm not sure how can I merge my custom variables (literally, they are just static) to Drupal.settings so ctools module can pick them up as it was added via regular `drupal_add_js` call.

Thank you in advance.

# Answer
Maybe I am missing a point to the question, but you should be able to do

```
scripts[] = path/to/your/script.js

```

in the .info file of your theme. And within the script file something like

```
(function ($) {
$(document).ready(function () {
    Drupal.settings.yoursetting = {};
    Drupal.settings.yoursetting.property = some_value;
});
})(jQuery);

```

or use the Drupal.behaviors convention.
> 1 votes

---
Tags: 7, javascript
---


title: Don't show message on View display page

text:
# Question
Title: Don't show message on View display page
I have some rules created and working fine. Some of them are made for messages, that are displaying after certain period of time. And that's alright, works. But, it also displays the message when browsing the page created in Views, that is listing all the content of X type.

So, let's say I have a *work* content type; Every *work* node older than few weeks is getting the message shown to the user. I also have a view, but I don't want the rules to display the message in there.

# Answer
> 1 votes
Well, answering myself. Turns out pure Rules are rather not enough. But together with Path Rules (https://drupal.org/project/pathrules) it works without a problem. So, question answered, issue solved. Maybe it will help someone.

---
Tags: views, rules
---


# Question
Title: Why don't I get a value from drupal_static()?
This post is basically a duplicate question of one I asked a little while back: Using Static Variables in a Custom Module. Unfortunately I can't get my own solution to work.

I'm trying to use a static variable in a custom module.

```
function tellafriend_userfullname_function() {
  global $user;
  $var = &drupal_static(__FUNCTION__);

  if (!isset($var)) {
    // generate contents of static variable
    $var = user_load($user->uid);
  }

  return $var;
}

```

The static variable will be used in the form submission handler and in `hook_mail()`.

```
function tellafriend_form_submit($form, &$form_state) {
  $var = &drupal_static('tellafriend_userfullname_function');
  $params = array();

  if ($form_state['values']['cv_included'] == '1') {
    $params['1'] =  array('uri' => $var->field_cv_upload['und']['0']['uri'], 'filename' => $var->field_cv_upload['und']['0']['filename'],);
  };

  // Other email set-up goes here.

  $message = drupal_mail('tellafriend', 'notify', $email, language_default(), $params);
}

function tellafriend_mail($key, &$message, $params) {
   $message['headers']['MIME-Version'] = '1.0';
   $message['headers']['Content-Type'] = 'multipart/mixed;';
   $message['body'][] = $var->field_full_name['und']['0']['safe_value'];
}

```

What have I done wrong?

# Answer
> 1 votes
Why do you want to call `drupal_static()` directly? You have a getter function `tellafriend_userfullname_function()`. This function takes care of your cache and handles it.

```
function tellafriend_form($form, &$form_state) {
  $var =  tellafriend_userfullname_function();
}

```

Furthermore, you don't even need to cache a `user_load()` call with `drupal_static()`. The entity cache takes care of it. So your construct is counter-performat.

So why not go the easy way?

```
function tellafriend_form($form, &$form_state) {
  global $user;
  $var =  user_load($user->id);
}

```

# Answer
> 4 votes
The default value returned by drupal\_static() is `NULL`; this means that, when you call the function passing for `$name` a value that has not been used from another function, the value associated with that name is `NULL`, or the second argument passed to `drupal_static()`.

In your case, you need to call `tellafriend_userfullname_function()` twice: once to initialize the static value, and once to get the static value.

```
function tellafriend_form_submit($form, &$form_state) {
  $var = tellafriend_userfullname_function();
  $params = array();

  if ($form_state['values']['cv_included'] == '1') {
     $params['1'] = array('uri' => $var->field_cv_upload['und']['0']['uri'], 'filename' => $var->field_cv_upload['und']['0']['filename'],);
  };

  // Other email set-up goes here.

  $message = drupal_mail('tellafriend', 'notify', $email, language_default(), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $var = tellafriend_userfullname_function();

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['body'][] = $var->field_full_name['und']['0']['safe_value'];
}

```

In this case, I would not use `drupal_static()`, for two reasons.

* The value you set and get from `drupal_static()` is a value you can get from a global variable
* Even if that would not be the case, you could simply use a static variable inside `tellafriend_userfullname_function()`, since `drupal_static()` is used for a static value that needs to be reset externally from the function that defines it

If you look at the code of drupal\_bootstrap(), you will notice the following comments.

```
  // Not drupal_static(), because the only legitimate API to control this is to
  // call drupal_bootstrap() with a new phase parameter.
  static $final_phase;
  // Not drupal_static(), because it's impossible to roll back to an earlier
  // bootstrap state.
  static $stored_phase = -1;

```

`drupal_static()` is not a replacement for every static variable that could be used from a function; it should be used when the static variable is used to save a state another function could need to reset. The documentation for `drupal_static()` says:

> A guideline is that if a function's static variable does not depend on any information outside of the function that might change during a single page request, then it's ok to use the "static" keyword instead of the `drupal_static()` function.

As example of when `drupal_static()` is used, see `menu_reset_static_cache()`, which contains the following code.

```
  drupal_static_reset('_menu_build_tree');
  drupal_static_reset('menu_tree');
  drupal_static_reset('menu_tree_all_data');
  drupal_static_reset('menu_tree_page_data');
  drupal_static_reset('menu_load_all');
  drupal_static_reset('menu_link_get_preferred');

```

If `menu_tree()` didn't use `drupal_static()`, resetting the static variable it uses would not be possible, if not changing the function to use the following code.

```
function menu_tree($menu_name = NULL, $reset = FALSE) {
  static $menu_output = array();

  if ($reset) {
    $menu_output = array();
  }

  if (isset($menu_name)) {
    if (!isset($menu_output[$menu_name])) {
      $tree = menu_tree_page_data($menu_name);
      $menu_output[$menu_name] = menu_tree_output($tree);
    }
  }

  return $menu_output[$menu_name];
}

```

This would have been possible, but it would have changed the interface between the function and the functions using it. Since this is a common pattern among different Drupal functions, defining `drupal_static()` and using it in those functions needing it has been a Smart Thing™.

---
Tags: 7
---


# Question
Title: how to make product with attribute which select admin and only this attributes be visible for user
So i for example: i have a commerce\_product, in this product there is attributes (select list or check-boxes)

attribute: **\[color white\]**

attribute: **\[color red\]**

attribute: **\[color pink\]**

attribute: **\[color black\]**

attribute: **\[color green\]**

attribute: **\[color orange\]**

when admin select only pink, green and red, these attributes must showing for user, without \[black\], \[orange\] and \[white\] attributes, in select list...

How it's can make? (without multiply commerce product) price not change if user selects black or other attributes

Thanks for any help!

# Answer
You should create a **Vocabulary** : **Color** . In the voacabulary list all terms with the list of colors: blue, red , green etc
. In your Product Display field add a Term Reference field and include vocabulary color to the product display.
For Red Shirt you should select the color Red in term reference field autocomplete or checkbox.
Similarly for other colors you should do the same.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Is there a printed map / tree / graphic of a sample array(s) during each phase?
This is a larger question to help me better visualize the Drupal array structure at each 'stage' of the life cycle. I'm looking for material to help me see what's happening behind the scene that center on the array structure exposed to the various hook calls.

Does anything exists in this fashion? I guess something could be pieced together by examining the APIs, but at it's core (version 7 at least), Drupal is about letting various components authored by different individuals to flexibly alter array(s) before their final HTML render.

# Answer
Devel is a good place to start. That will make the function dpm() available to you. This will allow you to print out arrays in an extremely user friendly visible way. If you're doing any sort of development you should really look into this module. I know when I'm trying to figure out what's being called for a given area I often use the combination of dpm and debug\_backtrace.

There's also a theme developer that relies on Devel that you can you to see a back trace of functions.
> 3 votes

---
Tags: hooks
---


title: Ubercart: has an order been paid?

text:
# Question
Title: Ubercart: has an order been paid?
Are there any good Ubercart hooks or other API features so I can learn about whether my Ubercart orders have been paid at all?

Basically all I need is a function that would tell me if an order invoice has been paid-in-full or not.

# Answer
> 3 votes
You can use
uc\_payment\_balance() function to know how much the customer still owes to you.

```
  uc_payment_balance($order)

```

where $order - the order object

---
Tags: ubercart, commerce
---


# Question
Title: Get the highest Matched output in result
I have a table like this

Now my requirement is like below:-

I have to fetch all Content ID related to User Id-31. Here the matching content id are 225,178. I am able to retrieve this. Now I want to do the following:-

I want to get all user id whose Content ID matches with Content ID of 31 in Decreasing order. It means that if all content id matches then it will appear first otherwise it will appear last. Here User ID 20 matches 2 times,User Id 19 matches 1, User ID 1 also matches 1 times. So Result set will be User ID 20,19,1. Now I want to achieve this in Mysql as well as db\_select in Drupal 7.

# Answer
> 1 votes
It's something like this ... Since I dont have your exact table in my database it could be slightly wrong. But this is 80% or 99% what you're asking.

```
$query = db_select('my_table', 't')
    ->fields('t', array('UserID'))
    ->condition('contentID', 31)
    ->groupBy('UserID')
    ->orderBy(2, 'DESC');
$query->addExpression('COUNT(t.UserID) AS num_items');
$results = $query->execute();

// dpm() is in the Devel module.
foreach ($results as $record) { dpm($record); }

```

**EDIT:**

The final query that worked was:

```
$query = db_select('flag_content','fcnt')
->fields('fcnt', array('uid'))
->condition('fcnt.content_id', array(178,225), 'IN')
->groupBy('fcnt.uid')
->orderBy('num_items', 'DESC');
$query->addExpression('COUNT(*)' , 'num_items');

```

---
Tags: 7, database
---


# Question
Title: Is it possible to disable a content type?
I am currently creating a small Drupal 7 website, but I don't plan to use the delivered Article content type. Is it possible to disable it without deleting it? What I mean by that is making sure no user will create articles by accident.

I could not find an option for this. Thanks.

# Answer
* You can't disable a content type, but you can prevent (almost) everyone from creating/viewing/modifying etc. an Article it with setting the permissions accordingly.
* If there's no Article content on the site, it's 100% safe to delete it. *(It's interesting to check out how the default and minimal installation profile provide different sets of content types. Article is just a "stock" content type which is by no means necessary to have.)*
> 17 votes

# Answer
For people not familiar with Drupal, you would prevent people from using a content type by going (in 7) `People > Permissions (url: admin/people/permissions)`

Then under **Node** unchecking the `Article: Create new content` permission for the selected roles. :)

Obviously you would change `Article` to the relevant content type.
> 7 votes

# Answer
In your .install file:

```
function YOURMODULE_disable() {

  // Disable content type MyContentType
  disable_content_type('MyContentType');

  //Activation message
  drupal_set_message(t('MyContentType is now disabled on your site.'));
}

```

and now in your .module or .inc file:

```
function disable_content_type($type) {
  $type_info = node_type_load($type);
  $type_info->module = 'node';
  $type_info->custom = 1;
  $type_info->modified = 1;
  $type_info->locked = 0;
  $type_info->disabled = 1;
  node_type_save($type_info);
}

```
> 5 votes

# Answer
You can also try the Content Access module to restrict users based on role to a content type. http://drupal.org/project/content\_access
> 1 votes

# Answer
There are some content types that can be "disabled" by virtue of disabling the module that uses it. For example: the poll, forum, book and blog content types disappear from the available types when you disable the associated modules. Basic page and article are the two exceptions.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Should I use different content types or tags?
I am working on my first Drupal site and I am worried about building things that will cause me trouble down the road.

The site is a move from a custom CMS to something more manageable. I didn't build the old CMS either.

I have several items under labels like news, press release, announcements, etc. As I'm building out the content types I realize they could all be the same thing except they are considered something different by end users.

Would something like this be a candidate for separate content types or one content type and I could tag each piece of content as "news" or "press release" etc. ?

I'm hoping I can learn from someone else's mistake and get some hindsight on the topic.

# Answer
The above responses are all excellent and this is a great question. I struggled with this and was unable to find much written on the topic.

When I initially built my first Drupal site, I only had a couple content types and almost all my content was an "article." I just added a ton of fields to my article content type! I don't want to say this approach is wrong for all projects, but it ended up being the wrong one for my project.

It seemed OK at first: as I got better with views, I realized I could display any fields in any context I wanted and I even started (erroneously) thinking that content types were somewhat irrelevant. And, as my colleagues above point out, you can do an awful lot with taxonomy.

But as I got closer to rolling the site out to the client and considered how they would maintain the site, I realized I was in trouble. Having everything lumped together under "article" makes for a long input form and confusion. Also, I came to realize that as much as I love fields, display types can come in handy in certain cases, and purpose-specific content types make managing display types easier/clearer.

So I overhauled my entire site and now I've got purpose-specific content types (it's a music label site)...

```
Articles (just for news articles now)
Album Reviews
Artists
Frequently Asked Questions
Quotes
Shows
Songs

```
> 1 votes

# Answer
I'd go for content types. That way you can easilly filter the content for the specific types when needed later.

It's easier to display all different content types at once, then to hide specific ones by their tags.
> 2 votes

# Answer
You could go either way. If the structure of the different pieces of content you listed is different, I'd go for different content types. Otherwise, taxonomy will be a simpler, and cleaner way to go.

As soon as you start requiring different fields on different pieces of content, then it's time to split off into a new content type.

Keep in mind things like presentation (display) - different layout will be easier to handle (with something like Display Suite) on different content types, rather than different taxonomy terms.
> 2 votes

# Answer
* Its pretty much depends on your vision of requirement you may want in future.Content types are field-able bundles which contains entities of same type.Same type in the sense of different fields you bind on them.
* In your case it looks like it will be good to have different content types reason being you might want to have word limit on body for news but not for press release,you may want to have videos linked with every(required) news item but not with other two,let say you want user with specific user role to add/edit news nodes only but not the other one,or you want anonymous user to see only press release nodes but not the other two.
* But again have a second thought if you are pretty sure that every thing is about to be same on all nodes,its just tagging, go for taxonomy.
* Last thing for consideration , if we consider content type as folders , nodes as files and taxonomies are tags files are tagged with. It makes more sense to have similar kind of files in one folder rather having all files in one folder,differentiated with tags. As the time you search for a file, you know what can be the worst case and that also when you have tons of files.
> 1 votes

---
Tags: taxonomy-terms, nodes
---


# Question
Title: How to show number of a views return results without submitting the view?
I have a view with some exposed filters.When selecting first exposed filter,I want to appear the Number of the view results without having submitting the view.Same thing for second exposed filter etc. I have seen this to other sites and I am not sure how to do this with drupal. thanks

# Answer
> 0 votes
How about triggering ajax call on key-press of that input field. In the ajax callback programatically call the view to get total count of results populate this count in field.

---
Tags: views
---


# Question
Title: How to show results from the last search?
I have this senario:A user makes a search (using search api solr). After some days he returns to the site and in the front page appear results related to the last search he made. How can I accomplish that with Search api? thanks

# Answer
You could try Search API Saved Searches Module

> This module offers users the ability to save searches executed with the Search API module and be notified of new results. Notifications are done via mails with token-replacement, their frequency can be configured both by admins and/or users and saved searches can also be created without first executing the search.
>
> Facet, Views or other filters set for the search will also be included in a saved search, thus reflecting exactly the same search results as displayed.
> 4 votes

---
Tags: search
---


# Question
Title: The best way to implement custom variables with Google Analytics
I need to use Google Analytics custom variables , but I want to give a different variable value depending of the urls.

I'm checking the G.A module, but I don't see how to define the variables to say when to use one token or other depending of the url.

The only way I see is build a token that checks the url and gives me back the value.

I'm thinking in something more close to Paths Breadcrumbs where you can define context and choose a token/value depending of the context.

# Answer
> 2 votes
"Custom variables" are now Custom dimensions and metrics.

The Google Analytics module supports custom dimensions and metrics.

See the module's README.txt:

> One example for custom dimensions tracking is the "User roles" tracking.
>
> 1. In the Google Analytics Management Interface you need to setup Dimension #1 with name e.g. "User roles". This step is required. Do not miss it, please.
> 2. Enter the below configuration data into the custom dimensions settings form under admin/config/system/googleanalytics. You can also choose another index, but keep it always in sync with the index used in step #1.
>
> Index: 1 Value: \[current-user:role-names\]

---
Tags: 7, google-analytics
---


title: Diagnosing drush sql-sync problem

text:
# Question
Title: Diagnosing drush sql-sync problem
Broadly, I'm having problems running drush sql-sync so that I can get a local copy of my dev database. I was getting an "The external command could not be executed due to an application error ... code: 255)" type thing.

To diagnose the problem more specifically, I ran *drush @local sql-conf* and got

```
 Array
    (
        [driver] => mysql
        [database] => soa
        [username] => drupaluser
        [host] => 127.0.0.1
        [port] => 33066
    )

```

When I then ran *drush @dev sql-conf* I got

```
Permission denied (publickey,password).

```

Running *drush @dev sql-conf -s* results in

```
Simulating backend invoke: ssh -o PasswordAuthentication=no git@dev.sub.mysite.com 'drush  --invoke --simulate --root=/var/www/dev --uri=http://default  sql-conf   --site=sub --env=dev 2>&1' 2>&1

```

# Answer
> 3 votes
> Permission denied (publickey,password).

This means the issue isn't with Drush, it's that the server that matches up to your @dev alias doesn't have your SSH public key set up to allow you access. Either your public key hasn't been added to the ~/.ssh/authorized\_keys file or the permissions on that file (or the ~/.ssh/ directory) have the wrong settings.

---
Tags: drush
---


title: Is there a theme with no grids?

text:
# Question
Title: Is there a theme with no grids?
Is there a theme I can use which has no grids set up, as I would like to write the mark up from scratch so I can have more control over the breakpoints.

Does such a theme exist?

# Answer
There are many themes which uses the conventional layout methods, one of which I know is the Bigdaddy.

The complete list of such type of themes is available here.
> 0 votes

# Answer
To start from something as close to a clean slate as possible you may want to look at making a subtheme of Mothership.
> 0 votes

---
Tags: theming
---


# Question
Title: Is there a module that can record when and for how long each user logs in for? (Drupal 7)
I'm working on developing a website as part of an academic project that requires tracking individual user activity throughout a long period of time. We need to do the very minimum track when users log in and for how long (or until they timeout). I haven't been able to find a module that does this, except for Open Web Analytics which is breaking some of our pages.

I'm not completely closed to the idea of rolling my own solution but I'd like to do it through a tested module if possible.

# Answer
> 2 votes
You are looking for User Visits Advanced module, It have the option to track the hours visited by the users.

> The User Visits Advanced module is a contribute module for the User Visits module. It is extremely useful for social networking sites who wish to provide their users with statistics about the number of times a the users profile page is being viewed and by which other users.
>
> This module comes with its own database table to store statistics per user profile (uid). At cron time, the data from the user\_visits table is collected, aggregated and stored in the user\_visits\_adv table. It stores
>
> * the total number of visits per uid
> * the number of visits of the X past days per uid
> * **the most recent visitors uids of the past Y hours**

# Answer
> 1 votes
I found this post after some digging.

> You can edit the googleanalytics.admin.inc file in the module. Uncomment forbidden tokens such as \[uid\] and \[user-raw\]. The forbidden tokens are at the very end of that file.
>
> Once that's done you can create custom measures in your google analytics account and track users.
>
> Good luck.

This requires Google Analytics obviously.

# Answer
> 0 votes
https://drupal.org/project/autologout might have some code that you could use as a starting point for your own solution.

Some details from the module's project page:

> This module provides a site administrator the ability to log users out after a specified time of inactivity. It is highly customizable and includes "site policies" by role to enforce logout.

---
Tags: 7, users, nodes
---


# Question
Title: File browser tab displaying in admin overlay
I've got File browser tab displaying in the admin overlay for all authenticated users. WHere is this setting coming from?

# Answer
There is setting under IMCE configuration to disable this option. Go to admin/config/media/imce click on edit link of Profile. See screenshot below.
> 1 votes

# Answer
I had the same issue when using the IMCE file uploader.

You can hide the File browser tab using this module: http://drupal.org/project/tabtamer

However, I think this module simply hides selected tabs from the frontend, and **DOES NOT** disable access or check permissions etc.
> 0 votes

---
Tags: modal-dialogs
---


title: Can't change ajax callback

text:
# Question
Title: Can't change ajax callback
I've got a confusing ajax issue that I'm not getting past for some reason. My submit callback loads some data and constructs a radio button with some questions. All cool. When the result set has a certain value ($lastquestion = true), then I want to change the submit callback, basically updating a different field in the form.

Here's the module (I apologize for the extra "fluff"):

```
function my_assisted_guide_menu(){
  $items = array();

  $items['assisted-guide']= array(
    'title' => 'Assisted Guide',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_assisted_guide_form'),
    'access callback' => TRUE,
    'description' => 'My Assisted Guide',
    'access arguments' => array('administer news feeds'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'my_assisted_guide.inc',
  );

  return $items;
}

/* Implementation of hook_form()
// * This is the main form function
 */
function my_assisted_guide_form($form, &$form_state){

  if(isset($form_state['input']['answer'] )){
    $next_qid = $form_state['input']['answer'];
  }else{
    $next_qid = 0;
  }

  $data = _nextquestion($next_qid);
  $questiontype = $data[0];
  $question = $data[1];
  $options = $data[2];

  $form['answer'] = array(
    '#type' => 'radios',
    '#title' => t('Answer'),
    '#options' => $options,
    '#size'=>2,
    '#title' => t($question),
    '#description' => 'Select one.',
    '#required' => TRUE,
    '#prefix' => '<div id="questions" class="qna">',
  );

  //Store question type value for later processing in submit function
  $form['question_type'] = array(
    '#type'=> 'hidden',
    '#value' => $questiontype,
    '#suffix' =>'</div>',
  );

  $form_state['redirect'] = false;

  $service_providers = "";

  if($questiontype < 3){
    $submit_text = "Next Question";
    $callback = 'get_next_question_callback';
    $wrapper = 'questions';
  }else{
    $submit_text = "Next";
    $callback = 'get_recommendations_callback';
    $wrapper = 'recommendations_list';
  }

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t($submit_text),
      '#ajax' => array(
          'callback' => $callback,
          'wrapper' => $wrapper,
          'method' => 'replace',
      ),
      '#submit' => array('my_assisted_guide_submit'),
      '#prefix' =>'<div id="q_button">',
      '#suffix' =>'</div>',
      );

  if((isset($service_providers)) && (strlen($service_providers)>0) ){
    $form['recommendations_list'] = array(
                                        '#markup' => '<h1>Recommendedations</h1>',
                                        '#prefix' => '<div id="recommendedations">'
                                      );
    $form['service_providers'] = array(
                                       '#markup' => '<div><h3>Service Providers: </h3>'.$service_providers.'</div>',
                                       '#suffix' => '</div>'
                                    );
  }

  return $form;
}

//
function get_next_question_callback($form, $form_state)
{

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#questions", render($form['answer'])),
      ajax_command_replace("#q_button", render($form['submit']))
    )
  );
}

//
function get_recommendations_callback($form, $form_state)
{

  return $form['recommendations_list'];

}

function my_assisted_guide_submit($form, &$form_state){
  $next_key = $form_state['values']['answer'];
  $data = _nextquestion($next_key );
  $questiontype = $data[0];
  $question = $data[1];
  $options = $data[2];

  $form['answer']['#options'] = $options;
  $form['answer']['#title'] = $question;
  $form['question_type']['#value'] = $questiontype;

  if($questiontype == 3){
    $form['submit']['#ajax'] = array(
          'callback' => 'get_recommendations_callback',+
          'wrapper' => 'recommendations',
          'method' => 'replace',
      );
    $form['#submit'] = array('my_assisted_guide_submit') ;
  }

  $form_state['rebuild'] = TRUE;

}

function _first_question_nid(){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'dt_questions')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->propertyOrderBy('created', 'DESC')
      ->fieldCondition('field_dt_questiontype', 'value', 1)
      ;
      $result = $query->execute();

    $nodeinfo = array_keys($result['node']);
    $nid = $nodeinfo[0];

  return $nid;
}

//Custom function to get the next question based on $next_qid = the question record's nid
//$answer_id is the fci of the selected answer, used to get the next question field value andload that node
function _nextquestion( $answer_id = 0, $question_type = 0 ){
  $next_qid = 0;

  if($question_type == 3){
    $data[0] = "0";
    $data[1] = "End of questions";
    $data[2] = array("0" =>"0");
    return $data;
  }

  if($answer_id == 0){
    //get first question id
    $next_qid = _first_question_nid();
    $questiontype = 1;
  }else{
    //get nid of answer where answer_id = $next_qid
    $next_q = db_query("select at.field_dt_answer_value as answer_text, at.entity_id as answer_key,
      a.entity_id as par_nid, q.field_a_dt_question_target_id nqid, qt.field_dt_questiontype_value as qtype
        from field_data_field_dt_answer at
        LEFT JOIN field_data_field_answer a on at.entity_id = a.field_answer_value
        LEFT JOIN field_data_field_a_dt_question q on at.entity_id = q.entity_id
        LEFT JOIN field_data_field_dt_questiontype qt on q.field_a_dt_question_target_id = qt.entity_id
      WHERE at.entity_id = :answerid", array(":answerid" => $answer_id ))->fetchObject(); //fetchAllAssoc('at.entity_id');
    $questiontype = $next_q->qtype;
    $next_qid = $next_q->nqid;
  }

  //Load the node
  $node = node_load($next_qid);

  $node_wrapper = entity_metadata_wrapper('node', $node);

  //$field contains an array of objects the answer and next question
  $field = $node_wrapper->field_answer->value();

  $answer_options_count = count($field);//['field_answer']);

  for($x=0; $x<$answer_options_count; $x++){
    //Check for final question
    $option_index =  $node->field_answer['und'][$x]['value'];
    $options[$option_index] = $field[$x]->field_dt_answer['und']['0']['value'];
  }

  $question = $node->field_dt_question['und']['0']['value'];

  $data[0] = $questiontype;
  $data[1] = $question;
  $data[2] = $options;
  return $data;
}

```

# Answer
> 1 votes
AJAX callback is not meant for making persistent changes. All it can and will do is:

* Make one-time changes to form array, that are *not* supposed to last
* Return proper part of the form for update

You cannot change your form in any permanent way, and changing callback there would last until next request. At next request it will get reseted, and old callback will be used. You need to modify things like that in form building function itself.

---
Tags: forms, ajax, javascript
---


# Question
Title: How to redirect anonymous users to a login page?
I have several type of nodes for content that is contributed by authenticated users. I would like the links to be visible to anonymous users but if they click the link to have it redirect them to the user log in page and if at all possible have the destination send them to the node creation page? I can use either a custom module or rules. How do I do this? Also, how do I have the flag links do this too?

# Answer
If you use the LoginToboggin Module. It Provides a login form on Access Denied pages for non-logged-in (anonymous) users, instead of just the standard "Access Denied". (Also, good for admins, who forget to login when trying to access admin areas too)
> 2 votes

# Answer
go for the site-information page in Configuration. In the Error-pages section give the path /?q=user in the text field, titled, Page Not Found 403(access deneid). This will help redirecting anonymous user to user login page.
> 1 votes

# Answer
I advise you to use Content Access \+ ACL does not show some parts of the site.
> 1 votes

# Answer
**First I created a block that uses theme\_links to create the menu.**

```
/**
* implements hook_block_view()
*/
function helper_block_view($delta = ''){
  $block = array();
  switch ($delta) {
    case 'helper_user_links':
      $block['subject'] = NULL;
      $block['content'] = array(
        '#markup' => theme('links', array(
          'links' => helper_user_links(),
          'attributes' => array(
            'class' => array('links', 'inline', 'clearfix', 'user-links', 'menu'),
            'id' => 'user-links',
          ),
          'heading' => array(
            'text' => t('User menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )),
      );
    break;
  }

  return $block;
}

```

**Then I created a list of paths in the function that uses another function to format the links array.**

```
function helper_create_links() {
  $links = array();

  $paths = array(
    "node/add/business" => 'Add Business Listing',
    "node/add/annotation" => 'Create Annotation',
    "node/add/discussion" => 'Create Discussion',
  );
  $links = helper_make_links($paths);

  return $links;
}

```

**Last I created a function that tests if the user has access to the link. If the user doesn't have access the link, it is written as 'user/login' with a query that sets the destination to the original link's destination and a css class added that can be used to deactivate the active class.**

```
function helper_make_links($paths) {
  $links = array();
  if (!empty($paths)){
    foreach ($paths as $path => $title) {
      $item = menu_get_item($path);
      if ($item && $item['access']) {
        $links[] = array(
          'title' => !empty($title) ? $title : $item['title'],
          'href' => $item['href'],
        );
      } else {
        $links[] = array(
          'title' => !empty($title) ? $title : $item['title'],
          'href' => 'user/login',
          'attributes' => array(
            'class' => array('deactivate',),
          ),
          'query' => array(
            'destination' => $item['href'],
          ),
        );
      }
    }
  }
  return $links;
}

```
> 1 votes

# Answer
There is nice module Redirect 403 to User Login.

> Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
>
> "Access denied! You must login to view this page."
>
> Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.
> 0 votes

---
Tags: redirection, rules
---


# Question
Title: How to disable multiple cardinality for a custom field
I've made a custom module that creates a new field type. Any single-cardinality instances of this field work fine. However, multi-cardinality instances of this field will not pass my #element\_validate function; see https://drupal.stackexchange.com/questions/86745/element-validate-function-is-called-on-sub-elements-of-a-form-form-items-are-c

Since I don't need this field to ever be multi-value, I want to disable multiple values for this field entirely.

Is there a way to do this?

# Answer
> 2 votes
Just alter the cardinality selection with this hook and provide only one value:

```
function <my_module>_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#field']['type'] == '<my_field_type>') {
    $form['field']['cardinality']['#options'] = array(1);
  }
}

```

---
Tags: entities
---


title: Theming of a webform node

text:
# Question
Title: Theming of a webform node
i would to theme a specific webform page and i achieve this with devel themer help but i find it not logical. Usually i use ID to specify a template for a page, node or other element. Then in my case i use the node-419.tpl for my node 419.normal For my page it's a bit more complicated because this the hierarchical applied template :

```
page-infos-profil-élève.tpl.php < page-webform.tpl.php < page-node-419.tpl.php < page-node.tpl.php < page.tpl.php

```

so why a template called page-webform-419.tpl.php doesn't work instead of page-infos-profil-élève.tpl.php ? Could i do this with php in my template.php file ? if yes how ?

thanks

# Answer
> 0 votes
yes i figure it out like this:

```
function cyrano_pf_preprocess(&$vars, $hook)
{
    switch($hook)
  {
      case 'page' :
      if (arg(0) == 'node')
      {
        $vars['template_files'][]  = 'page-' . $vars['node']->type;
        $vars['template_files'][] = "page-" . $vars['node']->type . "-" . $vars['node']->nid;

      }
      break;

  }

}

```

with the help of https://stackoverflow.com/questions/8956045/how-can-i-customize-a-specific-node-in-drupal-6-when-a-custom-template-has-alrea , then i get this choice for now (from devel) :

```
Candidate template files:
page-pentreprise.tpl.php < page-webform-420.tpl.php < page-webform.tpl.php < page-node-420.tpl.php < page-node.tpl.php < page.tpl.php

```

now, i can use a tpl file like page-webform-999.tpl to theme a specific webform page..

# Answer
> 2 votes
This depends on your template suggestions.

Open `template.php` in your theme folder, and look for a function named `YOURTHEME_preprocess_page`, if it does not exist, create it like:

```
function YOURTHEMENAME_preprocess_page(&$vars)
{
    debug($vars['theme_hook_suggestions']);
}

```

And see what suggestions (and in what order) you have.

**EDIT**: this is a preprocess function I used in a theme of mine, in theme's template.php:

```
/**
 * Implementation of hook_preprocess_page()
 * @param $vars
 */
function THEMENAME_preprocess_page(&$vars){
    // I like to store templates in different folders inside the theme dir
    foreach($vars['theme_hook_suggestions'] AS $i => $ths){
        $vars['theme_hook_suggestions'][$i] = 'pages/' . $ths;
    }
}
/**/

```

In your case, simply do `debug($vars, 'preprocess page vars!');` to see what variables you have a dispostion (please note: flush the cache after editing/creating this kind of function, and the output of debug($vars) can be very big!) and then add your template suggestion.

Maybe this can help: theming d7 webforms

---
Tags: theming, webforms
---


# Question
Title: Image upload broken when editing content
Sorry if I'm using incorrect terms here. What's going on is, when I edit any content, as the the types of content under 'Content Management \> Content Type', there's the Image: field, which I think is provided by the CCK Imagefield module or Imagecache. (I'm on 6.x-3.10 of Imagefield)

When I choose a file and click upload, I get a thumbnail image (http:/mysite.com/sites/mysite.com/files/imagefield\_thumbs/image.jpg?1357151034). When I click 'Preview', I get a preview with the image I uploaded (http://mysite.com/sites/mysite.com/files/imagecache/product/image.jpg). When I save, the image is gone, and going back to the edit form, it doesn't show up as an attached image. One possible clue; this content type isn't 'product', but it's in sites/mysite.com/files/imagecache/product/.

This all worked until a couple of weeks ago, when I updated a bunch of modules. I did a whole site backup before I ran the updates, and a development version of the site on my local computer doesn't have this problem on up to date modules. The only way I can replicate it on my local machine is to use a backup of the database from after this error occurred.

# Answer
> 0 votes
Make sure the file directory exists at sites/default/files and make sure it is writeable by the web server. For this you need to go to the file directory if you are familiar with terminal and type chmod -R 775 files when in the directory that contains the file directory. otherwise in an FTP client like Filezilla right click the file and click file permissions and change the permissions there. You may also need to check that this folder files/imagecache/product exists and is writeable.

---
Tags: 6, media
---


# Question
Title: How do I send an email to all users that has flagged a node using rules?
I need to send an email when there is a new comment on a node to all users that have flagged that node? How do I do this?

The flag is called "Follow" and the content type is "Blog"

# Answer
The exported code assumes use of Flag module to have a flag type as "follow" attached to Blog content type.

**As a summary:**

* set rule event as "After saving a new comment of type Blog comment".
* leave condition as none.
* set actions as
+ step 1: get all users who have flagged "Fetch users who have flagged a Node".
    + step2: loop through the list.
    - step2.1: send email

Here is the export for my Rule configured as per your requirement.

```
{ "rules_email_on_blog_comment" : {
    "LABEL" : "Email On Blog Comment",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "blog", "email" ],
    "REQUIRES" : [ "flag", "rules", "comment" ],
    "ON" : { "comment_insert--comment_node_blog" : { "bundle" : "comment_node_blog" } },
    "DO" : [
      { "flag_fetch_users_node" : {
          "USING" : { "flag" : "follow", "node" : [ "comment:node" ] },
          "PROVIDE" : { "users" : { "users" : "Users who flagged" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "[list-item:mail]",
                "subject" : "New Comment",
                "message" : "There is a new comment on the flagged blog post",
                "from" : "[site:mail]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```
> 7 votes

# Answer
You can use a loop to get all the users who have flagged, and you can add an action to send mail to all those users under that loop.
> -1 votes

---
Tags: rules, flags
---


# Question
Title: Upload a drupal site to the server to test
I have finished the drupal website on my localhost. I want to upload everything to the server, but only to test before officially launching it. Is there a way that I can keep my current non-drupal website running normally, but also upload this drupal site and test it at the same time?

If I create a new directory on the root, say '/drupal\_test, and put everything there for now, will that be a problem when I copy everything to the root later? Or is there any standard drupal way to do it?

Thanks!

# Answer
I suggest you instead use any other unused domain. In that case robots.txt, .httaccess will work normally. And also there is risk of Googlebot indexing this content.

Just add "Disallow:/" in the robots.txt as a first rule.
> 2 votes

# Answer
Just make sure you end up putting the drupal site, so that you can point it!,putting the drupal codebase let say in a folder named as drupal\_site inside your existing site root will help you accessing your drupal site with URL as www.existing.site/drupal\_site.It will not harm your existing site.
> 0 votes

---
Tags: migrations
---


# Question
Title: How to create a menu option with HTML in its title from a module?
HTML in a menu option would be very useful from a module too, i.e. inserting an image as a menu option. Is there a way to do use something like `function MODULE_preprocess_menu_link(&$variables)` inside a module, and not in template.php?

# Answer
> 3 votes
Modules can implement preprocess and process functions for theme functions using a template file; for theme functions not using a template file, Drupal 7 allows module to implement a preprocess function.
For example, the mymodule module could implement `mymodule_preprocess_menu_link()` which is a Drupal 7 preprocess function for `theme_menu_link()`.

Preprocess and process functions are useful when the variables passed to the theme function need to be changed. If there is the need of changing the output of the theme function, then a module needs to implement `hook_theme_registry_alter()` and change the function called to serve the output of a theme function.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_link'])) {
    $theme_registry['menu_link']['function'] = 'theme_mymodule_menu_link';
  }
}

```

With this implementation, `theme_mymodule_menu_link()` would be the function called when a module calls `theme('menu_link', /* … */)`.

### References

# Answer
> 1 votes
There is contrib module menu\_html available for adding html to the menu.

If you are trying this in your custom module than you may get some reference from it.

---
Tags: routes
---


# Question
Title: Will painless upgrading from Drupal 8 alpha 3.x to beta be possible?
I'd like to create a website with Drupal 8 Alpha 3. But I'd like to know for sure if it's possible to do a harmless upgrade to Drupal 8 Beta once that it's released.

I heard something about the Drupal 8 API being frozen, but after reading this article (http://buytaert.net/drupal-8-apis-are-freezing-but-not-frozen) i'm not so sure anymore.

Can anyone help out?

PS: The website i'm going to build is fairly simple (few content-types, views, blocks etc)

# Answer
No.

Upgrading from a previous 8.x version will be supported starting with the first beta.

Upgrading from 8.x-alpha *will* break, I know of at least one issue that will make major changes to the entity/node storage.
> 5 votes

---
Tags: updating, 8
---


# Question
Title: I have to remove HTML code that shows up on each page, where is it coming from?
I am very inexperienced in Drupal. I have been asked to remove commented HTML code that appears on each page of the website. What file should I look for in the root directory to find the source of this?

The comment was added by another developer as a joke or something. It's only wrapped in the body and appears close to the top.

The site is using Drupal 6.

# Answer
It's probably your theme files then, in /sites/all/themes/\[selected theme\]. You can also try to change the theme and check if it is gone.

Have a look at html.tpl.php and page.tpl.php files.
> 0 votes

---
Tags: theming
---