# Question
Title: How to can create a user profile with approve changes by admin
I want if user changes his/her profile information they not applied till administrator approve them,I am using drupal 7 ,How can I do this ? is there any module exist for this job?

# Answer
A custom way can be(will need custom coding) do not expose profile fields directly to users to edit, instead each user will have a node(one to one strict mapping) node will have fields that will be mapping to user profile fields. Once a user edits a node you can set a workflow to mark it as unpublished and once admin reviews and publish fields user profile fields will be updated with node fields.

So a possible workflow can go something like

1. User can edit node(name it user\_node) belongs to user only, you can keep user reference field on node to check the edit permissions.
2. When a node(user\_node) is edited check the current user if user is not admin set $node-\>status = 0, you can use hook\_node\_presave() for this.
3. If a node(user\_node) is edited by admin keep a checkbox as approve(field visible to admin only, you can use field permissions module to allow admin to see this field).If admin approves the node again in hook\_node\_presave() change $node-\>status = 1 and take the uid from the user reference field on the node, update the user profile fields with the current node field values, you can use user\_save() function for this.

This is just a rough idea which require coding, I have not checked if there is a module which can set workflow for user profile if there is any it can provide you want you want out of the box.
> 0 votes

---
Tags: users
---


# Question
Title: How should I display fields for a content type?
I have a complex content type with several user-defined fields. In Drupal 6, I used Contemplate to display the fields in an HTML table. I've just upgraded to Drupal 7 and I'm wondering how to best achieve this now. The Contemplate project seems to suggest that Drupal 7's field display features are the way to go. But how do I create and populate an HTML table with a node's fields in Drupal 7? Do I extend/override a theme?

Update: To clarify, let's say I have several nodes with the same content type `history`. How do I display each of these nodes in the same specific way, including some of the user-defined fields I've attached to that content type. In addition, I use the `pathauto` module to give each of these nodes a path like `history/<year>`.

# Answer
Show fields for a content type, you have to create a new file node.tpl.php inside your theme. And you have to use the function var\_dump, like that:
var\_dump(array\_keys($content)) //so you can see all the fields availables

After that, you can print all the fields inside the node.tpl.php in using the function **render**:
*print render($content\[FIELDNAME\])*

Check this url https://api.drupal.org/api/drupal/modules!node!node.tpl.php/7
> 1 votes

# Answer
You can use display suite module to theme your node.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

If you want to theme your node using code, then you should create *template* for your node. Check this link for reference.
> 2 votes

# Answer
As as option you can check views module, it basically provides ui to query and display your entities(nodes,users etc.) in different formats(table is one of them) out of the box.
> 1 votes

# Answer
As arpitr already wrote, the best way would be to use Views and its contextual filters. Add contextual filter: node id (nid) and provide default value nid. Add the fields you want and enable block display.

E. g. you have an article with "address" field. If you enter the address, it will be displayed in that block only on that page (the one that has address entered). You can display data in table format, grid, list, unformatted etc.

You can find out more about contextual filters here:

https://drupal.org/node/1578558
> 0 votes

---
Tags: 7, entities, nodes
---


# Question
Title: How to get author specific poll in most recent poll block?
I Created a poll with core module "Poll".

Can we get author of the poll and display in Most recent poll block?

I have using `block--poll--recent.tpl.php` to theme the poll. I have tried by global user. but how to get a poll of that user??

# Answer
As every content type polls are node then you can get the creator by get node creator :)

$title:the title of poll

```
$node = node_load(array('title' => $title, 'type' => 'poll'));
$userId=$node->uid;

```

not we have a userId of creator , maybe you need name or anything of it that you can get them by `user_load($userId);`
> -1 votes

---
Tags: 7, nodes, polls
---


title: Custom module library not detected

text:
# Question
Title: Custom module library not detected
I am writing a custom module to load the crossfilter.js library in Drupal 7. I have followed what I believe are the right steps to doing that when using the Libraries module API. However when I run `drush libraries-list` all I get for my library is 'not detected'

Below is my sample code. I intend to load version 1.3.7 of the library and already I have a directory called `crossfilter` and I have the crossfilter.js and crossfilter.min.js files in that directory.

What could I possibly be doing wrong?

```
function crossfilter_libraries_info() {
$libraries['crossfilter'] = array(
  'name' => 'Crossfilter JS',
  'description' => 'Crossfilter JS integration for Drupal',
  'download url' => 'https://github.com/square/crossfilter/archive/master.zip',
  'vendor url' => 'http://square.github.io/crossfilter/',
  'version arguments' => array(
      'file' => 'crossfilter.min.js',
      'pattern' => '/version="(\d+\.\d+\.\d+)"/',
   ),
  'files' => array(
      'js' => array('crossfilter.min.js'),
    ),
  'variants' => array(
      'source' => array(
          'files' => array(
              'js' => array('crossfilter.js')
            ),
        ),
    ),

);
return $libraries;

```

}

# Answer
Most likely your version regex ist wrong. According to the source code, the version string looks like this:

```
crossfilter.version = "1.3.7";

```

The regex pattern needs to account for the whitespace around the equal-sign. I'd probably write it like this

```
'pattern' => '/crossfilter\.version\s*=\s*"(\d+\.\d+\.\d+)"/',

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How create Redirect pattern from old to new URLs?
D7: I'm going to update an articles path pattern (/articles/\[node:uid\] → /post/\[new tokens\]) but I need redirect users from old path to new one using tokens. And I don't know how to do that. I tried using the Redirect module, but it allows set only separate URL for each node; no group redirect patterns are allowed. Also the Rules module doesn't allow to set patterns. How can I achieve this?

---

The problem partially solves by applying "Update url alias" option in admin/content. I do not find out how to show all selected type nodes at one page without pages, because it is terrible slow applying option page by page.
Anyway, by this way, old aliases still exist, work, and don't redirect to new aliases.

# Answer
You can use the pathauto module to construct your node aliases from tokens (admin/config/search/path/patterns). In addition, there is a setting to tell pathauto to leave the existing alias in place when creating a new one. At admin/config/search/path/settings, you can specify this in the Update action section:
> 2 votes

# Answer
You can use globalredirect module to redirect from one url to another url.

> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used. Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the
> 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private
> aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias
> "articles/cake-making" to node/123, then the user can access the
> alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin
> module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

---
Tags: redirection, path-aliases
---


# Question
Title: How do I populate an address field in php?
I want to import data from a external source and so am writing a module that creates content by populating the fields of node bundles in code. I followed this guide which is great.

So I am working on adding lists of properties (flats and houses) that belong to estates. I am using an address field to store the address and found this comment on the address field module page that tells me that the address field is an array and so I can access each element and set it in turn.

But what are the address field element and how do I get a list of them? Can they be anything I want? Does the create content form create the array when the form is submitted and therefore the form labels are just a guide or do I have to match them in my code? For example, a UK address has two textboxes for address (address1 and address2) that do not match any of the element names in the module documentation.

# Answer
> But what are the address field element and how do I get a list of them?

You can get a list of the available field columns from `addressfield_field_schema()`:

* country
* administrative\_area
* sub\_administrative\_area
* locality
* dependent\_locality
* postal\_code
* thoroughfare
* premise
* sub\_premise
* organisation\_name
* name\_line
* first\_name
* last\_name
* data

> Can they be anything I want?

Not by default, but as the addressfield module uses ctools plugins, it's easy to extend to add your own if necessary (see the Address Field Phone module for inspiration).

> Does the create content form create the array when the form is submitted and therefore the form labels are just a guide

Exactly right, the addressfield module provides labels and fields based on the currently selected country. They can be whatever suits the locale, but if you look at the names of the form elements, or inspect the field array on form submissions, you'll see they always match the keys from the field schema hook above. There's an excellent answer to a question on SO which goes some way to explaining the reasons for this implementation.

For a UK address specifically, you would populate it roughly like this:

```
$node->field_address[LANGUAGE_NONE][0] = array(
  'organisation_name' => 'Company',
  'first_name' => 'Joe',
  'last_name' => 'Bloggs',
  'country' => 'GB',
  'thoroughfare' => 'Street address 1',
  'premise' => 'Street Address 2',
  'locality' => 'Town/City',
  'administrative_area' => 'County',
  'postal_code' => 'SW1 1AA',
);

```
> 7 votes

---
Tags: entities
---


# Question
Title: Redirecting anonymous user to specific page
I have a view (d7, views3) that is set up as a table with several fields and the far right column is a global custom text field containing some html like this in the text box:

```
<a href="/[title]">Enroll</a>

```

When an anonymous user comes to that page and clicks on that link, it forces them to the login page. But then after they log in, it takes them to their main user page instead of the node that they would have gone to if they had been logged in. Is there a way to send the user to the page they should have gone to after login ??

# Answer
you can set destination after login to which you want the user to redirect to.

So consider this example a login link like www.sitename.com/login?destination=node/1 will take user to node/1 after login.

More detail:

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_get\_destination/7

one of you comment says you are using login redirect module, I have not used this module before the module page on drupal.org itself says it covers the functionality you are looking for.

> A simple module providing a method to redirect users according to an URL-defined parameter after logging in. Allows redirects toward non-Drupal location.

So the reason the that ?destination is not working, might be because of you a redirect rule triggered by login redirect module.

So solution can be set conditional redirection in login redirect module which can be checked using the parameters in url.
> 0 votes

# Answer
Go to configuration -\> System then clicks on Site information Come to the bottom of the page you will find out "FRONT PAGE"
> 0 votes

---
Tags: views, entities, users
---


# Question
Title: Related nodes by taxonomy term in a view block
In Drupal 7, I've got a content type called "Asset" with a taxonomy field called "Category". All I need is a Block on the Asset pages that looks at the current node's Category term(s), finds all other Asset nodes tagged similarly, and spits out a list of their titles, links to them, and a few other bits of info from their node.

A Views Block was my first thought... but I'm having a heck of a time making this happen in Drupal 7. Maybe it's problematic because my URL doesn't include the Term ID? Anyway, I've searched and followed a bunch of tutorials (like this one and this one), but to no avail. So, here are my questions:

1. If Views is the answer, what am I doing wrong?
2. Is there a Drupal 7 module that can do this for me?

# Answer
> 33 votes
I've done a little tweaking myself, and I seem to have gotten a working solution here.

1. Create a new block for the nodes you'd like to display
2. Add a new Contextual Filter: Content: Has Taxonomyterm-ID Select: "when the filter is not available, provide a default value: Taxonomyterm-ID from URL." Put a check next to "Load Standard Filter from node-page, useful for related taxonomyblocks" And you will probably want to limit the vocabulary as well

In order to exclude the current Node you have to add a second Contextual Filter for Node-ID, provide default value as the content ID from URL and at the bottom of the modal pop open 'More' and check 'Exclude'

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


# Question
Title: how i create panels with custom tag like header, section footer etc..?
My designs contain custom tags like `<header>`, `<section>` and `<footer>`, how can I create panels with these tags and put in it many of panels nested?

```
<header>
 <div>
 </div>
</header>
<section>
 <div>
 </div>
</section>
<footer>
 <div>
 </div>
</footer>

```

# Answer
I am not sure it will be the correct answer. However my opinion is the following. From the code you have specified it looks that you want to make your entire website with panels. (Remember with Panels you design only the node section of the website).

So you may want to consider Panels Everywhere Module. After Quick research I've just discovered that there is a new Theme AT Panels Everywhere. It is a Subtheme of Adaptive Themes - the best Drupal responsive theme (it is my opinion and I use it on every project).

I think you should invest some time learning Panels, Panels Everywhere and Adaptive theme, it will certainly pay for the efforts!

Best regards!
> 0 votes

---
Tags: theming, panels
---


# Question
Title: Best hook to use to save a new node when a node is saved
I want programatically create a new node of type B (status message), immediately after a node of type A (e.g. gallery post) is added (or updated).

Looking at this recipe, I see that I will have to add hook\_node\_insert inside my module and call node\_save to save the new node. But on the comments to the hook\_node\_insert docs ndvo claims I can't call node\_save in the middle of another node\_save operation. So what is the best approach to use?

# Answer
> 1 votes
There is no hook which is called AFTER the node is saved. No POST-SAVE hook.

But calling `node_save` within `hook_insert` actually works. The warnings were false:

So I ended up with something like:

```
function MYMODULE_node_insert($node) {
  if ( $node->type == 'blog_post') {
    MYMODULE_insert_statuspost($node);
  }
}

function MYMODULE_insert_statuspost($n) {
  global $user;
  $node = new stdClass();
  $node->title = "New blog post $n->title";
  $node->type = "statuspost";
  node_object_prepare($node); /* Sets some defaults.
     Invokes hook_prepare() and hook_node_prepare(). */
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->body[$node->language][0]['value'] =
    "New blog post: " . l($n->title, "node/$n->nid") . " has been posted");
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 2; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Status post with nid " . $node->nid . " saved!\n");
}

```

Here is a full commented code to programatically create a node.

---
Tags: 7, nodes
---


# Question
Title: How do I use a different node template on taxonomy term node listing pages?
For a node listing on a taxonomy term page, like:

> taxonomy/term/4

It's currently using the node template I set up just for when you are looking at a node:

> node--spot.tpl.php

I added this code to hook\_preprocess\_node:

```
if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node_taxonomy');
}

```

The node template file name I want to use is:

> node-taxonomy.tpl.php

I confirmed the hook is running but it's still using:

> node--spot.tpl.php

What am I doing wrong?

**Update 1**: According to the source code theme\_hook\_suggestions are listed in reverse priority order, so I changed array\_unshift to array\_push.

**Update 2**: I am correctly seeing in Devel themer that my template should be used first, even when it isn't:

> node\_taxonomy \< node\_*14 \< node*\_spot \< sites/all/themes/hotness/templates/node--spot.tpl.php

# Answer
This answer had two parts:

1. As detailed in my Update #1, you have to put your suggestion last in the theme\_hook\_suggestions array, as last is highest priority.
2. Your template files must be named with two dashes, not one.

File system:

> node--taxonomy.tpl.php

As added to theme\_hook\_suggestions array:

> node\__taxonomy
> 6 votes

# Answer
Actually there is `$variables['theme_hook_suggestions']` in hook\_preprocess\_node, `$vars` is in hook\_preprocess\_page I guess.
> -1 votes

---
Tags: 7, theming, hooks
---


# Question
Title: print individual field inside views-view.tpl.php
I need to theme my view inside views template. Inside custom views-view.tpl.php template I can add individual fields inside loop:

```
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
//after a loop I can add any other field for custom theming like so:
<?php print $item['myfield2']; ?>

```

Question: How can I add another field before the loop is executed? I tried this:

```
<?php print $item['myfield3']; ?>
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

```

But the field3 is not rendered because the $item is not defined, I think.

I am not php programmer so I came up with a dumb workaround

```
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php endforeach; ?>
<?php print $item['myfield3']; ?>
//field is rendered
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

```

What is the correct way of displaying an individual field without putting it inside foreach loop?

Thank you

# Answer
> 2 votes
You are wise to admit it before someone else points it out: "I am not php programmer." ;) This is a pure PHP problem, having very little to do with Drupal.

Your `foreach()` loop defines the variables `$delta` and `$item`. Unlike some other languages, they are still in scope when the loop finishes, keeping the values they had at the end of the loop.

You could do something like this (untested):

```
<?php
  $first_item = reset($view->style_plugin->rendered_fields);
  $last_item = end($view->style_plugin->rendered_fields);
  print $first_item['myfield1'];
  pring $last_item['myfield2'];
?>

```

After the `foreach()` loop, `$item` would be the same as `$last_item`.

The PHP docs are pretty good: arrays and array functions.

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


# Question
Title: Views contextual filter if field value is X then show this in views page Y
* I have content type Ads.
* I have multiple views pages.
* I have Views which shows this content type Ads as a view block. Views has multiple block displays, each display for each views pages.

Admin need to choose when adding new node Ads where he want this ad to be shown. He need to choose it from the list. List has for example values X, C, Z

In the Views which shows these Ads as a view block. How to configure contextual filter to check field value? Contextual filter should be set on PHP code - but how to code it?

**For example:**

* If field value is X -\> show this view block on the path: categories/x (which is Views page, not node!)

\** **Solution** \**

I found my own solution to do something like this.

1. Added custom manual list field type (field\_category). For example: X, Y and C
2. Add view block for each ad category and set filter field\_category for each category. (field category = X)
3. Then in admin/block edit view block: Show block visibility, set PHP format and added this code:

`<?php
if (arg(0) == 'products' && arg(1) == 'categoryX') {
return TRUE; }
else { return FALSE; }
?>`

As my views pages path are: products/categoryX.

# Answer
> -1 votes
This sounds like a job for Page Manager (part of C-Tools). Create variants that activate on content type AND field value.

---
Tags: 7, views
---


# Question
Title: Validate new user email name matching a pattern on registration
Upon new user registration, how could I validate that the email address has a ".edu" extension? Basically, I need to ensure that users are using only their ".edu" email addresses to register for accounts.

# Answer
> 1 votes
Try something like this, add a validate to user\_registration\_form and then in validate check email with your pattern and if not match use form\_set\_error. something like below

```
function registration_check_form_user_register_alter(&$form, &$form_state)
{
    $form['#validate'][] = 'registration_check_user_register_validate';
}
function registration_check_user_register_validate($form, &$form_state)
{
        $email=$form_state['values']['email']['und'][0];
        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)\.edu/i",$email))
                {
                form_set_error('mail', t('Email NOT VALID,TRY EMAIL WITH .EDU'));
            }
}

```

# Answer
> 1 votes
It's not ideal, but I ended up writing a Javascript based solution. Essentially, it looks for the string `.edu` in the email address on `blur` of the email field and `click` of the submit button. If it doesn't find it, it prevents the form from being submitted. It looks something like this:

```
<script type="text/javascript">
jQuery(document).ready(function() {

    function eduCheck() {
        if (jQuery('#edit-mail').val()) {
            if (jQuery('#edit-mail').val().indexOf('.edu') != -1) {
                // alert('Edu present');
            } else {
                alert('Please use a .edu email address only.');
                return false;
            };
        };
    }

    jQuery('#edit-mail').blur(function() {
        eduCheck();
    });

    jQuery('#edit-submit').click(function() {
        eduCheck();
    });

});
</script>

```

Like I said, it's not ideal. But it's a suitable alternative... especially since I couldn't get any of the other suggestions on this page to work.

# Answer
> 0 votes
To start, you can use the Rules Forms Module (dependent on the Rules Module)

You can state specific conditions during specific events with specific outcomes. I would also suggest installing the Token Module if you don't already have it.

You can of course do this manually by making a tiny module that validates the User Account form on submission with a simple `stripos()` like so:

```
if(stripos($emailField, '.edu', strlen($emailField) - 4) > 3) {
    // Success...
} else {
    // Failed - email doesn't end in .edu
}

```

This of course uses `$emailField` as the submitted field containing the user's e-mail address.

---
Tags: users, emails, forms
---


# Question
Title: How can I alter the breadcrumbs on a search page?
I just enabled search on my Drupal theme and when I go to the search page my breadcrumbs show like this:

> home \> Search \> Content \> Search

Is there any way to make it just:

> Home \> Search

Thanks!

# Answer
For ease of use you might want to look at Path breadcumbs:

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

There is also Custom Breadcrumbs which was pretty awesome, but be careful if you choose this route as there is serious discussion about deprecating it in favour of Path breadcrumbs.

Hansel Breadcrumbs is useful, but I have found it INCREDIBLY complicated to get set up and working properly. I would suggest to use it only if you're going to be setting up a lot of complicated rules. If it's just for one or two pages, it's probably overkill and might end up making you hate Drupal (and no-one wants that!) ;-)
> 2 votes

# Answer
# Search Page Breadcrumb Trail:

home \> Search \> Content \> Search

Make these highlighted changes in your active theme's template.php

```
function THEMENAME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    if(arg(0)=='search')
    {
      unset($breadcrumb[2]);
      unset($breadcrumb[3]);
    }

  $output .= '' . implode(' » ', $breadcrumb) . '';

  return $output;
  }
}

```

# Result:

Home \> Search

Like entries: \[https://drupal.org/node/2151655\]
> 2 votes

# Answer
Try out Hansel breadcrumbs module.

> provides custom breadcrumbs which are build by user defined rules. These rules are independent from the menu system. Rules can have logic switches and can add links to the breadcrumbs.
> 1 votes

# Answer
There are different breadcrumb customizing modules available for Drupal 7. They all have their own configuration or APIs. Which one you choose for a given site probably depends on more criteria than just the breadcrumbs on the search page - so choose wisely. As Binu pointed out, you can even do this without any breadcrumb-customizing module.

In this answer I am going to explain how to do this with Crumbs 7.x-2.0-beta12 (or up).

There is an issue for Crumbs asking for nicer search breadcrumbs, and a basic support for this has actually been implemented in Crumbs 7.x-2.0-beta12 natively!

If you are not happy with this, you can get more creative with hook\_crumbs\_plugins():

```
/**
 * Implements hook_crumbs_plugins().
 *
 * @param crumbs_InjectedAPI_hookCrumbsPlugins $api
 */
function MYMODULE_crumbs_plugins($api) {

  // The $key is needed so the user can configure a weight for this "plugin".
  // The plugin will be available in admin/structure/crumbs as
  // "MYMODULE.search.content.parent" ("MYMODULE." is always prepended)
  $key = 'search.content.parent';
  // Make <front> the parent of search/node/%.
  // Obviously this could be any parent path, your choice.
  $api->routeParentPath('search/node/%', $key, '<front>');

  // And now let's change the title of the search breadcrumb element.
  // This needs a new $key, so it can be sorted separately on admin/structure/crumbs.
  $key = 'search.content.title';
  $api->routeTitleCallback('search/node/%', $key, function($path, $item) {
    return t('Search for @terms', array('@terms' => $item['map'][2]));
  });
}

```

Troubleshooting / Notes:

* Most of the changes to hook\_crumbs\_plugins() need a flush-cache to have any effect.
* In admin/structure/crumbs/display there are settings that allow you to hide the current page, or that will hide the breadcrumb if it consists of too few elements. These settings can result in your MYMODULE stuff to be totally hidden.
* Go to admin/structure/crumbs and make sure your new plugins get a high enough priority. The easy way is to simply move MYMODULE.\* to the top.
* Obviously, MYMODULE needs to be replaced with your own custom module name.
> 1 votes

---
Tags: theming, breadcrumbs
---


title: show custom menu in page tpl file

text:
# Question
Title: show custom menu in page tpl file
```
<?php if (isset($custom_links)) { ?>
<div id="secondaryNav"><?php print theme('links', $custom_links) ?></div>
<?php } ?>

```

I've create a custom menu (machine name: menu-secondary-menu). And I want to display it in page.tpl. My condition is to show this this menu only if it has links added. I searched and found the above code. Please help me in customizing to my need.

# Answer
```
<?php
// Enter the machine name of the menu you want to show.
$menu_name = 'main-menu';
// Check if there are any menu items in it.
if (count(menu_navigation_links($menu_name))):
?>
<div id="secondaryNav">
  <?php print theme('links', array('links' => menu_navigation_links($menu_name), 'attributes' => array('id' => $menu_name, 'class'=> array('links', 'inline')))); ?>
</div>
<?php endif; ?>

```
> 0 votes

---
Tags: theming, routes
---


# Question
Title: Show new content count on the taxonomy term list view
I have a view that lists the terms in a specific vocabulary. I can also mark the terms if there is a new content tagged with this term. My view looks like this:

> * Term 1
> * Term 2
> * Term 3 (new)
> * Term 4
> * Term 5 (new)
> * ...

However, what I would like to achieve is a view that shows the count of the new contents tagged with a term. Like this:

> * Term 1
> * Term 2
> * Term 3 (2 new)
> * Term 4
> * Term 5 (7 new)

My current views configuration is like following:

1. Showing taxonomy terms of a specific vocabulary
2. Added a relationship of **Taxonomy term: Content using *my vocabulary***
3. Added field **Content: Has new content**: This has caused duplicate rows for the terms that has more than one new content. For example, if a term has three new contents, it was listed three times. So I did the next step.
4. Activated **Aggregation**, and set the aggregations settings of the field **Content: Has new content** to **SUM**: This has solved the duplicate rows issue, but it doesn't show the sum of the contents as I actually wanted to achieve.

Is there any possibility that I can show the number of new contents on this view?

# Answer
> 3 votes
**Solution A: Use Views Field View**

Using the Views Field View module it is possible to embed the results of one view into another view.

First create a view for nodes without a page/block (you only need the master display) and name it **New content count by term**. Add a context filter *Content: Has taxonomy term ID*. Ensure that only the *Nid* is listed in the fields section, add the filters *Content: Published (Yes)* and *Content: Has new content*, then enable aggregation, choose *Count* from the *Aggregation settings* of the *Nid* field and finally remove any pagers.

Now you may embed the **New content count by term** view into your principal view (taxonomy terms) by adding a "Global: View"-field (provided by the Views Field View module). In order to specify the tid-parameter of the embedded view, make sure that the Term id is also exposed as a field in the principal view. If you do not want to show it to the end user, just choose *Exclude from display* in the field settings. After the output of the tid field can be used as a parameter (token `[tid]`) for the embedded view.

**Solution B: Use hook\_views\_query\_alter**

There is a function in the forum module responsible of returning the number of new posts on a topic (term) on behalf of a given user (\_forum\_topics\_unread). Use this query as a starting point for your own implementation of hook\_views\_query\_alter.

I recommend to go for solution A and only try to implement B when performance is degraded beyond acceptable limits.

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


# Question
Title: How to do arithmetic on a contextual filter
Rather than specifying a contextual filter, is it possible to specify a contextual filter +1 (i.e. add one to the current filter value?)

If you have a view taking an argument, i understand that you can create a global text field to make a link to a different view using the original argument.

I.e. in view1/arg1 i can have a global text field which outputs as a link to view2/arg1

Is it possible to create a global text field which outputs as a link to view2/arg1+1

i.e. adds one to the current argument?

# Answer
> 1 votes
In Views for D7 (not sure about D6) you can add a field of type "Math expression" to do this sort of thing. Enter the expression `[!1]+1` (or maybe `[%1]+1`) in the Math expression field, and then later text fields can refer to this value (in their Rewrite sections) as `[expression]`.

# Answer
> 0 votes
Views PHP normally be my answer, but it appears that it doesn't support PHP in Contextual Filters quite yet...

So you'll need to create yourself a module and then:

I'm assuming your first argument is the one you want to change, and I don't have a view I can test against right now, so you'll need to `print_r(`$query-\>where\[0\]);\` to see what's going on in there and add to the correct value.

# Answer
> 0 votes
Do something like this.

```
<?php
  $view = views_get_current_view();
  $arg = $view -> args[0];
  $newarg = intval($arg) + 1;
?>
<a href="/view2/<?php print($newarg); ?>">Increment my contextual filter</a>

```

# Answer
> 0 votes
You can create views template for your views and do something like this below.

```
<?php $arg = arg(1);  ?>
<a href="<?php print base_path() . 'view2/' . ($arg + 1) ;?>">Link to view</a>

```

---
Tags: views
---


# Question
Title: What is the relationship between the node and the node revision table in Drupal 7?
I am trying to optimise the code in a Drupal 7 website by replacing node\_load functions to retrieve only the title with custom SQL queries.

So far, I have been successful in retrieving the same values. However I just cant seem to get the gist of getting the title from the latest revision of a node or retrieve any other value from the associated fields.

Can anyone point me out regarding the concept of revisions from a table point of view?

# Answer
I believe this is what you're looking for:

```
function MYMODULE_get_node_title($nid) {
  // Using Drupal's DB API.
  $query = db_select('node_revision', 'r')
    ->fields('r', array('title'))
    ->addTag('node_access');
  $query->leftJoin('node', 'n', 'n.vid = r.vid');
  $query->condition('n.nid', $nid);
  $title = $query
    ->execute()
    ->fetchField();

  // Using a custom query. This might help you understand better what's the
  // exact relationship. This approach is a bit faster as well.
  $title = db_query("SELECT r.title
                     FROM
                      {node} n,
                      {node_revision} r
                     WHERE
                      n.nid = :nid AND
                      n.vid = r.vid", array(':nid' => $nid))->fetchField();

  return $title;
}

```

To understand the relationship look at the second approach, using a custom raw query.
`vid` stands for *version ID* and if you look at the `node` table you will see that there is a column named `vid`.
This is the active version of that node and is the ID you should use to get all field values and other attributes of that piece of content.

Hope this helps.
> 2 votes

---
Tags: 7
---


# Question
Title: How to print a field value in page front tpl file?
I'm trying to load a field value (machine name: field\_theme\_image) from a content of node value 3, in "page--front.tpl.php".

```
<?php
  $node=node_load(3);
  print $node->field_theme_image[$node->language][0]['uri'];
?>

```

Using the above code I'm not getting full URL value. Please see the image below. I can see the path value in Devel themer.

# Answer
I am not sure if this is what you are asking for, I think you want to show a download link for an image on your home, you have image on your node with node id 3.

In this case you can use download\_file module, it allows to create direct download link for fils/images.All you need to do is create a view(through views module) of display type block, in your view add image field and keep the formatter as direct download file, place this block on front page.

If you want to render the download link programmatically, you can use the same function as defined in download\_file module to render the links.

If you want to print image programmatically consider this:

```
print theme('image_style', array('path' => $node->field_theme_image[$node->language][0]['uri'], 'style_name' => 'home_theme'));

```
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: need path of an image created using an image style
```
<?php
  $node=node_load(3);
  $theme_img = file_create_url($node->field_theme_image[$node->language][0]['uri']);  //origional image path
  print $theme_img;
?>

```

I am trying to load an image in "page--front.tpl.php", which was created from a content of node value 3.
Using above code, I am able to get origional image url. But I need path of image created using image style (home\_theme)

# Answer
You can use image\_style\_url($style\_name, $path)

Example:

```
$img_url = $node->field_image['und'][0]['uri'];
<img src="<?php print image_style_url("thumbnail", $img_url); ?>" />

```

Where you will be replacing thumbnail with the image style name you have in place
> 0 votes

---
Tags: theming, media
---


title: Guideline for users to view

text:
# Question
Title: Guideline for users to view
I have a website coming up soon and the editors for this website dosen't know how to use Drupal. I have made a content guideline for users to follow(guideline for like uploading content and such), now I want this guideline to appear on the website for only certain roles to view. In my example the role editor has the only permission to view this content and no one else.

Do you guys got any clue of how to fix this and also where I should place it? On their account page or just in the navbar?

Thanks for any tips and advice

# Answer
> 1 votes
One approach can be using content access module.So basically while creating content type you will get option to share content type with user role you want to.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Other approach does not require any module, and will be simple and out of the box.

1. Create a content type, lets say editor\_guide.
2. While creating the content type opt to keep the nodes unpublished.
3. Now create nodes,which can be single node(copying the complete guide to one node),multiple node(dividing the guide content into chunks as separate nodes),you can also keep the guide as file field on node.
4. Create a view of display type page with path say editor-guide.
5. In views you will get option to set permission for the page, set the permission for editor, in the views filter remember to change status for content for unpublished.
6. Now in you nav-bar menu block add a menu item, link it to editor-guide(or whatever).

This link will be automatically visible to editor role only.

---
Tags: users
---


title: show uploaded image in page.tpl

text:
# Question
Title: show uploaded image in page.tpl
I created a content type and added an image filed (machine name: field\_theme\_image). Then, I've added a new content in this content type and uploaded an image.
Now, I want this image to be shown in "page.tpl.php", so that this can be seen in all the pages. Please let me know how this can be done done.

# Answer
I would have rather used a block and put it in a region, so to show up on all pages. This would keep my tpl fiels clean and also will allow me show/hide block on some pages.
> 0 votes

---
Tags: theming, media
---


# Question
Title: Relate data in a custom sql table to a regular drupal field using views
I have a field collection, with a field "Attribute number", which contains a text value of the format "b1\_a1", "b7\_c2", etc.

I have a custom table that has a column that references an attribute number, and a column that contains a survey response value (yes or no).

I want to create a relationship between the attribute number field and my table, so that in views, I can list the attribute numbers, and display the corresponding response.

I'm looking at hook\_data\_alter(). There are example to extend a base table, such as node, and join with a new table, but there is no example to extend a non base table, such as my field\_data\_field\_attribute\_num.

How do I make a views join with a non base table?

# Answer
I assume you will be associating your "Attribute number" field to a node type, and that your view will be showing nodes. So, what you need to do here is describe your custom table (I call it "custom\_an" here) to the views API and provide a way to join it when displaying node data. Here is a way to do that:

```
function YOURMODULE_views_data() {
  // Assign a group for the custom table:
  // can be an existing group - e.g. t("Content") -
  // or, like I  do here, a new custom group.
  $data['custom_an']['table']['group'] = t('Extended content');

  $data['custom_an']['table']['join'] = array(
    // This table will be available for join for any 'node' view.
    // 'left_table' is the referenced table,
    // i.e. the one that contains your field's data
    // 'left_field' is the join key in the referenced table.
    // 'field' is the foreign key in the custom table.
    'node' => array(
      'left_table' => 'field_data_field_attribute_number',
      'left_field' => 'field_attribute_number_value',
      'field' => 'attribute_number',
    ),
  );

  // here we describe the field(s) in the custom table
  // that we want to show in the view.
  $data['custom_an']['response'] = array(
    'title' => t('Response'),
    'help' => t('Response field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  return $data;
}

```

Please be aware that this is only a proof of concept, and that it's meant to get you started but in no way you should use this code as is for a production site. Two major issues to be addressed would be:

* testing this code against a node type which does not contain the "Attribute number" field (and possibly find the right way to avoid that adding the custom data to that view results in a corrupted view), and
* if `attribute_number` in your custom table is not unique, the view could output duplicate rows. The join key in the custom table should actually be a primary key, according to `hook_views_data()` documentation.
> 1 votes

---
Tags: views
---


# Question
Title: files[]=lib.php fails to autoload classes of different namespace?
In my custom module, I've included a file using `files[]=foo.php` in the .info file. foo.php declares classes in a namespace.

Drupal does not seem to be autoloading this class: in my main module file `$foo = new Foo\Bar();` causes a Class Not Found error.

Is this because Drupal 7's registry can't cope with namespaces?

# Answer
Yes, Drupal 7 knows nothing of namespaces unfortunately (namespaces were only introduced in PHP 5.3 and D7 is compatible with earlier versions than that).

However, life gets infinitely better with the XAutoload module, which is PSR-0 compliant an thus knows all about namespaces.

> xautoload is a comprehensive and yet highly efficient PHP class loading suite. Most importantly, it provides Drupal-8-style PSR-0 autoloading for Drupal 7.

The latest release is even moving towards PSR-4 which is great news.

If you install that module you can remove all of the `files[]` references from your info files, as long as you follow the `\Drupal\my_module` namespacing pattern. Even if you don't, XAutoload has hooks to let you define your own patterns.
> 5 votes

# Answer
As Clive said above, the Drupal 7 core registry cannot handle namespaces, but \[xautoload\]\[https://drupal.org/project/xautoload\] is your solution!

The xautoload-7.x-5.x branch has PSR-0 and PSR-4 support, and it can generate classmaps by scanning a directory (and unlike core, this does support namespaces).

Now you have a number of options:

1. Use PSR-4 like in Drupal 8, with your classes in the `/src/` directory. See https://www.drupal.org/docs/develop/standards/psr-4-namespaces-and-autoloading-in-drupal-8
2. Put your classes in arbitrary files, and let xautoload scan these files. The result will be cached in the regular Drupal caches, so you need to flush the caches whenever you add a new class file. This is very similar to the Drupal 7 core class registry, but it does support namespaces.

```
/**
 * Implements hook_xautoload()
 */
function MYMODULE_xautoload($api) {
  // Add directories to discover php files with classes.
  // You can be creative with the wildcards.
  // '**' means to scan subdirectories of any depth.
  $api->addClassmapSources(array(
    'includes/**/*.inc'
  ));
}

```
3. Put your classes in arbitrary files, *avoid namespaces*, and use the D7 core registry + xautoload wildcards. Put this in your MYMODULE.info file:

```
files[] = includes/**/*.inc

```
4. There are some options that are supported for legacy reasons, but these should not be mentioned here.

An alternative is registry\_autoload, which uses the regular core registry, but supports namespaces and detects classes automatically.

Advantage of registry\_autoload: More light-weight (but does not mean it is faster, the jury is still out on this).

Advantage of xautoload: During development, classes are immediately available without running the registry build.
> 4 votes

---
Tags: 7
---


# Question
Title: Drupal view shows multiple results to a single row
I am using a view with table format.

I need to show results in a given format. I am unable to find..

Can anybody tell me how to achieve in views..

Thanks

# Answer
> 1 votes
Option 1: Set the format of the view to "grid" and columns to 2.
Option 2: Set the format of the view to "HTML list" and then with css set the width of the li and float it left.

---
Tags: views
---


# Question
Title: theme still use caching even when flushed cache and using devel
I am having a lot of issues with CSS editing on my site! Some colors don't change and I have tried the following to no avail: -flush all caches -performance - development: disabled all caching and "Aggregate and compress CSS files" -Devel module "Rebuild the theme registry on every page load"

I also removed the .css file and my page will still load with old colors in the body background and 2 other divs! Any help would be greatly appreciated as this is keeping me from opening up my site!

# Answer
> 1 votes
Since it sounds like you've got all the Drupal-related items checked, perhaps it's worth a shot in the dark...

Pull up the site in Chrome and inspect the element that's supposed to have the updated colors (right click and select "Inspect element"). This may reveal one of two things:

1. Click the "Computed" tab in the right-hand column. Is your color change being overwritten by a more specific declaration? (eg: `#foo .some-class { ... }` will supersede `.foo-class .some-class { ... }` regardless of the order in which they appear)
2. Perhaps you've been editing the wrong file? I know I've done it before... Click the Sources tab and make sure the page is loading the file you expect it to load. Make some random changes, reload and check that those changes show up.

Hope that helps.

# Answer
> 0 votes
Sounds like cache is still enable, disable it in admin/config/development/performance make sure the following are disabled:

* Cache pages for anonymous users
* Cache blocks

Also make sure bandwidth options are disabled:

* Aggregate and compress CSS files.
* Aggregate JavaScript file

Make sure when you are developing those options are disabled and in your production site they are enabled.

Another things that might cause:

* browsers plugins might be interfering.
* if you are using a framework like compass make sure you are compiling the last changes.

---
Tags: theming, caching
---


title: What is module dependency?

text:
# Question
Title: What is module dependency?
I see that modules can have dependencies on other modules.

Why is this, and how might I use this in my own custom module development?

# Answer
> 9 votes
Module dependency can be defined as follows.

If a module A requires that module B to be enabled before the module A is enabled then, module A is dependent on module B.

In other words, if module A uses some of the functions that are available or defined in module B then it becomes mandatory to enable module B prior to enabling of module A, as not doing so may result in a "call to undefined function error"

Dependencies are very useful as it may save lot of your development time by allowing you to use functions that are already available in other modules, instead of rewriting the function in your module.

A module's dependencies are mentioned in the module's .info file. Following is an example from the forum module

```
name = Forum
description = Provides discussion forums.
dependencies[] = taxonomy
dependencies[] = comment
package = Core
version = VERSION
core = 7.x
files[] = forum.test
configure = admin/structure/forum
stylesheets[all][] = forum.css

```

The lines :

```
dependencies[] = taxonomy
dependencies[] = comment

```

declare or make the forum modules to be dependent on the 'taxonomy' and 'comment' modules. We can also say that the 'taxonomy' and 'comment' modules are the dependencies for the forum module.

In your module A you can add dependencies for module B and module C by adding the following lines in the a.info file of your module A .

```
dependencies[] = b
dependencies[] = c

```

---
Tags: 7
---


title: Site looks different under SSL

text:
# Question
Title: Site looks different under SSL
I have a strange problem... I just uploaded our new Drupal site. Everything looks great - until we enabled SSL. When SSL is enabled, the look-and-feel of the sight changes slightly. The fonts change in a few places and the width is off on the main pane. It's as if something in CSS is getting messed up. But I can see that the CSS files are being loaded.

I disabled caching and Page Speed, thinking perhaps that was the issue.. but disabling that didn't fix the problem.

I'm really at a loss here. Does anyone have any suggestions on how to tackle this issue?

I'm running Drupal 7.24 on an Apache web server.

Thanks!

# Answer
> 5 votes
If you have enabled SSL, it may happen that some browsers may block the resources that are not using https:// in their URLs. While Chrome and Firefox manage to work fine in some cases, Internet Explorer has a strange behaviour.

I would suggest you to check if external scripts, images, or CSS styles you are using in you website use http:// in their URLs, and change them if they don't use https://.

---
Tags: theming, ssl
---


title: "$nid" for individual pages not working

text:
# Question
Title: "$nid" for individual pages not working
```
<?php
  $nid = arg(1);
  $arg0 = arg(0);
  if(isset($nid) && is_numeric($nid) && isset($arg0) && $arg0 == 'node') {
    $node = node_load($nid);
  }
  $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
  if(isset($theme_img)) {
    // print styled image
    print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
  }
?>

```

I am using the above code to load styled image (from node 6) in page.tpl file. This is working fine in all the pages but when I am trying to load images from individual images by using '$nid' it is not working.
I don't understand what I made mistake in code due to which I couldn't get the value of '$nid'. Please help.

# Answer
> 0 votes
I guess you want to replace the "6" by the current nid of the page. If so, you could use this code to get the nid of the current page:

```
$nid = arg(1);
$arg0 = arg(0)
if(isset($nid) && is_numeric($nid) && isset($arg0) && $arg0 == 'node') {
  //If you're using devel
  dsm($nid);
  //If not
  drupal_set_message($nid);
}

```

But as stated by Jeet, if the code is specific to one content type, you should do this in a node--mycontenttype.tpl.php and not in the page.tpl.php

# Answer
> 0 votes
As you are looking to edit/override node template, it is suggested to place your changes into `node.tpl.php` where you will get `$nid` as out of the box. `page.tpl.php` will not give you node variables by default.

If you still you want to get your code on `page.tpl.php` you can get `$nid` from url like `arg(1)`.

Let me know if I miss anything!

# Answer
> 0 votes
If you want to use $nid variable in your page.tpl.php, you can add that variable to be available in the page.tpl.php by implementing hook\_preprocess\_page() in your theme's template.php. In your implementation of the hook\_preprocess\_page() you have to add a key 'nid' to the $variables array. Eg: `$variables['nid'] = the_nid_you_want;`. After you have saved the changes, clear the Drupal cache and the $nid variable will now be available in your page.tpl.php

---
Tags: theming, nodes, media
---


# Question
Title: Print exposed filter in different postion
I have created a view with exposed filter, i need to print it in different position, for example filter will be in next to many & view will be in the content container. Gone through some forum, nothing seems to be working from my end. With the code below i got view array but no sure how to print the exposed filter.

```
$view = views_get_view('watchlist');
$view->set_display('default');
print_r($view);

```

# Answer
Are you trying to display it in a different region? Views has an option for that. When you have one or more exposed filters, you'll find an EXPOSED FORM option in the advanced tab that will allow you to detach the form and display it in a block.

From there you can place it anywhere just like a regular block.
> 5 votes

---
Tags: views
---


title: Add webform to content type

text:
# Question
Title: Add webform to content type
I would like create a webform and add to content type. so when user create node, webform automatially add to node (webform is same for per node of content type).

is this feasible with webform 3?

# Answer
> 5 votes
You can do it by node **reference**. Add those kind of field to your content type. You can always set default value for automatic add webform to node, but it doesn't add you form automatically to node edit form.

I test it by using node reference and views, but it doesn't display a webform on node edit page (in the same form).

You can try to use hook\_from\_alter, which means to add programatically fields from reference webform. IMO is the only solution or maybe there are some modules for this, but I didn't look for them.

You need add your submit function to this form too, because you need to filter and save webform fields programatically too. Check WebForm API for this. A lot of work, maybe you should think about better solution without programming and using webform at all?

# Answer
> 3 votes
I just came across this when searching for a similar thing. There are of course many ways to achieve this, and it also depends a little bit what is actually desired for a given use case. With this I mean whether a new webform should be attached to each node, or if the same webform should be shown on each of the node pages.

If you want to actually attach a new webform to each of the nodes, then you can enable webforms on that content type (from *Configuration* \> *Webform settings*). This allows to create a form per node on that content type, but it does not create the form for each node automatically, it has to be created per node. This is not really useful if you want the same form for each node, but if you want the form to be created automatically, then there are a few modules to help with that: https://drupal.org/project/webform\_template and https://drupal.org/project/webform\_default\_fields

The other approach is to create one webform and show that form on each of the node pages. This can be achieved by showing the webform as a block and specifying the block to display in the Content region and only on certain content type. First enable using a webform as a block by editing an existing webform node, click to *Webform* tab, click *Form settings*, open *Advanced settings* and check the *Available as block* checkbox. After that you can add the block from Blocks page normally and restrict visibility to a certain content type for example. If you need access to some values from the node where the form is displayed in the webform, you can add them as hidden fields and create a custom module that gets them from the node and sets the values to the form. Here is some discussion and examples about this: https://drupal.org/node/1470748

# Answer
> 0 votes
You can try to use hook\_from\_alter, which means to add programatically fields from reference webform. IMO is the only solution but what is IMO .

---
Tags: webforms, nodes
---


title: redirect index.php?var1=aaa&var2=bbb

text:
# Question
Title: redirect index.php?var1=aaa&var2=bbb
I just moved a website to drupal 7 and I have problems with the redirects.

The old website had all urls like this: www.example.com/index.php?var1=aaa&var2=bbb (where aaa and bbb changed for the different pages)

In the new Drupal website I use alias, so for example the page: www.example.com/index.php?var1=aaa&var2=bbb now it is replaced by www.example.com/content/something

I tried to redirect the old url to the new one with two different methods, but both failed. They redirect the users to the homepage.

1. I create an alias
2. I added a rewrite rule in the .htaccess file RewriteRule /index.php?var1=aaa&var2=bbb /content/something

As I said, both of them redirect to the homepage.

Any idea? thanks!

# Answer
Redirect is the drupal 7 version of path redirect. Path redirect This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status. and GlobalRedirect is a simple module which… Checks the current URL for an alias and does a 301 redirect to it if it is not being used. Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request. Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match. Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method. Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's. Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case. Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Automatically fill the default vocabulary term associated with a content type when editing a node
What I'm trying to do is to automatically select the default term in the "add content" page based on the user's location in the site.

**Example:** User is currently viewing classifieds listed under "Los Angeles", which is in "California", which is in the "Locations" vocabulary.
I want to automatically set the default value of the "Locations" vocabulary shown in the the content form for new classifieds to the term that identifies the area they are viewing.

Is this possible?

**NOTE:** I'm not referring to GeoIP or locations-based modules. I'm just looking for a way to automatically select the term they are already viewing, and use it for the node being created.

# Answer
> 1 votes
I think the answer will be to make your button/menu item dynamic using arguments from the URL. It sounds like when a user clicks the "Add Classified" they are already viewing the classifieds tagged with a particular location taxonomy term. In which case, I'd imagine that term name (or id) appears in the current url, something like http://yoursite.com/classifieds/LosAngeles. If so, I believe you can pull that term out of the url and use it in your link, something like http://yoursite.com/node/add/classified/LosAngeles. Then, you'd need to alter your 'Add Content' form to pull in the term from the url (the LosAngeles part). This should work in theory, however I'm not sure exactly how to do that in practice. I'll see if I can figure it out before you end up answering your own question, but that should at least help point you in the right direction for now.

# Answer
> 0 votes
You could use the smart\_ip module to determine the users location and then hook the form to modify the selected taxonomy term with hook\_form\_alter() / form api reference.Smart ip can use either W3C Geolocation API which isn't 100% browser compatible and accurate or maxminds geo databases. Maxmind offers a free Geolite database but if you want precision you should use the commercial geoip database.

# Answer
> 0 votes
You can probably put a link saying Add classified with the intented term appended to the URL as an argument, like yourdomain/?q=node/add/content\_type/. Now you can edit the field settings, so that you can write a PHP snippet for the default value field that fetches this term from the URL. Hope this would work for you.

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


# Question
Title: How to add an "apply for a job" button to a content type?
I am trying to add an apply button to a content type, like job, so when the user visit the content he could click "apply button", and his resume will be send automatically to the author of the content.

I would prefer this be achieved with AJAX. How can I make something like this?

# Answer
I would do that using Flag module, create a flag named 'Apply' and set it for job content types. You can then use Flag Actions or Rules to send emails.
> 3 votes

# Answer
If you want the apply button on the node detail page then you can make use of ctools link to get this functionality done.

All you have to do is implement a ctools menu item and a callback that will do the processing to send the users resume to the author of the node(job).

Then in the template file for the node you can add a ctools link by using the ctools\_ajax\_text\_button() function of the ctools module.

For more details on how to imeplement this functionality. Please download and enable the ctools module. It has got a very good example module that will give you a clear idea on how to implement a the functionality you are looking for..
> 2 votes

# Answer
Your situation looks like a case for a Webform module - it provides GUI and allows you to design apply forms without any coding. If you will add Webform steps or similar helper, you will be able to make your article a first "step", and actual applying for a job a second one.
> 2 votes

---
Tags: 7, ajax, nodes
---


title: Append Fields to node form by ajax call

text:
# Question
Title: Append Fields to node form by ajax call
I have a node form with some fields, now I want to append some more fields to it on an ajax callback. in the ajax page I have rendered the new form elements with `drupal_render` function
My problem is that I am not getting the newly built form fields in POST or form\_state. Shall I use `AHAH` or can I continue with this ajax calls?

```
$form['country'] = array(
            "#type"=>"select",
            '#title'    =>t('Ship To'),
            '#required' => true ,
            '#options' => $options,
            '#weight' =>10,
            '#attributes' =>  array('id' => $cn_var),
        );
        $form['dyn_cost'] = array(
            "#type"=>"textfield",
            '#title'    =>t('Shipping Cost'),
            '#required' => true ,
            '#size' =>25,
            '#weight' =>11,
            '#id' =>  $co_var,
        );

        print drupal_render($form);
        exit;

```

This is my ajax form and it is supposed to be appending to the node form.

# Answer
You can use Conditional Fields module to display form fields with certain conditions. No need to use custom ajax calls.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
> 0 votes

---
Tags: 6, forms, ajax
---


# Question
Title: Using an entity wrapper to change node->body value (with localization)
I try to programmatically modify the body of a node using an entity wrapper.
In my Drupal installation I also use Locale module (language for node is 'en', for body it is 'und') and Revisioning module.

Now, I've created a simple code to do this task:

```
<?php
// in database: field_data_body->body_value = 'old_value'
$node = node_load(1);

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

print_r($wrapper->body->value->value());   // prints 'old_value'
$wrapper->body->value = 'new_value';
print_r($wrapper->body->value->value());   // still prints 'old_value'

$wrapper->save();
node_save($node);
?>

```

yet it seems not to make any changes to the node.

Although, if I've tried to change the title:

```
$wrapper->title = 'ABC';

```

everyting worked fine.

I guess it's the problem related to using localization, but I can't find sufficient documentation on how to achieve what I want.

Could someone tell me how can I put it to work?

# Answer
> 8 votes
Documentation is up to date now.

Examples from drupal.org :

```
 $wrapper->author = 0;
 $wrapper->url = 'dummy';
 $wrapper->author->mail = 'foo';
 $wrapper->author = NULL;
 $wrapper->author->set($GLOBALS['user']->uid);
 $wrapper->author->set($GLOBALS['user']);

 // Localization Here
 $wrapper->body->set(array('value' => "<b>The second body.</b>"));
 $wrapper->language('de');
 $wrapper->body->set(array('value' => "<b>Der zweite Text.</b>"));
 $wrapper->language(LANGUAGE_NONE);
 $wrapper->set($node);

 $wrapper->reference->name->set('foo');
 $wrapper->reference->set($wrapper);
 $wrapper->save();
 $wrapper->delete();
 $wrapper->type->set('article');
 $wrapper->author = $user->uid;
 $wrapper->{$property}[0] = '2009-10-05';
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->$name->value();
 $wrapper->parent[] = $term_parent2;
 $wrapper->field_tags[1] = $term_parent;
 $wrapper->field_tags->set(array(2));
 $wrapper->field_tags = NULL;
 $wrapper->$field_name->set(NULL);
 $wrapper->field_text[0] = 'the text';
 $wrapper->field_text[0]->set(array('value' => "<b>The second body.</b>"));
 $wrapper->field_text2->summary = 'the summary';
 $wrapper->field_text2->value = 'the text';
 $wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
 $wrapper->field_file[0]->description = 'foo';
 $wrapper->field_file[0]->display = TRUE;
 $wrapper->field_file[1]->file = $file;
 $wrapper->field_file[] = array('description' => 'test');
 $wrapper->field_file = NULL;
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->field_image->alt = 'foo';
 $wrapper->field_image->file = $file;
 $wrapper->field_image = array();

```

You can follow this link to see full documentation and examples about entity metadata wrappers and localization.

Documentation about entity metadata wrappers on Drupal.org

---
Tags: 7, entities
---


# Question
Title: Alter default message presented to user on failed login attempt
I need to alter the default D7 message that gets presented to the user on a failed login attempt. I need to give them one message if their username isn't found, and another if their password is wrong. *Default Drupal behavior is to give a single, generic error message that doesn't distinguish between the two*.

For the password check, The best solution I've found is user\_check\_password(). This doesn't sit well with me. The password.inc file isn't included in all page requests, and as there are several different context dependent login pages on the site, it isn't always there. I've been forced to require\_once it in my custom validation handler which seems very un-drupal-ish.

# Answer
You can set your own custom message according to the validation by adding your custom validation function with login form.

```
function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login_block' || $form_id == 'user_login')
    $form['#validate'] = array('custom_module_login_validate', 'user_login_authenticate_validate');
}
function custom_module_login_validate($form, &$form_state) {
  $uid = _custom_module_is_user_exists($form_state['values']['name']);
  if(!$uid) {
    form_set_error('name','Username not found.');
  }
  else {
    if(!user_authenticate($form_state['values']['name'], $form_state['values']['pass'])) {
       form_set_error('pass','Incorrect password.');
    }
  }

}
/**
 * Query user table to check if such username is already exists.
 */
function _custom_module_is_user_exists($username) {
  return db_query("SELECT u.uid FROM {users} u WHERE LOWER(u.name) = LOWER(:username)", array(':username'=>$username))->fetchField();
}

```
> 2 votes

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


title: Theme image broken link

text:
# Question
Title: Theme image broken link
I am recreating an existing website and part of the process is enabling a theme from the same existing site on my new version.

The theme is called **microsite** and has an image located in **/microsite/images/**.

In the original site, the image from the above directory is loaded and displayed in a block. I copied the code from the block of the original site, pasted and saved in a block of my new site. The HTML markup is the following.

```
<a href="/publications" target="_self">
  <img src="/sites/all/themes/microsite/images/image.jpg" />
</a>

```

Using the exact HTML markup in my recreated site with the same theme and path to image shows a broken image link. The link shows up as http://192.10.10.1/sites/all/themes/microsite/images/image.jpg instead of http://192.10.10.1/mysite/sites/all/themes/microsite/images/image.jpg.

To resolve this, I set `$base_url` in settings.php to http://192.10.10.1/mysite, but the link is still broken.

Can anyone help, please?

# Answer
Use the `url()` function to perform the path/URL magic for you. Note that you will have to change the block's input format to "PHP code" for this to work.

```
<a href="<?php print url('publications'); ?>" target="_self">
  <img src="<?php print url('sites/all/themes/microsite/images/image.jpg'); ?>" />
</a>

```

(All of the above could be accomplished by a call to `theme_image()` followed by `l()` but that would obscure the answer. Also, it's good practice to use `path_to_theme()` to get the path to the current theme.)
> 1 votes

# Answer
You should remove the first slash from `src` in your theme to

```
<img src="sites/all/themes/microsite/images/image.jpg" />

```

That first slash is indicating that it is relative to your web root rather than your Drupal root.
> 0 votes

# Answer
If none of these answers work, make sure you have set the RewriteBase in your `.htaccess` file to be in the virtual directory /mysite

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
 RewriteBase /mysite
#

```
> 0 votes

# Answer
Try this:

```
<img src="<?php print drupal_get_path("microsite", "theme"); ?>/images/image.jpg" />

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: Easiest & most efficient way to embed vimeo code into blog post
All of my videos are hosted on Vimeo and I would like to create a way to embed videos into my blog posts.

Ideally I'd like to create a field in my content type where all I have to do is input the Vimeo video ID and then the embed code is wrapped around it. This way I don't have to always paste the entire iframe. Or is there a better way?

For example if my Vimeo embed URL is the following, I'd like to only have to input the ID of "60771416"

```
<iframe src="http://player.vimeo.com/video/60771416?title=0&byline=0&portrait=0&color=ff9933" width="896" height="504" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

```

I guess I could have a field and have the embed code be in there by default, but I'd like to have it be cleaner then that.

I'm using Drupal 7 and Panels.

# Answer
Video Embed Field is exactly what you are looking for.

To use:

1. Install the module and configure your video player at: /admin/config/media/vef\_video\_styles/list/normal/edit
2. Add a video url field to your content type

Test by adding a url to a piece of content in the video url field. Ex: http://vimeo.com/30403839

When you view the content, you should see the Vimeo video.

Video Embed Field is a very simple, straightforward module that works very well.

Emfield was great in D6, but in my experience has been less stable in D7.
> 0 votes

# Answer
I would create a field to input just 60771416 instead of the whole iFrame. Then use the theme\_field to wrap with iFrame and set attributes accordingly. Gives me more flexibility for the output. As well as its modular. The Google Analytic module do similar stuff.
> 0 votes

# Answer
Drupal Embedded field module and Vimeo media module does exactly what you need out of the box.
> 0 votes

# Answer
So far the answers I've seen depend on you having to add a field just for a Vimeo video. If you don't want to add a field and just want to embed them in the body, use the Video Filter module.

With Video Filter, you just enable the option for your text format filter (like Full HTML, etc) and then you can add a video using a tag that looks like `[video:url]`. If you use a WYSIWYG like CKEditor, it also provides a button you can use that makes it even easier.
> 0 votes

---
Tags: 7, panels, nodes
---


# Question
Title: How are Field API fields transfered from config entities to content entities?
So I am creating a content and config entities - exactly like node and node type. After I've created them I've noticed that I can add fields to the config entities, which is ok but then I've realised that I'm working with two separate entity types, so I wonder how re Field API fields "transferred" from the config entity to the content entity?

# Answer
> 2 votes
This works essentially the same way as in Drupal 7.

Config entities like node types, custom block types, vocabularies and so on are used as storage and are then exposed as bundles of nodes, custom blocks, taxonomy terms, ...

There's not much magic involved, you can see what happens in e.g. `node_entity_bundle_info()` and `taxonomy_entity_bundle_info()`, so the modules have to do that part themself, you'll notice small differences there e.g. how they handle the bundle label.

The bundle\_of annotation key was added recently that allows to explicitly define that relationship between two entity types, but it's currently only used by field\_ui\_entity\_operation\_alter() to automatically add operation links to the listings of node types, vocabularies and so on.

While it looks like you add the fields to config entities, you really add the field to the corresponding content entity for the given bundle. Just like it already was in 7.x, the only thing that really changed is all those different things now use the same API for storage, in 7.x, they were stored in separate tables and didn't have anything in common.

---
Tags: entities, 8
---


# Question
Title: Tracking multiple items in a Commerce order individually
I need to track items individually in a Drupal Commerce store that I'm building, and I'm wondering if anybody here have an idea how to make this happen. Let me expand on this a bit:

If a customer puts 3 items in the cart, does the whole checkout process, pays for them etc. the store manager should be able to set statuses individually for those 3 items.

Most of the times these items will be shipped seperately, therefore the store manager should be able to set the first item to shipped while the other two is pending for example.

The only solution we've came up with is to explode the order into three seperate orders so after that one order, the store manager would see three orders with each product on the admin interface. Making this solution happen perfectly (set the right order totals to each order, set them to paid after the one payment, delete original order etc) introduces a lot of problems and it's a lot more complicated than we've expected.

Is there more straightforward, better solution out there for this purpose?

Thank you!

# Answer
> 1 votes
Since line items are fieldable, why not consider adding a field to the line item type and either switching to the Inline Entity Form for line item management on the order edit page or else creating a custom interface (Views + editablefields?) for manipulating the value of those fields?

That's what I'm going to be doing on a friend's site to track related eBay listings.

---
Tags: commerce
---


# Question
Title: Commerce: programmatically create new product with my ID
I have database of products and I want to export it to Drupal Commerce database with my Ids being saved:

```
$product = commerce_product_new('product');
$product->product_id = '100500';
$product->title = 'my title';
commerce_product_save($product);

```

But it always returns STATUS\_UPDATE because in sites/all/modules/commerce/modules/product/includes/commerce\_product.controller.inc in line 80 there is:

```
// Determine if we will be inserting a new product.
$product->is_new = empty($product->product_id);

```

It always clears "is\_new" when "product\_id" is filled.

If I change that string like:

```
$product->is_new = !empty($product->is_new) || empty($product->product_id);

```

Everything works fine.

Is it a Commerce bug or I do something wrong?

# Answer
> 0 votes
I don't see this as a bug, as we do want to prevent arbitrary IDs from being set in general. If you're doing it intentionally, though, I think your best bet would be to implement an override in a custom entity controller that extends the core functionality and changes the behavior of the is\_new check like you've done.

---
Tags: commerce, entities
---


# Question
Title: How to create a token to render nodes in content?
The goal is to place one ore more polls and/or slideshows anywhere within my blog post.

Step 1 is easy: With the Token Filter module, I can place tokens anywhere in my content.

Step 2 requires a module that creates a token which takes a nid as an argument and renders the node within my content, e.g. \[render-node:1\]. The rendered node would have a content type of poll and/or slideshow.

Is this a good way to go, or is there a better way? If this is the way to go, how would I go about creating a module to do this?

# Answer
Even though Mołot made a point about your question, I will give you an answer:

Using dynamic tokens with parameters is possible, but some coding is necessary. See pass parameters with tokens for more info.

You can also achieve what you need with some contrib modules, more specifically Field Collection (https://drupal.org/project/field\_collection) and References (https://drupal.org/project/references). With these two, you can create a field collection for your content type which includes one field for text and one field for node reference. Field collection module makes it possible to have multiple values, so you could slice up the text and insert the node references in between. To render full nodes with node reference field, go to manage display and set it to Rendered node. You will end up with something like this (administration):
> 1 votes

---
Tags: tokens
---


# Question
Title: Creating nodes with Views Bulk Operations
This seems like it would be a common application but not sure if it is doable. I have a view (d7, views3) that is displaying fields in views bulk operation format from a content type (call it general). For each row the user selects, I want to create a node of a separate content type (call it userspecific) made up of the user id and some of the fields from the general content type. Is this something that is possible using VBO ??

# Answer
This can be done using views bulk operations. But you may have to implement hook\_actions\_info in a custom module to create an action and the use that action in the views bulk operation.

Following code illustrates the process.

```
function custom_test_action_info(){
  return array(
    'custom_test_create_new_node' => array(
      'type' => 'node',
      'label' => t('Create New Page'),
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
    );
}

function custom_test_create_new_node($node, $context = array()){
  global $user;
  $page_node = new stdClass();
  $page_node->type = 'page';
  $page_node->status = 1;
  $page_node->title = $node->title;
  $page_node->field_body[LANGUAGE_NONE][0]['value'] = $node->field_body[LANGUAGE_NONE][0]['value'];
  $page_node->uid = $user->uid;
  node_save($page_node);
}

```

After saving this code flush the drupal cache and the views bulk operations form will have the action available.

After saving the view you will get the operation available in the views bulk operation page.

select a node and then execute the operation and you will have a new basic page created.

i am attaching an export of the view which i created you can import this view in your system and give a try to understand the workflow.

# Export code of the view:

```
$view = new view();
$view->name = 'test_vbo_node_creation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test VBO node creation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test VBO node creation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::custom_test_create_new_node' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 1,
    'label' => 'Create a new node',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-vbo-node-creation';

```
> 2 votes

---
Tags: nodes, views
---


title: openatrium installation error?

text:
# Question
Title: openatrium installation error?
I installed openatrium locally on Wampserver2.4, after installing all the 186 modules, I goes to site home page, but it show following error

how to cope this error

# Answer
You might need to do a change in my.ini file which is configuration file for your mysql server.

Change

1. open the my.ini file.
2. you might not have this (max\_allowed\_packet) line already there.
3. So you need to add this line at some point in this file.

max\_allowed\_packet=24M
4. Save the file
5. Restart mysql server.

Reference: https://drupal.org/node/163145
> 1 votes

---
Tags: database, installation, distributions
---


title: Workflow module blocked my admin user

text:
# Question
Title: Workflow module blocked my admin user
today i was adding the workflow module to my site and as i was not clear i used a trigger in it. using this trigger I blocked the current user to view the page and now if i login from my admin user it just tell me that *The username webmaster has not been activated or is blocked.* please guide me what to do to restore my old position.

# Answer
> 0 votes
Use below Drush command to reset admin password.

```
> drush uli
    (or)
> drush uli user_name

// Display a one time login link for the given user account (defaults to uid 1).

```

Just copy the one time login link and paste it your browser. Here you will get reset password option.

After successfully login, disbale the workflow module and go ahead.

More about Drush.

---
Tags: 7, workflows
---


# Question
Title: Custom Validation while adding a term under taxonomy
I want to use custom validation while adding a term. I used form alter and #validate function it's not working.Default validation function under taxonomy module is working but my custom validate function is not.

Here is my code

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

    if ($form_id == 'taxonomy_form_term'){
      $form['#validate'][] = 'lms2_validate_term_validate';
    }
  }

  function lms2_validate_term_validate($form ,&$form_state){
      drupal_set_message('hello');
  }

```

# Answer
> 0 votes
This would solve your problem for sure. However I would recommend you to have a look at hook\_form\_FORM\_ID\_alter

It is recommended to use hook\_form\_FORM\_ID\_alter if your module is implementing the hook only for a couple of forms or so. It gives better performance as it is being invoked only for the particular form and not for all and then checking it in if/else or switch/case loop.

Example: Considering your module name is: lms2\_validate

```
function lms2_validate_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'lms2_validate_term_validate';
}

function lms2_validate_term_validate($form, &$form_state) {
 drupal_set_message('hello');
}

```

NOTE: There is no if/else loop needed.

# Answer
> 2 votes
In Drupal 7, if you go through **hook\_form\_alter**.

It uses **$form** as a reference. You need to use **&** before **$form**.

```

/**
 * Implements hook_form_alter
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      $form['#validate'][] = 'mymodule_taxonomy_form_custom_validate';
      break;
  }
}
/**
 * Implements hook_form_validate
 */
function hook_taxonomy_form_custom_validate($form, &$form_state) {
  //validation goes here
}

```

Let say if your **module name** is **lms2\_validate** then use:

```

function lms2_validate_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['#validate'][] = 'lms2_validate_term_validate';
  }
}

function lms2_validate_term_validate($form, &$form_state) {
  drupal_set_message('hello');
}

```

---
Tags: taxonomy-terms, forms
---


# Question
Title: How to print an image field on all the basic pages only?
In my custom type "**Page**" I've added an image field (field\_page\_cover\_image) and applied image style to it.

```
<?php
  $field = field_get_items('node', $node, 'field_page_cover_image');
  if($field){
     $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
     if(isset($theme_img)) {
        // print styled image
        print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
    }
  }
?>

```

I have a requirement show this image (if uploaded) in all basic pages only (in a separate div container). For this I added the above code in \`page.tpl.php

This code is working fine in all the pages but when I load search or other pages, I am getting error, as they don't have this field ($field).

# Answer
# Solution 1 : use node.tpl.php

You should use a template for your specific content type "Page" instead of using page.tpl.php.

So try to copy paste the node.tpl.php, put your code in it, rename it node--page.tpl.php and upload it inside your theme folder. Then it should only apply to content type "Page", and not all pages.

# Solution 2 : check that you're on a content type "Page" in page.tpl.php

If you need to put your code inside page.tpl.php, then you can check if you're viewing a content type "Page" this way:

```
$nid = arg(1);
$path = arg(0);
if(isset($nid) && is_numeric($nid) && isset($path) && $path == 'node') {
    $node = node_load($nid);
    if(isset($node) && $node->type == 'page') {
        // PUT YOUR CODE HERE
        ...
     }
}

```
> 1 votes

# Answer
I suggest you to use template\_preprocess\_page and save your image to a variable. You can refer the below code.

```
function mytheme_preprocess_page(&$vars) {
     $node = $vars['node'];
     $field = field_get_items('node', $node, 'field_page_cover_image');
      if($field){
         $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
         if(isset($theme_img)) {
            //print styled image
            $imagevariable = theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
           $vars['myImage'] = $imagevariable;
        }
      }
}

```

You can use **$myImage** variable to print the image in the tpl file :)
> 1 votes

---
Tags: theming, media
---


# Question
Title: How can i rewrite the views table output for endless scroll
I use the module views load more and for an horizontal infinite scroll i want only one row with many columns. When i click on the load more button, views rendered every new page as a table. Like this:

```
<div class="view-content">
  <table>... 1. Page ...</table>
  <table>... 2. Page ...</table>
</div>

```

I try to rewrite the views-view--VIEWNAME.tpl.php and the views-view-grid--VIEWNAME.tpl.php but when i reduce this i get a output. Like this:

```
<table>
  <tbody>
    ... 1. Page ...
  </tbody>
  <tbody>
    ... 2. Page ...
  </tbody>
</table>

```

I reduce the views-view-grid--VIEWNAME.tpl.php to:

```
<?php foreach ($rows as $row_number => $columns): ?>
    <?php foreach ($columns as $column_number => $item): ?>
      <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
        <?php print $item; ?>
      </td>
    <?php endforeach; ?>
<?php endforeach; ?>

```

and add the table and tr tags to the views-view--VIEWNAME.tpl.php.

Don\`t know where the tbody tag comes. Same Problem here: https://drupal.org/comment/4641640#comment-4641640

# Answer
You can use this module Views Infinite Scroll. It will help to integrate jquery.autopager plugin with your drupal website.

> Views Infinite Scroll provides a Pluggable pagers that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.
> 0 votes

---
Tags: views, theming
---