title: Facebook images timeline block

text:
# Question
Title: Facebook images timeline block
Is there a module and/or jQuery solution how to show multiple images in a block like the Facebook gallery on people's timeline? The images are always well aligned regardless of their size and landscape/portrait position.

I'd like to use a similar approach for my blog articles - Upload like 3 or 4 images and some text. I included a screenshot of a Facebook post to give you an example of what I mean.

# Answer
You can do this on a lot different ways regardless where you are using this, but it is mostly Front End question.

There is a Grid Field Formatter module that can help you with this, but it is not the best solution.

> Grid Field Formatter module provides a simple way to overridde the display of multi-value fields to show as a grid/table with a certain number of columns.
> 0 votes

---
Tags: javascript, media
---


title: How do I display questions in blocks?

text:
# Question
Title: How do I display questions in blocks?
How can I display questions in a block using the Quiz module?

I do it using the Views module, but when I click on *Start quiz*, it goes to a page. I want all functionality done inside a block.

# Answer
Though now 3 years old, the Quiz FAQ addresses this question: drupal.org/node/507090#1

## How do I create a quiz block?

Quiz 3.x has the Views module integration. To create a quiz block showing the top scorers or recent quiz you can use the Views module \[to expose as a block\]
> 1 votes

---
Tags: 7, quiz
---


# Question
Title: How to reset admin password with drush and Acquia Dev Desktop?
I realize that this is a pretty standard question that there is a lot of answers for elsewhere. The issue I have is that it seems that my drush commands aren't being reflected on my dev server.

I got locked out of my site, so I tried to use two methods to get in

1) drush upwd --password="mynewpass" "myuser"

and

2) drush ucrt "mynewuser" --password="mynewpass" followed by drush urol "administrator" "mynewuser"

Both command variations don't give me any errors and confirm the newly created user and his roles. Not sure what else I can do here. Before you ask, yes, I'm flushing my caches.

# Answer
I'm not sure why it's failing for you. Probably check the error logs to see if there are any warnings or notices being logged there.

The latest versions of drush have `drush uli` which just gives you a one-time login link for admin.

$ drush uli http://default/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3\_ciKfLqhE93SsS9YNAnaEY Unfortunately it doesn't get the hostname right in most cases (probably there's no way to know it if base\_url is not set) so you have to change "default" correct hostname.

So in the case above, I would paste the link into a browser and then change it to

http://example.com/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3\_ciKfLqhE93SsS9YNAnaEY There I have a one-time login link to user 1 on the site. Works flawlessly.

You can also run drush as admin by adding this:

drush -u 1 "command"

Eg:

`drush -u 1 cc all`
> 2 votes

---
Tags: drush, users
---


# Question
Title: How do I enable comments for user profiles?
With users being entities in D7 I assumed the user type would would have built in "comment" option. That doesn't seem to be the case. I just want to allow users to leave comments on the user profile page. Is there a simple way to doing that?

# Answer
> 8 votes
You can use Profile2, that attach node to user profile, so it can be commented and will look as commenting to user.

# Answer
> 7 votes
I have not tried it, but the Reply module looks really good.

> Reply is a D7 answer to entity comments. It is not intended to replace core comment module, more likely it supplements it's inability to work with entities other than node.
>
> Reply is basically a fieldable entity with subject and body fields which are hardcoded into module and are not Field API fields. This is because it is the essence of reply/comment. The entity is fieldable so you can create a 'review' or whatever you like by attaching fields to it's bundles.

# Answer
> 5 votes
Currently in Drupal 7 core, the comment module is still coupled to `node.module`. Comments are entities but can't be added to entities other than nodes.

You can see this issue to get the update: Decouple comment.module from node

# Answer
> 2 votes
I will encourage the use of statuses http://drupal.org/project/statuses for a "twitter-facebook" wall style. It's not a "comment" entity but it works pretty well.

I also looked the code, it is well written and has many hooks.

Statuses also integrates with: Views Activity Flag Rules Domain Mollom Notifications Messaging Pathauto Services Twitter Userpoints

# Answer
> 2 votes
If the use case is one where each user can only comment once (like a review for example), the best solution I've found is using the Flag Module. Version 7.3 of Flag is now fieldable. So you create an "add comment" flag and add a text field + whatever other fields you want to it. Then you can display the contents of the flags in a view. Very flexible, extendable and non-hack-y solution.

# Answer
> 1 votes
The way I ended up implementing comments on user profiles was to add a "guestbook" content type that has a user reference field.

When you look at someone's user profile you can click "sign guestbook" which links to "node/add/guestbook?edit\[field\_guestbook\_userreference\]\[und\]\[uid\]=user123".

The prepopulate module is used to prefill the username on the node add form with "user123" and I use css to hide that field. The guestbook has comments enabled to allow others to comment as well.

I use a view block to show the "guestbook" titles on the userprofile.

# Answer
> 1 votes
Inspired by @MotoTribe (similar question here), I solved it like this:

You'll need: views, panels, rules, entity reference and entity reference prepopulate modules.

1. Make a content type `user_comments`, remove body field (if you don't, users will have to input 2 fields: title and body). Comments will become node title (255 Maximum length). Add a entity reference field `field_user_reference_comments`.
2. Make a USER view (name: `user_comments`), add relationship to "entity reference". Add contextual filter: User Uid \> provide a default value -\> User ID from Url.
3. Inside view make 2 blocks (I did content panes).

* First block: add UID field, rewrite results: `<a class="" href="/node/add/user-comments?field_user_reference_comments=[uid]">Add comment</a>`.
    * Second block: add content title field using the relationship. Add more relations and fields as needed.
4. Add a new rule (import from here, make sure follow syntax explained above):

```
{ "rules_redirect_on_add_a_user_comment" : {
    "LABEL" : "redirect on add a user comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user account" ],
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--user_comments" : { "bundle" : "user_comments" },
      "node_update--user_comments" : { "bundle" : "user_comments" }
    },
    "DO" : [
      { "redirect" : { "url" : "users\/[node:field_user_reference_comments]" } }
    ]
  }
}

```
5. Enable from panels "user-view". Add user being viewed, add views First block, add views Second block.
6. Now you're done; it should work great. Build your view as complex as you need, add: fields, filters, sorts, etc. works perfect.

# Answer
> 0 votes
The user profile is essentially a view; you can hook into the view to include the comments.

# Answer
> 0 votes
create comment node with all fields. Among them one field must refer to the profile2 type(Using reference module). Then you can attach that node to profile2 using EVA module. If any better answer, let me know.

# Answer
> 0 votes
you can add a field collection item to your profile and then add arbitrary fields to it. so users can insert comment with it if you use field permision module and give all users the permision of inserting comment. it is works properly I've try it

---
Tags: 7, users, comments
---


# Question
Title: Drupal Deployment to Dev & Prod and Git Code Repository Setup
I have a dev and a prod server with 4 other developers. What is the most efficient way of setting up a development code push environment without the need to have to get too involved in the process? I know the term these days is called CI (continuous integration). But the thing is that it can involve many moving parts during deployment I've read some setups have automated testing in the process. I don't believe I would need that as that's an extra system to manage.

My sites are just mainly information sites and its mainly used internally which is less than 1000 hits a day.

What is the simplest way some people approach this issue?

# Answer
> 2 votes
CI (continous integration) can contain many moving parts during deployment and code pushes. But instead of using all of it, which isn't necessary for every site, I've come up with the following setup:

* 2 environments: Dev and Prod domains
* Code revisions gets stored in the git servers
* 2 git branches: dev and master, the master branch is the prod server code.
* Each developer will have their own local servers for testing and coding on their laptops.
* Each developer checks out the dev branch.
* Master (prod) branch should only be touched when dev is tested. Then, merge dev into master.
* Once a push to the Dev branch is detected, script on server will auto 'git pull' to get new changes.
* Once a merge with dev + master, script on server will auto 'git pull' to get new changes into prod.
* Drupal files content will be managed by the "Stage File Proxy" module without the need to download all files.
* Database will be synced by downloading a copy from the dev server with "drush sql-dump"

---
Tags: version-control, deployment, staging
---


title: My form validate function will not run.

text:
# Question
Title: My form validate function will not run.
I am using Organic Groups. That module has a form where you add new members to a group. I would like to run additional validation on that form. I use hook\_form\_alter and can identify the form. I add a validate callback and verify its been added to the form array. Yet that function never runs. I don't know why.

```
function organization_control_form_alter($form, &$form_state, $form_id){
  if($form_id == 'og_ui_add_users'){
    dpm("Validation Added");
    //This dpm displays.

    $form["#validate"][] = 'organization_control_og_size_control_form_validate';
    //I have also tried running my validate function first, like this
      //array_unshift($form["#validate"],'organization_control_og_size_control_form_validate');
    //I have also tried only running my validation, like this
      //$form["#validate"] = array('organization_control_og_size_control_form_validate');

    dpm("form");
    dpm($form);
    //This dpm shows the validate callback has been added.
  }
}

function organization_control_og_size_control_form_validate($form, &$form_state){
  dpm("Validation Started");
  //This dpm NEVER shows

  //hard code an error for testing
  $subscriptionInfo['field_total_seats_value'] = 4;

  dpm("Validation Run 2");
  //This dpm NEVER shows

  if($organzational_control_organization_size >=  $subscriptionInfo['field_total_seats_value']){
    dpm("ERROR");
    //This dpm NEVER shows

    form_set_error('edit-name', t('Your Organization has reached is current license size limit.'));
    //This error is not displayed and the form submissions continues and succeeds.
  }
  else{
    dpm("It thinks its Okay");
    //This dpm NEVER shows
  }
}

```

# Answer
It's not working because you're not using a reference to `$form`.

Change your function declaration to:

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

Note the `&` in front of $form. This means you're actually working on the variable as passed to the function, not a copy, or at least that's my understanding of it.

A useful thing to do to avoid this kind of error with hooks is to check out the API for the hook you are trying to use and copy the parameters verbatim.
> 1 votes

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


# Question
Title: How to use Drush for Particular Project?
In my *loalhost* there are few drupal 7 sites installed.

Suppose I have projects A,B and C then how to use for A,B Or C etc.

How to use Drush by project wise?

# Answer
> 1 votes
Goto each project folder to run drush command as project wise. If you are using multi-site goto the project folder under sites directory and execute your drush command.

# Answer
> 1 votes
Go to the project root directory and run the drush commands.

For eg:

For Project A,

Go to root directory i.e `cd var/www/html/A`(may vary) and run the drush commands.

```
$:/var/www/html/A drush cc

```

---
Tags: drush
---


# Question
Title: Show / Hide login menu item not connected to node
I have a login menu item that links to the login page of my website. I want to have the menu item disappearing when someone is logged in and an a **sign out** button appearing in its place.

Since the menu item is not connected to a node, i cannot alter it's visibility based on node access rights. I found Menu Item Visibility module but it is beta and it does not seem to be maintained. Is there a way to do this via Drupal?

If I have to make a custom module or js can you give me a link of a tutorial on how to do this?

# Answer
> 1 votes
For *login* add a menu item into main menu named as **Login** and path should be `user/login`.

For *logout* add a menu item into main menu named as **logout** and path should be `user/logout`

Now when user will be login then *login* menu will replaced by *logout* automatically. And when he/she will be logout then a *login* menu will appear again.

---
Tags: routes
---


# Question
Title: How to write a simple test case for users by using drupal_mail() function?
I have written a custom module for sending email to registered users. And I want simple test case for that users email module.

In this module I am taking a user from database and selected users preferred language and sending emails.

Same as I want *.test* file, I don't know how to write *.test* file for this module.

I am using the SimpleTest module, version 7.x-2.x (in Drupal 7).

# Answer
Finding documentation about the SimpleTest module has never been obvious (also because using the Read Documentation link on the module's project page causes a 404-error ...).

Here are some pointers I've found so far:

**Be aware**:

* Make sure to you take into account what's written in API.txt, i.e.:

> ... Provides a reference of the API changes between SimpleTest 7.x-1.x included with Drupal 7 core and SimpleTest 7.x-2.x.
>
> Modules that provided 2.x compatible tests are required to add the following attribute to their info file: `testing_api = 2.x`.

So SimpleTest requires a version number in the `.info` file, which you specify by adding that `testing_api = 2.x` in your .info file.
* This module has *Maintenance status*: Unknown, *Development status*: Unknown

**Note:** As of D7, there is the PHP Unit Testing Framework module (namespace = `testing`). Refer to the Community Documentation about Testing (D7 and D8) / SimpleTest (D6) for quite some more details on all this.
> 0 votes

---
Tags: 7, emails, testing
---


title: Where are my views being used?

text:
# Question
Title: Where are my views being used?
I created a clone of a view and have completely forgotten why I did that.

I suspect that I was experimenting, but before I delete the view, ***I want to make sure that it is not being used***.

### Is there a mechanism by which one can list where views are being used?

# Answer
> 1 votes
Open the View and you'll see if it is a page or block, if it is a page you can see the path to the page under Page Settings, if it is a block just look for that block in the list (/admin/structure/block).

The block is named like Views:\[view\_name\] and if it is disabled I think you can safely remove that View, if not you can see the region and where you can see that block when you edit block and look at Visibility settings.

I think that there is no other automated way to find out where some View is used.

# Answer
> 1 votes
I have a tricky solution for you we know that the hook\_views\_pre\_render `called right before the renderprocess`So we just need put a dpm `$view->name` and just need visit all your pages and write down the views name that getting run, after that delete the other ones you create and not used any where.

**update : more deatils about creating custom moudle**

create a directory "my\_module" then create 3 file in it

* my\_module.info
* my\_module.module
* my\_module.views.inc

fill the below codes in them

**my\_module.info**

```
name = My Module
description = Behold my awesome module.
core = 7.x
package = Other

```

**my\_module.module**

```
<?php
/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'my_module'),
    'template path' => drupal_get_path('module', 'my_module'),
  );
}

```

**my\_module.views.inc**

```
function my_module_views_pre_render(&$view){
   dpm($view->name);
}

```

put the directory in `site/all/modules` then go to `admin/modules` and find and enable it (Also enable devel module)

# Answer
> 0 votes
There are 3 cases which you may use a View (I omitted the Panels)

* as a block
* as a page
* load the View by some functions like `views_embed_view()`

@mixerowsky told you how to check for the first and the second one. for the third option you can use the following code to to check every file (or at least `.php` file) inside your theme directory and see if the View name is used in there or not. If it is used then see if it is loaded via some functions or not

```
$di = new RecursiveDirectoryIterator('./');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    if((strpos($filename,'.php') != false)){
        $file_data .= file_get_contents($filename);
        if(strpos($file_data,'THE_VIEW_NAME') != false)
            echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
    }
}

```

Put this code in a `.php` file and put it in any directory that you need to search for files content. This code will loop in every file and subfolders of that directory.

---
Tags: views
---


# Question
Title: Add <style> element to node body field via WYSIWYG
I am working on a project where the admin wishes to be able to insert a element into a node's body field. The site makes use of TinyMCE editor (wysiwyg module) to edit text area fields.

Currently admin is able to add the element to the body field by switching to source mode of Full HTML text format (by toggling "disable rich-text"). He can then insert the element and then save node. In this case the element will be preserved in the saved markup.

But if the node is edited again the wysiwyg appears to filter out the element, which means the admin has to re-add it using the method just described.

This unwanted removal of element also occurs when switching back and forth between the rich-text editor (toggling the "Enable rich-text" or "Disable rich-text" link below the field) after adding the element.

So it seems it is the wysiwyg is filtering this element out.

Is there a way of preventing this from happening?

# Answer
> 1 votes
TinyMCE outputs HTML 4.01 Transitional markup by default, and is not allowed inside in that (or XHTML) because styles are not block elements.

You can however force TinyMCE to accept \[the invalid\] style elements inside the body by overriding the valid\_children setting.

```
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['valid_children'] = '+body[style]';
  }
}

```

Thanks to TwoD for supplying the answer.

---
Tags: input-formats, wysiwyg
---


# Question
Title: How to programmatically list member entities of an Organic Group?
How can I programmatically get a list of member entities of an Organic Group?

(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)

# Answer
Or via DBTNG:

```
$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $yourGroupID, "=");
$query->condition("ogm.group_type", "node", "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();
print_r($result->fetchAll());

```

...which allows you to join other tables, rather than having to filter the result set in PHP code as you would if using `EntityFieldQuery`.
> 11 votes

# Answer
Using directly the Organic Groups API:

```
og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');

```

gives you an array of user ids.

To obtain only active, pending or blocked users, you can put 'members\__1', 'members\__2' or 'members\__3' in place of 'members', like in this example:

```
og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');

```

of, if you prefer, like this one:

```
og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');

```

Example of the returned value:

```
Array
(
    [0] => 48
    [1] => 49
    [2] => 51
)

```
> 14 votes

# Answer
```
$query = new EntityFieldQuery();
$query
  ->entityCondition("entity_type", "og_membership", "=")
  ->propertyCondition("gid", $yourGroupID, "=");
$result = $query->execute();
print_r($result["og_membership"]);

```

(Based on http://api.drupal.org/api/drupal/includes--common.inc/function/entity\_load/7#comment-14544)
> 8 votes

# Answer
smokris solution worked but I found another way with `EntityFieldQuery`:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('og_group_ref', 'target_id', $yourGroupID)
  ->execute();

```

Example of the returned value:

```
{"node":
  {"22":{"nid":"22","vid":"22","type":"panoramique"},
   "32":{"nid":"32","vid":"32","type":"panoramique"},
   "35":{"nid":"35","vid":"35","type":"panoramique"},
   "36":{"nid":"36","vid":"36","type":"panoramique"}
  }
}

```
> 2 votes

# Answer
Extending answer from @smokris.

The active status for the memberships is "1" (`->condition('ogm.state', 1, '=')` ).

```
function _get_users_in_group($gid) {
  $query = db_select('users', 'u');

  $query
    ->condition('u.uid', 0, '<>')
    ->condition('u.status', 1, '=')
    ->condition('ogm.state', 1, '=')
    ->fields('u', array('uid', 'name'))
    ->join('og_membership', 'ogm', "ogm.gid = :gid AND u.uid = ogm.etid AND ogm.entity_type = 'user'", array(':gid' => $gid));
  return $query->execute();
}

```
> 0 votes

---
Tags: 7, organic-groups
---


# Question
Title: get rid of decimal scale of stock field in commerce
product shows stock as 1.00 -\> how do i get it to show 1 (i get this to work in admin lists : admin/commerce/product but when showing in start screen or product detail page its 1.00..

how can I get rid of `.00` ?

**notice:** I have and create some product and in `admin/commerce/products/types/product/fields/commerce_stock` stock field property it is disabled

**edited** I update the module to new released , I unnistall fully pervious version and install new, all stock set 0, in display of product display I can do it that dont show scale digits .00, but in edit of product display it is 0.00 with 2 digit scale yet

# Answer
That bug has been fixed a long time ago; update from 7.x-2.0-alpha4 to 7.x-2.0-rc1. https://drupal.org/project/commerce\_stock and that will fix it, along with a lot of other issues.
> 1 votes

# Answer
Sorry folks, but i believe this is still an issue in current version `7.x-2.1`. Although there is a decimal formatter option available in the manage display tab of the product settings page, it has no effect if you render the data outside *Default*, *Full content*, *Line Item* or *Teaser* settings.

For example if you load commerce product like this in a form template :

```
$product = commerce_product_load((int)$form['product_id']['#value']);

```

It still renders with default defined 2 decimal positions
> 0 votes

---
Tags: 7, entities, commerce
---


# Question
Title: Drupal insert query with uploaded CSV file
```
array
  0 =>
    array
      'id' => float 1110
      'description' => string 'Culture de céréales (à l'exception du riz), de légumineuses et de graines oléagineuses' (length=86)
      'field2' => float 11
      'field3' => float 26.631
  1 =>
    array
      'id' => float 1120
      'description' => string 'Culture du riz' (length=14)
      'field2' => float 11
      'field3' => float 7.556

```

With this array what is the correct process for the string "description" to avoid SQL error when data is added with `db_insert` ?

I use this code for multiple insert :

```
$query = db_insert('table')->fields(array('id', 'description', 'field2', 'field3'));

foreach ($sql_query as $record) {
     $query->values($record);
}

$query->execute();

// $sql_query is the array described above.

```

# Answer
The data come form a file where string were not convert to utf8 at the opening thus the Drupal 7 parsing function for database query couldn't convert string to avoid SQL error.

Sorry but I didn't think that the problem could be as much upstream...
> 1 votes

---
Tags: 7, database
---


title: views header (contextual) filter

text:
# Question
Title: views header (contextual) filter
I have a node type news with a taxonomy reference (news categories). And I have a view for the news. In this view I have a contextual filter by this categories. The category comes with the url.

In this view I need a rendered entity (node type "views header") within the view header. These node type also uses the taxonomy "news category". At this point all works fine.

BUT: for every news category I need another entity within the view header.

This approaches I have:

1. Adding all nodes of type "views header" in the view header and filter them in the same context as the view itself. I tried if it is filtered per default with the view context filter but is does not.

The BUT here: I don't know how. How I can filter the nodes in view header. Is there a module for it which I didn't find?

2. Publishing the view header nodes as blocks. Adding the blocks in views template and configure the block visibility settings pages/only the listed pages. This solution works but I think there's too much overhead.

Does anyone know a more elegant solution?

# Answer
I can see a couple of ways ahead.

1. Instead of creating a content type (a Node) just for the header, why not use the taxonomy term (an Entity) itself? Terms are fieldable, so you can add your additional content there, including image, other terms, &c. Then you can grab the term fields using the \*replacement patterns from the "first row". *You may need to create a Relationship to the term*.
2. If you really want another *Node* I think you could use the Views Field View module. This way you can create a second View on your "Views Header" type, returning only one result, and pass the term ID from the first View's header to your second View.

Note: Using Views Field View in this manner follows a pattern known as a *representative view*. IE: A View on a node that is representative of all other nodes using this term. Views 3 does actually support representative views natively though it has some limitations and is generally more difficult to use. I talk about it more over here.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal allows menu tabs on Views pages. Why, and why not on other kinds of content?
In my question Most maintainable way to make page with one top half and alternative bottom halves selected by tabs?, I've asked about making a page with, as the title says, alternative bottom parts selected by tabs. There are various modules (Quick Tabs, Panels Tabs, etc.) that do tabs. But I have found that core Drupal itself has a feature for adding tabbed menus to Views pages. It's explained for example at Randy "Wilson" Brown's Drupal: How To Add A Tab To A Views Page. Why only to a Views page?

And — suppose I try to use these menus to select between things that really aren't views. For example, suppose I try to set up a page that has three tabs called "Photo 1", "Photo 2", and "Photo 3", each of which selects a different photo of my cat. I don't know whether I can make the views menus do this, but should I even try? Or is it likely to lead to problems, for example by being hard to do and maintain?

(Added a few days after posting) I'm adding the paragraphs below to clarify the spirit of what I'm asking.

I've coded with many languages and libraries where, to get a job done, you must "pervert" them because they lack the features needed to do the job cleanly. One example is passing primitive types by reference in Java. Suppose you want to write a method that takes an 'int' parameter and gives it a new value. You can't do that cleanly, because Java lacks call-by-reference for primitive types. But you can fudge it by giving your method an integer array parameter and passing your 'int' in an array. It works because arrays are compound entities, and Java passes those by reference. But it's bad, because arrays are intended for storing sequences, and you're misusing them for something else. It makes the code harder to read.

How does this relate to Drupal? I've come across several articles, in blogs and elsewhere, which appear to be doing the same kind of thing with views. For example, there's a post by Ron Golan at https: //www.urbaninsight.com/2013/11/01/views-menu-tabs-quick-guide which uses views to tab between different tabbed pages about a coffee grinder. One of these tabbed pages is a photo of the coffee grinder. In my mind, that's not a "natural" thing to use views for, because they are, in essence, database queries. And you don't need database queries in order to place one photo whose identity you know in advance.

Therefore, I suspect Golan is using views because he wanted their tabbed menus. When I see something like that, I have to think like an engineer and ask: somebody clever thought this trick worth using. Why? Why didn't he use a more direct technique? Is it because the trick, though perverse, is less risky than other techniques? For example, because it will not collapse if I update my Drupal or my jQuery. If I didn't ask such questions, I'd be betraying my client, because I'm ignoring information that *might* indicate dangers in some of my tools.

# Answer
> 2 votes
This functionality is built into the Drupal menu system *but is not exposed as a configurable option through the web interface by Drupal core*. You would normally have to write some code that implements hook\_menu to accomplish this.

Views happens to give a user interface for this functionality, so some people will take advantage of that to do things that maybe aren't best done in Views just because it lets them do it without having to touch code. I should note that Page Manager and Panels also give you configuration that let you do this through the UI and that would be a better way to achieve this if you have pages that aren't naturally Views.

---
Tags: views, routes
---


# Question
Title: How to redirect user using Rules when user visits a link with view?
I have a rule that redirects a user when visiting a view. But it does not work with the event "view page" or "Drupal is initializing".

Here is the rule:

```
{ "rules_uid_141" : {
"LABEL" : "uid=141",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "redirect manager" ],
"REQUIRES" : [ "rules", "pathrules" ],
"ON" : { "node_view--page" : { "bundle" : "page" } },
"IF" : [
  { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "38" } },
  { "pathrules_checkpath" : { "path" : "team", "operation" : "equals" } }
],
"DO" : [ { "redirect" : { "url" : "team?field_manager_uid=38" } } ]
  }
}

```

Any suggestions?

# Answer
> 0 votes
# Use 'Drupal is initializing'

To get this to work, you should be able to use the "Drupal is initializing" event (which is NOT shown in the rule included in your question). That will ensure that the rule gets triggered BEFORE the actual content of your "link with view" is shown (otherwise you are too late, it "is" already shown).

# Use a 'Regular Expression'

That link that you want to "intercept", should be formatted in some type of regular expression, which you then use as your Rules Condition. So that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules Action is probably fine.

# Sample rule

Refer to the "Option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this Rule in export format:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

Here is some suggested tuning of the above sample to make it work for your case also:

* machine name and label.
* replace the `node/*` by your path of your view (in the "label", and the regular expression).
* replace the action part of the rule by your action that you have already.

**Note**: the rule included in your question also shows that you tried to use the Path Rules module, which implements Rules Conditions for checking an URL against a given string for triggering Rules Actions. That module is another interesting add-on module the Rules, but if you just use a regular expression as shown in my answer, you don't need that module for getting your rule to work.

---
Tags: views, rules, redirection
---


title: Error in hook menu

text:
# Question
Title: Error in hook menu
I have used drupal 7.38.I have created a custom hook\_menu function(). My code is:

```
function jasmine_custom_menu(){
$items = array();
$items['review'] = array(
    'title' => 'Review Page',
    'page callback' => 'review_page',
    'access arguments' => TRUE,
    'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function review_page(){
  return 'hello workld';
}

```

after module enable error display like this: **Warning: Invalid argument supplied for foreach() in menu\_unserialize() (line 400 of D:\xampp\htdocs\jasmine\includes\menu.inc)**

# Answer
Your `access arguments` need to be an array. But I believe you are wanting to grant access to this page to everyone, so `access arguments` isn't the right key anyway; you want `access callback`. Try this:

```
$items['review'] = array(
    'title' => 'Review Page',
    'page callback' => 'review_page',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
);

```
> 4 votes

---
Tags: hooks, 7
---


title: Exporting block with features

text:
# Question
Title: Exporting block with features
I want to export block with features.I have installed features\_extra and enabled fe\_block and then exported my block into my feature. But there's only hook\_default\_fe\_block\_settings. I want to export into code also a content of block. So block viem etc. How can I do that? Thanks for help.

# Answer
You can use **Blockexport**

Functionality List

* It will import all system specific block into a feature.
* Import all custom blocks within a feature.
* Import all system blocks associated with content type
* Import all block roles
* No configuration is required.
* This module not create any table in your database to minimise the performance issue as much as possible.
> 1 votes

# Answer
Try upgrading Features Extra and see if that's already fixed.

Alternatively use Boxes module which is a reimplementation of the custom blocks (boxes) that the core block module provides. Or use Mini panels in Panels module.
> 0 votes

---
Tags: blocks, importing-exporting, features
---


# Question
Title: How do I effect the page that a menu item redirects to?
I am trying to do something that seems simple, but I have yet to have to do it with my development because I have always dealt with forms and views.

On the page that I get redirected to when I click on a menu item, I want to have a page with a href on it.

So for example, I have created a menu item as follows:

```
$items['admin/vendor/auth-stripe'] = array(
        'title' => 'Authenticate Stripe Account',
        'description' => 'In order to receive payments, you must authenticate your Stripe Account.',
        //'page callback' => '_bh_vendor_auth_stripe',
        'access arguments' => array('vendor administration'),
        'type' => MENU_NORMAL_ITEM,
);

```

When I click on this menu item, I am taken to a page. I want to add items to this page. Namely an href link.

Do I need to create a block that only shows up on this page? If so, how do I add a link on the page. I know how to create a block programmatically using `hook_block_info`, but I am not exactly clear on putting content in this block programmatically.

# Answer
> 2 votes
`hook_menu` serves, among other things, to map paths onto callback functions. Whatever function is marked as the `page callback` for that path will be responsible for returning a either a rendered string of HTML or a Drupal render array. So, for your very simple use-case, you could do the following (assuming your module's name is bh\_vendor):

```
function bh_vendor_menu() {
 $items['admin/vendor/auth-stripe'] = array(
        'title' => 'Authenticate Stripe Account',
        'description' => 'In order to receive payments, you must authenticate your Stripe Account.',
        'page callback' => '_bh_vendor_auth_stripe',
        'access arguments' => array('vendor administration'),
        'type' => MENU_NORMAL_ITEM,
 );
 return $items;
}

function _bh_vendor_auth_stripe() {
 return l('My link', 'my/path');
}

```

You could, in fact, define a block using `hook_block_info()` and `hook_block_view()`, then embed that block on your page by calling `module_invoke('bh_vendor', 'block_view', 'yourblockdeltahere')` but that really only makes sense if the stuff you're embedding is re-used elsewhere. If it's only meant for this one page then you should stick the code to generate that markup in your `page callback` directly.

Another option, if this isn't for a module that's to be widely distributed and is only configuration for a specific site: use the Panels module. You can create a panels page at a specific url (admin/vendor/auth-stripe) and embed whatever blocks/content you wish. If you want it in code it is exportable and/or can integrate with Features.

---
Tags: routes, blocks
---


# Question
Title: Is it possible to export all block's region settings to Features?
I'm about use Features to deploy all configuration of my Drupal (7) site.

Now I'm wondering if there is a way to export the entire settings for block to region assignment without having to export all blocks into one big feature.

One big feature containing all blocks would create conflicts with other, more atomic feautures. Even worse, it seems only blocks that have a region assigned seem to be exportable, so I can't figure out yet how to export my defintions of disabled blocks. For example: I move a previously displayed block to the *disabled* region - is there a way to deploy this setting to remove the block on the staging site, too?

# Answer
> 4 votes
We abandoned managing the blocks through the normal Structure-\>Blocks page a long time ago. Now we use it simply to set block titles, and the individual block's settings.

For assignment onto pages we use Context module:

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

This module lets you assign blocks to regions using criteria based on more than just page paths, such as taxonomy term of the content, type of content etc. And also it allows you to react with more than just blocks as well. Also one block can be assigned to different regions using more than just 1 context.

Overall the most important thing to this question regarding Context module is, the context rules are exportable via features!

# Answer
> 0 votes
You can consider using Features Extra which allows export of blocks which includes settings such as region, visibility, etc. Or try Blockexport module.

Alternative solutions to blocks are:

---
Tags: 7, features, deployment
---


title: Export blocks with features extra

text:
# Question
Title: Export blocks with features extra
I installed the Features extra module to export custom made blocks in my Drupal 7 environment. But for some reason, it doesn't work...

What I do is the following:

1. I create a custom block
2. I give it a machine name, description, title and body, just like it's required.
3. I go to `Structure - features - Create feature`
4. I create my feature by clicking the custom block under `FE Block`
5. The `fe_block` dependencies fills in automatically.
6. I download the feature and place it in `/sites/all/modules/features`
7. In my install profile I add this line: `dependencies[] = custom_blocks`
8. I try to reinstall the website and... nothing!

The blocks aren't showing up in my `Block`-page, but the feature is... What am I doing wrong in this process? Do I need to enable something or install an extra module in order to get my custom blocks exported?

# Answer
Alternative:

Use the **Panels** module to get the ability to create "*Mini-panels*" which function as equivalents to the standard Drupal block.

I believe there is much better support for exporting mini-panels into Features, since exportability was a key design component for the Panels module.

Personally, I've been successful using Panels, mini-panels, and Features.
> 1 votes

# Answer
IIRC, you can't put drupal blocks into features without patching it.

Have a look at the Boxes module, this is a replacement for the blocks system and is compatible with features.

> Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
>
> The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.
>
> Boxes provides an inline interface for editing blocks, allowing you to change the contents of blocks without going to an admin page.
>
> Boxes provides exportables for its blocks via the (required) Chaos tools module. This allows modules to provide blocks in code that can be overwritten in the UI.
> 1 votes

# Answer
Try upgrading your Features Extra module. Or try Blockexport module instead.
> 0 votes

# Answer
I think that you need to enable your features. Use drush, it's an interesting tools for drupal

> drush en your\_feature\_name.
> -1 votes

---
Tags: blocks, features
---


# Question
Title: make view modes for commerce enabled by default when exporting with features
I am trying to make the Drupal Commerce view modes administrator and checkout\_pane enabled by default when I export with features.

I have strongarm dependency required; but I do not see the view mode options available.

Does anyone have some ideas? I would greatly appreciate the help.

# Answer
> 0 votes
That info is stored in the `field_bundle_settings_node__contenttypenamehere` variable. So make sure you export that for each of your content types.

---
Tags: commerce, features, entities
---


title: How to make an OR statement in rules?

text:
# Question
Title: How to make an OR statement in rules?
I am using Rules with Rules Once Per a Day. Although Once Per a Day is not part of the default Rules, the general core of my question applies to default Rules.

I want Rules per Once a day to activate either on Monday or Thursday. To do this I am using an OR condition:

But it did not work. Is my OR statement set up correctly?

I’ve looked at several Drupal Rules tutorials about creating OR conditions, but they all seem to give different advice. Some say you need a separate OR grouping for each condition, others say all the conditions need to be in one OR group.

NB: My rule exists on the main rules screen and NOT under the components tab.

# Answer
> 5 votes
Both the conditions should be nested under the "OR" line like this:

```
+ OR
  + Current day of the week (is Monday)
  + Current day of the week (is Thursday)

```

What you have at the moment is a clause that says "if the current day of the week is a Monday *and* one of the following conditions is true: the day of the week is Thursday"

# Answer
> 2 votes
# Error in your current conditions

Your rule is not setup correctly. The logic you have in your "conditions" is like so:

* Current day of week is Monday
* **AND** one of the next conditions in the **OR** group must be true:
    + Current day of week is Thursday.
    + **OR** ... nothing else (full stop).

So the condition will never be met: not on Monday, not on Thurday, and not on any other day.

What should work, is that you move the Monday-condition below the **OR**, and also indent it (same indent as for Thursday).

If you'd ever add some other condition, say ABC (at the top, before the **OR**), and with the Monday-condition moved as in my prior paragraph, then that ABC-condition will be combined with an **AND** with the (Monday OR Thursday) condition.

For an interesting video tutorial about this, refer to "Combining conditions". Somewhere around '9:00' (near the end), it has a similar **OR** condition. Here is a summary of that tutorial:

* How to be confused over the positioning of the AND and OR statements
* How to combine conditions with AND requirements
* How to combine conditions with OR requirements
* How to combine AND and OR groups to create complex conditions
* Some advice about the order of conditions
* How to delete reaction rules
* Why you shouldn't use the "send e-mail to all users in a role" action
* Why it might be useful to have messages printed out when configuring complex rules

# Alternative solution

For a possible solution (or at least a work around), refer to my answer to the question "How to publish nodes 3 times a day?".

In your case, you could make it work by creating 2 similar rules, 1 of them to run only on Monday, the other one only on Thursday. That would work also. It's what I sometimes do if multiple AND/OR conditions to be combined are getting too complex (to enhance it's readability).

---
Tags: 7, rules
---


# Question
Title: What is the "correct" way of reporting problems detected by sanity checks, or catching exceptions?
Example I:
You do something with Entity API, which sometimes throws an EntityMalformedException. So you wrap it into a try/catch block. You develop a fallback behavior, but you also want the admin to know that something is wrong.

Example II:
You expect that a specific field on a node is mandatory. There is a block that only works correctly if this field is set, and not empty. You develop a fallback behavior for the case that the field is empty, but you also want to let the admin know that something is wrong.

Example III:
A file you need is not readable. You develop a safe fallback behavior, but also want to let the admin know that something is wrong.

So far what I came up with is to do two things, plus the fallback:

1. Call `watchdog($module, $message, array(), WATCHDOG_WARNING)`.
2. Call `drupal_set_message($message, 'warning')`, if the user has `user_access('administer site configuration')`. Regular users will not see this message.
3. Move on with a safe fallback behavior. E.g. if we cannot render a specific block, we just return an empty block. If we cannot load an image, we show a placeholder image. Etc.

What I see in other parts of Drupal 7 is that corrupt data can travel quite far, without being checked, before something blows up. And mostly I get uncontrolled PHP errors and warnings like "trying to get property of non-object", instead of controlled and checked warnings.

So, what is the "correct" or recommended way to do this stuff? The fact that I am manually doing two separate things here and manually doing the access check indicates that I might be missing something..

# Answer
> 1 votes
In core Drupal `try-catch` blocks are pretty rare, because code is consistent, and core (boldly) assumes that code in contrib and custom modules will be good, too. One core function simply won't send malformed data (like non-objects where object is expected) to another - and won't expect another code to send inconsistent data to it. So `try-catch` would only slow things down. On the database side, and on the user input side, checks are performed all right. This, of course, is by far most recommended approach. If you can make sure your data is coherent, do it. Don't call Entity API at all if you haven't ensure you will not cause `EntityMalformedException`.

The only place it's not possible is a border between Drupal and other systems (including database and http connection). There, you need to put safeguards up. Your points are correct then, but you need to add one more:

1. Call `watchdog`
2. Set message for admin
3. **Tell your user** that what he think he did might have not happened. For example, if your code failed to delete a photo user really, really need to have taken down and you won't tell him, he may be disappointed. In some situation, you may also find yourself in legal trouble.
4. And only now proceed

---
Tags: debugging
---


# Question
Title: How to test Drupal distributions and see examples
Is there a way to see Drupal distributions already installed for testing as demo sites? I was searching drupal.org, where I only found 'case studies'. Sites there are sorted only by categories, not by used distributions, so it is difficult to check every site to find it out.

I want to use and feel distributions before installing them. It would be perfect if link to the demo site would be included in distribution description.

# Answer
> 2 votes
Distributions and modules can easily be installed and tested at simplytest.me

---
Tags: distributions, testing
---


# Question
Title: how to refer to fields with multiple values in node--content-type template
I currently have a template for the article content type.

node--article.tpl.php contains:

```
<?php
    print render($content['body']);
    print render($content['field_file']);
    print render($content['field_tags']);
?>

```

All of those fields are rendered just fine. All the values of field\_tags are rendered. However I'd like to be able to refer to each individual value of the tags field.

For instance, I'd like to be able to do

```
    <span class="customClass i">field_tag</span>

```

and iterate i for each item the field spits out.

I've made some attempts with no luck. I tried

```
$i = 0;
while($content['field_tags']){
    print "<span class='customClass ".$i."'>";
    print render($content['field_tags']);
    print "</span>";
    $i += 1;
}

```

However that just created an infinite loop. I attempted it with

```
while(render($content['field_tags']))

```

as well but that created an infinite loop as well. Is there a way to access the tags field as an array? rather than just one element in the $content array?

# Answer
I managed to accomplish this by appending \[value\] to the end of the field\_tag array. Then by using the 'count' function I created a for loop to iterate through each value like so

```
$j = count($content['field_tags']);
for( $i = 0; $i < $j; $j+= 1){
    if(render($content['field_tags'][$i]) != ''){
        print "<span class='customClass ".$i."'>";
        print render($content['field_tags'][$i]);
        print "</span>";
    }
}

```

Note: For some reason I had to insert a check for if the tag was empty because the array ended up being a lot larger than the number of the tags.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: Use taxonomy_get_term_by_name when there are duplicate names across multiple taxonomy categories
UPDATE: I see that most likely the best way to accomplish this is to grab the term id from $content\['field\_tags'\]. However I'm not sure how to do that. Whenever I retrieve $content\['field\_tags'\]\[value\] all that gets returned is an array object. And when I attempt to render it all I get is the tag name.

---

I'm attempting to grab the taxonomy term id in the node template for a content type. I'm grabbing the taxonomy term by referencing the field that contains the taxonomy terms. Like so

```
$tag = render($content['field_tags'][$i]);

```

I then use taxonomy\_get\_term\_by\_name in order to grab the id for that term like so.

```
$term_array = taxonomy_get_term_by_name(render($content['field_tags'][$j]));
$term = reset($term_array);
$term_id = $term->tid;

```

It works like a charm except for one issue. I have a taxonomy category for tags as well as events, and when there is a term with the same name in both the 'event' and 'tags' category it grabs the event term id instead of from the 'tags' category, which I want.

Is there another way to grab the specific term id for the tag field? Would it be possible to grab the term id directly from this object?

```
$content['field_tags'][$j]

```

# Answer
> 0 votes
Yes, you should pull the term ID directly from the field value rather than first rendering it to a term name, then trying to look up the term based on the name.

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


# Question
Title: View of users having same taxonomy terms?
I'm running a D7 system where every user has a skills field which is a taxonomy field.

How do I create a view to pull users where they have/share same skills (taxonomy id's) with the login user.

So for example If I've added 'photoshop' to my skills and when I login the view should provide me other user who have tagged their profiles with taxonomy term 'Photoshop'.

**Note:** view of users having same taxonomy term as well as login user have.

Thanks

# Answer
The right way to solve this is by writing a default argument handler. A patch to do this was started here: https://www.drupal.org/node/721390

A "shortcut" to doing this would be to use the PHP Code default argument handler and plug it in directly. This is not generally recommended; it would be much better to put the code in a custom default argument handler so you should Google around for how to set one of those up as that's a bit beyond the scope of this question. But here are the steps for using the PHP Code approach and you can use the same logic for a default argument handler:

1. Create a view listing users
2. Add a contextual filter to filter on the user skills field
3. In the contextual filter option, for "When the filter is not in the URL" choose "Provide a default value" and select "PHP Code" from the list.
4. Assuming your field is named "field\_skills", enter the following:

PHP code:

```
global $user;
$account = user_load($user->uid);
$terms = array();
if (!empty($account->field_skills['und'])) {
  foreach ($account->field_skills['und'] as $value) {
    $terms[] = $value['tid'];
  }
}
return implode('+', $terms);

```
5. Down towards the bottom of that form there's a "more" link. Be sure to open that section of the form and select "Allow multiple values".

At this point, you should have the list that you want with one caveat: the currently logged-in user will show up in this list. You probably don't want this. To prevent that from happening add another contextual filter that excludes the current user from the list:

1. Add a contextual filter on the User:Uid value
2. Choose "Provide default value" for "When the filter is not in the URL" and, out of that list, choose "User ID from logged in user".
3. Under the "more" link at the bottom, choose the "Exclude" option.
> 2 votes

# Answer
This is so simple to create views of users having same taxonomy terms.

1. Add a new views of type user.
2. Under **Filter Criteria** add your term field ie *skill field* and select a term(photoshop) according to which you want to filter. Save the views and cheers.
> 0 votes

# Answer
This is how it should be done -

* Create a views block of users.
* Add a **relationship** for your required taxonomy vocab (in your case it's skills)
* Add a contextual filter of **User:uid**, provide value from URL & add default argument as **Userid of logged in user**.
* Place block on relevant page & check.

Note - I haven't done it myself or have similar exp. But logically, this should work.
> 0 votes

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


# Question
Title: What are my options to visualise a views table with many fields grouped in columns?
I have a view with 30 fields. Displaying its results would look best using a table, but with fields grouped in columns.

Default table in Views can't do this because there are to many fields.

So instead of what it looks now:

> field-1 header, field-2 header, field-3 header, field-4 header, field-5 header, etc. (with default field under each header)

I need:

> **header1 I header2**
>
> field-1 I field4
>
> field-2 I field5
>
> field-3 I field6

Any suggestions?

**Notes**:

* It's something I would like to do on several views with a module or "simple" theming.
* I tried the groupfield views module (broken when using table format, works great on html, unformated, etc.).
* I tried DS views layout, but can't use CSS on each field on that one.
* I'm thinking of Panels, but that seems like overdoing it just to get simple view display for my case.

# Answer
> 2 votes
The DataTables module might help for answering this question. Here is a quote from its project page:

> The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:
>
> * Variable length pagination
> * On-the-fly filtering
> * Sorting with data type detection
> * Smart handling of column widths
> * Themeable by CSS
> * And more ...

Another feature that it offers is that you can "hide" specific columns from the default table display. But still the user has the option to do things like:

* expand the hidden columns.
* use the DataTables search feature to search for rows containing one or more strings contained in ... even those hidden columns.

So in this question here, I'd use an approach to only show, by default, a subset of all those columns, and leave it to the user to yes/no also display these (initially hidden) columns.

A few more links you may want to look at:

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.

The last link in these settings relates to hidden and collapsed columns (you can see the link in the video, though it is not expanded). So there is where you can then specify which of your (many?) columns you want to be processed as collapsed columns (not sure if you want any of them to be "hidden "in you case. Experiment a bit with those options in your environment to check if it is an acceptable compromise (or alternative) for "grouping" your fields (table columns), i.e.:

* fields you **always** want to be shown.
* fields you want initially to be excluded from the display, but for which you **let the user decide to optionally also shown one or more of them**.
* fields you **never** want to be shown.

# Example

Below is a screenprint of such display using DataTables. It's a display I created using Views (of course) with a table with:

* 8 fields in (defined in my view).
* 5 table columns for the 5 fields I have decided to always show.
* 3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

For each row there is a link '***Show Details***' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to '***Hide Details***'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.

**Bonus**: assume none of the rows are shown expanded, and you type "`Basic`" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with `Basic Page` as value for "Type". But wait, there is even more: if you'd type a string like part of "`21:15`" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.

# Remarks

* Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

> While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables \<= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.
* When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).

---
Tags: views, theming
---


# Question
Title: How do I load specific page template for /store-locator
I want to control the region the store locator and panel being placed into. I was hoping I could just use a content-type page .tpl to move things around within the rest of the layout, but that doesn't seem to be working.

After trying it and it not working I'm guessing all that would do is change the display of the actual "/name-of-store" path and not the sitename/store-locator path.

Store Locator seems to be an odd duck. I can't find anything in the code that would point to a tpl file. It certainly isn't a view in a block since it's basically being rendered in the primary content area of my standard tpl file.

My first wish is to have a separate page.tpl so I can get all the parts of pieces of the page where I want them. Being that it looks like all the code is generated in JS, I can't even think of a way load that into a view and then but the view in a panel layout that's full width.

Any thought on what the page tpl needs to be and what the right theme hook would need to be in preprocess? This is what I have working for my other hinting for page tpl's.

```
  if (isset($variables['node'])) {
  // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $variables['node']->type);
  }

```

# Answer
There are many possible ways to solve this problem. My suggestion, however, would be to use the Page Manager Existing Pages module. This module will let you easily override the callback at that URL and place the content for the page in any region of your Panels layout.

If you want to do it the same way as you've been doing it for other pages, then there will already be template suggestions automatically provided for you, derived from the path. So if the path to the item is `sitename/store-locator` then the template suggestions that will already be automatically created for you are page\__sitename and page\__sitename\__store\_locator. You need only to create those tpls.

That said, I'd still generally recommend the PM Existing Pages module for this type of functionality.
> 0 votes

---
Tags: theming, google-maps
---


# Question
Title: Taxonomy term title not displayed as page title in Panels when paged
I have use case where for some terms, on the term pages (where nodes with that term are displayed) where for selected terms, I need to display an image instead of the title. To (try to) do this, I've done the following steps:

1. Add field\_image to the vocabulary.
2. Upload images for selected terms
3. Enabled the built in taxonomy term panel page.
4. Created a content pane in the built in taxonomy term view that passes the tid.
5. Created a term view with a content pane display with term name and field\_image as fields.
6. Hide term name from display, and set term name to be displayed in the No Results settings for field\_image.
7. Add the content pane to the panel page display above the content pane from the taxonomy term view.

This all works great - on the first page. However, once I use the pager (from the view) to go to any subsequent pages, the page title (i.e. the term name or image) disappears. Looking at the page source, you can see that the panel pane with the term title (step 5 above) is not added at all, which makes sense, since there aren't multiple pages of term titles.

Is there a way to do what I need with the Views and Panels UI, or will I need to wield some code fu to replace the name with the image selectively?

Thanks.

# Answer
> 0 votes
Your pager IDs are conflicting. Adjust the pager settings for one of the views to have a pager ID of 1 rather than 0.

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


# Question
Title: How to add a div tag after a specific field?
I have a view with four fields: *title, body, poster, podcast*.

I want to **add a div tag after poster field**. How can I do this?

# Answer
You can simply rewrite result of poster field (it's in poster field settings), but you need to display fields, not content. Just add there poster token and div

Upd: ong, what am I about. If you display fields in your view, you can add custom Global text field. And write there custom html, remember to use php filter(works 100%, mb one another works too).
> 0 votes

# Answer
Use the **Rewrite Results** in your View in combination with a Token. That way you can customize your field's output to your needs. To do so:

1. In your *View*, within the *Fields* area, click on the desired field. E.g. *Poster*
2. Click on *Rewrite Results* and check *Rewrite the output of this field*. So, assuming that your field's machine name is *field\_poster*, you just have to add its corresponding token and your div where desired. E.g.

As you can see, in the **Replacement Patterns** area right below you can find all the available tokens in your View, so change accordingly.

*Note that I'm assuming your View allows Fields (since it's not specified in your answer), which is required to use these instructions.*
> 0 votes

---
Tags: 7
---


# Question
Title: How to programmatically delete a display from a view
Is it possible to programmatically delete a display from a view?

The view object has numerous member functions related to displays (add\_display, attach\_displays, choose\_display, set\_display, new\_display, etc.) and I can also disable a display like this:

```
<?php
  $view_name = "faq";
  $display_name = "page_1";
  $view = views_get_view($view_name);
  $view->display[$display_name]->display_options['enabled'] = FALSE;
  views_save_view($view);
?>

```

But I can't see how I can remove the display completely. Can anyone advise? Thanks!

# Answer
> 3 votes
This is how you do it. It is how it is done in views\_ui\_edit\_view\_form\_submit() when you delete a display via the admin UI:

```
unset($view->display[$display_name]);

```

---
Tags: views
---


# Question
Title: How do you go to an overlay view within Drupal using drupal_goto?
I want to redirect to a page with an overlay within code. I have tried the following, which is the path in the URL.

```
 drupal_goto('#overlay=admin/vendor/auth-stripe');

```

The path I want in overlay is admin/vendor/auth-stripe. When I remove the #overlay= it works, but I want my user to see it in overlay mode.

# Answer
> 4 votes
You cannot pass a URL fragment into drupal\_goto() like that or it will get escaped and won't work properly.

From the drupal\_goto() docs it says the second parameter is an array of `$options` that get sent through to the url() function.

Looking at the url() function docs shows that one of the allowed `$options` is:

> **'fragment':** A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

So you should be able to do this:

```
drupal_goto(current_path(), array('fragment' => 'overlay=admin/vendor/auth-stripe'));

```

Note the use of current\_path() as the path so that the page under the overlay will be the on the user was previously on.

If you didn't want that, then this would use the front page instead of the current page (because if you pass an empty path into the url() function it uses the front page as a default):

```
drupal_goto('', array('fragment' => 'overlay=admin/vendor/auth-stripe'));

```

---
Tags: modal-dialogs
---


# Question
Title: How does Drupal 7 page/block cache work?
I have a few questions about drupal 7 page/block cache.

If I enable the cache and set the expiration time for 15min., and the content in page A is updated within next 10min., will the cached version be updated? or will it only update every 15min.?

Does same apply to blocks?

# Answer
From your question I get that you are trying to set the caching from the performance page `admin/config/development/performance`.

**Cache pages for anonymous users** only works for anonymous users, and the page markup is stored in database (to reduce the number of queries). And you can check the HTTP Header `X-Drupal-Cache` to see if this cache is HIT.

**Cache blocks** (if Page caching is disabled) works for anonymous and logged-in users. And again, the whole block markup is stored in database for the same reason.

**Minimum cache lifetime** is the amount of time before the Page cache gets cleared (the cache is cleared on cron run).

**Expiration of cached pages** works only if page caching is enabled and is only applied to external caching mechanisms (like the browser cache)
> 8 votes

# Answer
There is a lot of confusion about how settings such as Minimum cache lifetime works. The best description I have found on it is this article by Brian Osborne. This article is a must read for anyone getting their heads around how caching in Drupal core works.

In your example, if you set the Minimum cache lifetime to 15 mins. The first time a cache clear is triggered (e.g. you edit a node, create new comment, etc.) Drupal will preserve the existing cached page (if it already exists) and note the current time. The next time an action which triggers a cache clear is called it will compare the current time with the previously noted time. If the elapsed time has exceeded 15 mins the cache (including pages and block cache) will be cleared.
> 2 votes

---
Tags: caching
---


title: Title showing 'Home' on Tabs

text:
# Question
Title: Title showing 'Home' on Tabs
I am creating a module for searching a library of books. I have created a set of tabs on the module display page.

* Search
* Results
* Item

The title when the Search page is selected (or default) is as I would expect "Search" however when I go to either of the other tabs (via link or a click) the title of the page is shown as "Home". While not a major issue it doesnt look good.

I have set the 'title' attribute of the render array for each page to 'Results' and 'Item Details' respectively. How do I force this title rather than 'Home'.

I have noticed the same behaviour for pages using 'MENU\_CALLBACK'.

# Answer
> 2 votes
> I have noticed the same behaviour for pages using 'MENU\_CALLBACK'.

I had this problem today, and changing the menu type to `MENU_SUGGESTED_ITEM` allowed the title callback to be used.

# Answer
> 2 votes
The page title is by default the title defined in `hook_menu` for the menu item. If you want to alter the title, you should use `drupal_set_title`.

Note: Drupal set title can't be used to late in the theming process (like `template_preprocess_page`), as the value for the title has already been populated at that point. Using it in the menu callback should work just fine.

# Answer
> 1 votes
This relates to an outstanding bug in Drupal core.

Often when you have menu tabs you want the page title to be that of the parent page, not the current tab. The tab in effect is its own sub-title.

This doesn't work all the time though. In the case where the parent page is not relevant (in this case the home page) you end up with an unexpected page title.

This issue is currently in progress to resolve this problem. The current patch in comment #26 specifically singles out the case where the parent page is the `<front>` page and then uses the title of the current tab.

I am using that patch and it seems to work as expected.
It fixes the very long standing problem of incorrect "Home" titles on those user login/register/password pages.

# Answer
> 0 votes
Perhaps you did not set one tab to be the default local task. MENU\_DEFAULT\_LOCAL\_TASK is the constant to use in the definition of such menu callbacks.

---
Tags: 7, routes, hooks
---


# Question
Title: See which context is used on a page when looking at the page
When you are watching a page, is there a quick way for seeing all of the contexts that are being applied? Ideally I would like to be able to see which context is responsible per the blocks.

# Answer
You can use the active context api to get this done.,

```
$contexts = context_active_contexts();
print_r (array_keys($contexts));

```

Place the above code in your form\_alter or in any hook\_node\_view. This will list the active context in the page.
> 4 votes

# Answer
Apart from using the Devel module as suggested in the previous answer, there is also the Devel Catcher module (which has Devel as a module dependency).

Here is an excerpt from its project page (why you may want to consider this module):

> ... aggregates or "catches" all development debug info into one easy to access place.
>
> Similar in style to Firebug or Chrome's Inspector. Devel Catcher intercepts common debug info into a tabbed interface as opposed to having to assign debug blocks to a region or dumping the output at the end of your HTML document.
>
> Currently Devel Catcher can catch the query log from the Devel module, node access rules from the Devel Node Access module and the context inspector block from the Context UI module.

Another way to look at this: it enhances your "debugging" experience (hm, hm ...).
> 1 votes

# Answer
If you have the Devel module enabled it provides a block called "Context Inspector" which you need only place in a region on your page in order to see the current contexts output via Krumho.
> 0 votes

---
Tags: 7
---


# Question
Title: Is there a module for cataloging images (and other media)?
I am looking for a tool to catalog images (and other media) that would let me retrieve an image (for insertion into content) based on several search criteria.

# Answer
I would strongly warn against using the Media module. And this is from a person who has spent many years implementing the Media module on many major sites. It still has virtually-insurmountable problems with its WYSIWYG integration along with lesser-but-still-significant bugs of other types. I don't want to take away from the many great developers who have contributed to it over the years, but I just cannot in good conscience recommend it as it stands.

I would, instead, point you to the Scald module. Its approach of having a separate media entity (called an Atom) is less intrusive than Media/File Entity's approach of taking over all of your files. Scald also has far superior WYSIWYG integration.

The Asset module is another to consider. It's similar to Scald in terms of overall architecture but it hasn't seen as much maintenance so it's probably best to stick with Scald.
> 2 votes

# Answer
I'm not sure why you were down-voted. It is a good question to ask.

I would recommend the Drupal Media module. This one has the most integrations and allows you use views with exposed filters to be able to easily search through your media library. And easily catalog it with taxonomy. You can add content to the media items when you're selecting these from the browser, and even use the exif module to insert automated meta data upon upload.

Another option would be as Aaron mentioned, the Scald module But I have seen inconsistencies on how they handle different media items outside of WYSIWYG. Eg. Not being able to use it on a video file field.

In D8 there will be a module called Media Entity which integrates the different Media Browsers. That lists MediaBox and Asset too.
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to validate webform with JavaScript?
I've got a Webform for which I need additional calculations to hidden fields.

I've added a JavaScript file to the page by using `drupal_add_js`. And let that be the only part that works...

My **calculate.js** file looks like this:

```
document.getElementById("webform-client-form-80").onsubmit = function() {
  window.alert("Test!");
  document.getElementsByName("submitted[aantal18plus]")[0].value = 5;
};

```

Why don't I get an alert? And why doesn't the value of "**submitted\[aantal18plus\]**" get altered?
If I change "document.getElementById("webform-client-form-80").onsubmit" to "document.onload", **everything works**. But unfortunately, there isn't any data yet (tried with windows.alert("");)

**A bit more context:**
The form is a subcription form for a BBQ. I Have 16 fieldsets (for 16 persons at once) with 4 dropdown menus (for choice of meat). A LOT of fields, and a lot of different prices. I want to calculate things like 'total' and 'number of steaks'. I want to send those in the submission e-mail, so I created 12 hidden fields, and I do need to calculate those values on submit.
I don't (necessary) need JQuery. At submit will do fine, 'cause the fields I'm altering are hidden.

Simply put: `onsubmit`, how on earth do I get it to work with javascript in drupal??

# Answer
You can create a **custom module** for that:

1. webfv.info
2. webfv.module
3. webfv.js

Put all these files into a folder called **webfv**.

This is the **webfv.module** file:

```
<?php
function webfv_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'webform-client-form-80') {
    $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'webfv') . 'webfv.js',
    'type' => 'file',
  );
}
}

```

And this is the **webfv.js** file:

```
    (function($) {
      $(document).ready(function() {
      // Put your code here. //
      });
    }) (jQuery);

```

And of course, you should have a **webfv.info** file:

```
name = webfv
description = JavaScript Webform Validation
core = 7.x
files[] = webfv.module

```

Note: this is just one way of doing it, there are some other ways.
> 5 votes

---
Tags: 7, webforms, forms, javascript
---


# Question
Title: How to call AJAX on check-box of form API?
**I need to get radio buttons in a form, whenever a checkbox gets enabled/clicked.** Say, I have 5 items listed in a checkbox, named orange, apple, .....When I enable orange checkbox, a set of radio button comes that will ask color of the corresponding fruit. Any working example regarding this will be highlyy appreciated.

**EDIT**:

```
$form['toggle_me'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Tick this box to type'),
   '#options' => array(0 => t('Orange'), 1 => t('Apple')),
);
$form['settings'] = array(
  '#type' => 'radios',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"][#options][0]' => array(0 => t('red'), 1 => t('yellow')),
    ),
  ),
);

```

# Answer
> 1 votes
Try This, may be helpful for you

```
$form['checkbox'] = array(
    '#title' => 'Select',
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('Orange'), t('Apple'))),
    '#ajax' => array(
      'callback' => 'fruits_callback_form',
      'wrapper' => 'fruit-check',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  $checkbox = !empty($form_state['values']['checkbox']) ? $form_state['values']['checkbox'] : 0;
  $form['slots']['#prefix'] = '<div id="fruit-check">';
  if ($checkbox == 'Orange') {
    $color = array(0 => t('Red'), 1 => t('Blue'));
  }
  $form['color'] = array(
    '#type' => 'radios',
    '#title' => t('Select Color'),
    '#options' => $color,
  );
  $form['slots']['#suffix'] = '</div>';

  //Callback function

  function fruits_callback_form($form, &$form_state) {
    return $form['color'];
  }

```

---
Tags: forms
---


# Question
Title: How to remove a comment based on it's field value?
I have a multilingual site, Comments in this site include a language field (`field_language`), so users who send comment to nodes must specify in what language they are sending the comment. On loading a node I want to display only the comments which their `field_language` is equal to the current website language. I tried this code based on the following result

```
function THEME_preprocess_node(&$variables) {
    global $language;
    foreach ($variables['content']['comments']['comments'] as $comment)
        if($comment['field_language']['#items'][0]['value'] != $language->language)
            unset($comment);
}

```

The `$comment['field_language']['#items'][0]['value']` prints the comment `field_language` so I'm sure this is a correct syntax and the condition holds for a few comments but `unset($comment);` doesn't unset the comment.

I tried the following code

```
unset($variables['content']['comments']['comments'][71]);

```

and it successfully worked and removed the comment. The ID inside the `[]` is stored in the `$comment['#entity_view_mode']['id']`, I can easily use this ID to remove the comment but I think there must a more straightforward solution.

Is there any other solution like using `hook_comment_load` or anything else?

# Answer
> 2 votes
This code should work for you

```
function THEME_preprocess_node(&$variables) {
  global $language;
  foreach ($variables['content']['comments']['comments'] as $key => $comment) {
    if ($comment['field_language']['#items'][0]['value'] != $language->language) {
      unset($variables['content']['comments']['comments'][$key]);
    }
  }
}

```

---
Tags: nodes, comments
---


# Question
Title: How to set 'html' email template for webform email setting?
Is there any way to use html email for e-mail template in webform email setting?

In my webform node I go to: node/113/webform/emails/1 to change the setting but I don't see any 'html' option. Look my capture:

# Answer
HTML Mail will give you that option. It integrates with Webform. To use HTML Mail you will also need Mail System.

Go to Configuration \> Mail System and set the Site wide Default to be HTML Mail and the HTML Mail module to be HTML Mail.

And if the option "Send e-mail as HTML" does not appear while editing a Webform email. Go to: `admin/config/content/webform` **check** "HTML mail system".
> 22 votes

# Answer
If the option "Send e-mail as HTML" does not appear while editing a Webform email, visit admin/config/content/webform and select *HTML mail system*.

This was my issue.
> 7 votes

# Answer
You could use the Mimemail module which I have used in the past. It allows you to have a html mail option per webform email configuration. This also needs the Mail System Module
> 2 votes

---
Tags: webforms, emails
---


# Question
Title: Accessing content for a specific node revision via a relationship in Views
A module I've written implements hooks defined by the Field API to provide a custom field for defining references to specific node revisions by storing vids. (The module borrows functionality from the Entity Reference, Node Reference and Node Revision Reference modules.)

I have a requirement for "parent" nodes to reference a specific version of one or more "child" nodes. The child node(s) may be modified (i.e. new revisions created) after a reference to it is stored against a parent node. It's essential that the reference on the parent node continues to refer to the same revision of the child node unless the reference is manually updated to a newer revision by a user with sufficient permissions.

I'm currently working on Views integration for the field defined by my module. When creating displays containing one or more parent nodes, I'd also like to be able to display field data for any referenced revisions of child nodes. I've defined the following relationship in my module:

```
/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Get database table info for $field.
  $storage = $field['storage']['details']['sql'];

  foreach ($storage as $table_data) {
    $table = key($table_data);
    $columns = current($table_data);
    $id_column = $columns['vid'];

    if (isset($data[$table])) {
      // Relationship: node revision referenced from $field.
      $data[$table][$id_column]['relationship'] = array(
        'title' => t('Referenced node revision'),
        'label' => t('Node revision referenced from !field_name', array(
          '!field_name' => $field['field_name'],
        )),
        'help' => t('A bridge to the node revision that is referenced via !field_name.', array(
          '!field_name' => $field['field_name'],
        )),
        'group' => t('Node revision reference'),
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'vid',
      );
    }
  }

  return $data;
}

```

This relationship allows me to display field content for child nodes where the referenced revision is the *current* revision. However, if an *old* revision is being referenced by a parent node, the field data is empty. This behaviour occurs when I create a view displaying either content or content revisions.

Does anyone know of a way of accessing field data for a specific node revision via a relationship in Views regardless of whether it's the current revision or not?

Thanks in advance to anyone who can offer any suggestions!

# Answer
One thing you could try is creating a class that extends views\_handler\_relationship and override it's query() method using logic that's specific to your use case rather than the generalised logic that's in views\_handler\_relationship-\>query(). Then change the "handler" in your relationship declaration to point at your subclass.

Hope it helps.
> 0 votes

---
Tags: entities, nodes, views
---


# Question
Title: footer block through custom module and fetch node image field in Drupal 7
I want to create footer block through custom module and want to add five images through node.Five images should change one by one after one hour.

Can anybody tell me how to do this ?

```
<?php

function chat_block_info() {
  $blocks['chat_footer'] = array(
    'info' => t(' FOOTER'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

function chat_block_view($delta = '') {
  $block = array();

  switch($delta) {

    case 'chat_footer' :
      $block['chat_footer'] = array(
        '#markup' => chat_footer_block('footer'),
      );
      break;
  }
  return $block;
}

function chat_footer_block($parm) {
 if ($param == 'footer')
 {
   $node = node_load(11111);
    $uri_top = $node->field_footer_image['und'][0]['uri'];
    $alt_top =$node->field_footer_image['und'][0]['alt'];
   $image_top = theme('image_style', array('style_name' => $footer_chat,
        'path' => $uri_top,
        'getsize' => TRUE,
        'alt' => $alt_top,
        'title' => "IMG"
      ));

}

}

```

# Answer
> 0 votes
To accomplish this I would probably use a combination of hook\_cron() to check in every hour, *persistent variables* to track the last loaded image (see variable\_set and variable\_get) and the great Ajax Blocks module so that your block is refreshed without having to rebuild the entire page each time.

---
Tags: 7, theming, commerce, blocks
---


title: Add JavaScript to a node form

text:
# Question
Title: Add JavaScript to a node form
I'm trying to add a custom JavaScript file to the forms to create or edit a node.

I've tried `mythemename_preprocess_page()`, `hook_form_alter()` and `theme_content_type_node_form()`. They seem to pick up the page I am on, not the form in Drupal's Overlay with the form in it.

Obviously I want the JavaScript code to fire only when I'm actually on the form. So just putting it in a `onReady` function in a JavaScript file loaded on every page won't suffice.

This is the code I am using on the *template.php* file.

```
function zeilschepen_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'node-accommodation-form':
      $form['#after_build'][] = 'zeilschepen_after_build';
      break;

    case 'views_exposed_form':
      if (isset($form['field_country_value'])) {
        $form['field_country_value']['#attributes'] = array('placeholder' => array(t('Land...')));
      }
      break;
  }
}

function zeilschepen_after_build($form, &$form_state) {
  $theme_path = drupal_get_path('theme', variable_get('theme_default', NULL));
  drupal_add_js ("$theme_path/js/test.js");
  return $form;
}

```

This is the content of the *test.js* file.

```
(function ($, Drupal, window, document, undefined) {
  Drupal.behaviors.test = {
    alert('test');
  }
})(jQuery, Drupal, this, this.document);

```

How can I correctly add JavaScript code in a node form?

# Answer
This:

```
node-accommodation-form

```

Is the **HTML ID** of the form, found in `$form['#id']` (confusing I know). You need the **internal ID**, which is

```
node_accommodation_form

```

As in:

```
function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node_accommodation_form':

```

Using `#attached`, as mentioned in comments, is far preferable to `drupal_add_js()` when you get to that part.

As an aside, you may find coming back to your code later on a bit easier if you separate out your form alters like so:

```
function MYMODULE_form_node_accommodation_form_alter(&$form, &$form_state, $form_id) {
  // Logic specific to the accommodation node form, no need to check form ID.
}

```

Also, as noted in another answer, theme hooks are only run when the theme is actually in use. So if you're using the admin theme for your node edit forms, your code will never run. If that's the case, you need to move the logic to a module.
> 8 votes

# Answer
I think **hook\_form\_alter()** will help you. Try this:

```
   function yourmodule_form_alter(&$form, &$form_state, $form_id){
     if($form_id == "your form id") {
       drupal_add_js('your js file');
     }
    }

```
> -1 votes

# Answer
You need to use hook\_form\_alter(&$form, &$form\_state, $form\_id) function. place this function in the `template.php` and print the `$form_id`, So now you can get the ID of the `add/edit` form.

Now you must use drupal\_add\_js function to load that Javascript file.

```
function THEME_form_alter(&$form, &$form_state, $form_id){
      if($form_id == "YOUR_FORM_ID")
                drupal_add_js(drupal_get_path('theme', 'mytheme') . '/JS_DIRECTORY/mytheme.js');

```

This code loads `mytheme.js` from `JS_DIRECTORY` of your theme folder.
> -1 votes

---
Tags: 7, nodes, forms, javascript
---


# Question
Title: Get all users with edit/view permission for a node
I'm working on a Drupal 7 project. And for this I need to get all the users that have a certain permission for a `node`. I need this info in the `hook_node_update` method, which means that I can currently get the `$node` object just fine but I'm unable to find a way to query a list of users that have edit rights to the particular node that's being updated.

Can anyone provide an insight? That would be great!

Thanks.

# Answer
So I managed to come up with the following solution:

```
function revision_author_token_node_update($node) {

  $users = entity_load('user');
  foreach ($users as $user) {
    $account = user_load($user->uid);

    if (node_access("update", $node, $account) === TRUE) {
      dsm($account);
    }
  }

}

```

This seems to do the trick as it first loops through all the users and then checks if they have edit rights.
> 0 votes

# Answer
Every content type has fix pattern of permission

For node edit permission, Just use user\_access() with string parameter "edit own \[content-type\] content" OR "edit any \[content-type\] content" If current user has this permission it return TRUE else FALSE

AND

If you want this permission for other user, Just pass user object as second argument in user\_access()
> 0 votes

# Answer
One problem you might run into is that you can't reliably get this list of users via a database query only since access (or editing) rights can be modified in code by any module. This means that a views based solution probably won't cut it either.

One possibility is to get a shortlist via a view / EntityFieldQuery / db\_select(), and then loop through and check if each user has edit access using node\_access(). For performance your query could limit to certain roles if you have large numbers of users without edit permissions.

Once you have you have your shortlist (I'm using an array of user objects here but adjust this code if you're working with a different format) do something like this:

```
$node = node_load(12345);
$accounts_with_edit_access = array();
foreach($shortlist as $delta => $account) {
  if (node_access("update", $node, $account) === TRUE) {
    $accounts_with_edit_access[] = $account;
  }
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: Drupal 7 comments spam with Captcha installed
I have a multilanguage - multidomain website developed in Drupal 7, and the database have been flooded with spam comments, even if I have Captcha module (image) installed. The spam comments are from 60 different IPs, and I have seen attempts to add node and add user (which is blocked) in the incidents reports.

So I cannot block so many IPs at the risk of them being dynamical and loosing potential users.

What could I do to prevent the spam and also to prevent the attacks? Thanks

# Answer
**"to prevent the attacks"** \- not much can be done here. If an attempt to access node/add page ends with access denied page, its ok. You cant prevent users from entering urls in their browsers.

As for spam in comments, try some different modules for Captcha (Google reCaptcha with noCaptcha for example). For different aproach, Honeypot can help limiting "robots" behavior.
> 0 votes

---
Tags: 7, comments
---