# Question
Title: What is a one line mysql query that can update all body fields of matched nodes?
I am trying to do a bulk node update that affects 100+ nodes. I want to set each of these node's body field to a specific string. Say I want to affect all content types: "basic page".

Since my sql skills aren't up to par with join statements. I only got this far:

```
UPDATE field_data_body SET body_value = 'This is my string.' WHERE type = "basic_page" left join node;

```

# Answer
In drupal 7 it is a bit simpler. You don't need the join.

```
UPDATE field_data_body
   SET body_value = 'This is my string.'
 WHERE entity_type = 'node'
   AND bundle = 'basic_page';

```

You must clear the drupal cache after updating content directly in the database.

Also, if you are using revisions, note that you have just changed the latest revision without creating a new revision. This may not matter to you but it's worth noting.
> 3 votes

---
Tags: 7, nodes, database
---


# Question
Title: How can I create a Views field template per display?
I successfully could create a template file for views field after reading this page.

https://api.drupal.org/api/views/theme!theme.inc/group/views\_templates/6

However `views-view-fields--myviewsname.tpl.php` override all the displays in "`myviewsname`"

Is there any way I can make a template that overrides just one display in a View?

For example, a template that overrides just "`display-1`" in "`myviewsname`"

# Answer
`views-view-fields--myviewsname--display-1.tpl.php` will do it, eg, `views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php`. (Along with changing any underscores in the names to single dashes)

On the api page you reference, you can see this in their example as the display mentioned there is called `page`.

These and other template names can be easily discerned from clicking on the Theme Information link in the Style Settings in the Views UI.
> 2 votes

---
Tags: views, 6, theming
---


# Question
Title: How do I programmatically create a view?
There is a set of products in Drupal Commerce. How do I programmatically create a view that would select products for a particular field?

# Answer
The classic way is to create it manually, via UI, then click "export" (path like http://example.org/admin/structure/views/view/default\_demo/export), and wrap resulting code into a module using hook\_views\_default\_views(), maybe fine-tuning details.
> 4 votes

---
Tags: 7, views
---


# Question
Title: How to use group audience in drupal 7 views filters
How to use the Group audience field in our drupal 7 views filter. I have to fetch the values for the appropriate groups node. So i want to add the group audience field in the views filter. By default the filter having the fields of Groups audience (group\_audience:gid), Groups audience(group\_audience:delta) likewise. Please suggest me some ideas how to fetch the values based on the group audience field in the views filter.

Thanks, Sathish

# Answer
> 1 votes
Please check the screenshot.Basically you need to add a relationship as in screenshot.

# Answer
> 1 votes
First You need to add a relationship in view, for that follow the below procedure.. 1. Click on Advanced button which is on right hand side. 2. Click on Add a relationship. 3. search for the og from node and add it.

Here it is done. Now, Add the filter criteria, it will available in this. :)

---
Tags: organic-groups
---


title: Retrieve deleted Heartbeat activity

text:
# Question
Title: Retrieve deleted Heartbeat activity
I am using D7 + Hearbeat module

Previously my heartbeat setting was when cron runs delete activities older than a month. So a cron run removed the activities.

Is there any way of retrieving the deleted heartbeat activities?

# Answer
> 2 votes
I don't think so because data was deleted from database. If u have old copy of database, then here you can do something, Create an other database and import that old database into it. and Fetch the required tables(means required rows and column) and dump into your current database.

---
Tags: heartbeat
---


# Question
Title: Drupal 7, Faceted results from Search Form
I hope this is not a duplicate of something as I've been searching for hours and I'm pretty confused.

So what I need to do is to have a Search Form/Block like the one the core uses (I've already themed it so if I can use the same one would be splendid, if not, no problem), who's results will be organized in a faceted sort of way kinda like this:

```
Results:
All(100)
Cakes(43)
Wrappings(12)
Random Stuff(25)
Misc(25)

```

Cakes, Wrappings, Random Stuff and Misc would be Content Types, and clicking on them (links) should display in a view next to them the appropriate results (as thumbnails).

Since my Content isn't *that* much I'd like to avoid Solr if possible.

Any hints?

EDIT: In case this wasn't clear, the results are yielded according to given keywords, I don't want a simple sitemap.

# Answer
Check out these tutorials for faceted / "drill-down" / filtering searching and browsing navigation without the need for solr.

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/ (really good tutorial and this worked for me but for me the URLs need to be made more user friendly, not covered by this tutorial admittedly)

http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages and http://webwash.net/tutorials/intro-search-api-part-2-faceted-search (similar to the first tutorial)

They use the Database Search module: https://drupal.org/project/search\_api\_db but the settings can be modified later to use SOLR for when your site hits the big time and needs the sophistication and scalability that SOLR provides. But for now, database search gets you going without needing SOLR.

For pretty URLs check out module: https://drupal.org/project/facetapi\_pretty\_paths \- this module aims to make your URLs generated by the faceted filtering and search pretty.

The drupal recruiter distribution is an example of using facetapi\_pretty\_paths : https://drupal.org/project/recruiter \- on this page you'll find more information including how to run a demo via simplytest.me with just a few clicks!

Myself I will be working out how to use facetapi\_pretty\_paths in my project and any steps I that work I will follow up on here (not an empty promise as I do write up my findings whenever I can)
> 1 votes

---
Tags: 7, search
---


title: Drupal 7 Site: Targeted for spam

text:
# Question
Title: Drupal 7 Site: Targeted for spam
Okay, I'm not sure if this question should be here, but it's more of a general question. So I'm hoping if anyone can relate to this, perhaps you can suggest something to get around this. So I worked on this particular site. Using drupal 7. It's a kind of article site and content is about anything out there, nothing specific, it's more on the fun side. Since we've allowed sign ups, we've been getting a lot of sign ups of users, but most of them seem to be a group of spammers or trolls. No matter how much I try to contain it, they just keep coming and sign up. I have enabled captcha to prevent bot signups, as well as on the commenting sections so we don't get tons of spam more than we can handle. I also enabled sign up approval so I could see who signed up, and for sure everyone of them have tell tale signs of spammers. Imagine usernames that don't make sense. Randomly generated or whatever. Should we ban the ips, or the email domain names? No room for just one question, it may be all general but it concerns the whole site in itself. Not sure what the work around is, but I sure appreciate any suggestions from those who got around this. Thanks. Cheers.

# Answer
One module you can make use of in this situation is the honeypot module. The Honeypot method basically inserts a hidden form field to Drupal (or other). End users don't see the field, so they don't fill it out. But spam bots (usually using prewritten scripts) do see the field, and always fill it. The Honeypot module detects this and blocks the form submission if there's something in the field.

**EXTRA OPTIONS YOU COULD ADD**

Another Simple thing you can do according to this site is hooking into the Drupal user registration process and using a php snippet like this:

```
flood_register_event('reg');
if (!flood_is_allowed('reg', 4)) {
header ('HTTP/1.1 403 Forbidden');
die();
}

```

Using the flood\_register\_event() method to register a possible flood event. The method records every registration when used in this context. Next, using the flood\_is\_allowed() check if the current user has triggered the flood register event more than 4 or XX times. If the user has tried to access the form 4 times they get another lovely 403 and all output is killed. You could use this logic either when rendering the Drupal registration page or upon every new submission.
> 1 votes

---
Tags: advertising, users
---


title: Block Permission for user

text:
# Question
Title: Block Permission for user
I have faced a new problem, here I have poll block which is already displayed for administrator or user who has the permission of "view published content". When I made another user and give the complete permission for the poll but does not giver the permission of "view published content", it is not displayed for the user. Can any one help me to show that in the block for user except administer or user who has the permission of "view published content".

cheers

# Answer
> 0 votes
You want to be looking at the permission "vote on polls" that is the one you want to enable for that user.

---
Tags: users
---


title: Drupal JQuery Issue - Need some help

text:
# Question
Title: Drupal JQuery Issue - Need some help
I have the following scriptthat runs on $(document).ready where the script alter some form elements such as radio buttons.

When the form is updated via JQuery ,the script is not run.

I need the script to alter radio buttons after successful AND unsuccessful form submissions.

Here is a link to my test site:http://test2.bratpaks.co.za/home

```
    (function($) {
      Drupal.behaviors.icheck = {
        attach: function (context, settings) {
          $('input[type=radio]', context).each(function(){
          var label = $(this).next(),
          var label_text = label.text();
          label.remove();
            $(this).iCheck({
            checkboxClass: 'icheckbox_line-realred',
            radioClass: 'iradio_line-realred',
            insert: '<div class="icheck_line-icon"></div>' + label_text
            });
          });
         }
       };
     })(jQuery);

```

# Answer
> 4 votes
You should never use simple document ready in Drupal.

Drupal Behaviors was created specifically to address issues like yours. Nice entry manual can be found here.

Quick example:

```
(function($) {
  Drupal.behaviors.yourmodule = {
    attach: function (context, settings) {
      // your code here
    }
  };
})(jQuery);

```

In your code, remember to use context, like `$('input[type=radio]')` should become `$('input[type=radio]', context)`

---
Tags: javascript
---


# Question
Title: Multi-site variables table for shared variables (extending variable_set)
I have a multi-site setup with some shared tables using db\_prefix. The variables table is NOT shared. Sharing ALL variables would cause lot of trouble, but sharing only some selected variables wont.

The picture below visualizes my problem:

The entries in the green box are shared and available on all multi-sites. Whereas the selected entry information is part of the config and stored in variables. Changes in the red box are not shared and lead to inconsistency when changed on one multi-site.

At the moment I use "drush @sites variable-set ..." to make consistent changes on all multi-sites. But to keep it more simple, I want to integrate it into Drupal's backend.

I found out that there was a failed patch request already. See issue here. The patch modifies variable\_get() and variable\_set() with an extended query-statement, if a defined variable is set in an array. I am aware of the fact, that the patch is for drupal 5, but it could be easily adapted to drupal 7.

The workaround in the patch modifies the core, but i cannot touch it. Overwriting variable\_get() functionality is quite an easy job. You just have to hook\_boot() or hook\_init() and replace the desired values in $conf array with your custom values.

**Whats the deal?**

I need to extend variable\_set() and variable\_del() functionality without touching core. Any ideas how i get into that?

# Answer
As pointed out by Mołot trying to get variable\_set to write into a different database would be complicated - it may be achievable by implementing your own database adapter, but there are simpler alternatives.

After some thoughts I realised that while Drupal did not offer a way to hook into the changes made by variable\_set, PHP itself did.

This relies on the fact variable\_get, variable\_set and variable\_del all use a global variable (on top of the database) to store the variable values - $conf. Whenever a value is read, added, changed or removed from the variables, the global $conf is modified accordingly. A solution would be to replace the $conf global variable by a custom object that implements ArrayAccess. This way you could monitor every time $conf is accessed or modified. Here is an example:

```
class MyGlobalConf implements ArrayAccess{
  private $conf;

  function __construct($conf = array()) {
    $this->conf = $conf;
    $this->loadMySharedVariables();
  }
  public function offsetExists($offset) {
    return isset($this->conf[$offset]);
  }
  public function offsetGet($offset) {
    return $this->conf[$offset];
  }
  public function offetSet($offset, $value) {
    if ($this->isASharedVariable($offset)) {
      $this->saveSharedVariable($offset, $value);
    }
    $this->conf[$offset] = $value;
  }
  public function offsetUnset($offset) {
    if ($this->isASharedVariable($offset)) {
      $this->unsetSharedVariable($offset);
    }
    unset($this->conf[$offset]);
  }
  private function loadMySharedVariables() {
    // Populate $this->conf with the shared variables
  }
  private function isASharedVariable($offset){
    // Return TRUE if $offset is a shared variable
  }
  private function saveSharedVariable($offset, $value) {
    // Save the shared variable
  }
  private function unsetSharedVariable($offset, $value) {
    // Unset the shared variable
  }

}

```

Then in settings.php you could replace $conf with your own:

```
$conf = new MyGlobalConf($conf);

```

While I like the creativity of this approach, I fear the performance impact would be noticeable. So if I was to implement a solution to this problem, I would probably try to synchronize the variables rather than share them.

You could do this, for instance, by implementing hook\_exit :

```
function mymodule_exit($destination = NULL) {
  global $conf;
  // The variables to share
  $shared_vars = array('shared_var_1', 'shared_var_2');
  // The table prefix for each of the site we want to share with.
  $all_prefix = array('myprefix_1', 'myprefix_2');
  // Synchronize...
  foreach ($shared_vars as $var) {
    foreach ($all_prefix as $prefix) {
      $table_name = $prefix . "variable";
      db_query("
        UPDATE $table_name
        SET value = :value
        WHERE name = :name
      ", array(
        ':value' => serialize($conf[$var]),
        ':name' => $var
      ));
    }
  }
}

```

This should probably be improved:

* If only logged in users could cause variables to be changed, then add a test to not do anything for anonymous users:

`global $user;
 if ($user->uid == 0) {return;}`
* Cache the shared variables in `hook_boot`, so that you only update them when they change.
> 1 votes

# Answer
## Reading is possible, but may be costly

Code for variable\_get() is:

```
function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

```

So you need to set:

```
global $conf;
$conf['shared_variable'] = your_function_to_obtain('shared_variable');

```

### Where to put it?

If your function uses other site variables, including ones provided via UI, best place seems to be a hook\_boot(). You need to make sure your `hook_boot()` is called first. To get your module to run first, use hook\_module\_implements\_alter() or easier and less reliable way - Modules weight module.

If you don't use any values provided via UI, you can (maybe should) put it in `settings.php` instead. You don't need to use `global` in `settings.php`.

## Writing is way more trickier

Code for `variable set()` is:

```
function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}

```

As you can see, there are no hook calls, nothing. It just saves data altogether. `variable_del()` shares that problem.

What you can do is to override very forms, providing your own save handler that will copy data to shared table. This will not solve the issue of saves and deletes outside form submits, if they happen in module in question. Other approach would be to use triggers directly in RDBMS to synchronize tables - more reliable, but harder to maintain.

### Advanced PHP debugger

A bit hardcore approach is to override built-in functions. Yes, you can do it without touching core.

You need PECL apd \>= 0.2

In your settings.php (or in your module's \*.inc, but include in settings.php) implement override\_function($function\_name, $function\_args, $function\_code) for `variable_del` and `variable_set`. **Do not** attempt this for reads, unless you want huge performance hit.
> 1 votes

---
Tags: 7, hooks, multi-sites, configuration
---


# Question
Title: block_admin_display_form_submit not getting called
I am having trouble saving my block regions(admin/structure/blocks).

**Problem:** I am doing my thing on block admin page, saving blocks, moving them around and what not. but the changes i make are not being saved.

**What i found:** after some debugging efforts, i figure out that the function \*block\_admin\_display\_form\_submit\* is not called when the block form submits.

the site i am having problem is on a lamp server somewhere. i have another copy of this site on my local machine, which has no problem saving block regions.

any idea on how to fix this? thank you.

# Answer
> 0 votes
I'm having the same issue, I cannot call function block\_admin\_display\_form\_submit($form, &$form\_state).

I've set a custom variable that should be updated if I change block region.

Everything works if I do it from the block edit page(admin/structure/block/manage/menu\_block/ID/configure), but if I try to do it in the block admin display form (admin/structure/block), It will not work.

I've tried to increase max\_input\_vars with no success.

Have you solved it?

---
Tags: 7, blocks
---


# Question
Title: How do I create slideshows for Youtube videos?
Like this website, I want to make a slideshow of you tube videos as done in LATEST VIDEOS section.

In order to achieve this:

1. I created a **view of content type Video** (in my case), added the field which has the **video in the field's section**.
2. To have the same videos as **pager**, I added the **video field in the pager**. But there is no option to **resize the video** to a smaller size so that it can be used as a pager.
3. And lastly, videos are also not getting displayed as expected in case of **"SLIDESHOW"** formatter, **vertical** list of videos is getting displayed.

# Answer
Follow these steps

1. Install and enable these four modules:\[

CTools
Views
Views Slideshow
Libraries

You're also going to need a single file that contains a JQuery slideshow script. This will need to be uploaded manually.

Visit link Click the Download the Cycle Plugin link. It's hard to spot so i had highlighted it on the image below:

Download the file which will be called jquery.cycle.all.js Access your site files. Browse to the /sites/all/ folder. Create a folder called /libraries/ so that the path is /sites/all/libraries/ Create a folder called /jquery.cycle/ so that the path is /sites/all/libraries//jquery.cycle/ Upload the jquery.cycle.all.js file into that last folder.

Step 2: Views

We're going to create our slideshow using Views.

Go to Structure \> Views \> Add new view. Check Create a block Choose Slideshow for the Display format Choose 1 for the Items per page

Click Add. Select video. Click Apply (All displays).

Check the box which says Exclude from display. Click Apply (All displays).

Find the Format area on the left-hand side of the Views page. Click Settings next to Slideshow.

Scroll down to the cycle options. Click Apply (All displays).
> 1 votes

---
Tags: views
---


# Question
Title: What to do if you don't want to load JS files on mobile devices
What to do if you don't want to load JS files on mobile devices? Let's say, the navigation of a website uses javascript (dropdown for example), and that Javascript is loaded within the .info file

Example of the .info file of an Omega Subtheme

```
scripts[0] = 'js/navigation.js'
scripts[1] = 'js/hoverintent.js'
scripts[2] = 'js/jquery.fancybox.pack.js'

```

Let's say, I don't want to load scripts\[0\] on mobile. What would be the easiest solution for this?

# Answer
> 3 votes
The easiest (probably only realistic) way would be to create a second, javascript-less theme, and use the ThemeKey module to show that theme to mobile users based on user agent string. It's not exactly a foolproof method but then device-sniffing never is.

The other option would be to write some javascript which responds to the Omega media query change event, and hooks/unhooks all other javascript events on the page based on the current device size. I can imagine that being very difficult to manage though.

The proper solution would be to design the theme in a mobile-first manner, building up the javascript functionality as you go and managing how it reacts to different breakpoints at an earlier stage.

Removing all javascript for mobile devices means your users will be experiencing a site like they would have 10 years ago, with no UI richness. These days people expect more than that, especially since their devices can easily handle javascript/

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


# Question
Title: How do I apply a defined Image Style as a View Mode for a File field?
I'm currently working my way through O'Reilly's "Using Drupal", but I appear to have reached an impasse.

I'm trying to specify a view mode for a File field-type which utilises the Media File Selector widget. The problem is, I'm not getting any of my set Image Styles in the View Mode drop-down. I'm just getting:

* default
* teaser
* Full Content etc.

(see screenshot of view mode options: https://i.stack.imgur.com/fKXtj.png)
(this screenshot shows my image styles: https://i.stack.imgur.com/ssFBk.png)

The book was published April 2012 so I'm not sure if anything might have changed significantly since then? I'm using the most up-to-date version of Drupal and all modules.

Can anyone tell me if this is wrong way to perform this task, and if so what the right way is?

Cheers!

# Answer
> 1 votes
It appears that things have changed.

Applying image styles is now done exclusively through the structure-\>file types-\>images menu.

More extensive instruction can be found in this answer: How to set Media Styles in Media 7.1.2 / Media 7.2.X?

---
Tags: media, entities
---


title: Filter by multiple taxonomies in URL

text:
# Question
Title: Filter by multiple taxonomies in URL
I need to display nodes in a view, based on a **combination of multiple taxonomy terms**, in multiple vocabularies. For example, for car sales, one vocabulary lets the visitor select one `model`, and another selects the `color`.

My custom path looks like this:

```
/sales/cars/models/%            // taxonomy view
/sales/cars/colors/%            // taxonomy view

/sales/cars/model/%/color/%     // taxonomy filter

```

URL:

```
mydomain.tld/sales/cars/model/land-rover/color/red

```

I assume I can do this by exposing filters but how?

# Answer
> 8 votes
When you create your views page you set the path to `/sales/cars/model/%/color/%`

**Add contextual filters:**

You need to create 2 Contextual Filters, both of them are: `Content: Has taxonomy term id` so repeat the process below twice.

On configuration of first contextual filter, you need to set:

> "WHEN THE FILTER VALUE IS NOT AVAILABLE" -\> Provide default value -\> Raw value from URL -\> Path component

Also check "Use path alias" if the URL is an alias rather than a system path.

Now you need to validate it, on same configuration overlay screen under

> "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED"

tick "Specify validation criteria"

and select "Taxonomy Term" for Validator. Check the appropriate Vocabulary for each contextual filter, and finally set "Filter value type" to "Term name converted to term id" and check the checkbox "Transform dashes in URL to spaces in term name filter values".

Set "Action to take if filter value does not validate" to whatever your needs.

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


# Question
Title: After preview node is not saving the content.
I added the data to node, after that i clicked on the preview button and it displaying preview of that node, but the problem is, node not saving the content. When i click the submit button it shows the **error message**

"The content on this page has either been modified by another user, or you have already submitted modifications using this form."

Please any one help me out.

# Answer
This is an error that comes from the node module.

The error occurs when you submit the node form and the node has been changed by something since you loaded the form.

The change could be caused by another user editing the content, you editing it in a different tab/browser, some background task editing it, etc.

How it happens is:

1. You load the node edit form. The node object is pulled from the database at this time.
2. You make the changes.
3. You save the node.
4. The system checks the last changed date of the node object that was loaded when you loaded the edit form (in step 1) with the last changed date for that node directly in the database (the current last changed date).

It does this to stop two people changing a node at the same time, in which case one persons changes might accidentally override the other persons.

To get around the error, you have to refresh the node edit form and make your changes and save it again.

There is no way around it but there are ways to lessen the annoyance of getting to the end of an edit and being told you have to refresh. One such way is the content locking module.

That module makes it so that when you load a node edit page it "locks" that node, so if someone else goes to the edit page while you have it locked it will give them a warning and won't let them make edits until you have finished editing and the node is unlocked.

This means you won't waste time on an edit that you won't be able to save.
> 1 votes

---
Tags: entities
---


# Question
Title: How to add a custom field which dynamically renders different output according to certain conditions?
I am writing a module which adds a new field. Similar to the serial module, the field cannot be changed or filled anyhow when creating a new node.
I just want the field to create a different output according to certain conditions, for instance if the user has a certain role or not.

For instance, when a user visits a node of a content type which has this field enabled, check for php conditions and then output different html.
Is the user a guest or registered? If guest, output a link which says "register to do this".

It would be really cool if this would then automatically work with views? Like a view which outputs this field for every node of that content type.

Ive tried using computed field but this module computed the result once and then displays this all the time... only solution would to alter the cache db, which seems a little unsmooth to me.

I already added a field using the examples module, so this is what I got so far:

```
function proposal_field_field_info() {
  return array(
    // We name our field as the associative name of the array.
    'proposal_field' => array(
      'label' => t('Proposal Field'),
      'description' => t('Adds proposal feature'),
      'default_widget' => 'proposal',
      'default_formatter' => 'proposal_field_simple_text',
    ),
  );
}

```

# Answer
Computed Field seems to meet your needs.

> 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. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or **have them "calculated" on the fly during node views**.

Emphasis mine. Either require it in your module and use it, or use it's code, it is open source after all.
> 0 votes

---
Tags: entities
---


# Question
Title: Display date field labels within selectors
Is there a way to move the labels of the day/month/year components inside the selectors (like Facebook has it on their registration page, see 'Birthday')? I have placeholders in all my text fields and it looks silly that the labels of date fields sit on top.

# Answer
Ok I've just quickly whipped up a `sandbox` module to modify date options array. And here's the code, hope this helps:

```
/**
 * Implementation of hook_form_alter()
 * @param array $form
 * @param array $form_state
 * @param string $form_id
 */
function sandbox_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'article_node_form') {
    // Only call after builder if we're using date_combo type which is 3 select fields
    if($form['field_date'][$form['field_date']['#language']][0]['#type'] == 'date_combo') {
      // Add our after build function
      $form['field_date'][$form['field_date']['#language']]['#after_build'][] = 'sandbox_field_date_after_build';
    }
  }
}

/**
 * After build callback
 * @param array $element
 * @param array $form_state
 * @return array
 */
function sandbox_field_date_after_build($element, &$form_state) {
  // Loop through each delta if more than 1 value
  foreach(element_children($element) as $delta) {
    // Loop through each granularity e.g. month, day, year, hour, minute, second
    foreach(element_children($element[$delta]['value']) as $key) {
      // #options not set means this type of granularity isn't set, so we skip
      if(isset($element[$delta]['value'][$key]['#options'])) {
        // If there's an empty value, change the option label to be '- [#title] -'
        if(isset($element[$delta]['value'][$key]['#options'][''])) {
          $element[$delta]['value'][$key]['#options'][''] = '- ' . $element[$delta]['value'][$key]['#title'] . ' -';
        }
        // Otherwise insert an empty value at beginning with label '- [#title] -'
        else {
          array_unshift($element[$delta]['value'][$key]['#options'], array('' => '- '. $element[$delta]['value'][$key]['#title'] . ' -'));
        }
        // Make the title invisible
        $element[$delta]['value'][$key]['#title_display'] = 'invisible';
      }
    }
  }

  return $element;
}

```

Which produces this result provided you have set "No default value" in the field instance setting:

Or you can always do it in the Advanced Settings of any date field.
> 1 votes

# Answer
**OPTION 1:**

Field placeholder adds a new option in field settings page to enter the placeholder value, which is included automatically when the widget is rendered.

**OPTION 2:**

This Placeholder adds an extra FAPI attribute called '#placeholder' to textfield field elements. Often textfields should have some text in them like "Enter your text here" until the user clicks on (or tabs to) the element in question. At that point, the text should disappear and the user can enter his or her desired input.
> 1 votes

---
Tags: forms
---


title: D7 Field template syntax

text:
# Question
Title: D7 Field template syntax
My D7 content type has a field for an MP3 file. I want the field to display as an image which the user can then right click to download the file ie like this. My field template file looks like this:

```
<div style="border:10px solid cyan;margin-bottom:20px">

<?php
$link = 'http://www.desertcow.co.uk/pirates.mp4'; // url link?>
<a href="<?php print $link;?>"><img src="/download.jpg"></a>
</div>

<div style="border:10px solid pink;margin-bottom:20px">
<a href="<?php print render($items); ?>"><img src="/download.jpg"></a>
</div>

<div style="border:10px solid red;margin-bottom:20px">
<a href="<?php print render($items); ?><img src="/download.jpg"></a>
</div>

```

The result is here and you can see that the syntax for the pink and red boxes is not correct.

Can anyone please tell me the correct syntax or is there some reason that this approach is not going to work?

Thanks...

# Answer
> 0 votes
This is because you're rendering the full item when all you want is the url as a string, if you add this line of code in the template you will be able to see where the url is held in the $items array.

```
<?php var_dump($items); ?>

```

then you can find the part of the array where the url string is so your final markup would be something like this.

```
<div style="border:10px solid pink;margin-bottom:20px">
<a href="<?php echo $items['url']; ?>"><img src="/download.jpg"></a>
</div>

```

---
Tags: entities, theming
---


# Question
Title: find out object properties passed to a function
which is the best way of debugging codes in drupal? for instance in election module there is a submodule called conditions, and there is a function:

```
function election_example_conditions_access_gmail($post, $account) {
  if ($account->uid == 0) {
    return FALSE;
  }
  return (bool) preg_match('/g(oogle)?mail\.com$/i', $account->mail);
}

```

in the above code, what is the easiest and fastest way to find out what is the $account object passed to function?

# Answer
> 1 votes
You can make use of the devel module for debugging.

Download and install the latest version of the Devel module.

**dpm()** Prints a variable to the ‘message’ area of the page using

**dvm()** Uses var\_dump() to print a variable to the ‘message’ area of the page

So in your situation in your function use dpm($account)

```
function election_example_conditions_access_gmail($post, $account) {
   dpm($account)
  if ($account->uid == 0) {
    return FALSE;
  }
  return (bool) preg_match('/g(oogle)?mail\.com$/i', $account->mail);
}

```

and go to the page normally and you should see the debug backtrace appear in the message area

---
Tags: 7, debugging
---


# Question
Title: Json views not displaying in json format, instead displaying in web view
I created a json view for a CCK.

I am trying to display the view on my webpage. The data is rendered as a web page. But i need something like exact json response.

Here is the screen shot

Please help to find out the solution.

Thank you

# Answer
> 2 votes
ya i got the solution. Just un\_check the Viewa API

Hope this will help some one

---
Tags: views, 8
---


title: Site Offline After Saving a Setting

text:
# Question
Title: Site Offline After Saving a Setting
I'm trying to fix a menu problem for a client - I tried saving new settings in the Appearance tab and I got this error

PDOException: SQLSTATE\[28000\] \[1045\] Access denied for user 'tester'@'88.208.252.203' (using password: YES) in lock\_may\_be\_available() (line 167 of /home/linweb12/7/7a7.co.uk-1059923790/user/htdocs/includes/lock.inc).

What would cause this error?

# Answer
This is a MySql error. MySQL is not getting fed the correct logon information. Can you logon to mysql using your drupal credentials - either by command line or PHPMyAdmin or some other method. If you can't logon it's a credentials problem. Otherwise it's likely a path problem.

In your settings.php file, make sure everything is correct. Double check it

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'MYDATABASENAME',
      'username' => 'MYUSERNAME',
      'password' => 'MYPASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

```

);
> 2 votes

---
Tags: database
---


# Question
Title: Drupal 7 - Array to string conversion in DatabaseStatementBase
I have an error on a Drupal 7 site that I cannot solve.

```
Notice: Array to string conversion in DatabaseStatementBase->execute() (line 2168 of ...

```

I cannot use dpm, can't find a way to debug, and can't see what is the data that causes the problem.

Anyone would know how I could debug this? really appreciated

# Answer
> 8 votes
Webchick's Quick-and-dirty debugging is so useful in this type of situation that I've sometimes had a projects with it as a ready to apply patch.

Find drupal\_set\_message()

```
function drupal_set_message($message = NULL, $type = 'status') {

```

in bootstrap.inc, and add

```
// DEBUG: Go track down that stinkin' error...
if ($type == 'error') {
  $message .= '<pre>'. print_r(debug_backtrace(), 1) .'</pre>';
}
// END DEBUG

```

at the very top. This will give you a backtrace on the error, helping you to trace down it's source. It could be good to know that there are instances where this runs PHP out of memory, if you have a lot of errors, so you may need to add extra conditionals in there at times.

---
Tags: debugging
---


# Question
Title: Issues with Term Reference and Multilingual Taxonomy
The issue:

* We have a multilingual Drupal 7 website which allows users access to a content type e.g. `Blog` \- where they can use `/node/add/blog` and `node/*/edit` in their chosen language
* A taxonomy has been created called `category` which has been set to 'Localize' under MULTILINGUAL OPTIONS \>\> Translation mode
* Terms listed under `category` have been translated to FR, DE, NL etc.
* On the content\_type `Blog` \- a term reference has been set up to reference the `category` taxonomy, with a select list widget being used.
* When visiting e.g. `www.multilingual-site.com/node/add/blog` (default site language is EN) - the dropdown list shows all the terms.
* When visiting e.g. `www.multilingual-site.com/fr/node/add/blog` or any other language e.g. /de/ or /nl/ etc the dropdown list is blank - the translated terms do not appear.

In an attempt to create the option list ourselves - using `hook_form_alter()` with `taxonomy_get_tree($vid)` as suggested here https://drupal.stackexchange.com/a/64666/5253 \- when trying to dpm the output the array is empty for every language other than the default EN.

Can anyone offer any direction? Thanks

# Answer
> 10 votes
Turns out we needed to unselect 'Select taxonomy terms by language' - found `admin/config/regional/i18n/select` \- hope this helps someone. More reading at: https://drupal.org/node/1868418 #2

---
Tags: taxonomy-terms, i18n-l10n
---


title: Count Unique Visits to the Drupal Site

text:
# Question
Title: Count Unique Visits to the Drupal Site
Is there any way I can count unique visits to my Drupal Site. I have a customized reporting module for the Drupal within which I want to put the unique visits to the site based on date.

I am using this query:-

```
SELECT
  n.title, n.nid, a.timestamp AS visited,
  COUNT(*) AS times
FROM
  {node_view_count} a, {node} n where a.nid = n.nid AND a.uid = :uid AND n.nid <> 2120
GROUP BY
  n.title
ORDER BY
  times desc,
array(':uid'=>$_GET['uid'])) -> fetchAll();

```

Do you think there is any way?

Thanks.

# Answer
Try the Visitors module to either use it or help you with your code. It provides many features concerning visitors info and among them is the "unique visitor" feature you are interested in. A similar approach would be also the Counter module.
> 1 votes

---
Tags: database
---


# Question
Title: Loading module-related files only on certain pages
I installed the Chosen module and it is conflicting with my JavaScript code. That module gets loaded on every page, even if there is no select box on the page. It is definitely unnecessary to load the files from that module when they are not necessary at all.

What I want to do is modifying the module to only load on certain pages.

How should I go about doing this? What function do I have to call or look for within that module?

# Answer
You should use hook\_js\_alter() within template.php

```
function yourthemename_js_alter(&$javascript) {
  if ('this is true') {
    unset($javascript['sites/all/modules/chosen/chosen.js']);
  }
}

```

I'm wondering if either solution will result in caching issues though. If I may: I would first try to figure out why my JavaScript collides with the module and fix it there.

You can also use the hook within a custom module if you already have one that relates to what you're trying to accomplish here.
> 3 votes

---
Tags: 7, javascript
---


title: Drush: Watchdog search explained

text:
# Question
Title: Drush: Watchdog search explained
Can somebody explain how watchdog searching works? I can never get it to locate the log entries I'm looking for.

Let's say I have the following watchdog entries:

```
476722  10/Jun 10:31  notice    content  page: updated Protective Factors in Elementary School.
476723  10/Jun 10:31  notice    php      Notice: Undefined offset: 3 in _menu_translate() (line 777 of /var/www/html/domainnamehere/includes/menu.inc).
476724  10/Jun 10:40  notice    content  page: updated School/District Administrators.
476725  10/Jun 10:42  notice    content  page: updated Teachers.
476726  10/Jun 10:42  notice    php      Notice: Undefined offset: 3 in _menu_translate() (line 777 of /var/www/html/domainnamehere/includes/menu.inc).

```

All of following return "No log messages available":

```
drush wd-show "Undefined offset"
drush wd-show "%Undefined offset%"
drush wd-show "menu_translate"

```

If I want to find all of the "Undefined offset" watchdog entries, what Drush command do I have to run?

# Answer
You could just pass the stdout from Drush as the stdin to `grep`.

Example:

```
drush wd-show | grep 'Undefined offset'

```

**As a bonus** \- If you want the errors in a file, try the following:

```
drush wd-show | grep 'Undefined offset' > ~/Undefined-errors.txt

```

This'll put the errors into a text file in your home directory :-)
> 3 votes

# Answer
Actually I wrote this feature for drush. Didn't realize this problem untill now.

The explanation: the watchdog message is stored as a text with variables that are replaced by using the t() function. OTOH drush wd search functionality is based on a database query.

That's the output you get:

```
# drush wd-show --type=php

 ID  Date          Type      Severity  Message
 95  20/Jun 22:28  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 94  20/Jun 22:27  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 93  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 91  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 89  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 88  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 87  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 86  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 85  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of
 84  20/Jun 22:26  php       notice    Notice: Undefined variable: output in mothership_item_list() (line 304 of

```

But that's the database content:

```
# drush sql-query "SELECT wid,message FROM watchdog WHERE type='php' LIMIT 10"

wid message
27  %type: !message in %function (line %line of %file).
59  %type: !message in %function (line %line of %file).
60  %type: !message in %function (line %line of %file).
61  %type: !message in %function (line %line of %file).
62  %type: !message in %function (line %line of %file).
63  %type: !message in %function (line %line of %file).
64  %type: !message in %function (line %line of %file).
66  %type: !message in %function (line %line of %file).
67  %type: !message in %function (line %line of %file).
68  %type: !message in %function (line %line of %file).

```

It doesn't seem there's an accurate fix for this. Drush could try to do its best on searching by filtering also by the 'variables' column of the watchdog table though.
> 1 votes

---
Tags: drush, log-messages
---


# Question
Title: Is there any way to disabling caching for a single field for anonymous users?
I ran into an interesting, but probably a common, problem. With caching turned on, stock is not updated immediately for anonymous users (which makes sense as that's the point of caching). However this results in a little bit of a UXWTF. When a product is out of stock, users are still shown that '1' is still available. It's only when they try to add it to the cart, they are met with a notice

The maximum quantity of 'product name' that can be purchased is 0.

I would still like to keep cache pretty much for everything else, but is there a way to disable caching of the available stock count?

# Answer
Just an idea - in this case a workaround might be to hook a function after an order has been placed and then clean the cache programmatically.

You can use the `hook_commerce_checkout_complete()` and there call the `cache_clear_all()` function.
> 1 votes

# Answer
The caching mecanism in Drupal is very flexible. You could use a custom cache for the parts of a page you want to be "un-cached" on certain conditions, and when the condition is met (a checkout), just reset the cache for that particular $cid in the checkout's form submit.

See this post for a good overview of the caching api.
> 0 votes

---
Tags: 7, caching, commerce
---


# Question
Title: How do I correctly load user_profile_form() to use in my theme?
I am trying to theme the user profile edit page using user\_profile\_form() and need help how to achieve this. In my template.php I have the following code:

```
function marinelli_theme($existing, $type, $theme, $path) {
  $hooks['user_profile_form'] = array(
    // Forms always take the form argument.
    'arguments' => array('form' => NULL),
    'render element' => 'form',
    'path' => drupal_get_path('theme','marinelli'),
    'template' => 'templates/user-profile-edit',
  );
}

function marinelli_preprocess_user_profile_form(&$variables) {
  global $user;
  $form_id = 'user_profile_form';
  $form_state = array();
  $form_state['build_info']['args'] = array($user);

  // Load user.pages.inc and ensure it is automatically reloaded if
  // this form is rebuilt via AJAX or other means.
  form_load_include($form_state, 'inc', 'user', 'user.pages');

  $variables['rendered'] = drupal_build_form($form_id, $form_state);
}

```

# Answer
> 1 votes
Here is the code you need to follow:-

```
function THENAME_theme(&$existing, $type, $theme, $path) {

return array(
    'edit_profile_user_profile_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'templates/edit/user-profile',
        'render element' => 'form',
        ),
);
}

```

Next thing You need to create a file called user-profile.tpl.php and save it in template folder.

In the user-profile.tpl.php file, write the following code to print out the fields:

```
<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>

```

---
Tags: 7, forms, users
---


# Question
Title: How can I display a custom form in a popup?
I have created a form in my custom module, and I want to show it in a popup. I used the Modal Forms module, but it has some issues.

How can I display a custom form in a popup?

# Answer
> 4 votes
You can do it with the Lightbox module, for example using the following.

```
<a href="calc.html" rel='lightframe'><img src="sites/all/images/calc.png" /></a>

```

Don't forget to add `rel='lightframe'`. See this page at the bottom, and click on "Mortage calculator."

The other option is the Popup Filter module which allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and PHP-generated content. Even you can mention the block to appear in popup window. And it has the option to popup the login form, register form etc.

Also look at the Popups API (Ajax Dialogs) module.

> API for building modal ajax dialogs. Its focus is on putting forms inside of ajax popup dialogs. Current example can present pages as popups (of the lightbox type). This is amazingly useful for things like confirmation pages. And the best part is it can be applied retroactively to a page without needing to modify the generating module, and (of course) it degrades gracefully.

---
Tags: 6, forms, javascript
---


# Question
Title: Why would a (working) theme function defined in nodequeue module not be registered in theme registry?
Trying to overide a theme function defined in nodequeue from another custom module:

```
/**
 * Implements hook_theme().
 */
function nodequeue_theme() {
  return array(
       'nodequeue_arrange_subqueue_form_table' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Theme the subqueue overview as a sortable list.
 *
 * @ingroup themeable
 */
function theme_nodequeue_arrange_subqueue_form_table($variables) {
  $form = $variables['form'];
  // Build output snipped for clarity...
  $output = 'bunch of code';

 return $output;
}

```

I was expecting to use `theme_registry_alter` but upon doing a var\_dump of `$theme_registry` in the alter hook (after cache was flushed), it seems the function is not registered. Did I miss something?

# Answer
> 1 votes
Try

```
function yourtheme_nodequeue_arrange_subqueue_form_table($variables) {}

```

I don't think you can override module functions from the theme layer without theme\_hook\_function or hook\_function\_alter... You'll need to create a module to override nodequeue\_theme() - take at look at drupal\_alter()

---
Tags: hooks, theming
---


# Question
Title: Slideshow caption when logged in displays in different location when logged out
I've got a slideshow displaying on the homepage, and at the bottom of the images, I've got captions. I am using:

```
.views-field-body { margin-top: 250px; }

```

To position the caption, but the position is not consistent when logged in and out. For example, the code above displays the caption in the correct location when logged out, but when logged in, the caption is pushed further down.

What is the correct way to position the caption?

# Answer
> 0 votes
First of all, this problem is not just for admin, its for all users with access to administer views.

Since the user have access to administer views, Drupal views adds some additional classes to provide contextual-links and wrappers for easy edit of that particular view.

I think, you must have used `position` attribute somewhere in your css for that particular field or the container holding that `div` you mentioned, which gets contradicted to the attributes provided by contextual wrapper classes.

See if you really need that attribute, or write one more css property for admin too.

# Answer
> 0 votes
You are checking your CSS by log in as an administrator. Try those of you who have Google chrome installed.

1. Go to **Option**
2. Open a new incognito window (or shortcut **Ctrl+Shift+N**)

and check your css there when you logged in as an administrator. The extra space your slogan is getting is due to the edit this link and all other links which are for administrator use only.For a normal user these links are not available (which is the case when you logged out) so it works fine.

---
Tags: views, theming
---


# Question
Title: What hooks are being invoked on a node edit form
I'm using Drupal 6 with many modules. It often happens that I'm trying to track down which hooks are being invoked on a specific form, but up till now I've been making educated guesses. How can I figure out which hooks are being invoked on a node edit form (or other forms)?

# Answer
> 1 votes
hooks are basically functions provided by drupal to developer , so as to create a communicating medium between developer and drupal. hooks get called or render on a page when particular action associated with them take place it is more like drupal send a message to hook "describing what action drupal is doing " and hook ask developer "drupal is doing this do you want to add more stuffs or to perform any action on this action of drupal"

so depending on action taking place hooks are invoked

# Answer
> 0 votes
If you have to do something on node edit page then use hook\_form\_alter.But remember to check $form\_id while coding. And if you need any thing on node\_update, then use this hook.(hook\_nodeapi).But code this like:-

```
function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'update':
      //Here your code goes...
      break;
  }
}

```

---
Tags: 6, forms, hooks
---


# Question
Title: Stuff added to <head> not included in cached version
I have a page on drupal 7 where I have the text format set to **PHP Code**. I am using the drupal\_add\_html\_head() to include a few CSS/JS files, and an RSS link. My problem is that everything I add with `drupal_add_html_head` is only visible for a single view after the caches are cleared. After that single view they do not show up in the view source.

It can be demonstrated with a Body that is as simple as below. The first view will show an alert. If you reload the page, the script is not added, and alert() is not called.

```
<?php
drupal_add_html_head(array(
  '#tag' => 'script',
  '#value' => 'alert("Hello world!");',
  '#attributes' => array(
    'type' => 'text/javascript'
  )
), 'jscripttest');
?>

You should see "Hello world!"  But you don't unless you have just
cleared the cache.

```

I have also tried `drupal_add_css`, and `drupal_add_js` with similar results. The CSS/JS is displayed after the cache is cleared, but only once.

# Answer
This is a totally valid question in my opinion. Using the PHP input filter (or `eval()` in general) is almost never a good idea, but the fact that this code only runs once is not intuitive.

That said, I actually can't reproduce this.

My first thought was that the rendered HTML was being cached in the `cache_filter` table. But by default, the PHP Input filter is not cached in the `cache_filter` table. `php_filter_info()` from `php_module`:

```
function php_filter_info() {
  $filters['php_code'] = array(
    'title' => t('PHP evaluator'),
    'description' => t('Executes a piece of PHP code. The usage of this filter should be restricted to administrators only!'),
    'process callback' => 'php_eval',
    'tips callback' => '_php_filter_tips',
    'cache' => FALSE, // <- This is set to FALSE in the module
  );
  return $filters;
}

```

My next guess was that the anon user Page Cache was somehow ignoring the fact that those functions had been called. But I tested both `drupal_add_html_head` and `drupal_add_js` (the latter with both an external file and inline JS) and even for anonymous users, the JS was loaded and executed on all page views with and without the page cache enabled. I also tried all of these scenarios in the default `body` field and with a field added with the Field API.

I guess that means that my answer is one of the following:

1. Something is overriding `php_filter_info()` to set `'cache' => TRUE`
2. You have an additional layer of caching that's causing this on your server
3. Something else???
> 3 votes

# Answer
In template.php:

```
function YOURTHEME_preprocess_page(&$vars, $hook)
{
     $req_path = request_path();

     switch ($req_path)    // in your case, the /some-path-that-you-want
     {
         case 'your-path':
             drupal_add_js('/path/to/your/js/foo.js');
         break;
     }
}

```
> 2 votes

# Answer
Try drupal\_add\_css() and drupal\_add\_js(), but set the 'every\_page' flag to true.

**every\_page** For optimal front-end performance when aggregation is enabled, this should be set to TRUE if the JavaScript is present on every page of the website for users for whom it is present at all. This defaults to FALSE. It is set to TRUE for JavaScript files that are added via module and theme .info files. Modules that add JavaScript within hook\_init()
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Not able to reference Javascript functions inside jQuery wrapper
I have custom module called interface, through which I'm adding a javascript file. This code is in plain old javascript, no jQuery, and has been working for me.

I now want to be able to add some jQuery functions to this code, I thought this would be possible since jQuery and javascript should be compatible with each other, right?

So here's a simplified example of what I'm doing inside the .js file:

```
(function ($) {
    Drupal.behaviors.interface = {
    attach: function()
    {
        function foofunction() {
        // execute some code
        }
    function WelcomeScreen()
    {
        Screen.apply( this );
        this.html = function(){
        return "<p></p>";
        };
this.activate = function(){
document.getElementById("main").innerHTML = "<a id=\"button\" onClick\"foofunction()\">Test</a>";
        };
        }

    }
    }
})(jQuery)

```

This code results in the following error in Chrome dev tools:

```
Uncaught ReferenceError: foofunction is not defined

```

My guess is that somehow the required jquery wrapper or the drupal behaviors wrapper are causing the functions to no longer be 'global'.

One obvious answer, I think, is rewriting everything in proper jQuery syntax. But I'm interested in how to make these javascript functions compatible with jQuery.

# Answer
First off, onClick misses an `=` sign. Secondly, Chrome is right. From the point of view of the `<a id="button">` element, the function is not visible even though it seems to be in scope of `WelcomeScreen` function. That's because it's not the function that invokes it, but the element on a page. Try `onClick="Drupal.behaviors.interface.foofunction()"`. But better off - make it unobtrusive by removing the `onClick` attribute and saying at the `document.ready` level:

```
(function ($) {
    Drupal.behaviors.interface = {
    // code
    }

    $(function(){
      $('#button').live('click', Drupal.behaviors.interface.foofunction);
    });
})(jQuery)

```

Of course this is just a rudimentary suggestion, you might want to optimize the code further. If you're using jQuery 1.7+, you'd rather use `.on()` than `.live()`.
> 1 votes

# Answer
Artur is basically right - "Drupal way " is to attach events in behaviors. Here is code I'm using without problems:

```
(function($) {
  Drupal.behaviors.mymodule= {
    attach: function (context, settings) {

      function test(param) {
        alert($(param).attr('token'));
      }

      $(':input', context).on('keyup change', function(){
        test(this);
      });
    }
  };
})(jQuery);

```

Or simpler:

```
(function($) {
  Drupal.behaviors.mymodule= {
    attach: function (context, settings) {

      function test() {
        alert($(this).attr('token'));
      }

      $(':input', context).on('keyup change', test);
    }
  };
})(jQuery);

```

Rewrite your code to that syntax, make sure you are using jQuery Update, and you should be good.
> 1 votes

---
Tags: javascript
---


# Question
Title: The best way to store drupal Configuration
I know three options to store the configurations:

Use the UI and store the values into the variable table.

Also you can store them in settings.php and use the $conf\[''\] array to store the information.

The last options is to store the values with variable module.

What do you thing is the best one, not for an final user but for a developer.

Oskar

I don't add "strongarm + features" because sometimes features is a little nightmare, and I'm trying to leave it far from me.

# Answer
If you're literally looking for variable storage, then `variable_set()` and `variable_get()` are the way to go...during development. However - that means the variables are stored in the DB rather than the file system which *can* make deployment a bit painful later on. From your question, I assume this is what you are trying to avoid.

If you're looking to store sitewide *configuration* as opposed to just variables, then there are a couple of options.

**Features**

I know you said you don't want Features, but Features 2.x is actually a MASSIVE improvement over 1.x, so if you've not ooked at it for a while I'd suggest giving it another go.

***Disclaimer***: I *love* Features 2.x :-)

**Configuration Management**

Then there's Configuration Management which is an attempt at working some of the Drupal 8 CMI work to Drupal 7. It's relatively easy to use, and also pretty easy to extend.

On another note; Clive is kind of a Configuration Management evangelist - so if you have any difficulties with it then you have a wealth of information here.

**Manual**

Lastly, you could create a custom module that implements default configuration hooks (such as `hook_views_default_view` or `hook_default_rules_configuration`). A keen eye will notice that these hooks are a key element in getting configuration into Features :-)

Strongarm is also not dependent on Features, so you can utilise the Strongarm API yourself :)

**Extra**

I tend to use `$conf[]` in combination with a Git-excluded `local.settings.php` (see this question for a reason as to how and why) file for storing environment-specific configuration (such as site e-mail - things that might change between environment).
> 5 votes

# Answer
If you need to store site-wide config variables, use the variable table with

Keep in mind, `variable_set` flushes and rebuilds the entire variable cache, so use sparingly.

The variable table should also only be used for small conf settings, as it's loaded on every page request.

`variable_set` works well with system\_settings\_form for admin settings forms.

The difference between `variable_set` and `$conf['name'] = 'value';` in settings.php is that the former stores in the database, while the latter adds the conf value dynamically at runtime.

If you want to add module specific config variables, or larger settings, create a table in your module.install file with

and add your config settings to that.

It will install automatically on module install, else you can install the schema later with an update hook and
> 3 votes

---
Tags: 7, configuration
---


# Question
Title: reCaptcha has blocked me out of my website
I had enabled reCaptcha yesterday on my site. The keys that I had entered were generated for my real site while I had been working using my temp.

My site displayed this message continuously:

> Input error: Invalid referer

I didn't take it seriously for I thought it will be resolved when I start using the real url for my site.

Today, when I logged out, I realized that I was wrong. I am not able to log inside my administrator account because the captcha is blocking me out. This is the message that I got when I tried to enter the site using my login id password:

> The answer you entered for the CAPTCHA was not correct.

I can not disable the captcha on login screen because I am not able to enter the site. Should I delete the captcha module from my directory right way? Or will that screw up things further because I won't be able to clear the cache of my website?

# Answer
**If you can use SSH, or other shell,** it's easy:

1. Install Drush. On Ubuntu, follow this document. Or simply unpack it and add it's directory to system's PATH variable (OS dependant).
2. Enter your Drupal's directory
3. Execute `drush dis recaptcha`

I strongly advise this approach, it may be a bit hard to set up initially, but drush is a powerful tool that can help you in future.

**If you cannot, but you can use SQL client,** it's not so bad too:

1. Login to your Drupal database with your SQL client
2. Back up your entire database
3. Execute `UPDATE system SET status = 0 WHERE name = "recaptcha";`

In both cases, you should be able to login, and uninstall reCaptcha module via UI to get rid of messed configuration data.
> 6 votes

---
Tags: users, captcha
---


# Question
Title: How to save validated third party API data if form validation fails
Here's my issue. During user register I'm adding fields via form\_alter and creating a stripe account. When validation fails $form\_state gets wiped out and when the user passes through validation again a second account gets created.

I'm thinking about using cache\_set to hang on to the account info until the user gets through the registration process error free but is there a better way to do this?

# Answer
It sounds like before your `mymodule_form_validation($form, &$form_state)` function returns you want to store the Stripe information in the users `$_SESSION` array as a valid attempt/data.

You write to user session using the global session value in PHP and Drupal adds it to the Users' DB/Mongo user session info at the end of page execution. For example:

```
// in your form validation code ...
$_SESSION['stripe_username'] = 'john_doe';

```

On form load simply prepopulate the form data from $\_SESSION. Eg, you're stuffing the content into session because it will be wiped on form reload -- then you're replacing it so a 2nd account isnt created.
> 1 votes

# Answer
Another option for this particular use case may be

To set the form value during validation.

> Use this function to change the submitted value of a form element in a form validation function, so that the changed value persists in $form\_state through the remaining validation and submission handlers.

For example, on validation error, you could store the stripe ID in a `'#type' => 'value'` form element and thereby make it available for the subsequent request.
> 0 votes

---
Tags: forms
---


# Question
Title: How to add a class to vertical tabs created using Form API?
Form API element `vertical_tabs` does not have `#attributes` property.

I have two kinds of tabs. The first one is language dependent. The second one has language independent values, just shows a preview in the selected template. I want them to be visibly different on first glance.

How can I mark them, possibly without adding dummy containers that makes the form tree more complicated than form logic requires?

# Answer
> 1 votes
If you don't want the wrapper container, another option may be to override the theme function in template.php:

theme\_vertical\_tabs

You could add some logic and classes there.

e.g:

```
$output .= '<div class="vertical-tabs-panes my-class">' . $element['#children'] . '</div>';

```

# Answer
> 1 votes
You are right vartical tabs don't have #attributes element. But you can:

1) place vertical tabs in `#container` element with class. There you can use `#attributes`

2) you can add `#prefix`, `#suffix` into tabs:

```
$tabs['#prefix'] = '<div class="my-class">';

$tabs['#suffix'] = '</div>';

```

---
Tags: theming, forms
---


# Question
Title: Workbench Delete or Unpublish Multiple Nodes
I have recently installed work bench, when we view all contents there is no option to select multiple nodes and apply delete or unpublish action on them. I need to edit each node and then delete each node separately. Please suggest any solution.

# Answer
> 0 votes
I cloned the ie. needs-review view

and added field "views bulk operations: Content", marked a few possible actions,

rearranged the fields so bulk ops are first col as one expects

and that's it.

---
Tags: nodes, workbench
---


# Question
Title: How to create a node programatically with drupal_form_submit()?
How to create a node by programatically submitting the existing node add form, and most importantly using it's validation process instead of re-implementing all of the property/field validation logic so we piggyback off of the existing code.

# Answer
The advantage of this method over node\_save is that if you have field validation done by modules like field\_validation or your own custom validations that you have previously implemented, the node saving will fail if the data sent does not comply with those validations.

```
global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'MYCONTENTTYPE',
  'language' => LANGUAGE_NONE,
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['MYCONTENTTYPE'] as $field_name => $values) {
  $form_state['values'][$field_name] = array(LANGUAGE_NONE => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body'][LANGUAGE_NONE][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
$form_state['values']['field_MYFIELD'][LANGUAGE_NONE][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('MYCONTENTTYPE_node_form', $form_state, $node);

// Tell watch dog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message', array('%message'=> $message, '%field' => $field_name));
  }
}

```
> 9 votes

---
Tags: 7, nodes
---


title: How to change my maintenance page?

text:
# Question
Title: How to change my maintenance page?
As the title explains, I want to make a custom maintenance page, different from the default one.

For that I've read this tutorial: Theming the Drupal maintenance page.

I copied the file /module/system/maintenance-page.tpl.php to my theme folder, changed it a little bit, and I enabled the `$conf['maintenance_theme'] = 'themeName';` line in settings.php; but I can't see the changes

What else do I need to do?

# Answer
> 3 votes
Hope this will help you,

Before site goes offline for maintenance mode, check the user who has permission to access the site during maintenance mode via **admin/people/permissions** and check for this permission **Use the site in maintenance mode**. Default access will be given to the **admin**.

In Drupal 7, to create a custom maintenance page we have to override the default maintenance template file

We can do it by the following steps:

* Copy **maintenance-page.tpl.php** from modules/system/
* Paste it in **active theme** folder inside **templates** folder
ie., sites/all/themes/your\_theme/templates/
* Make the changes in new maintenance template file.
* Clear the Drupal cache - configuration \> performance \> clear all caches

Note:

* If you want how to **Put Drupal 7 in Maintenance Mode**, you can go through this link
* To bring the site back online

+ The user who has permission to access the site during maintenance mode can
    able to login using **login page**
    + Go to admin/config/development/maintenance and uncheck **Put site into maintenance mode** and save it.

# Answer
> 1 votes
double check that you have done the changes

Drupal API

And copied the file into your themefolder?

There is also the option of using maintenance-page--offline.tpl.php when the db is off.

# Answer
> 1 votes
If clearing your cache doesn't work, you can explicitly set the template in the preprocess.

```
     template_preprocess_maintenance_page(&$variables) {
      if (isset($variables['db_is_active']) && !$variables['db_is_active']) {
    // Dead databases will show error messages so supplying this template will
    // allow themers to override the page and the content completely.
        $variables['theme_hook_suggestion'] = 'maintenance_page__offline';
      }
      else {
    // Default maintenance template
        $variables['theme_hook_suggestion'] = 'maintenance_page';
      }
    }

```

---
Tags: theming, maintenance-mode
---


# Question
Title: Sort 2 views in a page by 2 different ways
I have a simple view, i create a page and a block for view and place them in a page, but How can I sort them in different way:

View Page (sort with nid : asc) \- View Block (sort with nid : desc) \- How can I do this with php field (use with Views\_PHP)

Have a nice day THanks.

# Answer
You can do this following steps:-

1.go to your page view: and then click on "sort with nid : asc" or whatever selection criteria. 2. Then it will open a pop-up, so look at the top left most part, there will be a select box, select display overide thing.

Repeat same thing for block view

:)
> 1 votes

# Answer
Well, as I understand,

1. You have created a 'page view' and a 'block view'.
2. Now you want those to be sorted in two different ways.

Well, that's straight forward. But I got a confusion with your statement '..and place them in a page..'. Do you want to mean that you shall place your 'page view' and 'block view' in a another page? If so, then it's not the right approach, as you already have a 'page view' which will have it's own URL or, MENU.

Now, considering the feasible scinario where you want to display 'block view' in the 'page view' where both will have same content but in different sort orders, that you can just manage from drupal view's sort criteria.

Hope it helps
> 2 votes

---
Tags: views
---


title: Stop footer from reloading

text:
# Question
Title: Stop footer from reloading
I have a background audio module running on a site I am building. (I know WHY? but the client wanted it). Anyway I need to know if it is possible to stop the footer from reloading every time they click to another page on the site because the song starts over.

# Answer
## Pre-HTML5 way

Sorry no, it is not easy nor stable. Footer is a part of HTML structure, and HTML is send with each request. You would need to remake a lot of Drupal to make it's navigation AJAX based to leave footer in place and reload just changes. I did it, once.

First problem is - if you change anything before `#`, browser will reload, it's mandatory. So you would need to send `HTTP 204 No Content` and hope user's browser really understands it. Then, JavaScript would need to detect answer like that, generate proper AJAX query. Or you could use js to insert # into every link and then send AJAX.

Either way, in PHP you would need to be able to serve stripped version of HTML structure. I did it by appending `?ajax=true` and in theme stripping everything before and after my `#main-container` and sending only it's content. Of course if you use "# way", you cannot just paste content. You need to treat links inside.

Long story short, it was complicated, dirty, and worked like a magic. But worked all right.

## HTML 5 way

Use `<audio>` tag like this:

```
<audio autoplay loop>
  <source src="ambient.mp3">
</audio>

```

And let the browser care.
> 3 votes

---
Tags: javascript
---


# Question
Title: How do I add an image for each menu column?
I have 4 columns in the footer, and am displaying a different menu in each block(column). I would like to add an image above the menu items for 3 out of 4 menus. What is the best way to do this? Is it possible to add a field to the menu content type as such? If this was possible I could then create a view for each block/column, by pulling in the menu items and images...

What would be the best way to do this?

# Answer
> 1 votes
It's pretty easy to do that with CSS

```
#column-1{
  padding-top:20px; /* Space for image */
  background: transparent url('../images/bg-col-1.png') no-repeat left top;
}

```

# Answer
> 0 votes
Additionally, if you need to add individual image for each menu item in a particular menu block you can use this module

You can try Menu Attributes module. You can add specific class and do the css.

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

---
Tags: views, routes
---


# Question
Title: How do I set the default value for a checkboxes element?
I'm trying to set the default for a checkboxes element in `hook_form_alter()`.

```
$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a','b','c'),
  '#default_value' => array('a'),
  '#title' => t('The average vote is more than'),
);

```

I'm expecting *a* to be checked, but this doesn't happen. I'm using the Better Exposed Filters module, but I doubt that would make a difference.

# Answer
> 2 votes
Simplistically, the issue is that the default value uses the array key, not the array value. So, there are two ways you can change this to make it work.

One:

```
$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a' => 'a','b' => 'b', 'c' => 'c'),
  '#default_value' => array('a'),
  '#title' => t('The average vote is more than'),
);

```

or

```
$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a','b','c'),
  '#default_value' => array(0),
  '#title' => t('The average vote is more than'),
);

```

# Answer
> 0 votes
Ok, got it. Try this :

Here, I am altering a form, it can be a new form as well.

```

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $options = array();
    $options = array('a','b','c');
    $form['chekbox_check_issue'] = array(
      '#type' => 'checkboxes',
      '#options' => $options,
      '#default_value' => array(0), /* Set the key values of the options array you want to be checked*/
      '#title' => t('The average vote is more than'),
    );
  }
}

```

Hope it helps

---
Tags: views, forms
---


title: Panels Custom Context

text:
# Question
Title: Panels Custom Context
I have created a Panels Everywhere variant that uses a single View with a contextual filter (Content Type). The Panel variant is set to page paths. These paths are related to content types. For example:

Path:

```
drivers (list of 'driver' Content Type)
lawyers (list of 'lawyer' Content Type)

```

So if I go to /drivers the Context of Content Type 'driver' should be passed to the View, etc. I know this is possible as %user context is a variable object; therefore, I should be able to create another variable object and pass this to the View. The problem is that I don't know where to start :( Any ideas?

# Answer
> 1 votes
Large parts of the question doesn't actually make sense to me, but...

If you want to pass an arbitrary part of the URL as a string to a View, just assign that variable part to a string in the argument settings, and then set that argument, `%url_from_string`, as the argument to the View.

The better solution though, would be to create a new context type called 'content type', because I don't think a context like that is available out of the box, and then assign the argument to that instead. That allows you to do validation of the incoming context and gracefully handle an argument that's not valid.

A third solution, though mostly a workaround, is to tell the View to pull it's arguments directly from the URL. This setting is available for all content pane displays under their argument settings.

---
Tags: views, panels, 7
---


# Question
Title: Set fields in uc_addresses checkout pane to disabled
I want to disable the billing address fields in `uc_addresses` so they cannot be altered by the user while they're checking out. However, I cannot find a form to use `hook_form_alter` on. It seems those fields are living inside a pane, but I don't know how to isolate and edit that.

I suppose this is one of those times they told me about where all I want to do is hack the other modules.

**edit1**: If you're interested here's the function that controls the panes and calls up the form. I don't really understand how it works.

# Answer
Okay I finally figured it out:

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

  $form['panes']['delivery']['#disabled'] = TRUE;

}

```

They're all greyed out and uneditable -- a work of art really.
> 0 votes

# Answer
It must be a form and You can alter via hook\_form\_alter. But in function you should must check the form\_id and after that print\_r or dpr or dsm (whatever you like ) the $form. And search for the address field and unset it.
> 0 votes

---
Tags: forms, ubercart, panels
---


title: D7 - syntax in Field template

text:
# Question
Title: D7 - syntax in Field template
My D7 content type has a field for an MP3 file. I want the field to display as an image which the user can then right click to download the file ie like this. My field template file looks like this:

```
var_dump($items) =

<div style="border:10px solid violet;padding:4px; margin-bottom:10px">
<?php var_dump($items); ?>
</div>

print_r($form) =

<div style="border:10px solid maroon;padding:4px; margin-bottom:10px">
<?php print_r($items); ?>
</div>

<div style="border:10px solid orange; margin-bottom:20px">

<?php echo $items[filesize]; ?>
<?php echo $items['filesize']; ?>
<?php echo $items["filename"]; ?>
<?php echo $items['url']; ?>
<?php echo $items['uri']; ?>
</div>

<div style="border:10px solid green;margin-bottom:20px">
<a href="<?php echo $items['url']; ?>"><img src="/download.jpg"></a>
</div>

```

The result is here. Can anyone please tell me why the orange box is empty / not printing out, and the correct syntax re the green box to make the image link to the MP3 file URL instead of the page URL?

Thanks...

# Answer
I think your are printing wrong the array $items. It should be something like

```
print $items['#file']->filename;

```

The same is happening with the image issue.
> 1 votes

---
Tags: theming
---


title: load node_type_form form

text:
# Question
Title: load node_type_form form
I need to load and print drupal 'internal' form on the page, which id is "node\_type\_form" I have:

`$form = drupal_get_form("node_type_form");`

`$html = drupal_render($form);`

`echo $html;`

it only prints "Menu settings" and "Save and add fields" button.

I get:

`Notice: Undefined index: node_type_form in drupal_retrieve_form()`

`Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_type_form' not found or invalid function name in drupal_retrieve_form()`

`Notice: Trying to get property of non-object in menu_form_node_type_form_alter()` `Notice: Undefined index: #node_type in menu_form_node_type_form_alter()`

# Answer
`node_type_form()` lives in modules/node/content\_types.inc, which the system only includes when it needs to (to fulfil menu paths etc).

If you include it manually before your call to `drupal_get_form()` it should work...

```
module_load_include('inc', 'node', 'content_types');
$form = drupal_get_form("node_type_form");
// ...

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to create an end date field in a hook_form_alter
I've succeeded creating a simple date\_popup field with the following code :

```
$form['date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#default_value' => '',
  '#date_format' => 'Y-m-d',
);

```

Now, is there any way to directly create the "End date" field without having to create a second field declaration ? Is there any bundled widget I can use ? I've seen something about date\_combo but I'm not sure to understand it well.

Thanks for help !

# Answer
> 2 votes
there is no way to do it with the standard field widgets, you have to craft your own, the examples module may help you

---
Tags: datetime, forms
---


# Question
Title: Render template file for view if no result?
I need to render a view's template file even if there are no results for the view. Is this possible out of the box? If not, any idea on how to hack it?

# Answer
> 3 votes
Even though there is no results to display, views will call the appropriate theme functions and template files to render other information.

For example, If you go to views-view.tpl.php file you could see that views is rendering lot of information conditionally. For example if you have some exposed filters and there is no result for the execution, still view will call this template file to render the exposed form

If you specified **No Results Behavior** or **exposed some filters** you can check this.

Below is the sample code on how the views is rendering conditionally,

```
<?php if ($rows): ?>
    <div class="view-content">
      <?php print $rows; ?>
    </div>
  <?php elseif ($empty): ?>
    <div class="view-empty">
      <?php print $empty; ?>
    </div>
  <?php endif; ?>

```

If there's nothing to render it will skip all the conditions and will not render anything.

If you want to override the way views is rendering the output, then you can create your own template for your view and place it in your theme directory. Template name should be something like this - **views-view--.tpl.php**

---
Tags: 7, views
---


# Question
Title: Remove all markup from user registration field
I have been searching in vain for days trying to find the right hook or theme override to basically change a few fields I have defined in a custom registration form.

The default markup generated by Drupal is too verbose and the designer has requested that I not change the CSS -- I need to bend the markup to meet the CSS not the CSS to play nice with Drupal.

I have tried hook\_field\_widget\_form\_alter and have managed to wrap the existing markup in *div*'s but I need to remove the default:

```
function tweakform_field_widget_form_alter(&$element, &$form_state, $context) {
  //$element['#prefix'] = '<dir style="background-color: red">';
  //$element['#suffix'] = '</div>';

}

```

Can someone please show me how this is done? I don't want to re-write the entire form.tpl.php as I only need to override a few fields markup -- then again it may be handy to override the whole thing. These fields are dynamic and controlled by designer and more may be added later or possibly removed.

Alex

# Answer
```
function tweakform_field_widget_form_alter(&$element, &$form_state, $context) {
  $element['#theme_wrappers'] = '';
  $element['#prefix'] => '<div class="red">';
  $element['#suffix'] => '</div>';
}

```
> 0 votes

# Answer
If you wish to change markup, do it in your theme template.php using `THEME_form_element()` just take the function from theme\_form\_element and modify it for your theme. There are also theme hooks for the form and fieldsets.
> 0 votes

---
Tags: hooks, theming
---


title: The 'Drupal' way to query the database

text:
# Question
Title: The 'Drupal' way to query the database
I'm using the method below to query the database within a custom module but it doesn't seem to be the 'Drupal' way of doing things. Is there a better way?

```
$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = $var1 AND field4 = $var2";
$result = db_query($sql);
$num = $result->rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}

```

# Answer
> 6 votes
welcome.

The only tweak needed I see is:

```
$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));

```

The method you've written your query allows for SQL-Injection -- using placeholders in the SQL helps to defend against this.

I invite you to read up on the Database API documentation, specifically queries:

---
Tags: database
---


# Question
Title: Views - display node referenced by user profile field
Office is content type

User accounts have a **Node reference** to Office, field\_office.

I need to create a view which displays `Office->name` where `Office->nid` = `Current_User->field_office`

I can't believe something this simple is so difficult to setup. I've setup another view where `User->field_office` = `Project->field_office`. In that case I created two relationships:

```
Field: Office
(field_office) Content: Office (field_office) - reverse (to User)

```

And a Contextual Filter

```
(field_office) User: Uid

```

Where the default value is current logged in user's uid.

That was easier since both fields are the same (field\_office). But I can't figure out how to link a field to a Content nid.

**Update**

It would be simple if I could just create a Contextual filter on Content: nid and set the default value to User: field\_office. I can't figure out how to do that though. The only contextual filter option which might support that is PHP code, but what would I tell it to return? This doesn't seem to work (breaks AJAX)

```
$user_data = user_load($user->uid);
return $user_data->field_office['und']['0']['value'];

```

# Answer
Figured it out. Had to create a contextual filter on Content: nid and set the default value to PHP code:

```
$uid = $GLOBALS['user']->uid;
$user_data = user_load($uid);
return $user_data->field_office['und'][0]['nid'];

```

Really weird that this isn't easier to do.
> 2 votes

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


title: drupal webform sliding radio button

text:
# Question
Title: drupal webform sliding radio button
I m trying to build a form that has questions with radio button answers when someone clicks on a radio button the next question comes up and it should have a next and prev button is there any php code i need to put in? or will it be just jquery as i m very new to php and javascript

# Answer
> 1 votes
You may use Webform module and read this.

The full documentation is at http://drupal.org/documentation/modules/webform.

You can achieve the conditional field with Webform Conditional.

> This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.

Here's a youtube video Screencast demo.

> Webform already has support for conditional fields on multi-page forms. For example Field C on Page 2 can be dependent on Field A on Page 1. This module adds the ability to have conditional fields on the same page. This module adds the ability to have Field B on page 1 be dependent on Field A also on Page 1.

Check the version of the Webform module; you may have it already.

# Answer
> 0 votes
You can have a look at https://drupal.org/project/webform\_ajax\_page it renders all pages at once and uses AJAX to go to the next page, you might be able to add a sliding effect by hooking into the javascript

# Answer
> 0 votes
The conditional field module will let you set conditions for a field to appear or not.

For example if the question is do you have a cat? Then fields like:

Siamese Stray Kitten

And if you click on the radio button dog:

German Shepperd Bulldog Pitbll

Ect...

http://drupal.org/node/1704126 does this

---
Tags: webforms, javascript
---


# Question
Title: Webform doesn't send hidden input if sender is not logged-in
I have a webform which works fine only it is submitted for logged in users.

The problem is that the webform includes a hidden input. When I receive the email (sent by the webform) I can see all the values for the inputs, but the hidden input value is missing.

This does not happens if the webform is submitted for a logged in user.

Is this something related to permissions?

thanks

# Answer
Can you give us the token you use for the hidden field? Maybe the token you use only available for logged user. I used hidden fields but with a general token (for example date or ip\_adress) and it works fine for non logged users
> 1 votes

# Answer
I had a similar issue when I was using the direct input instead try using the token for raw input. That can help solve the issue.
> 0 votes

# Answer
I'm way late to the party, but I don't think the problem has anything to do with your user's status. It's a quirk in the Webform module itself. It doesn't store hidden values in the server-side cache.

That issue queue discussion has a fix to $form\_state that apparently works. I'm going to give it a whirl.

I think switching from "Secure value" to "Hidden element" (down at the bottom of the field settings) as making it a regular field and hiding it with CSS. But I could be wrong.
> 0 votes

---
Tags: webforms
---


# Question
Title: Date field select option in custom module
I am using drupal 7 and i am need of create a custom module to show the selected filter option values to be displayed on some other pages. By default we using the filter in the views, it shows the filter result values on the same page. So that only i prefer to go custom module.

In my custom module i have four fields which are two drop down values and one keyword search functionality and final one is year based search. I have a problem with passing the drop down option year based filter. The functionality works fine for me. But while the we show the drop down of the year it doesn't mention the default select year. The first option shows empty and rest of the option shows the year. While picking a year it searches fine, But I want to show the default value in the year field, to know the field was choosing the year.

I code is

```
    function customsearch_box($form, &$form_state, $form_id){
    $form['release_date']= array(
        '#type' => 'date_select',
        '#title' => t(''),
        '#title_display' => 'invisible',
        '#date_format' => 'Y',
        '#size' => 40,
        '#default_value' => 'RELEASE DATE',
        '#attributes' => array('title' => t('Enter the terms you wish to customsearch for.')),
      );
    }
    function customsearch_box_form_submit($form, &$form_state) {
      if($form_state[input][release_date][year]=='RELEASE DATE'){
        $form_state[input][release_date][year]='';
      }
      $form_id = $form['form_id']['#value'];
      $form_state['redirect'] = array('research-result',
      array('query' => array(
        'field_srch_release_date_value[value][year]'=>trim($form_state['input'][release_date][year]),),),);
    }

```

# Answer
> 1 votes
I can't find a link to any documentation for this at the moment, but the default value for a date field expects the date in a certain format: yyyy-mm-dd. It might sound counter-intuitive but something like this should work:

```
// Make up a date with the correct year
$time = mktime(0, 0, 0, 1, 1, $year);

// Format the date
$default_value = date('Y-m-d', $time);

// Set the default value
$form['release_date']['#default_value'] = $default_value;

```

# Answer
> 0 votes
> By default we using the filter in the views, it shows the filter result values on the same page. So that only i prefer to go custom module.

Reading between the lines, you could perhaps just use the

"Exposed filters in a block" setting for the view.

You could then place that block anywhere and it will redirect through to your view results.

---
Tags: 7, forms
---


# Question
Title: Prevent anonymous users from accessing "node/" node/%nid and taxonomy/term/%tid
So far, I have been reading some similar questions but I haven't found an elegant and simple way of doing this (if there is any). As I say in the question title, I don't want anonymous users to access the complete list of nodes (in node/) nor a particular node (under node/%nid), nor even a particular taxonomy term. :)

My approach to this is as follows. As far as I know, I can override the default node/%nid system page using a variant in Drupal panels. I actually did this and, if the user is not logged in, when he/she tries to access the node/%nid he/she will see a log in box. For the list of nodes, I removed from the front page all of the nodes and none is shown. I would expect to do with taxonomy/term/%tid the same as I did with node/%nid but, for a strange reason, Drupal panels is not able to create the variant (not sure if it is a bug).

Anyway, I would like to know if you have a more elegant or simpler approach to this (no matter if using panels or not).

Thanks in advance for your help!

# Answer
Have you tried in the template.php? what if you do something like:

```
function yourtheme_preprocess_page(&$variables, $hook){
   if(!$user->uid){
      if((arg(0) == 'node') || (arg(0) == 'taxonomy')){
         //redirect to login
      }
   }
}

```
> 0 votes

# Answer
If you're using Panels, it can be done that way by using the default pages:

* node\_view
* term\_view

The trick with term\_view is to enable the default taxonomy\_term View, give it a *different path*, e.g 'view/taxonomy/term/%' and embed that in the term\_view Panel.

Lastly, make sure you add a catch all "HTTP Response Code: 403" variant to your Panel page to catch those that don't have access to view the content.

Another option is

and added your own access callback to the node view and taxonomy term view menu items.

For example, to disable access to '/node'

```
/**
 * Implements hook_menu_alter
 */
function MODULE_menu_alter(&$items){
  $items['node']['access callback'] = FALSE;
}

```

Lastly with node view it's also possible to use the comprehensive
> 0 votes

---
Tags: users, panels
---