# Question
Title: Redirect to front page after emptying the shopping cart (ubercart)
How can I redirect to the front page after emptying the cart. I am making a commerce site using the Ubercart module, but it is not redirecting to the front page after the cart is empty.

# Answer
You can use drupal\_goto function.

`drupal_goto('<front>');`
> 0 votes

---
Tags: views, 7, ubercart
---


# Question
Title: Use a field's values in database to populate an exposed filter's options
I have a content type with a field named year (integer).

In a view, I'd like to expose this field to the user as a filter.

Instead of the default text boxes, I want to populate select lists with the values in the database for that field. Then the user will just have to click to select.

My php code writing is on copy-paste level.

I am using D7.

# Answer
> 0 votes
This topic migth be useful for you.

You can also create taxonomy vocabulary years and than select filter will be able to use in views.

---
Tags: 7, views
---


# Question
Title: Setting field values according to user input in a custom form?
i am using FAPI to create nodes through a custom form. the code below creates the nodes and assign them with a title and a body, so if i wanted static field values everything was perfect. my problem is, i want the value of `$body_text` to be determined by the user's input in the "order" textfield. i tried doing something like -

```
$body_text = $form['name'];

```

but that didn't work.

this is the code i'm using -

```
<?php
function nodeform_menu() {
  $items = array();
  $items['nodeform/form'] = array(
    'title' => t('My form'),
    'page callback' => 'nodeform_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function nodeform_form() {
  return drupal_get_form('nodeform_my_form');

}

function nodeform_my_form($form, &$form_state) {

  $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="box">',
    '#suffix' => '</div>',
    '#markup' => '<h1>Initial markup for box</h1>',
  );

    $form['order'] = array(
    '#type' => 'textfield',
    '#title' => t('My order'),
    '#default_value' => 'Products',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'ajax_example_submit_driven_callback',
      'wrapper' => 'box',
      'name' => 'submit1',
    ),
    '#value' => t('Submit'),
  );

$body_text = $form['order'];
$node = new StdClass();
$node->type = 'page';
$node->status = 1;
$node->title = "name";
  $node->language = LANGUAGE_NONE;
  $node->body[$node->language][0]['value']   = $body_text;
  $node->language = LANGUAGE_NONE;

node_save($node);
  return $form;
}

```

can anyone help me understand how to do this? i tried googling and reading the FAPI guide's but couldn't figure it out... plus, this is the first time i am using FAPI so in-spite the code is working, if anyone have any insights on this code (such as coding it more properly) i would also very appreciate that.

# Answer
You should put node creating into form submit function. In your case it should be nodeform\_my\_form\_submit. You can read more about it here under "Submitting Forms". Btw, you can use drupal\_get\_form as page callback function and with that skip using separate function.
> 1 votes

# Answer
write:

```
print_r($_POST);
exit();

```

somewhere in that script and copy/paste the values here.
> 0 votes

# Answer
the problem was i tried accessing `$form['name'];` array value the wrong way... instead of `$body_text = $form['name'];` , it should be done this way -

declare the array's value as the `$body_text` variable -

```
$body_text = $form_state['values']['order'];

```

then, set it as the body field content -

```
  $node->body[$node->language][0]['value']   = $body_text;

```

plus, i had to add `_state` to `$form` in order to fetch the value... Form API is really useful once you get the hang of it... thanks a lot everyone!
> 0 votes

---
Tags: 7, forms
---


# Question
Title: default value imagefield -> get from field collection item
I've got a contenttype "gallery" with an imagefield "thumbnail", used in listviews oder teaserviews. This contenttype also has a field collection with "image", "title" and "description". So what would be great now, if there's no value set for the "thumbnail" field, the default value should be the value from the first field-collection image.

any chance to realize this? Thanks for your help

EDIT:

i tried this:

That's not a solution

```
function channelportal_gallery_node_presave($node) {

    $galleryimage = field_get_items('node', $node, 'field_gallery_and_caption');
    $firstimageID = $galleryimage[0]['value'];

    $item = field_collection_item_load($firstimageID);
    dpm($node->field_thumbnail);

    $node->field_thumbnail = field_get_items('field_collection_item', $item, 'field_gallery_image');
    dpm($node->field_thumbnail);
}

```

But nothing is stored, to the field, even if the first dpm gives back an empty array and the second one containing the values it should contain. But after all, nothing is stored to the field and it's empty again...

Thanks for your answer Chad Payne

# Answer
> 0 votes
I would look in to something like

hook\_node\_presave

As a rough example I would have it work like this

```
function MY_MODULE_node_presave($node) {
     if(!isset($node->field_thumbnail)) {
          // load field collection and save that image to this image field
     }
}

```

I haven't tested this code but i think this would be the direction you would want to go in.

---
Tags: 7, entities
---


# Question
Title: How to use the right menu_tree and menu_link depending on region
How can I have specific menu\_tree and menu\_link for specific region?

Example:

left region will have his own menu\_tree menu\_link which will be different from the right region.

How can I achieve this?

Do I need to build a custom module?

If I use template\_preprocess\_region() , how can I call menu\_tree and menu\_link?

Thanks in advance

----------- UPDATE ----------------------

I've seen that preprocess\_block gives back "region" and "module". Is there anyway to use the different menu\_link() and menu\_tree() depending on the region and module?

# Answer
To theme only specific regions within your drupal page simply filter your css by prefixing your class with the class or id of the region in question. You can find the region by inspecting HTML output. I use chromes inspector which is accessed via inspect element within contextual menu.

```
#region-sidebar-first .menu_tree menu_link_my_class { css }

```

and if you want a different style for the right hand sidebar

```
#region-sidebar-second .menu_tree menu_link_my_class { css }

```
> 2 votes

# Answer
Use the `menu_block` module together with `hook_block_view_MODULE_DELTA_alter()`
> 1 votes

---
Tags: routes, theming
---


title: fivestar module get count

text:
# Question
Title: fivestar module get count
I am interested in getting the average count for a node. Currently I am able to show the nodes rating with:

```
$fivestar = field_view_field('node', $node, 'field_cg_rating', 'basic');
render($fivestar);

```

But I just want to get the count instead of the entire html showing the vote. Just a numerical value.

Is there an easy way of doing this?

# Answer
> 1 votes
You can calc it with formula which is used by Fivestar on theme layer: http://drupalcode.org/project/fivestar.git/blob/refs/heads/7.x-2.x:/includes/fivestar.theme.inc#l132

```
$fivestar = field_view_field('node', $node, 'field_cg_rating');
$stars = 5; // Stars count from your field instance settings. Settings can be loaded with field_info_instance() if needed.
$rating = round(($fivestar['#items'][0]['average']/100) * $stars, 1);

```

---
Tags: 7, rating
---


# Question
Title: How to insert onload="initialize()" class into the body tag for google maps
I am trying to display a simple 'hello world' Google Map on my page via the Google Maps API v3. I get it so far but what I'm cought up on is adding `<body onload="initialize()">` class attribute to my body tag. What would be the right way to handle this?

# Answer
I was able to find my own answer. This line doesn't necessarily add the attribute to the body tag, but it does call up the map.

```
drupal_add_js('jQuery(document).ready(function () { initialize(); });','inline');

```
> 2 votes

---
Tags: 7, google-maps
---


# Question
Title: Show default image when no uploaded image
I have a view with a thumbnail of the image uploaded by user. I would like to setup a default image which appears in place of thumbnail in case the user did not upload any image. Is that possible? Any advice appreciated.

# Answer
In a view, you can set the "empty field behavior, so you could put a hard coded image in there if one isn't present, or, in the content type itself, you can set up a default image if one isn't set for that field.
> 4 votes

# Answer
This can be done when you edit the content type \> your image field \> fieldsettings. There you can upload a default image. This image should show up in views.
> 5 votes

# Answer
I tried numerous things to solve this problem for Drupal 7: Display a default icon on the teaser, but not the full view. In the end I came up with this solution:

1. Edit the field on the content type and set your placeholder image as the default image for the field.
2. Now the placeholder image shows up for teasers without thumbnails. But it also shows up on the full node view, which we don't want.
3. In my theme's template.php I implemented template\_preprocess\_node(). Inside this hook I check the node's type to see if it's one of the ones I want to change. Then I check the view mode to make sure it's set to 'full'. Then lastly I check the contents of the field and see if it contains the default image. If so then I hide the field using the Drupal hide() function.

It took a bit of trial and error but here is my working code. I am looking at three different content types, my field was named "field\_hero\_shot" and my placeholder image was named "placeholder.png". You will of course have to adjust these to match your content type and field names.

```
 function mytheme_preprocess_node(&$variables) {

  // For Press room news types, hide the default thumbnail placeholder
  // image in the full display mode.

  // turn on for debugging: dpm($variables);

  if (isset($variables['type']) &&
        ( ($variables['type'] == 'company_update')
          || ($variables['type'] == 'media_clipping')
          || ($variables['type'] == 'news_release')
        ) &&
       isset($variables['view_mode']) && ($variables['view_mode'] == 'full')) {

      // then it's a press room type and it is in full display mode!

      // See if the Hero Shot field contains "placeholder.png".
      if (isset($variables['field_hero_shot'][0]['filename'])
            && ($variables['field_hero_shot'][0]['filename'] == 'placeholder.png')) {

         // If so that's the default image and we should hide it!
         hide($variables['content']['field_hero_shot'][0]);
      }
    }
}

```
> 1 votes

---
Tags: 6, media
---


# Question
Title: Add to cart link for product that sends user directly to checkout?
I'm working on a Drupal 6 site with Ubercart 2.9. I need to create a link for a single product that adds that product to the cart and proceeds directly to the checkout page. The link would be in an email blast, and by clicking it the user would completely skip the product's node/page, would skip the Cart page, and would be deposited directly onto the Checkout page where they can enter their payment/shipping info and proceed.

Possible? If so, how?

# Answer
The Ubercart Cart Links Builder turned out to provide the exact functionality I needed.
> 1 votes

---
Tags: 6, ubercart
---


# Question
Title: Customize Ubercart checkout page CSS when certain products are in cart?
On my Drupal 6 / Ubercart 2.9 cart website, I have the need to modify the CSS of the checkout page when a certain product is in the cart. For instance, if the customer is ordering red flowers, the background would change to a red flower background image. Is this possible via CSS? If not, any other ideas on how it can be done?

Thanks!

# Answer
I have two ideas:

1) render **the code of the article in the class attribute** of the cart div. you can do that "intercepting" the render function in your template.php file.

2) **using jquery**
> 2 votes

---
Tags: ubercart
---


# Question
Title: Distinct classes for each row in views-table
Is there a code that I add to my views style tables file that will give me distinct classes for each row in a views-table? or is there a module? I am working in Drupal 6

# Answer
I have two ideas:

1) with **:nth CSS selector** you can reach every row you want with your style rules. For example the third row can be selected with the selector:

```
.table-class .tr:nth(3) td { background: red; }

```

2) with **jQuery**
> 1 votes

---
Tags: views, 6
---


# Question
Title: Why is Drupal 7 loading the wrong .js file?
There is a very strange bug that is happening on one of our client websites, and we have been unable to figure out what's going on. It's a tough one.

**The Issue**

---

In simple terms, Drupal is loading the wrong JavaScript file. We have a custom theme for the site. In the theme's .info file there is this line:

`scripts[] = script/script.js`

A couple of weeks ago we updated the .info file. The original .info file contained:

`scripts[] = script/script-min.js`

The script and script-min files are completely different files, and the server should be loading the `script.js` file.

Here is the behavior we are witnessing:

* When we flush theme cache, Drupal reads in the .info file and loads `script.js`
* After cron runs (every 5 minutes) Drupal will randomally decide to load `script-min.js`
* If we check the database, the `system` table shows that Drupal has cached `script-min.js`

*It should be noted that nothing in the code is loading script-min.js. We have grepped through and cannot find where Drupal would even be trying to load the file from. The script-min.js file exists in the script directory along-side the script.js file, but nowhere is it referenced.*

**Our Setup**

---

* Acquia Cloud Hosting w/ Git and PHP 5.3+
* 3 environments (dev, stage, production)
* Production environment has two web servers, a balancer, varnish and MySQL. Web servers use Gluster file system to sync files
* This issue does not appear to show up on our dev/stage servers

**What we've tried**

---

None of these fixes worked: * Rebuilding registry
* Removing script-min.js file
* Targeting web server IPs to rule out an issue with the dual-server setup
* Clearing all caches
* Clearing Varnish cache

**Why we need help**

---

We have been trying to diagnose this issue for nearly two weeks now, and we've run out of the obvious ideas. Our main theory right now is that their might be an issue with the two web servers, but from all of our testing, it doesn't appear to be the case... But does make the most sense.

We are aware that we could probably get the server to use the right JS file by just using `drupal_add_js` instead of the .info method, but we really want to know *why* the server is loading a file that we are not telling it to.

**EDITS**

---

These modules implement hook\_cron() on the site: acquia\_agent, acquia\_spi, ctools, dblog, field, googleanalytics, node, scheduler, system, update, xmlsitemap\_node, xmlsitemap, xmlsitemap\_engines

I have already checked, and during cron, the `drupal_clear_js_cache`, `system_rebuild_theme_data`, and `drupal_theme_rebuild` functions are **not** hit. My original assumptions had to do with those functions, but if they are not running during cron, they are probably not the issue.

We think the issue might be related to this bug report: http://drupal.org/node/1765812

# Answer
> 0 votes
Turns out the issue was with a rogue server that was hitting our site. The old web server was hitting our database and caching the old files.

It was hard to find because the two servers had the same hostname for some reason.

---
Tags: 7, caching, proxies
---


title: Compare two menu tree objects

text:
# Question
Title: Compare two menu tree objects
I'm trying to add custom css class to a particular menu, same task mentioned here.

I moved a little further and found this article. So I put following code in template.php:

```
<?php
function phptemplate_menu_tree($tree) {
  if ($tree == menu_tree()) {
    $output .= "<ul id=\"foo\" class=\"bar\">";
    $output .= $tree;
    $output .= "</ul>\n";
    return $output;
 } else {
  return '<ul class="menu">'. $tree .'</ul>';

 }
}
?>

```

but constantly getting 502 error when trying to compare `$tree` and `menu_tree()`.

Can anyone suggest what am I doing wrong?

**UPDATE**

I've fixed the initial issue in the question and posted the solution here. Hope it helps.

# Answer
You cannot call `menu_tree()` from within `theme_menu_tree()` because `menu_tree()` contains a call to `theme_menu_tree()`. Your code contains an infinite loop.
> 0 votes

---
Tags: 6, routes
---


title: Taxonomy Menu & Hierarchy Trees

text:
# Question
Title: Taxonomy Menu & Hierarchy Trees
So I tried this tutorial on Taxonomy Menu and Menu Block. Now I set up the block to go in the header showing only 1 level deep.

My goal is to click on that 1 level deep link and generate a second menu showing the hierarchy. Instead I get a generic template that displays all posts of the parent taxonomy.

So, ideally:

1. \[Header Menu Item\] \> Goes to hierarchy tree
    * Sub category 1 \> Goes to hierarchy tree
        + Nodes of sub category 1

# Answer
> 0 votes
Have a look at Taxonomy Split, Drupal 6 only at the moment.

> if you have a vocabulary in the form of a tree, eg it has terms within terms with nodes attached to them.
>
> It will place all the first level terms in a block and when a term is clicked displays the tree below that term in another block.

# Answer
> 0 votes
I have successfully used DHTML menu for a similar need. The module allows several behaviors - I used the javascript-based tree browsing. The tree also auto-expands to show reveal the active term, but as far as I recall you'll need Taxonomy Menu Trails for that to work.

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


title: Theme specific taxonomy page

text:
# Question
Title: Theme specific taxonomy page
I cant seem to find a proper way to do this, I found ways for d5 but nothing on d7 so I am asking how can I edit a specific taxonomy page in d7?

# Answer
You can use template suggestion to override page.tpl.php for specific taxonomy term page. For this to work template suggestion file should be named page--taxonomy--term--\[ID\].tpl.php., where \[ID\] - ID number of taxonomy term for which you want to edit the page.

More on template suggestions: http://drupal.org/node/1089656
> 4 votes

# Answer
Just in case, if you want to override the taxonomy term page per vocabulary you can use Taxonomy Display module.
> 0 votes

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


title: Node display mode on taxonomy page

text:
# Question
Title: Node display mode on taxonomy page
How do you choose the display mode for a node that is used on an taxonomy page?

As default the nodes are displayed using the node-teaser mode but i would like to create a custom style for nodes that are show a taxonomy page.

I could change the teaser mode to what i need but then that would be changed on every place the teaser view is used.

# Answer
You can change this be enabling the Taxonomy Term View (I suggest cloning it in case you mess something up) and then you can change the view to suit your needs.
> 4 votes

# Answer
You can use taxonomy term display which also plays well with ds.

When you enable this module you can reuse the core functionality of Drupal or either change them completely using the ds module.
> 0 votes

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


# Question
Title: file_field_widget_form error when programatically creating nodes
I have a simple routine which I use to create nodes. The logic is something like this:

```
function make_node($node_type, $field_data) {
    foreach ($field_data as $k => $detail) {
        $field_key = _get_field_keys('field_' . $k);
        $field_key = $field_key[0];

        $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
        $form_state['values']['field_' . $k] = $detail;
    }
}

```

Then I run drupal\_form\_submit and it returns any errors from that and everything is great.

I'm having an issue with creating nodes which have a file upload field which uses the file u widget. I get the error:

```
Notice: Undefined offset: 0 in file_field_widget_form()

```

I had a look at the offending line (line 511 of modules/file/file.field.inc) and I can see why it occurs, the function file\_field\_widget\_form has an argument called $element, which is supposed to have an index 0, but when I set up the form programatically, that index is not set up.

When I make a node of the same type using the web interface, I can see that the $elements array is set up with the 0 index before even submitting the form.

How do I rectify this issue, do I need to call something else *before* making my form programatically? I'm using Drupal 7 if it helps.

# Answer
> 0 votes
Looks like this is actually a problem in Drupal itself. In modules/file/file.field.inc the function field\_form\_get\_state has a line like this near the bottom (just before the return statement):

```
$elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));

```

The issue is a small if condition a few lines back which looks like this:

```
if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
    $elements[$delta] = $element;
    ...
    some more stuff
}

```

Since I am submitting the form programmatically with `drupal_form_submit()`, it adds in `$form_state['programmed']`; thus, the control statement's condition fails, and `$elements[0]` does not exist.

---
Tags: 7, forms
---


title: Upload media to different sub-domain

text:
# Question
Title: Upload media to different sub-domain
I want to store all the uploaded media files on a different sub-domain on the same server (for CDN origin purpose). I think I can point drupal to upload files to this location (using the File System configuration \> "Public file system path ") but how do I config it to use the correct URL? I guess I can do some htaccess redirects but it makes it more complex with multisite installation.

Does the CDN module does that?

Thanks, Bnaya

Edit: I use Media module and only needs the files uploaded by it will use the CDN, I will handle the theme files.

# Answer
> 1 votes
this might help you a bit: http://drupal.org/project/remote\_stream\_wrapper

That's for the Media module, it enables you to 'read' files from a remote system, including subdomains if i'm not mistaken. Getting the files on that remote location is another story, the CDN module also won't help you there (a tool exists to sync files, see the CDN project page), but Media Mover will. It's still in development for Drupal 7, and i'm not sure what works and what does not in Media Mover at this stage, but it's at least something. Keep track of http://drupal.org/project/media\_mover linked from http://drupal.org/node/566364 . More is in development at the moment, but the future looks very good.

ps. just found this question, kinda related: How to upload static files to a remote server in Drupal 7 instead of local filesystem?

What i (at this moment) do, is sync the complete site to our CDN and then use the CDN module to only load the images from the CDN server. So i save them to the local filesystem and that's synced to a remote server. That was the easiest way for us, but other options obviously exist. (for example upload all media to 1 subdirectory inside the 'files' dir and rsync/ftp/sftp/whatever that single diretory to another server. You can set the directory to save files to for every media field, not sure about body fields at the moment. If it's on the same server, you can also just symlink to it. (if your on GNU/Linux/have the correct permissions.) (and remember to also sync the generated images to the other server, those are actually used on the display of the site)

You can then use a CDN module to actually load the image from any system when a user visits the site.

Hope this all helps a bit!

# Answer
> 2 votes
I'm not 100% sure of what your goal is, but I just accomplished something similar and in case it helps you here is what I was looking to do and what I did.

I am uploading all images to the /sites/default/files/images directory and I wanted them to become available via http://images.example.com/filename.jpg and display on the node via ths subdomain.

To do this I setup a virtual host in /etc/httpd/conf/httpd.conf

```
<VirtualHost *:80>
  ServerName images.example.com
  DocumentRoot /var/www/html/example.com/sites/default/files/images
</VirtualHost>

```

You can then alter your subtheme node.tpl.php to reference the attached images via this subdomain.

```
<?php $img = 'http://images.example.com/' . $field_image['und'][0]['filename']; ?>
<img src="<?php print $img; ?>" />

```

I wanted the convenience of having the variables already present in the node so I used the `template_preprocess_node(...)` function in *template.php*.

```
function MYTHEME_preprocess_node(&$vars) {
  $node = &$vars['node'];
  if ($node->type == 'image') {
    $base_url = 'http://image.example.com';
    $vars['image_base_url'] = $base_url;
    foreach ($node->field_image['und'] as &$image) {
      $image['url'] = $base_url . '/' . $image['filename'];
    }
  }
}

```

With this I can access inside the node both `$image_base_url` as well as `$field_image['und'][0]['url']`

* `$image_base_url` is *http://image.example.com*
* `$field_image['und'][0]['url']` is *http://image.example.com/filename.jpg*

---
Tags: files, cdn
---


# Question
Title: drill down taxonomy node count using views
I don't know if I'm the only one having this issue but my problem seems to be common. I just could not find the solution here and Google.
My site have the taxonomy menu:
Classifieds
Electronics
Autos
Jobs
Accounting
Information Technology
I just want to show a summary for every term that has children on it. E.g., When you click on Classifieds it should show like this:
Electronics(160)
Autos(310)
And when you click on Autos(310) it should show for example:
Aston Martin(200)
Toyota(110)
And then drill down to the last child item with node count. (e.g. DB9 Coupe (xx) etc..)
When I use the views default summary display and you clicked on 'classifieds' it will show:
Free Stuffs(xx) DB9 Coupe(xx) \<-- this should should first as 'Autos' and not show the last child in the hierarchy!

Basically, it's just a page with summary counts of terms being used in nodes and count them by level in the taxonomy hierarchy. So, from clicking a parent term, the first child terms will only show with node counts, then when clicking on one child only the children of this child will show with node counts etc..

Thank you in advance!

# Answer
FYI. For those who have the same issue above. I managed to do this in Drupal 7 and it's called facet search primarily using Apache Solr or without Apache Solr here
> 0 votes

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


# Question
Title: how to get password as submitted by the user in hook_user_insert?
I have extended the core using hook\_user\_insert. but when i print the $edit argument inside the function i get password fields as encrypted.

Is there any way i can get the non-encrypted value of password as submitted by the user.

I am using drupal 7

Following is the $edit array

```
Array
(
    [uid] => 28
    [hostname] => 127.0.0.1
    [roles] => Array
        (
            [2] => authenticated user
        )

    [cache] => 0
    [administer_users] =>
    [name] => raul1
    [mail] => raul1@tst.com
    [pass] => $S$DskyNMYOrdQoEdErlYPN701I1jSBBrzetjSjb2XPzlooVcfcp8Rp
    [status] =>
    [notify] => 0
    [timezone] => Asia/Kolkata
    [signature] =>
    [picture] =>
    [picture_delete] => 0
    [picture_upload] =>
    [signature_format] => filtered_html
    [init] => raul1@tst.com
    [field_first_name] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Raul
                        )

                )

        )

    [field_last_name] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Garcia
                        )

                )

        )

    [is_new] => 1
    [created] => 1356067366
    [theme] =>
    [access] => 0
    [login] => 0
    [language] =>
)

```

is there any tweaking to get the user submitted password from D7 registration form?

I know its impossible to get back the hashed value. or how to find out the salt associated with each hashed password

# Answer
Any hook that is invoked from user\_save() is too late to get the password as entered from the user. In fact, the first lines executed from `user_save()` are the following ones.

```
$transaction = db_transaction();
try {
  if (isset($edit['pass']) && strlen(trim($edit['pass'])) > 0) {
    // Allow alternate password hashing schemes.
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
    $edit['pass'] = user_hash_password(trim($edit['pass']));

    // Abort if the hashing failed and returned FALSE.
    if (!$edit['pass']) {
      return FALSE;
    }
  }

  // …
}

```

What you can do is adding a form submission handler to the form used to create new user accounts. That submission handler can access the password as entered from the user in `$form_state['values']['pass']`. I would rather add a form submission handler that is executed right after `user_register_submit()`, as that submission handler contains the following code.

if (!variable\_get('user\_email\_verification', TRUE) || $admin) { $pass = $form\_state\['values'\]\['pass'\]; } else { $pass = user\_password(); } $notify = !empty($form\_state\['values'\]\['notify'\]);

// Remove unneeded values. form\_state\_values\_clean($form\_state);

$form\_state\['values'\]\['pass'\] = $pass;

I would use the following code.

```php
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Add your submission handler.
  $form['#submit'][] = 'mymodule_user_register_submit';
}

function mymodule_user_register_submit(&$form, &$form_state) {
  // The password is in $form_state['values']['pass'].
}

> 4 votes

---
Tags: hooks, users
---


# Question
Title: Images within content of page but not separate fields
I would like to create a basic page within Drupal 7 that would consist of some images mixed with HTML. I would use CSS to position the images within the HTML content, sort of like a magazine or newspaper article.

I would like for the end user to be able to edit/replace these images along with the HTML yet the image field did not seem to give me flexibility to place the image within the HTML content.

I could upload the images via FTP directly to the `../sites/default/files` directory and manually reference the images ...

```
<img src="../sites/default/files/image-name.png" />

```

but that would not allow the end users to manage the images from with Drupal, plus I would need to give them FTP access to the filesystem which I would like to avoid.

Any suggestions on how to work around this?

# Answer
> 3 votes
You can do this with the following modules:

Lot of setup and config, but once its there, its there so to speak.

---
Tags: media, 7
---


title: Count the number of views

text:
# Question
Title: Count the number of views
How can I count the number of views for a video? I am using the Profile2 module to display user's information.

Users add videos which any user can see. I would like to count the number of video's views, and use that number to sort the result shown by the Views module. Is it possible?

# Answer
> 3 votes
You should use the Radioactivity module

> This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.

You can add an 'emitting' field to any entity (including a profile2 entity), and the module can be configured to do basic page counts without the decay profiles if you don't need them.

As it's a field, you can use it in Views as normal for sorting.

It has several storage options (some of which do not relay on the database), integrates with memcache etc, so it doesn't have the same performance problems as the core Statistics module that Letharion has mentioned.

Make sure you read the instructions though, it took me a while to realise that the statistics won't be counted unless the field is actually *displayed* on the entity type in question (not just attached to it, it needs to be visible in 'Manage Display' - nothing will be printed to the screen but it needs to be there for the stats to be counted).

# Answer
> 3 votes
I believe the reason there is not common "Out of the box" solution for this, is that the statistics module has a long-standing reputation of ruining performance, as it performs *a lot* of database writes.

While it could certainly be "upgraded" to being entity agnostic, I guess there's little interest in doing so.

The most common solution then, I think is to use a tool like Google analytics for counting impressions, and exposing your video (or other entity) in ways/with urls that make their views easily countable in your tool of choice.

For Views integration, the easiest options seems to be Google analytics statistics, (Thanks Chapabu), but other interesting modules could also be GA counter, GA reports and GA importer

---
Tags: views, files, nodes
---


title: Associating nodes to a user

text:
# Question
Title: Associating nodes to a user
I'm trying to create a Parish website. I have a list of parish members with email ids and without email ids. I've imported the users with email addresses as users, and the rest as nodes. Members that belongs to same family shares a common family code, and when a user log in I want to have a view of all family members and their necessary details (i.e. address,phone no,etc).

But the problem I have is that some users are created using user import and some (people without email) are created as nodes.

So how can I display all the members with same family code in a single view? How to relate a user with another user/nodes.

Is it with contextual filters/relationships? I tried with it but couldn't get it.

# Answer
Firstly you must make all users users and not nodes. Somebody I know recently had an issue where users didn't have email addresses. His solution was to create fake email ids for those users since having an email id is mandatory for an account on a Drupal site. Once you have everyone as users, I think you can add relationships between users using this module - User Relationships and hence easily show related users in views.
> 0 votes

---
Tags: nodes, users, views
---


# Question
Title: Display all taxonomy terms's ids associated with nodes in a view
I need to display the term ids of each node under its title in a view.

I can do similar display by adding node: title and node: all taxonomy terms. But I just want to display tid's instead of term names.

My view result should look like this:

title: Node title 1

tids: 1, 2, 4

title: Node title 2

tids: 3, 5, 6

Is there a way to alter or add a views field for this?

Also in general, how are fields that is available to the views constructed?

# Answer
> 5 votes
Add field "All taxonomy terms". Then check the "rewrite output of this field" box, and in the rewrite box enter the token `[term_node_tid-tid]`.

# Answer
> 2 votes
Addition to the @beth 's answer:

"all taxonomy terms" field apparently provides multiple replacement tokens:

\[term\_node\_tid\] == Content: All taxonomy terms \[term\_node\_tid-tid\] == The taxonomy term ID for the term. \[term\_node\_tid-name\] == The taxonomy term name for the term. \[term\_node\_tid-vocabulary-machine-name\] == The machine name for the vocabulary the term belongs to. \[term\_node\_tid-vocabulary\] == The name for the vocabulary the term belongs to.

Hidden gem :) I wonder how many other fields come with similar behavior..

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


# Question
Title: can we use one argument for two contextual filters
can we use one argument for two contextual filters **OR** can we create and pass dynamic argument from one filter to another by using validation php code in first one?

drupal7.com/location-map/region-or-type-field-here

i want to use contextual filter for region and type fields for same argument.

# Answer
> 1 votes
You should be able to set "WHEN THE FILTER VALUE IS NOT AVAILABLE" on the contextual filter to "Provide Default Value" and set "Type" to "Raw value from URL" and set the Path component, in case of example provided in your question, Path component 0 is `location-map` and Path component 1 is `region-or-type-field-here`

---
Tags: views
---


# Question
Title: Adding an editable field to a custom block module
I have a custom module that registers a 'block' and echoes some HTML content.

I want to make this customisable to admin users, which means enabling 'Configure' for the block: with one textfield, and a drop down when you can select a node of a specific type.

How do I go about starting this:
A) Enabling 'Configure' for the block
B) Choosing/Coding Fields that store variables, seen when you click 'Configure'
C) Echo the variables in the block module code

Thanks for your help!

# Answer
> 2 votes
I believe the block example module should show what you want

---
Tags: 7, blocks
---


# Question
Title: How to speed up Drupal 7 compiling PHP to C++?
I would like to improve Drupal 7 performance with HipHop or any other similar solution transforming the code from PHP to C++ or C.

What steps are needed to properly do the scenario below ?

I would like to :

1. maintain @development environment as not-compiled php, adding and testing contrib and custom modules.
2. after testing @development, I do rsync @development to @staging ...
3. ... and compile @staging
4. test @staging
5. rsync @staging to @life

I think it is a bit oversimplification but should bring an overview.

If it is not possible, are there any other options ?

# Answer
Here is a link to the complete solution article where webtutor.pl shows how Drupal 7.4 compiled using HipHop for PHP is "up to 6 times faster than in a pure PHP environment".

Here are the benchmark test results comparing standalone Drupal vs Drupal with APC vs Drupal compiled using HipHop for PHP.
> 3 votes

# Answer
Following the chain from a comment on this great Wordpress tutorial on the new HHVM, I was led to Nick Veenhof's blog where he posted very recently about his unsuccessful efforts to get hiphop-php working with Drupal.

For what it's worth, the awesome maintainer of hiphop, Sara Goleman, said in the comments that she was interested in supporting Drupal and was going to try to reproduce the issue.

I'm working at building a vagrant VM to help reproduce the error and get everyone on the same page as easily as possible. The plan is to \[use a patch that supposedly worked against Drupal 7.4, and hopefully move forward from that working state :)

https://github.com/patcon/vagrant-hiphop-drupal
> 5 votes

---
Tags: 7, performance, staging
---


title: IMCE and user privileges

text:
# Question
Title: IMCE and user privileges
I have a taxonomy like this in our Drupal 7 website.

```
(Group1)
 |
 +---- (Group1SubGroup1)
 +---- (...)
 +---- (Group1SubGroup10)

(Group2)
 |
 +---- (Group2SubGroup1)
 +---- (...)
 +---- (Group2SubGroup4)
 ...

```

And we've use a module (I dont remember the name) that gives users rights depending on the term. For example, for `user1` we give him CRUD rights on `Group2SubGroup4`, but nothing on `Group2SubGroup1`.

There's a shared directory where you can upload media files when you create an article.

So, when the `user1` want to create a new article with term `Group2SubGroup4`, we'd like to give him rights to upload a file, but ***only*** in a sub-directory of the "shared multimedia files directory" called `Group2SubGroup4`.

For example if the directory is `/www/htdocs/multimedia`, when the `user1` want to create a new article with term `Group2SubGroup4`, he will have rights to upload multimedia files but its "base" directory will be `/www/htdocs/multimedia/Group2SubGroup4`

How would you do this?

And if you have an easy solution for this, I'd like to do more: have the rights to write on the right directory (`/www/htdocs/multimedia/Group2SubGroup4`) ***and*** still the possibility to read everything else (`/www/htdocs/multimedia` and other subdirectories). How would you do this?

# Answer
The solution was easy: it's already integrated in Drupal. Just activate the `media` module and go to `Administration->Configuration->Media` and there's a very, very, **very²²³** powerful IMCE configuration panel.
> 0 votes

---
Tags: files
---


title: Field sort random via PHP

text:
# Question
Title: Field sort random via PHP
I have a image field and use on cycle.

field.tpl.php:

```
<?php
?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

My field items sorting default alphabetical but i want random. How can i do this?

EDIT: I find this codes, it valid for me? And how can i use this code for my field?

```
function my_theme_preprocess_field(&$variables, $hook) {
 if($variables['element']['#field_name']=="field_project_release_packages"){
 usort($variables["items"], "_my_theme_sort_package_list");
 }
}

function _my_theme_sort_package_list($a, $b) {
    return $a["#title"] > $b["#title"];
}

```

# Answer
You should be able to use template\_preprocess\_field() and shuffle() to do this. This is an example randomizing the entries in field\_photo for a theme called dummy:

```
  function dummy_preprocess_field(&$variables) {
    if ($variables['element']['#field_name'] == 'field_photo') {
      shuffle($variables['items']);
    }
  }

```

You could also try to replacing you call to `usort()` in your original code with `shuffle($variables["items"])`.

The above isn't tested, but I think it should work.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Views 2 Drupal 6 Filter Result if none of the fields have a value
What I need seems pretty straightforward but I cannot seem to accomplish it.

I have a view, a content pane to be precise, fetching specific fields of the node that it's parent panel overrides.

What I need, is for the view to return 0 results (and thus be hidden completely) if NONE of the fields are populated. If even one fields is populated I want it to display, but if NONE of the fields in question have a value I need the content pane to dissapear completely. I understand I have to do it with filtering and the NOT NULL option but I cannot understand how since in 2.x-6.x there is no AND/OR capability of what I can see.

Any help?

# Answer
Module Views Or allows me to add OR clauses to my filters and get the job done. Here is an excerpt about it from the module's project page:

> ... allows Views to combine filters or arguments with OR and fields with COALESCE.
> 0 votes

---
Tags: 6, views, panels
---


# Question
Title: Hiding nodes based on geographical location
I am setting up a ecommerce site for a client using drupal and ubercart. They have a number of products on the site that are not available in certain countries. We have discussed solutions using subdomains, but ideally they want to be able to control whether or not a product visible in any giving country.

So my question. Is there a module that allows a person to block the visibility of a node based on the user's geographical location? Ideally, this would block everything including any views the node might appear in. Any ideas?

# Answer
I'm going to assume that you wouldn't mind writing a custom module for this. Lets call it say, `my_mod`. The use-case you have mentioned is perfectly suited to take advantage of the Drupal Node Access system.

A few assumptions:

1. You have a vocabulary, *Locations* that houses a growing list of locations with which either a user or a piece of content on your site can be tagged with.
2. Attach a Taxonomy Term Reference field `field_location` with this vocabulary to both *products* and *users*.
3. Say for a given user, based on his access, you "guess" his location from his IP and set/append this field for him.

Then all you need to do is let Drupal know that users can only see products that have been *tagged* with the locations that they are a part of using the Node Access hooks as shown below.

```
/**
 * Access realm that defines access control to content by user location
 */
 define('USER_GEOGRAPHY_REALM', 'user_geography');
 /**
  * Taxonomy term reference field. Allows tagging a user/node with a
  * a given term from the "Locations" vocabulary.
  */
 define('LOCATION_FIELD', 'field_location');

/**
 * Implements hook_node_access_records().
 */
function my_mod_node_access_records($node) {
  $grants = array();
  $items = field_get_items('node', $node, LOCATION_FIELD);
  // In the USER_GEOGRAPHY_REALM access realm, we say that a user
  // who has the grant ID equivalent to the {taxonomy_term_data}.tid of
  // a term with which the node was tagged is allowed to see it.
  foreach ($items as $item) {
    $grants[] = array(
      'realm' => USER_GEOGRAPHY_REALM,
      'gid' => $item['tid'],
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0
    );
  }
  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function my_mod_node_grants($account, $op) {
  if ($op == 'view') {
    // Reload to make sure fields have been attached.
    $account = user_load($account->uid);
    $gids = array(USER_GEOGRAPHY_REALM => array());
    $items = field_get_items('user', $account, LOCATION_FIELD);
    // In the USER_GEOGRAPHY_REALM, a user's grants are the different
    // locations that he is a part of.
    foreach ($items as $item) {
      $gids[USER_GEOGRAPHY_REALM][] = $item['gid']
    }
    return $gids;
  }
}

```

You are free to extend the logic to include per-location limits for a user if you'd like.

You may have to remember to disallow the user from editing his own *Location* field and can use `hook_field_access()` for this purpose.
> 0 votes

---
Tags: 7, ubercart, location
---


# Question
Title: Programatically Submitted Form With 'file' Field Throws Notice
This seems to actually be a problem in Drupal itself. In /modules/file/file.field.inc the function file\_field\_widget\_form has a line like this near the bottom (just before the return statement):

```
$elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));

```

The issue is a small if condition a few lines back which looks like this:

```
if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
    $elements[$delta] = $element;
    ...
    some more stuff
}

```

Since I am submitting my form programatically with drupal\_form\_submit, it adds in $form\_state\['programmed'\], thus the if condition fails, $elements\[0\] does not exist and I get the error

```
Notice: Undefined offset: 0 in file_field_widget_form()

```

My form is submitted by a custom routine (in a custom module) that looks a bit like this:

```
foreach ($field_data as $k => $detail) {
    $field_key = _get_field_keys('field_' . $k);
    $field_key = $field_key[0];

    $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
    $form_state['values']['field_' . $k] = $detail;
}

drupal_form_submit("{$node->type}_node_form", $form_state, $node);

```

The form state before I call drupal\_form\_submit looks like this:

```
Array
(
    [values] => Array
        (
            [title] => some title
            [name] => admin
            [op] => Save
            [field_person] => 88
            [field_lead_type] => 1
            [field_lead_details] => some stuff
    )

```

)

What is the fix? I'd rather not mess with core modules. Is there something I can do to my own code to resolve the problem?

# Answer
ok, why are you not submitting a File (or FID) along with your form\_state? I don't understand your problem, because I do this all the time (even with files).

Drupals file widgets usually use like Ajax to upload a file in the background and the form takes a FID in `$form_state` to process your forms if it has files attached.

When I asked you what the `$form_state` was I meant:

1. what are you sending to drupal.
2. what does drupal typically send as the `$form_state` when that form is sent through the user interface, because you're just trying to do that programmatically.

I dont think you know the answer to (2) above, because you cant get this to work right. You showed me what you're sending for (1). Here is a tutorial on using Firefox's Firebug plugin to view the submitted POST form state values for a drupal form. You want to drupal\_form\_submit form state to have the exact same parameters passed to it. In firebug you simply press `Persist` in the `Net` tab and you can capture URL requests.

So I'm saying goto the form in the website and submit it using your browser and Firebug to see what it expects to be passed.

You may ask how you get a FID for a file, you simply upload it using php before submitting the form and pass along its `$file->fid`. See this community documentation comment here how to do that.

You're just posting a simple HTTP Form, I really doubt Drupal is doing anything wrong.
> 0 votes

---
Tags: 7, forms
---


title: How to exclude page from Redis cache?

text:
# Question
Title: How to exclude page from Redis cache?
I'm using Redis and need one dynamic page to be excluded from being cached. How can I do that?

# Answer
> 1 votes
Not sure how you are generating this dynamic page, but somewhere in the mix, you could put something along the lines of:

```
drupal_set_header('Cache-Control', 'public, max-age=0');       // set max age to 0
drupal_set_header('Expires', 'Sun, 18 Dec 1983 02:28:00 GMT'); // some date in the distant past

```

before any other output, eg, at the top/start of your page's menu callback or in right before you select its custom template if it has one.

If this doesn't work, a quick hack would be to do a `drupal_set_message('Welcome to my dynamic page');` which would cause drupal's core functions to try not to cache the page :)

# Answer
> 0 votes
How about this snippet in `hook_init()`?

```
$cache_class = variable_get('cache_class_cache', NULL);
if (isset($cache_class) && class_exists($cache_class)) {
  // Check if Redis is being actively used as a cache backend
  if ($cache_class == 'Redis_Cache') {
    if (TRUE) { // Add condition here for your page
      drupal_page_is_cacheable(FALSE);
    }
  }
}

```

---
Tags: caching
---


# Question
Title: Verification code when adding new telephone number
i used Sms Framework send sms to user if someone comment on their nodes system run ok, no problem. And also i create new cck field for users phone, when user goes their account they able to add or update this field. My question is how should i control if this telephone number belongs to user. How can i verificate this.

# Answer
> 0 votes
You can follow verification message method. When a user add/updates a phone number, you can send a unique random number which he must enter to verify his phone number.

Create a table that will contain three columns phone-number, unix time stamp and the verfication-code. When a user adds a phone number, create and store the random number. When the user inputs the verfication-code(random number), look it up in the database and then authenticate the user. Once he is authenticated, you can remove the entry from the database.

If you mention that verification code is valid only for 5 mins, then you can run a cron job to clear the database entries which are older than 5 mins.

---
Tags: 7, entities
---


# Question
Title: Can I create a view of watchdog log entries?
We want to view a more detailed view of watchdog log entries, filtered by module and level and showing the details section in a table. When creating a new view, watchdog logs is not in the list. Is there a way to do this like a Views3 plugin or something what would integrate this?

# Answer
You're probably looking for Views Watchdog

> The Views Watchdog module extends the Views module and allows to create customized lists (pages, blocks, feeds) of watchdog entries.
> 1 votes

---
Tags: views, log-messages
---


title: Add custom class to a particular menu

text:
# Question
Title: Add custom class to a particular menu
I need to know how to add extra class to a perticular menu.For example i have custom menu "menu-header-let",This menu is rendering like below,

```
<ul class="menu"><li class="leaf first"><a title="Redirecting to Help Page" href="/vsv/content1">Help</a></li>
<li class="leaf"><a title="" href="/vsv/content1">Home</a></li>
<li class="leaf last"><a title="" href="/vsv/content1">home2</a></li>
</ul>

```

Now i want add extra class to the ul like below

```
   <ul class="header-top-menu">

```

I used phptemplate\_menu\_tree(), but i need different class for each custom menu.If is override menu theme and adding same class for all custom menu.

I have no idea how to add different class when different custom menu renders in drupal.

please help me.

# Answer
Well, the code in tutorial that **beth** mentioned has bugs and does not work. The best solution I've found up to now is this:

```
<?php
function YOUR_THEME_menu_tree($tree) {
  if (preg_match('/A unique string in your menu/', $tree)) {
      return '<ul class="header-top-menu">' . $tree . '</ul>';
  } else {
    return '<ul class="menu">'. $tree .'</ul>';
  }
}
?>

```

You can use any unique path or link title as string to identify the menu. This solution was inspired by a comment in the cited tutorial.
> 4 votes

# Answer
There's a tutorial just for you: http://programmingbulls.com/complete-drupal-6-menu-theming
> 0 votes

# Answer
I should agree that theming of menu items in Drupal sucks.

There is a module Menu Attributes which does just that. You can also add `Id,Name, Target, Rel,Class,Style,Accesskey` attributes to the particular menus.
> 0 votes

---
Tags: 6, routes, theming
---


# Question
Title: Creating first module, and How to alter text field on new content creation in Drupal 7?
I am trying to set the text in a custom content field when saving a node. I think I need to create a module to do this. (I am new to module creation.)

I started with a blank directory called - let's say `myModule`. I placed `myModule` into path `sites/all/modules`.

I placed into the myModule directory two files that I understand to be required and gave them the following naming conventions which I also believe to be the standard:
myModule.module
myModule.info

```
myModule.info holds the following text:
name = Some Descriptive Name
description = does stuff.
package = relatedName
core = 7.x

```

Inside `myModule.module` I have tried various things that are to much to elaborate , but include these exact functions and parameters.

**Attempt 1:**

```
function myModule_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
    if ($node->type == 'theNameOfACustomContentTypeICreated'){
        foreach ($items as $delta => $item) {
          //I am ver unclear at this point, and this function does not seem to be called when creating new content.
        }
    }

```

**Attempt 2:**

```
myModule_nodeapi($node){
    //this function does not seem to be called when creating new content.
}

```

I am at a loss. Neither function is even getting called - nor working.

**Edit, the issue is resolved.** The correct start was hook\_jba\_node\_presave($node) , but I had syntax errors.

# Answer
A couple of pointers:

* Use only lower case for module names.
* `$node` is not available in `hook_field_presave()`. `$entity` should contain necessary info.
* `hook_nodeapi()` is not available in Drupal 7.
* It's possible you can make these alterations in your theme's `template.php` file as well.

You can use the devel module to help with debugging, e.g. `dpm($entity, '$entity contains')`.

Also see Module developer's guide and Drupal 7 API reference for more info.
> 1 votes

# Answer
Another way to achieve your goal of saving a value to a field without writing a custom module is to use the Computed Field module.

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.
> 1 votes

# Answer
Check the module creating guide for module names (applies to the names of your functions, too).
Then try to go through the hooks for nodes - just enter "hook\_node\_" into the search box @ api.drupal.org.
I guess one of these could be useful to you :

good luck :).
> 0 votes

---
Tags: 7
---


# Question
Title: empty ajax block not loaded on cached page
Drupal 6 user. I came across interesting problem: I would like to use ajax block on cached pages on my webshop. The block would display some products which other customers have bought along with products inside current customers cart. The tricky part is that this ajax block is initially empty, so after warming all pages in cache, this block is not rendered by drupal. Which means that ajax can not be working with this block.

My question is: how can I render the block even it is initially empty? The block is made in views, I tried to add attachment displaying some data, so there would be some content inside the block, but the block is not rendered anyway.

Thank you for help

# Answer
> 0 votes
My solution was to create a view where I displayed random node element (i.e. title) in a block and in the same view I attached the attachment display to the block, which contains the fields that should sit in ajax block. Finally I hid the block with css rule. This way the block get's rendered in theme.

---
Tags: views, blocks, ajax, ubercart
---


title: How do you style an individual webform?

text:
# Question
Title: How do you style an individual webform?
How to style individual webforms with different css class and html elements?I have a few webforms and I need different html elements like divs, spans etc and css class for each webforms

# Answer
> 2 votes
If you just need to apply CSS styling, then if you view the source of the webforms you will see they have container divs with classes that contain an ID number. This ID will allow you to directly target a specific webform.

If you mean you want to add your own divs etc. and template different webforms, then the best way to do this is by creating a specific template file for it.

In your theme folder you can add a template file such as: `webform-form-[nid].tpl.php` you can get the ID by viewing the source of your form, it displays in one of the forms parent divs.

As your base you can use the default template from the webforms module. Goto (or other location where you have installed the webforms module):

```
/sites/all/modules/webform/templates/webform-form.tpl.php

```

and make a copy of this.

I have themed webforms that appear in blocks in the following way too:

```
block--webform--client-block-112.tpl.php

```

# Answer
> 0 votes
For few changes drupal provide a class wrapper for each page node for example :

```
<body class="html front logged-in no-sidebars page-node page-node- page-node-109 page-type-page domain-ircam-mpmaroc-com i18n-fr lang-fr color-scheme-default corolla fs-medium bs-n bb-n mb-dd rc-6 rct-6 ia-r coffee-processed lightbox-processed admin-menu">

```

this is the class for the node 109 so in css you could use :

```
.page-node-109 input{}

```

and then for each web form you will use the .pane-node-(**node id**) to theme it **separatly**

But for big changes you must use the hook\_form\_alter

# Answer
> 0 votes
To modify each Webform separately you should use the forms css ID. The ID should always be unique.

For example, when you look at the source of your webform, you will notice in the `<form>` element, there will be an ID. For example `<form id='the_unique_id'>`.

I believe the ID should be something like `webform-client-form-<NODEID>`

You can then use your themes CSS file to modify the form.

Note that ID selectors start with # and not .

```
#the_unique_id {
   background-color: red;
}

```

---
Tags: 7, webforms
---


title: Use Pathauto with Image Name

text:
# Question
Title: Use Pathauto with Image Name
With **Drupal 7** I'm trying to use Pathauto to create aliases for images that we upload. The images are renamed with File Field Paths. An example of what I'm trying to do

**What I'm trying to do**

* Image content type
* Has an Image Field (CCK), field\_image
* Upload image with content type (example.jpg)
* example.jpg is renamed to Ax54jk.jpg (File Field Paths)
* mysite.com/node/523 is altered to mysite.com/Ax54jk (Pathauto)

I set a pattern for the Image content type of `[node:field_image]` which appears to yield *httpmysitecomsitesdefaultfilesAx54jkjpg*

So instead of creating *http://mysite.com/Ax54jk*, it creates *http://mysite.com/httpmysitecomsitesdefaultfilesAx54jkjpg*

While I was going for a unique URL, this is a bit more unique than I'd hope. Does anyone know how to accomplish what I'm looking to do?

# Answer
> 0 votes
The unfortunate answser is that Pathauto does its deed after File Field Paths. A custom solution will be needed.

---
Tags: 7, media, path-aliases
---


# Question
Title: what are the consequences of altering the users schema?
I was tasked with altering the signature/signature format and make the length larger than 255. Within the given time, I had to alter the table using hook\_schema\_alter, db\_change\_field and hook\_update. While I am aware this is semi hacking, I want to know what if this could have a huge consequence on my website.

# Answer
For your case, as you are just altering a field's length, without adding new fields, or new indexes, the only problem could be code that handles the same field, and which uses an hardcoded value for its length. That could be code executed from a third-party module, or a future version of Drupal.
For example, user\_validate\_name(), the function that is used to validate the username entered during the account registration, or when the user account is edited, uses the following code.

```
if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}

```

If a module alters the database field containing the username to make it bigger, Drupal would still throw an error when the username length is higher than `USERNAME_MAX_LENGTH` (actually 60, also in Drupal 8).

The reason why altering a database table defined from a module is not something suggested to do is that it would cause problems when more than one module do that for the same field. Imagine what would happen if a module increases the length of the signature field to 350, and another module changes it to 300.
The other problem is when the modules are uninstalled. Which size would the field get when one of the modules is uninstalled? If modules remember the size the field had before they were installed, there would be a problem when modules are uninstalled in an order that is different from the installation one. If modules restore the field size to the original one, that would cause a problem when only one module changing the field is uninstalled.

In the case a module adds a new field, there could be some performance issues if the module doesn't introduce an index. If the module introduces an index for the added field, there could be errors with the SQL queries used from the module that introduced the database table; if then those queries are not dynamic, it would not be possible for the module that added the field to alter them.
> 0 votes

---
Tags: entities, users, database
---


# Question
Title: Difference between views handler and views plugin?
What are the main differences between view handlers and view plugins?

I checked the documentations for view handlers and view plugins, but I find them quite similar.

Can anyone show me what a view handler can do that a view plugin cannot?

# Answer
The difference is summarized in the first sentence on About Views plugins:

> In Views, a plugin is a bit like a handler, but plugins are not directly responsible for building the query. Instead, they are objects that are used to display the view or make other modifications.

A view handler is implemented using a class derived from the views\_handler class, which has methods to build the query, or to alter the result obtained from a query, such as:

On the other hand, the views\_plugin class has only a method that is related to the query: views\_plugin::query().
> 6 votes

---
Tags: 7, views
---


title: Alter pagination start index

text:
# Question
Title: Alter pagination start index
Is it possible to make the pagination system numbering correspond to the page number you are on?

For example, instead of having /media-releases (page 1), /media-releases?page=0 (page 1), and /media-releases?page=1 (page 2) having /media-releases (page 1), /media-releases?page=1 (page 1), and /media-releases?page=2 (page 2).

This seems like a small change, but I believe an important one for usability.

# Answer
> 1 votes
You could do it by implementing hook\_url\_outbound\_alter(), and hook\_url\_inbound\_alter().

With the first hook, you alter the links that are being output from Drupal; you would increase the value of `$options['query']['page']`.
With the second hook, you alter the links being received from Drupal; you should find the `'?page='` string in the URL, and decrease the number after that string.

Keep in mind that `$_GET['page']` can be a string like `'1,2,4,5,6'` if the page has more than one pager. See the code of pager\_find\_page().

Also, `hook_url_outbound_alter()` receive the query parameters in `$options`, while `hook_url_inbound_alter()` receives just a string for the URL, which also contains the query part.

---
Tags: 7, hooks, paging
---


# Question
Title: Does Drupal's theme('table') works in email body?
I want to send the list of some of the node information in email to users.

I have created table of information using theme('table') function. Now I want to send this table to email to user.

Is it possible to send theme('table') using Email ?

Will it work when user will see the information in Email ?

I am sending table structure in Email, is this possible to achieve it?

I have attached the relevant code to generate table and send mail.

```
$header = array(
            array('data' => t('Title'), 'field' => 'n.title'),
            array('data' => t('Author'), 'field' => 'u.name'),
    );
    $query = db_select('node', 'n');
    $query->leftjoin('users', 'u', 'u.uid = n.uid');
    $query->fields('n',array('title', 'created', 'nid', 'type'))
    ->fields('u',array('name', 'uid'))
    ->fields('b',array('body_value'))
    ->fields('c',array('subject'));
    $query->condition(db_or()->condition('n.type', 'post', '=')->condition('n.type', 'forum', '='));
    $query->condition('n.uid', $user->uid, '=');
    $result = $query->execute();
    $rows = array();
    foreach ($result as $row) {
        if($row->subject) {
            $titlerow = l($row->subject, 'node/'. $row->nid).'</br>'. $row-
        }
        $rows[] = array( $titlerow,
                t('Reply Posted by: ').l($row->name, 'user/'. $row->uid)
        );
    }
    $params = theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('ajax-sample-table'))));
    $language = language_default();
    $send = TRUE;
    $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
    if ($result['result'] == TRUE) {
        drupal_set_message(t('Your message has been sent.'));
    }

```

# Answer
You can read drupal\_mail() in HTML for how to output HTML in an email sent with `drupal_mail()`.

As you are outputting links, I will add a note about that. By default l() outputs relative links that outside the website are not much useful. You need to force Drupal to output absolute links, for example using the following code.

```
if ($row->subject) {
  $titlerow = l($row->subject, "node/{$row->nid}", array('absolute' => TRUE)) . '</br>' // Your code here is not complete.
}
$rows[] = array(
  $titlerow,
  t('Reply posted by !user-link', array('!user-link' => l($row->name, "user/{$row->uid}", array('absolute' => TRUE))))
);

```

If you have the Devel module installed, you can see (using the following code) the difference between the output of your code, and mine.

```
print l('Test page', 'node/1') . "\n";
print l('Test page', 'node/1', array('absolute' => TRUE));

```

In my test site, what I get is the following.

```
<a href="/dr72/node/1">Test page</a>
<a href="http://tero.local/dr72/node/1">Test page</a>

```

As side note, remember that the `$options` parameter for `l()` can receive the same values the `$options` parameter for url() accepts.
> 2 votes

---
Tags: 7, emails
---


title: Get search to index meta tags keywords?

text:
# Question
Title: Get search to index meta tags keywords?
So I am using the Meta tags module and really would love if search would index the meta tag keywords of nodes. How would I go about this?

# Answer
I can't check it right now, but I guess the following should work:

1. For each content type (its meta tags you want to be indexed), go to "Manage display".
2. Add the "Search" display.
3. Add the metatag field to that display.

Assuming that the metatag module uses fields. If not, you'd have to create a dummy field (comment, if you need that explanation).
> 1 votes

---
Tags: 7, nodes, meta-tags
---


# Question
Title: Advice for reference the same image for several nodes?
I need to show the same image for a several nodes. I have uploaded the image to the server. But, I am not sure how to accomplish or reference this using the image field. Do you have any experience that you can share it? or any other way that I can do this?

# Answer
In my case the easiest was to do the following steps:

1. In content/media add the picture.
2. In your content type create a field type **File**. Save your content type.
3. When you add your new content, in your new field, use select media and choose the file that just upload it.

Note: If you delete the new content and there is no other content that reference that picture or file, the file will be deleted and you need to upload it again.

I created my content by using web services. So, I needed to do this programatically. The only I needed was the fid.

In my case I need to use services to create the content type, after testing you need the following and to tell if it should be displayed or not. This is the code in case anyone feels it is useful.

$node-\>field\_file\_name\_field \['und'\]\[0\]\['fid'\]='fid number';
$node-\>field\_file\_name\_field\['und'\]\[0\]\['display'\]='1';

If you feel there is a better way or another way to do this. It be great to hear it.
> 1 votes

---
Tags: nodes, media
---


# Question
Title: how to change teaser display output via views
I have a view that is displaying teasers of a content type. I would like to change order of one of the fields to come AFTER node links, any pointers?

Thanks.

# Answer
> 2 votes
Download and enable Display Suite module.

Then go to /admin/structure/types/manage/{content-type}/display/teaser and select layout of your choice.

Then add the links feature to the region of your choice

---
Tags: views
---


title: Adding workflow to files

text:
# Question
Title: Adding workflow to files
I'm working on a site that should let users to publish files (images), but I would to add a kind of workflow for these files. Is there a way? I was thinking to use private/public files, in this way:

* by default files are stored in "private" mode (so only certain users can see them)
* create a module that simulates a workflow that "publish" a file, moving it to the "public" mode

Could be a solution?

# Answer
The easiest way would be to create a content type called images, remove all the clutter and just add an image field. Since your images are now nodes, you can use any workflow module that you generally use. (Note you will have a overhead of one node for every image you upload)

If you don't want to follow the above approach then you can consider using rules and VBO module along with the the private folder options in image field settings.
> 1 votes

# Answer
Im not sure how you will tie this into like user roles or what your business logic is.

Here are some ideas / resources:

* MediaMover module -- can add abitrary workflows to files. The examples are transcoding files, but its likely it could attach remove files to a public/privately made node for content viewing or sharing.
* File Entity for D7, files are entities in D7.... woo!
* Relation ACL, Relation is a module to add "relations" to entities. Relation ACL creates access logic to the given entity.
* Encrypted Stream Wrapper or Encrypted Local Stream Wrapper, setups up a private filesystem URI and uploads files to that location. Allowed users can stream a de-crypted copy of the file to the enduser, files are stored encrypted on the filesystem.
* Private Dynamic File Stream, store file entities of a certain type in a private filesytem and stream them as neccesary.

From your brief question I think you want to look at file\_entity and either media mover or relation\_acl.
> 1 votes

---
Tags: 7, media, workflows
---


# Question
Title: How to substitute values on a page, without PHP?
There are certain values that are liable to appear in many places on my site (corporate-owned stores, independent stores, # of brands carried, and so forth) that content authors and editors are not likely to keep up-to-date very well on every single page in which they appear.

I can put them in variables in (e.g.) settings.php, and then put PHP snippets in any nodes that need to use them, but that has obvious downsides:

1. content authors cannot update the values when they change
2. content authors cannot edit the text that contains the PHP snippets
3. unless of course I give them permission to do that, but that's probably not a great idea

I'm currently experimenting with using the Token Filter module to allow putting tokens like `[node:field_corporate_stores]` in content fields in a node. This works just fine if that field is on the node that also has the body content in which it is being replaced. But of course that would defeat the purpose: I want ***one*** node that contains the values, and to be able to use an indefinite number of other nodes that will consume the values. But I don't see how to do that.

How do I define `data_node` for a token like `[data_node:field_corporate_stores]`??? (Without using any PHP snippets in the node.)

# Answer
> 1 votes
The Custom Tokens module seems to be a nearly perfect solution for this.

In its favor, it provides an administrative interface that is easy for my content editor to use (something that requires dealing with regular expressions would likely confuse her, even if it is a more powerful, more general-purpose tool). Being easy for my content editor to use is very important, as she may identify more and more values over time that are good candidates for replacing tokens, so that they can be centrally managed and kept up-to-date.

On the downside it limits me to a particular syntax for the tokens, such as `[custom:my-token-name-here]`. It would be nice if I could in the very least use underscores instead of hyphens. It would be even better if I could use something like `{{my_token_name_here}}`, but that's not a big deal. All in all a good module to have in your bag of tricks.

# Answer
> 1 votes
This is even more new than Beta, but look at the Sandwich module that looks like most of its configuration is in 1 place (across all nodes of X type for instance).

The module sits at ~400 lines of code and has it looks like 2 small example usage modules/themes.

**EDIT:** to be clear this goes off custom markup I believe like, MY\_CUSTOM\_VALUE, in a body field of a node which would regex out to be whatever value you implement in a module. With page caching turned on shouldnt be a huge hit. You keep your "values" in code and dont depend on the Token module.

# Answer
> 1 votes
I would take a look at the Custom Filter module. I looked at it a year or so ago but decided to roll my own, but from memory, it allows you to specify your own systemwide token substitutions.

# Answer
> 0 votes
You can have a admin form which will capture all these values and store it in the variables table. Then you can use Token Var module to use those values as tokens.

Note : Currently it supports only non array values, but it can easily be extended to support the arrays too.

---
Tags: tokens
---


# Question
Title: Better Exposed Filters and a Node Relationship
I'm using Better Exposed Filters to enable datepickers for exposed date fields on my View. It's great, except that my view displays nodes via a taxonomy relationship. If I try to filter by node creation date, I don't get any Better Exposed Filters options. However, if I choose a date field that doesn't use a relationship (even if it doesn't exist on the term and therefore doesn't work), I get all the Better Exposed Filters options.

How can I best go about putting a popup datepicker on my exposed filter that uses a relationship?

# Answer
> 0 votes
I don't think this is related to the relationships. It looks like Drupal core date fields (post, changed, etc.) are not getting the proper BEF options, namely the datepicker. That's a bug in BEF -- it was mentioned at the end of this issue, but I never saw that because that issue is closed. Feel free to post a bug in the BEF issue queue for this.

Thanks.

---
Tags: views
---


title: Ajax field in products page

text:
# Question
Title: Ajax field in products page
I have downloaded the Commerce Kickstart distro. In the product page there is a quantity field which you can use to enter your custom value; I want to display the total cost of current product in AJAX. Is it possible?

# Answer
There is no such default functionality in drupal commerce.

Commerce Cart Ajax

This module will ajaxify your cart page. If you need this in product detail page then you can build a custom module for that with Ajax Api in Drupal 7
> 0 votes

---
Tags: commerce
---


title: Is there a secure mongodb wrapper?

text:
# Question
Title: Is there a secure mongodb wrapper?
I was looking into MongoDB module, but found it very verbose and overly complicated to perform simple DB operations and this module seems to be tightly integrated with Drupal entities.

Is there any other Drupal-PDO wrapper for Mongodb that is easy, secure (NO SQL injection free) for simple DB operations in Drupal?

Thanks for your time.

# Answer
> 1 votes
As far as I can see, there isn't any PDO wrapper for MongoDB, and there isn't any code that allows to use MongoDB as database for Drupal, simply for the fact Drupal expects to use an SQL database engine, while MongoDB is not an SQL database. You cannot generally convert a static query into code that uses MongoDB.

The Mongodb module allows you to use MongoDB in those cases where Drupal is not expecting to get data from a database, although the default implementation uses database table. That is what happens for the cache, entity fields, and Drupal queue, for which a module can define a new PHP class to implement a different mechanism to store data.

Notice that the Mongodb module is not tightly integrated with Drupal entities, as it doesn't use any Drupal entity to work. It eventually allows you to store field data in Mongodb, but that is an additional module you can eventually use. If you are not interested to store field data in MongoDB, the main module (mongodb.module) still works, and can be used from the other sub-modules.

# Answer
> 1 votes
First, NOSQL injection, as such doesn't exist. Second, the MongoDB project allows you to plug in higher level systems where such pluggability is available. Third, the mongodb\_dbtng project is a proof of concept but it's bereft of problems and it won't go anywhere. Fourth, Drupal 8 will support MongoDB much better but still not in a way that you can write PDO-like code against MongoDB.

---
Tags: database
---


# Question
Title: Can't access to password input on registration form
I have a problem. I can't access through module to password field on registration page.

```
function customization_form_user_register_form_alter(&$form, &$form_state, $form_id) {
$form['account']['pass']['#id'] = 'userRegInput';
}

```

It wont change id of input. I don't know why...

Thank you!

EDIT: Btw. i have installed user\_registrationpassword module, maybe is because of that...

# Answer
You can access the password form field in the registration form, but the ID you are setting is not used.

When a password\_confirm form field is being added to a form, Drupal is really adding two password form field with a process function (form\_process\_password\_confirm()); that function doesn't use the ID set for the password\_confirm field for the new fields.
There isn't a theme function for the password\_confirm form field, which means that the following code (executed from theme\_password(), and theme functions for other form fields) is not executed.

```
element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
_form_set_class($element, array('form-text'));

```

What you can do is to wrap the password\_confirm form field with a `<div>` tag to which you assign your ID.

```
$form['account']['pass']['#prefix'] = '<div id="userRegInput">';
$form['account']['pass']['#suffix'] = '</div>';

```

If you are using the CSS ID to execute JavaScript code, or to style the field, keep in mind that the default output for the password\_confirm field (for the form field you are interested) is the following one.

```
<div class="form-item form-type-password-confirm form-item-pass">
  <div class="form-item form-type-password form-item-pass-pass1 password-parent">
    <div class="password-strength">
      <div class="password-strength-text" aria-live="assertive"></div>
      <div class="password-strength-title">Password strength:</div>
      <div class="password-indicator">
        <div class="indicator"></div>
      </div>
    </div>
    <label for="edit-pass-pass1">Password <span class="form-required" title="This field is required.">*</span></label>
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">
  </div>
  <div class="form-item form-type-password form-item-pass-pass2 confirm-parent">
    <div class="password-confirm">Passwords match: <span></span></div>
    <label for="edit-pass-pass2">Confirm password <span class="form-required" title="This field is required.">*</span></label>
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">
  </div>
  <div class="password-suggestions description" style="display: none; "></div>
  <div class="description">Provide a password for the new account in both fields.</div>
</div>

```

The HTML output includes also the output from the JavaScript code that outputs the password strength.

As alternative, you can add a process function that is executed after the process functions normally used by Drupal.

```
$form['account']['pass']['#process'] = array('form_process_password_confirm', 'mymodule_process_password_confirm', 'user_form_process_password_confirm');

```

Use form\_process\_password\_confirm() as guideline for the code you should write.

```
function form_process_password_confirm($element) {
  $element['pass1'] =  array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-field')),
  );
  $element['pass2'] =  array(
    '#type' => 'password',
    '#title' => t('Confirm password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-confirm')),
  );
  $element['#element_validate'] = array('password_confirm_validate');
  $element['#tree'] = TRUE;

  if (isset($element['#size'])) {
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  }

  return $element;
}

```

user\_form\_process\_password\_confirm() just adds the JavaScript code to handle the password strength, and any messages about the used password (e.g. *Make it at least 6 characters*, *Make it different from your username*).

I tried using the following code in my test site, and the output for the password field didn't change.

```
function code_testing_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#attributes'] = array('id' => array('userRegInput'));
}

```

The ID is not being added to the form field.

```
<div class="form-item form-type-password-confirm form-item-pass">
  <div class="form-item form-type-password form-item-pass-pass1 password-parent">
    <div class="password-strength">
      <div class="password-strength-text" aria-live="assertive"></div>
      <div class="password-strength-title">Password strength:</div>
      <div class="password-indicator">
         <div class="indicator"></div>
      </div>
    </div>
    <label for="edit-pass-pass1">Password <span class="form-required" title="This field is required.">*</span></label>
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">
  </div>
  <div class="form-item form-type-password form-item-pass-pass2 confirm-parent">
    <div class="password-confirm">Passwords match: <span></span></div>
    <label for="edit-pass-pass2">Confirm password <span class="form-required" title="This field is required.">*</span></label>
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">
  </div>
  <div class="password-suggestions description" style="display: none; "></div>
  <div class="description">Provide a password for the new account in both fields.</div>
</div>

```
> 1 votes

# Answer
Try this:

```
$form['account']['pass']['#attributes'] = array('id' => array('userRegInput'));

```

IDs and classes must be passed in as arrays in the '#attributes' form API property for a form item.

Note that Drupal automatically adds an ID of `edit-[field_name]` on all form inputs, so you'll be overriding that generated ID. I'd recommend setting a class instead, in most circumstances, unless you have good reason for using an ID.
> 0 votes

---
Tags: users
---


title: Using menu tab for each panel variant

text:
# Question
Title: Using menu tab for each panel variant
I'm trying to use Panels to arrange content on my site. I've made some strides in creating a panel that displays a view of images based on different criteria.

I added a page (panel) which allows me to tap into Drupal's menu system and make a tab called Photos. Now I want to add a number of variants to this panel, and I want links to those variants to show up in the sub-tab (MENU\_DEFAULT\_LOCAL\_TASK). Since there does not seem to be any way to add a menu item for each variant, I'm wondering what is the best way to do this.

I see two possibilities, both of which don't seem ideal:

* I could write a module, that adds the default local tasks to the menu item.
* I could add a separate panel page for each variant, and use the menus there.

It seems like there should be an easy solution to this. Can anyone help me?

# Answer
> 6 votes
I sort of figured out a way to do this.

1. Add a variant within the Panels module
2. Add a visibility rule so that different variants show at different URLs (clean URLs and paths required), for example, example.com/paneltitle/variant1, example.com/paneltitle/variant2.
3. Create a custom module to hook into the menu. There is a great example of a menu module in the module code samples on drupal.org. A example here for above variants:

\`

```
function custom_module_menu() {
  $items['paneltitle/variant1'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['paneltitle/variant2'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

This seems to have worked for me.

# Answer
> 2 votes
You can use the Views module to implement this feature.

Using Views, you can set sub menu task also.

# Answer
> 0 votes
@user379468, could you share your code? I cannot seem to implement the page callback in hook\_menu() properly (step 3. in your answer).

---
Tags: panels, routes
---


# Question
Title: Large var_dump when looking at $variables
This might not be the correct place to ask this question, please remove if it is wrong...

But, when I do a var\_dump($variables) in one of my nodes I get a very large output that repeats several times... Is this just the way Drupal normally acts or might this indicate that there is something wrong with my site?

Thanks

# Answer
Yes, it is normal as Drupal pass enormous amount of data trough functions and hooks using array. But for better answer you should provide more information.
> 1 votes

---
Tags: theming
---


# Question
Title: WYSIWYG edit view of text is below image in content but node view isnt.
In my WYSIWYG edit view ive hit return to make some text apear below an image in the content. However when I save the text is alongside the image, half way down but below.

Why does the edit and node view look different? How can I solve this? Thanks

# Answer
It is quite possible that the text format with which your field is being displayed is restrictive i.e. it only allows a subset of HTML tags.

I'm going to assume that you are talking about the *Body* field or more generally a text field attached to a Content type.

1. Ensure the `field_ui` module is enabled and go to the *Manage display* page for your content type. For the field in question, check if the formatter says *Default*.
2. Now, go to *Administration \> Configuration \> Content Authoring \> Text formats* and inspect the first text format in the list.

If you are going to view as a different user, remember that Text formats are linked to permissions and an user's default text format is the first from the list in 2. *that he has access to* use.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: adding a grid with specific class in adaptivetheme
I'm trying omega and adaptivetheme to use responsive webdesign. On omega that uses 960grid, I can add a "grid-X" class to an html element to display it in the grid, with the right width etc. Is there a way to do the same thing with adaptivetheme?

# Answer
> 1 votes
AT does not use Grid classes embedded in markup (it does not use grid classes at all).

If you are asking this I assume you do not really understand how this theme works - you use the layout system (in theme settings, for the main container/page and panels layouts) and write content/element specific CSS yourself, aka use a semantic grid approach.

Grid classes in markup are a huge limitation - what seems so easy now, turns quickly into a massive roadblock later on.

answer by author of adaptivetheme http://drupal.org/node/1861948

---
Tags: theming
---


title: Varnish cache not region aware

text:
# Question
Title: Varnish cache not region aware
We have a Drupal 7 site whose content is split into geographic regions. The concept is that page view blocks and filters will display region specific content based on the users IP address or selection of their country, the page URL is the same throughout. The issue we now have is that Drupal cache and Varnish cache are not regionally aware in that the cache is built up by the first visit upon start and clearing of cache so the wrong content gets displayed to a user who wishes to view content for his region, because someone before him opened the same page from another region. Any ideas?

# Answer
Possible solution of separating your caches, by regions, in Varnish is to use GeoIP VMOD: https://github.com/lampeh/libvmod-geoip

Simple example:

put country code to hash

```
sub vcl_hash {
        hash_data(req.url);

        if (req.http.host) {
                hash_data(req.http.host);
        }
        else {
                hash_data(server.ip);
        }

        # separate caches by countries
        hash_data(geoip.client_country_code());

        return (hash);
}

```

Now caches for different countries will be different. Of course, you still need to take care about page generation in Drupal, it should provide different content for different regions too.
> 2 votes

---
Tags: proxies
---


# Question
Title: Locked out of my local site after transfer
I put an old site on my new machine and got it up and running, except for clean URLs. The login creds in my notes didn't work so (after a few attempts) I used mysql via drush to change the password, no dice. I also checked to be sure I had the correct user1 name and it is. Though all this, the account got blocked because of all the login attempts, which I also tried to remedy via drush, however it alert still says the account is blocked and I still can't login. I don't know where to go from here.... please help.

# Answer
well you can first

```
drush upwd --password="yourNewPassword" UserName

```

to reset your password.

then you would need to remove the attempts so you can try to login again, you need to truncate the table flood.

```
TRUNCATE TABLE flood

```
> 2 votes

---
Tags: drush
---


title: Question about drupal_add_js

text:
# Question
Title: Question about drupal_add_js
I used `drupal_add_js()` to add a jquery plugin, but there is an error `TypeError: $ is undefined` at console of firebug. So how should I add the js?

# Answer
I think you'd find this article in the Drupal documentation relevant and helpful.

The solution is to wrap your custom Javascript code within a closure as shown below:

```
(function($) {
  // Your Javascript code goes here
})(jQuery);

```

Javascript files from all Drupal core modules follow this convention. So, you can look them up for reference.

I'm not really sure but either before/after some version of jQuery, the `$` was a global alias for the jQuery object itself and could be used directly without the closure but was later removed as it conflicted with other libraries.
> 2 votes

---
Tags: javascript
---


title: Creating a job system in Drupal 7

text:
# Question
Title: Creating a job system in Drupal 7
I want to create a job system in drupal 7 with the following workflow.

1. Administrator can add the jobs.
2. A for jobs listing.
3. On detail job there should a link of apply for this job.
4. The form will contain the fields and upload application form.
5. The back end must have trackers such as Response received at, action trackers: 'Candidate contacted, Candidate data transferred to HR', Vacany filled.

I have tried it with the views and the webform module.

Created a view for job listing. and use webform for apply form. But what should I do with the trackers in point 5. I have no idea about this.

Please guide me in this situation or any module for this requirement which should use?

# Answer
There are various distributions available in Drupal.org

You can check it out Drupal jobs and Recruiter. both are well maintained.

Take these distributions as base and develop your project. They almost support all of your usecases.
> 2 votes

---
Tags: 7
---


title: Poll in two languages

text:
# Question
Title: Poll in two languages
I've installed Poll Core module in Drupal 7 trying to display the same poll with the same result in two languages (English and Arabic) but Drupal treats each one as a separate poll with different result ...

How could I do this?

Is there any other module can handle this?

I've tried Advanced Poll but I cannot use it I do not know how?

# Answer
> 1 votes
I've solved my problem as follows:

1. Download the i18n patch from here
2. Apply the patch using any preferred technique, you can refer to Drupal
3. Applying should be on a test drupal installation in order to avoid any problems
4. After that go to modules page and enable the Poll Aggregate module under i18n, this will synch the voting results for all installed languages
5. After testing the patched module and getting happy result, install the module on your live site.

I have test this solution and it is OK with some small problems that I am trying to solve, and I will share the new things.

---
Tags: 7, i18n-l10n, polls
---