# Question
Title: read new menu link id (mlid) before new menu item is saved
I'd like to do something with menu links when they are saved.

I can use hook\_menu\_link\_alter():

```
function my_module_menu_link_alter($item) {
  my_module_do_something($item);
}

```

This seems like the best and only hook I can use here. Only, the my\_module\_do\_something function requires $item to have the mlid propety (menu link ID) set, and when a new item is being saved, the property doesn't exist yet.

I can fake it by querying the database for the most recent mlid value and incrementing 1:

```
$item['mlid'] = db_query('SELECT mlid FROM {menu_links} ORDER BY mlid DESC LIMIT 1')->fetchField() + 1;

```

(I'm not sure if I can use MAX() here, I don't know enough about dbs that aren't MySQL or Postgres)

And I think this will work fine for my specific use case, but I'm curious to know if there is a better, more generic solution. It seems to me that this one will break down if content is being imported rapidly while users are active on the site, for example.

What is the best way to pass the future value of the item's mlid property to my function?

# Answer
> 0 votes
As Clive points out, the best way to do pass a menu link ID (mlid) when a menu item is created or updated is to use hook\_menu\_link\_insert(), hook\_menu\_link\_update() and hook\_menu\_link\_delete() instead of hook\_menu\_link\_alter().

---
Tags: 7, routes
---


# Question
Title: Filter Taxonomy reference field on Workbench Access permission
i need some help with Workbench access based on taxonomy.

**This is my use case:**
I have this taxonomy structure for my site:
\- Term A
\- Term B
\- Term C

And i have 2 roles:
\- editor
\- editor C

Editor c users must be able to create or update only the term C nodes.

I installed Workbench, Workbench Access and Field Property to control this behavior.
I configured Workbench Access on Taxonomy.
In admin/config/workbench/access/roles i put Roles “Editor C” only in “Term C” Section.

I created in each content type a Taxonomy Reference field, based on Workbench Access (i checked “Workbench Access control field”).
So this fields has two purposes:
\- tagging the node on my taxonomy structure
\- Assign the proper editorial group

**The problem:**
When an Editor C user adds a content, he can select any term value, not only “Term C”.
In other words the Taxonomy Reference field display all result.

How can i filter/limit the record of taxonomy reference on workbench access permission?

P.S.
If i check “Require a Workbench Access form element” in admin/config/workbench/access/settings the module add a “core” access control field in each content type.
This fields are filtered on Workbench access permission but i loose my first purpose (tagging the node on my taxonomy structure).

Can anyone help me?
Thanks in advance,
Matteo

# Answer
> 0 votes
You must install Taxonomy Access Control module. Follow this steps:

1) Enable the module.

2) Go to admin/config/people/taxonomy\_access

3) Click configure link for role "editor"

4) Click "Add vocabulary" link. Then select the vocabulary where you have terms "Term A", "Term B" and "Term C" and press "Add" button.

5) Click "Add term" link. Select "Term A". Configure permissions for this role and term (you should select "Allow" in every case). Once done press "Add" button.

6) Do the same for Term B

7) Do the same for Term C, but this time select "Deny" in every case.

8) Press button "Save all"

9) Go to previous window and do the same but this time for role "editor c". However you have to do the opposite: Terms A and B should have "Deny" in every case and Term B should have "Allow" in every case.

I hope this helps you! If it doesn't, you should checkout the Organic Groups module too. In case you need Organic Groups notice you also have OG Vocabulary module.

---
Tags: taxonomy-terms, users, workbench
---


title: Display non search results in Drupal 7

text:
# Question
Title: Display non search results in Drupal 7
I've been looking for a way to show all taxonomy terms that are not searched for in a view.

What I mean is: I want a search to sort out safe food for customers that are allergic to some food. If a customer is allergic to nuts the customer type nuts in the form and the customer gets a list of all dishes that DON'T contain nuts. Anyone know a module that will help me do this?

# Answer
> 0 votes
Sure, you can do this with Views.

1. Build a view that displays your dishes.
2. Set a *FILTER* for 'Has taxonomy term', expose it, and use the 'is none of' operator

I made that example using the 'dropdown' option, you may find the 'autocomplete' option more suitable to your needs. I recommend trying both to see which fits best and allowing multiple values so that people who are allergic to nuts AND gluten can still use it.

---
Tags: search
---


# Question
Title: Drush Aliases into Remote Hosts not Working - Tried everything
I've been struggling with a drush-related issue for awhile now and have more 'evidence' to write about. So here's what's going on: I'm trying to drush INTO two different servers (one on bluehost, another on rochen) and I get the same errors when I use my local drush on my computer to drush into either server. The error is Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

I get this error trying to drush @rochen status OR drush @bluehost status (the @name being the name of my alias files rochen.aliases.drushrc.php and bluehost.aliases.drushrc.php respectively.

I have installed drush on both servers already and can do drush commands on both using putty terminal.

I can drush just fine into Pantheon and any local sites I setup. I can also SSH into both rochen and bluehost just fine using Putty (I'm on Windows).

If I use drush --root=/home/username/public\_html --uri=websiteurl status it returns results...which is weird because I thought that command was supposed to be the same as doing drush @alias status which gives the error.

So I think maybe I have something wrong with my alias. See my alias file (I've confirmed the root is OK with my sysadmin):

```
<?php
$aliases['bluehost'] = array(
    'root' => '/home/username/public_html',
    'uri' => 'http://url.com',
    'remote-host' => 'url.com',
    'remote-user' => 'username',
);

// the following line is something I've tried to add in hopes it would help but it doesnt
//$options['ssh-options'] = '-o PasswordAuthentication=no -i C:/keys/ppkfile.ppk';

```

SOLUTION:

I fixed the permission denied error, the stdin: not a tty error, AND the bash: drush: command not found errors all in one fell swoop. See here: http://learningwithsage.com/wp/?p=236.

# Answer
> 0 votes
Try this first:

```
ssh-copy-id username@url.com

```

Make sure that the username and url match what is in your alias, of course. The "Permission denied" error is complaining that the remote site does not have your public key stored in its "authorized keys" file. ssh-copy-id will fix this for you.

If you are on a Mac, you can get ssh-copy-id from here:

https://github.com/beautifulcode/ssh-copy-id-for-OSX

It should be bundled with openssh on linux.

---
Tags: drush
---


# Question
Title: Drupal 7 Custom Page shown only for logged-in users
My problem is that, I need to create a new Page (path f.e. //panel), but I want there only logged-in users. If user is not logged in, he should be redirected to login form. I was trying to do it with Custom Pages, but I dont know how to do it, I can create variant only with HTTP response code, and its working good, but I dont know how to show content of this page, it's simply redirected me if I'm not logged in or displaying, that page is not found if I'm logged in. Do you know a solution for my problem?

# Answer
You are creating a custom page, so you should use user\_is\_anonymous() in the calback of the page.

For example:

`$form['custom_path'] = array(
 'page callback' => 'some_random_function',
);
function some_random_function() {
 if(user_is_anonymous()) {
 //call the login block
 }
 else {
 // What ever u want.
 }
}`
> 0 votes

# Answer
Yes, but can I do it non-programmatically? I want to have as little as it's possible custom code. Of course there will be some my custom functions and modules, but is it possible to set it in drupal without my code? Or, if it's not possible, can you tell me on which hook I can do it?
> 0 votes

# Answer
You can do this without custom code if you like by using panels. Create a custom panel for the path that you want. Then add a variation so you have 2 panels variations, the first one with a context for logged in users that shows them the content you want to show them. Then you can have the other variation be a http response (302) and set them to redirect to /user so they will have to login.
> 0 votes

# Answer
This can easily be accomplished using Rules:

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

Set up a new Rule:

Trigger: Drupal Initializes

Condition: Check Path: panel (the path)

Action: Page Redirect: user/login
> 0 votes

---
Tags: 7
---


# Question
Title: how to make URL aliases of nodes created via form include node title of original page?
Say I have a content type called "X", and every node of Content type "X" has a form that will create content type "Y"

How do I go about setting up the URL alias of content type "Y" so it will be something along the lines of "www.drupal.com/(Node title of X)/(Node title of Y).com

Thanks for any help!

# Answer
try the Pathauto module:

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

Once set up, you can have it assign the path based on the title of the current node (X) and the field value you assign to the title of node (Y). If you are using nodetitle or something to automatically assign the title for node (Y), you will have to run some custom code when content type (Y) is created in order to assign its alias.
> 0 votes

---
Tags: forms, tokens, path-aliases
---


# Question
Title: How do I put a reset button on my view's exposed filters?
This a really basic question, but it stumped me for a moment and there was little I could find on the net that answered this most basic need.

By default when you expose filters in a view, the only button that shows is 'Apply'. I have seen reset buttons elsewhere on the site and on example sites but I don't know how to make it appear on my view.

How do I put a 'Reset' button on my view to reset the exposed filters?

# Answer
> 3 votes
1. In your view configuration go to Advanced -\> EXPOSED FORM -\> Exposed form style: Basic | **settings**.
2. Check 'Include reset button' and save.

---
Tags: 7, views
---


# Question
Title: Custom module blocks: where to put html code?
I have a custom module that implements hook\_block\_view. I would like to know where should I put extensive html code for a block content.

For example:

```
$block['title'] = t('TEST');
$block['content'] = '<div id="user-custom-block">';
$block['content'] .= ... 50 LINES OF HTML.
$block['content'] .= '</div>';

```

What I did so far was to create a **.tpl.php** file and put all this code there, and then only call:

```
$block['title'] = t('TEST');
$block['content'] = theme('user_custom_block');

```

Is it correct?

If yes, so far, so good. But what if I have a "complex" logic inside of this block content?

For example:

```
$block['title'] = t('TEST');
for...
  $block['content'] = '<div id="user-custom-block">';
  if:
    $block['content'] .= ... 50 LINES OF HTML.
  endif;
  $block['content'] .= '</div>';
endfor;
etc
etc

```

Is this still ok to use in a **.tpl.php** file? If not, which approach should I use?

Should I use something like this?

```
/**
 * Implementation of hook_block_view().
 */
function custom_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = custom_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function custom_contents() {
  return '
      </p><div class="body">
        Hello World, this is a example custom Block
      </div><p>
    ';
}

```

# Answer
> 1 votes
Your goal should be to keep all processing out of the template file. Treat the template as a template - just some HTML and in some places, you print out variables.

From what you are describing though, it would be most useful to use a template for the '50 lines of HTML'. It is one thing to maintain a few lines of HTML in a PHP function, but 50 sounds like a nightmare.

```
<!-- my-template.tpl.php -->
<div class="50-lines-of-html">
  <?php echo $this; ?>
  <?php echo $that; ?>
</div>

```

Next, create some function that runs your for ... loop and builds the content using that template:

```
function process_my_things($things) {
  $output = '';
  foreach ($things as $thing) {
    if ($it_is == TRUE) {
      // do some stuff with $thing
      $output .= theme('my-template', array('this' => $this, 'that', => $that));
    }
  }
  return $output
}

```

Note that this can be a theme function too, but it doesn't have to be unless you want to allow overrides.

Finally, use another theme function or a template as a wrapper to arrange what you've got. You could even just use $block\['content'\] here as above:

```
$block['content'] = '<div id="my-wrapper">';
$block['content'] .= process_my_things($things);
$block['content'] .= '</div>';

```

# Answer
> 1 votes
You could improve that with 2 different options: 1) Creating a theme function 2) Creating a template file (tpl)

The tpl may be a cleaner option, but they are both similar. In both cases, you should pass preprocessed variables instead of putting the logic inside the theme function/tpl file.

Also, note that the literal strings should go through the t() function.

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


# Question
Title: View: show title of field where user is entity-referenced
I've got a content type of "Course" with entity references to users for Professor, TA, and Designer. Each user can be any of the three roles for any course.

I've got a View that shows, for the logged-in user, what courses they are the professor, OR TA, OR designer for.

What I'd like to add to that View is a column that tells the user which role they play in the course - or, in Drupal terms - which entity reference field their account is referenced in. I'd like to do this with exactly one column in the view.

The view already has Relationships from the Course to each of the referenced entities - but I am not sure how to get the conditional into a single column.

Is there a way to accomplish this with the Drupal 7 Views features, or do I need to re-write a column...?

# Answer
So you can print the user reference fields, but that will show all users and their roles, and you only want to show the one?

This might seem a little hacky, but it should work.

1. First of all, add all three user reference fields, and add them to the same table cell using the views table settings.
2. Next, you need to hide the user reference fields that do not contain the current logged in users name. To do this, we will be overriding the fields with a tpl.php template. In your view, click on "advanced" and at the bottom, click on "theme: information". In the relevant row, you will find something like `views-view-field--course--professor.tpl.php`. Note that this is overriding the field, and has the view name type in it (which will not override any other views with the same field).
3. In your FTP, go to the views module folder. Click on the "theme" folder, and find the file `views-view-field.tpl.php`. Copy this file to your themes template folder, and rename it `views-view-field--course--professor.tpl.php`, or whatever your field name was in step 2. Then flush your cache. This should now be overriding that field in the view. (To make sure, you could edit that file, and add some text below the `<?php print $output; ?>` to see if it worked.)
4. Now that we are overriding the field, we can influence what will be shown in that field. I would replace `<?php print $output; ?>` with the following....

```
<?php
global $user;
$username = $user->name;

if (strpos($output, $username) !== false) {
  print $output;
}
?>

```

I haven't tested the above, but something similar to that should print the fields output, only if the current logged in users username matches the output.
> 0 votes

---
Tags: views, entities
---


# Question
Title: What are the major differences between solr modules
I am looking into Solr search for my site and am seeing two equally well-used modules.

Why would I pick one over the other?

# Answer
> 2 votes
I would recommend using Search Api Solr. Search Api Solr is a little bit more complex; however, it is more powerful. In addition there are many sub-modules that allow you to extended the search funcionality.

You should consider reading the article Battleplan for Search & Solr in Drupal 8.

According to this post.

> The two maintainers of Search API and Apache Solr have meet in person and have determined a way forward for advanced searches with Drupal and they both have agreed that Search API is it.

# Answer
> 2 votes
Both of the modules deliver the same base functionality but search api solr came later and is now well maintained widely supported. It integrates better because it has all the support from search api. The Solr is only a backend. That is why with search api you can extend almost endlessly. I would also propose to not use an external backend at all. Just search api with database backend would do just fine when you have not more then a 1000 nodes. The database backend also supports facets like Solr does.

# Answer
> 2 votes
I have made a few sites with each solution and have done some custom work also with both and I would be happy to recommend either solution.

Initially there were differences between them that made it more easy to decide which would be better for you based on your requirements (like non-node entity searching or support for certain add-on modules) but these days they are very similar as others have said.

If you have very basic requirements you can really pick either.

If you have specific performance concerns then you would be best to try both options and benchmark them for speed with your particular setup to know which performs better and is it by enough that it matters.

If you require specific add-on functionality then investigate what is available for each and see how well those add-ons are maintained etc. and that can sometimes help you decide.

The other thing if you have time is to try them both out and see which you find better to use. If you don't have much in the way of complex requirements then usability may be the deciding factor.

There are still some example use cases where one seems to be clearly better than the other however those are getting less common and more niche.

It really depends on your specific requirements and your personal preference (which can be determined by trying them both out).

Since they are joining forces for Drupal 8 I would expect an upgrade path from both Drupal 7 options to the new Drupal 8 option.

---
Tags: 7, search
---


title: ajax update block on click to link

text:
# Question
Title: ajax update block on click to link
I am using jQuery Ajax Load module in my site to load some contents from url to show on specific div which has a required class. With this module I am able to fetch the Page content from URL through ajax & displays on specific block. I need to replace the blocks when click on the link. for-example I have a block A displayed on content area, also I have block B & C which are hidden for now. when I click on link B the block A should be replaced with block B & so on using AJAX. Please help me? Thanks

# Answer
> 0 votes
What have you already tried?
Having a look at the module JS, there is a function `jquery_ajax_load_load(el, target, url)`. Have you tried calling it?

**EDIT**
To load block content you could either use another module specifically for it (search "drupal block ajax load") (ajax blocks) or you could create your own module that just returns block content when navigating to a url. This should be quite easy by implementing hook\_menu and returning the value returned by block\_load()

---
Tags: 7, ajax, javascript
---


# Question
Title: How to adjust weight of profile 2 fields
I added some fields to the default user registration form. I then installed the Profile 2 Module through which I added three (3) fields- "first name", "surname" and "place of work".

Is there a way to make the first name and surname fields appear above the default user registration fields while the place of work appears below it?

Thank you.

# Answer
You will have to use the Drupal Form API to achieve that.

You basically need to alter the structure of the form before it gets rendered.

If you are using the Profile2 module, the best way to go about it would be to implement `hook_form_profile2_edit_PROFILE_TYPE_form_alter()`in a custom module.

You will then need to transform the `$form` array as needed (change field weights, and field positions).

For example:

```
function MODULE_NAME_form_profile2_edit_YOUR_PROFILE_TYPE_form_alter(&$form, &$form_state) {
  // Apply transformations to $form
  // e.g. change field weights
  $form['your_custom_profile_type']['place_of_work']['#weight'] = '-10';

  // e.g. copy field into new position
  $form['account']['place_of_work'] = $form['your_custom_profile_type']['place_of_work'];

  // Add a custom pre_render function to prevent the field from showing up again in the form
  $form['#pre_render'][] = 'MODULE_NAME_pre_render';
}

```

The pre\_render function could look like this:

```
function MODULE_NAME_pre_render(&$form) {
  // Prevent custom field from displaying twice
  unset($form['your_custom_profile_type']['place_of_work']);
  return $form;
}

```
> 0 votes

---
Tags: users
---


title: Define variables for specific template

text:
# Question
Title: Define variables for specific template
I would like to pass variables to a single specific template file(tpl.php). My setting is the following:

my\_entities.module

```
function my_entities_theme($existing, $type, $theme, $path) {
  return array(
    'my_entities_property' => array(
      'variables' => array('element' => null),
      'template' => 'my-entities-property'
    )
  );
}

```

I am using a template file at my\_theme/templates/my-entities-property.tpl.php

In the module file I am trying to invoke a preprocess function to add a variable but it is not being invoked.

```
function template_preprocess_my_entities_property(&$variables) {
  $variables['test'] = "test";
}

```

How could I make this work? I followed https://www.drupal.org/node/2275895#comment-8832701 but it seems that I am doing something wrong.

# Answer
> 1 votes
You should put your template in your module as well.

```
my_theme/templates/my-entities-property.tpl.php

```

Make sure to update your theme function like this :

```
function my_entities_theme($existing, $type, $theme, $path) {
  return array(
    'my_entities_property' => array(
      'variables' => array('element' => null),
      'template' => 'my-entities-property',
      'path' => drupal_get_path('module', 'my_entities') . '/templates'
    )
  );
}

```

Try to use THEME\_preprocess\_my\_entities\_property(&$variables) in template.php instead.

# Answer
> 1 votes
In module preprocess function is `moduleName_preprocess_[theme_function_hook]`. here it will be my\_entities\_preprocess\_my\_entities\_property

---
Tags: theming
---


# Question
Title: Does a redirect by Drupal's Global Redirect Module occur immediately or is there a delay?
I have a website that was migrated from a WordPress blog to Drupal 7.

After running Moz Report I found lots of duplicate pages in the form of

```
/blog/wp-content/uploads/2013/09/</body></</body></http</body</http</body>
</http</body></</body></http</body></http</body></http</body></http</body>
</http</body></http</body></http</body></http</body></http</body></html>

```

Installing and enabling the Global Redirect Module does not seem to help. I have enabled the default settings + add canonical link.

1. Does the redirect occur immediately or is there a delay?
2. Am I missing something?

# Answer
> 0 votes
/blog/wp-content/uploads/2013/09/

Is a path from a Wordpress installation, not Drupal.

Global redirect, being a Drupal module, not Wordpress, can only help you to set up redirects/canonicals on Drupal paths, not those from your Wordpress installation.

Presumably you'll need to add redirect/canonical functionality to your Wordpress installation to continue.

---
Tags: 7, redirection
---


# Question
Title: Unable to load URL when drupal is installed on a server
My drupal URL was loading normally until when I deleted two modules in the Windows server.Now after deleting the modules from the server the site is not loading. I know that deleting a module does not result in the URL not loading it simply removes the module from the Module List.

I can't exactly find out what exactly is the reason behind this

\[Update\]I have checked under my Modules Menu and verified that both the modules are disabled and then un-installed from the modules list.

# Answer
> I know that deleting a module does not result in the URL not loading it simply removes the module from the Module List.

That's incorrect. If you delete a module without first disabling and uninstalling it, you could easily break the whole site. You're removing code that you've told the system exists when you installed the module, and it has no way to recover from that.

You should restore the deleted files temporarily, disable then uninstall the module properly with Drush, or through the UI, and only then should you delete the files.
> 2 votes

---
Tags: uri
---


title: Using drupal_add_js with google maps

text:
# Question
Title: Using drupal_add_js with google maps
I want to pass down an array to my javascript. So that i could create markers on google map.

By doing this:

```
drupal_add_js('https://maps.googleapis.com/maps/api/js?key=AIzaSyDcl28Qcn9GTi02rRtQaLgVS4GWZbGcQ8E', 'external');
$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');
drupal_add_js('sites/all/modules/GoogleMapByDave/DGMap.js','external');

```

The javascript that is DGMap.js dosnt seem to work.

Here is the js in the DGMap.js:

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

  //var locations = Drupal.settings.myModule.locations;

 function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var locations = [
                    ['Mājas',56.956344, 24.197409],
                    ['Domina',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

     }

      google.maps.event.addDomListener(window, 'load', initialize);

   }
   }
)(jQuery);

```

But if I add it through the module as an inline it works! But I dont know if i can use the variables there?

```
drupal_add_js('jQuery(document).ready(function () { function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById(\'map-canvas\'),
        mapOptions);

    var locations = Drupal.settings.myModule.locations;

    var locations = [
                    [\'Mājas\',56.956344, 24.197409],
                    [\'Domina\',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][\'locationLat\'], locations[i][\'locationLng\']);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][\'locationTitle\']
      });
    };

  }

  google.maps.event.addDomListener(window, \'load\', initialize); });','inline');

```

EDIT//////////////////////

I got further in this. Adding script like this:

```
$path = drupal_get_path('module', 'GoogleMapByDave');
drupal_add_js($path . '/DGMap.js', array('weight' => 1));

```

And the script:

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

var mapOptions = {
    center: { lat: 56.9714744, lng: 24.1291624},
    zoom: 9
};

var locations = Drupal.settings.GoogleMapByDave.locations;
alert(locations);

var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

var locations = [
                ['Mājas',56.956344, 24.197409],
                ['Domina',56.966058, 24.162004]
                ];

for (var i = 0; i < locations.length; i++) {

  var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

  var marker = new google.maps.Marker({
      position: loc,
      map: map,
      title: locations[i][0]
      });
  };
}
};

```

Now the script is runned. But the problem now is that how can i get settings? I get unidentified from "locaitons" var.

Btw i changed the $settings\['GoogleMapByDave'\]\['location'\] part.

# Answer
You should add your array in the Drupal.settings object.

In your module, you should use drupal\_add\_js, with the `setting` option :

```
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

It makes your array accessible in javascript. It is stored in the Drupal.settings javascript object. From your js easily access your array :

```
console.log(Drupal.settings.myModule); // returns your array
console.log(Drupal.settings.myModule.key); // returns "value"

```

The Drupal.settings object is available from page load, and is refreshed each time you use Drupal ajax functions.
> 0 votes

# Answer
Your DGMap.js script isn't `external`, you should use `file` as type parameter instead.

```
drupal_add_js('sites/all/modules/GoogleMapByDave/DGMap.js', 'file');

```

or use an absolute path.

```
drupal_add_js('http://example.com/yourscript.js', 'external');

```
> 0 votes

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


# Question
Title: How to perform calculations using a field from another content type?
I have a spreadsheet as in the screenprint below:

---

---

Here are some details about the screenprint above:

* I have 2 content types: Product and Invoice.
* It consists of 3 datablocks:

+ Product: a table with 4 columns, and 1 row for each available product, such as the price for each product.
    + Invoice: a table with 4 columns, and 1 row for each invoice, which includes the total invoice amount, which is the quantity sold for a product, multiplied by the price of the product (derived from the product data block).
    + Total income per product, which is like a join of some of the columns of the Product data block with the Invoice data block, and to which "Subtotal" and "Page Total" row were added.

Any suggestions about building the equivalent of this spreadsheet in Drupal?

# Answer
> 1 votes
You can go for Views Calc or Views Aggregator Plus

This module adds simple calculations to a views table.

You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns.

---
Tags: entities
---


# Question
Title: How to assign nodes to an organic group in code
How can I assign a node to an organic group in code? After consulting following page

And de OG API I ended up with this code, but it throws an error 'The website encountered an unexpected error. Please try again later.'

```
$node = node_load(5827);
$values = array('entity type' => 'node', 'entity' => $node, 'field_name' =>'og_group_ref');
og_group('node', 3, $values);
node_save($node);

```

More info: OG-7.2.7

# Answer
Found out removing the last line from the snippet 'node\_save($node)' and the above type error was the reason for my problem. Thanks for the support.
> -1 votes

---
Tags: organic-groups
---


title: Exposed filter AJAX error

text:
# Question
Title: Exposed filter AJAX error
I have put an exposed filter on my page, which is an auto-submit textbox without any submit button. When I put the focus on this textbox and **refresh** the page with no value inside the textbox, the page gives me an error which is caused by emptiness of the textbox.

```
**Error:**
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /************/views/ajax
StatusText:
ResponseText:
ReadyState: 4

```

What is your solution for it?

# Answer
When you give the focus to your field, it triggers an ajax call to the server. If you reload the page right away, it breaks the ajax call and throw this error in an alert.

This only happens as you reload the page during an ajax call. As far as i know you can't do anything about it, unless you modify the core I guess - which is "unclean".

You could use the classes added in css to display a loader while there is an ajax call to the server, and let the user know the page is working on something.

**EDIT:**

Thanks to clive's comment I actually got rid of this alert by overriding Drupal's `Drupal.ajax.prototype.error` function.

In a js file, you can add :

```
Drupal.ajax.prototype.error = function (response, uri) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  // Reattach behaviors, if they were detached in beforeSerialize().
  if (this.form) {
    var settings = response.settings || this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }
};

```

This is a copy of the original error handler callback without the alert() function. This will remove your message, but will also hide any error message returned by Drupal's Ajax.
> 2 votes

---
Tags: 7, ajax, views
---


# Question
Title: How to access label of List (text) via node_load()
In my module I'm generating some json based on some node content.

```
$node = node_load($nid);

```

One of the fields in the node is field\_sport\_type which is of type `List (text)`. The allowed values look like this:

```
mens-surfing|Men's Surfing
womens-surfing|Women's Surfing
junior-mens-surfing|Junior Men's Surfing
junior-womens-surfing|Junior Women's Surfing
skate|Skate

```

When I var\_dump($node), the field\_sport\_type section looks like this:

```
["field_sport_type"]=>
      array(1) {
        ["und"]=>
        array(1) {
          [0]=>
          array(1) {
            ["value"]=>
            string(14) "womens-surfing"
          }
        }
      }

```

So, the 'value' is the key from the allowed values, but I want to get the Label, not the key. In other words, I won't want `womens-surfing`, I want to get `Women's Surfing`.

How can I get access to the label of my List (text)?

# Answer
You can get the list of values as a keyed array using list\_allowed\_values, and use it to show the "key" with whatever logic you want.

An example from the API comments section is as follows:

```
<?php
/*
assuming there's a field named machine name is 'field_my_field_name' whose
type is a list (float, integer or text), and you want to get the values that
were entered into the "Allowed values list" textarea on the edit screen for the field
*/
$all_fields_on_my_website = field_info_fields();
$allowed_values =       list_allowed_values($all_fields_on_my_website["field_my_field_name"]);
/*
$allowed_values is now an array of $key=>value pairs that
can be dropped into the '#options' value for a form field array, for instance
*/
//example:
$form = array();
$form['my_form_element'] = array(
  '#type' => 'select',
  '#title' => t('Choose something, sucka!'),
  '#description' => t('Descriptive text under form elements rather than above them is a great UX choice, really.'),
  '#options' => $allowed_values,
);
return $form;

```

Being a "field" in drupal the List field instance attached to a bundle has configuration and settings such as the custom list of items, the default value, whether its mandatory, etc.
> 6 votes

# Answer
You can access the key label in a simple way using an Entity Metadata Wrapper:

```
$wrapper = entity_metadata_wrapper('node', $nid);
$label = $wrapper->field_sport_type->label();

```

Or using de $node loaded vía node\_load():

```
$wrapper = entity_metadata_wrapper('node', $node);
$label = $wrapper->field_sport_type->label();

```

You will need the Entity API module, but I think that this module is almost mandatory in custom module coding.
> 5 votes

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


title: advance search to show post by date

text:
# Question
Title: advance search to show post by date
i trying to make the search on drupal show result by date. for example if i type 25/05/2010 it should return posts for that date and also search by key work which is default on the search. how can i acheive that.

```
function mytheme_preprocess_search_result(&$variables) {
    $result_node = $variables['result']['node'];
    $image_realpath="";
    if(!empty($result_node->field_op_main_image)){
        $image_field = $result_node->field_op_main_image;
        $image_realpath = file_create_url($image_field['und']['0']['uri']);
    }
    $variables['image_uri'] = $image_realpath;
    $author_name="";
    $info = "";
    if(!empty($result_node->field_op_author)){
        $author = $result_node->field_op_author;
        $lang = $result_node->language;
        $author_id = $author[$lang]['0']['nid'];
        $author_detail = node_load($author_id);
        $author_name = $author_detail->title;
        $info .= $author_name . ' - ';
    }
    if(!empty($result_node->field_date)){
        $date_obj = $result_node->field_date;
        $date_val = $date_obj['und']['0']['value'];
        $info .= date('d/m/Y', strtotime($date_val));
    }
    $variables['info'] = $info;
    // dpm($variables);

```

above is the code for displaying my result for now.

please help thanks

```
=======================================================================

```

EDITED

so this is what i got so far: let me try to explain:

i was trying to modify the search-form and the search-block-form i was able to add a jquery date picker so that the user might search for a specific date or a key word.

the date picker is working

now the issue is:

when i search for key words and press submit it return the article with key word. but if i enter date only it give error to enter keyword and if i enter keyword and date it search by keyword only and ignore the date

code is below

// function to modify search form function fiveplus\_form\_alter(&$form, &$form\_state, $form\_id) {

```
// $variables['form']['actions']['submit']['#value'] = 'search';
if((array_key_exists('#id', $form) && $form['#id'] == 'search-block-form')){
    $form['actions']['submit']['#value'] = '';
}
if((array_key_exists('#id', $form) && $form['#id'] == 'search-form')){

    $form['basic']['submit']['#value'] = 'submit';
    $form['basic']['keys']['date_field']['#title'] = 'search';
    $form['basic']['date_field'] = array('#type' => 'date_popup','#date_format' => 'Y-m-d');
    dpm($form_state);
    //$form['advanced'] ;
}

```

so anyone can help me figure out how to make a user be able to search only by 1. date 2. date and keyword 3. keyword

thank you

# Answer
> 0 votes
You can use views to search all of your content.

Rather than me write out every step for you, Please try the tutorial at http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7

---
Tags: theming
---


# Question
Title: Adding taxonomy filter at the top of image gallery
I've spent some time trying to discover how can i add taxonomy filter at the top of the gallery view in Drupal 7. I've created View called Gallery which contains of images,title and author. In content type I've declared that it is a term reference to Gallery type taxonomy. My purpose is to allow user to sort the image gallery by tag, simple example would be animal gallery, for example:

> 'all' 'pigs' 'dogs' 'cats'
>
> 'image' 'image' 'image'
>
> 'title' 'title' 'title'
>
> 'user' 'user' 'user'

So far I've created this View of images,title and author, I've no idea how to include taxonomy tags. I hope this explanation is understandable. Any help would be appreciated.

# Answer
> 0 votes
You can add your taxonomy field in the "Filters" section of the view. In the filter settings, select the option "expose filter to users".

It will add a taxonomy filter in your view, based on the terms from the vocabulary selected in your field.

It will allow users to filter the view by taxonomy term.

# Answer
> 0 votes
You can create menu block with items/links which you need and then add this block into views header via Views block area module

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


# Question
Title: How to add a report an error button in a Drupal 7 website and collect user's browser details?
We just did a website upgrade. On some sites I have seen a 'Report an error' icon (in the right hind corner). After clicking on it, a user can report an error which will send along other information about their system like OS, the user's browser and what link they were on when the error occurred.

Question: Any suggestions on which module to use for it and/or how to add such 'Report an error' to the website?

**Update**: I am looking for something like whatismybrowser.com, which can be added like a button or tool.

# Answer
> 1 votes
You could check out the Feedback module to see if it meets your needs - it's pretty simple and lightweight. If you don't want to use a contrib module, you could do something similar to the Feedback module - create a block (either using existing blocks in your theme or create a new block region programmatically), position it absolutely, and then link the 'Report an Error' block text to some kind of web form where you can collect the desired information. You could also use the Webform module to help you quickly create a form.

---
Tags: 7, notifications, debugging
---


title: Problem upgrading from 7.22

text:
# Question
Title: Problem upgrading from 7.22
I'm trying to update from Drupal 7.22 to the current (7.26) version. I keep getting the following error on the Configuration page after updating.

`Fatal error: Class 'DatabaseTasks_mysql' not found in /server/path/stuff/here/domainname.com/html/modules/system/system.install on line 188`

I have tried upgrading incrementally 7.22 -\> 7.23 I've tried upgrading directly to 7.26 I've tried uploading files via FTP, following the standard upgrade instructions, and I've tried upgrading with drush. I always get the same error. (though the line number does change depending on which version I'm updating to.)

Does anyone have any suggestions?

# Answer
> 3 votes
I was experiencing this problem on two different test servers (different Debian and PHP versions) using data imported from our production server. All of the cache tables were emptied first, and I did try reinstalling Drupal using various methods. Couldn't find a solution anywhere.

What finally fixed it for me was emptying the registry and registry\_file tables, then running update.php. (Update didn't find any database changes, but it reset the registry - clearing the cache may have worked as well.)

Hope this helps someone - this problem was driving me crazy for two days.

# Answer
> 1 votes
If you are updating through 'drush pm-update drupal', I would try updating the files manually through git or 'drush dl', then running drush updb or update.php. If you are updating though git, make sure a merge conflict didn't butcher anything.

Class "DatabaseTasks" is declared in includes/database/mysql/install.inc which shouldn't have changed in years. Check that the file still exits and is identical to the one before.

Otherwise, it is most likely an issue with bootstrap level. If the site is not bootstrapping high enough, it will break. A bug or hack in drush or core could cause a site to bootstrap to too low a level.

---
Tags: 7, updating
---


# Question
Title: How do I maintain aspect ratio of scaled image with max-width?
When I use an Image Style that scales the original image, Drupal 7 (now 7.14) prints the height and width attributes in the img tag whereas before it didn't.
So before, my CSS `img {max-width: 100%;}` preserved the images aspect ratio when displayed in a small box (i.e. on a mobile screen), but now clashes with height and width attributes. Drupal generates enclosing boxes with no explicit height so the result is an elongated distortion.
What can I do - preferably with CSS alone, but in a template file's php if necessary - to preserve the aspect ratio?

# Answer
> 16 votes
It's as simple as just adding `height:auto;`

```
img {
max-width:100%;
height:auto;
}

```

# Answer
> 4 votes
I haven't tried it but using CSS you might just get away with:

```
img {max-width: 100% !important;}

```

If not, I think the simplest solution would be just to stop the `theme_image()` function from outputting the width and height attributes (in template.php as you suggest). There are couple of ways you could do this.

Firstly, you could implement `hook_preprocess_image()` to remove the attributes from the theme vars:

```
function MYTHEME_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    if (isset($variables[$key])) {
      unset($variables[$key]);
    }

    if (isset($variables['attributes'][$key])) {
      unset($variables['attributes'][$key]);
    }
  }
}

```

That method *may* have the potential to be overridden by something else in the system though. To get around that you can simply override the `theme_image()` function altogether (it's not a long function):

```
function MYTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  // 'width' and 'height' have been removed here
  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

# Answer
> 0 votes
I use this technique for responsive images with fitting into its container (and aligned to whatever point in it) which is also responsive. With this technique you can make miracles. Responsive miracles.

https://stackoverflow.com/a/28073729/1663572

---
Tags: media, theming
---


title: Exec JS after flag ajax result

text:
# Question
Title: Exec JS after flag ajax result
In my portal I need to use "flags" module to create a simil twitter "follow/unfollow". I have installed and configurated this module. All works, via AJAX too.

Now I need to exec some other JS function after that the flag module has completed his call. I think that I need to add (on the backend) some "commands" before flags return "commands" to execute in the frontend.

How I can I do this ?

Thanks, M.

# Answer
> 0 votes
here is API https://www.drupal.org/node/336122

The two events

The flagGlobalAfterLinkUpdate event

This event is triggered immediately after a flag link has been updated. (Flag links appear in two flavors: "Bookmark this!" and "Unbookmark this!", and when we speak of "update" we mean this change in appearance).

The flagGlobalBeforeLinkUpdate event

This event is triggered just before a flag link is updated. As will be explained later, the existence of this event is for cosmetic reasons only: it allows us to carry out actions while the throbber () is still visible.

```
$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  alert('Object #' + data.contentId + ' (of type ' +
    data.contentType + ') has been ' + data.flagStatus +
    ' using flag "' + data.flagName + '"');
});

```

---
Tags: 7, ajax, flags
---


# Question
Title: Form Permissions not working in Module with Multiple Forms
This works great in a module with a single form, however in a module with multiple forms the form does not show up in the permissions list. Is there something that I need to do differently for modules with multiple forms? For example, do I need to add security to each form before it will recognize it for any forms in the module?

I add this to hook menu:

```
'access callback' => 'user_access',
'access arguments' => array('Spring Grove Scorecard Access'),

```

Then use this function:

```
function form_scorecard_permission() {
    return array(
       'Spring Grove Scorecard Access' => array(
       'title' => t('Spring Grove Scorecard Access'),
       'description' => t('Allows users to access the Spring Grove Scorecard.'),
    ),
  );

```

# Answer
> 0 votes
This was my fault for not completely understanding how the permissions function worked. I didn't realize only one function is needed to house all form permissions. The following code works great. Hopefully it will help others who aren't all that bright like myself:

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

  $items['sar_performance_form'] = array(
    'title' => 'SAR Performance',
    'description' => 'SAR Performance Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_performance_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR Performance Form Access'),
  );

    $items['sar_sdr_form'] = array(
    'title' => 'SAR SDR/NCR',
    'description' => 'SAR SDR Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_sdr_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR SDR Form Access'),
  );

  return $items;
}

//***PEFORMANCE FORM***
function sar_performance_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_performance_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_performance_overview']['sar_performance_overview'] = array(
     '#markup' => t('Performance form overview goes here'),
   );

   //Display the form
   $form['sar_performance_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//***SDR FORM***
function sar_sdr_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_sdr_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_sdr_overview']['sar_sdr_overview'] = array(
     '#markup' => t('SDR form overview goes here'),
   );

   //Display the form
   $form['sar_sdr_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//This function adds the forms to the permissions menu
function glatfelter_supplier_action_register_permission() {
    return array(
       'QCA SAR Performance Form Access' => array(
       'title' => t('QCA SAR Performance Form Access'),
       'description' => t('Allows users to access the SAR Performance form.'),
       ),

       'QCA SAR SDR Form Access' => array(
       'title' => t('QCA SAR SDR Form Access'),
       'description' => t('Allows users to access the SAR SDR form.'),
       ),

    );
}

```

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


title: Updating Large Number of Sites

text:
# Question
Title: Updating Large Number of Sites
At my current job we have a large number of Drupal installations(not multisite) and we are facing some issues regarding things like applying security updates (really any kind of update). Currently we have a mix of D6 and D7 sites, though all new sites are D7....hopefully we can eventually move all to D7.

I was curious what strategies you guys would suggest for approaching mass updates in this environment. Do you think it would be worth converting our sites to using Aegir for update administration? Will this come down to manually updating/working through each site?

Thanks, Ryan

# Answer
> 3 votes
There really isn't any right answer to this question. I do something similar to what tenken suggests; see:

https://github.com/greg-1-anderson/utiliscripts/blob/master/drupal-backup-all

The basic idea is, every time I back up a site, I also make a second local copy, and run pm-updatecode on it. The backup and update sites are live (but accessible only on the internal network), so it's possible to look at either and see if they are running or not.

My experience in doing this is that the task of copying a site and running pm-updatecode is **not** the main bottleneck in upgrading sites promptly and frequently. The main bottleneck is testing. You have to set aside time to do this, or you won't be able to confidently deploy your sites. Upgrades rarely, but sometimes do break your site, so you cannot really automate this last critical step.

One thing that can really help is good automated tests. Behat and Selenium are really useful here. See the small project below for a quick start template:

https://github.com/arithmetric/badcamp2014-behat-travisci

# Answer
> 1 votes
Create a master drush alias file, scrape all your drupal settings using Bash for example across remote servers you control. Then use drush aliases manually as-needed to apply updates .... or yet again script updates via cron using a Bash script.

---
Tags: drush, updating
---


title: EntityFieldQuery vs Db_select()

text:
# Question
Title: EntityFieldQuery vs Db_select()
Why should I use EntityFieldQuery when I can do the same work with Db\_select() to fetch the value.

It would be better if someone can provide an example, not only a link.

# Answer
> 11 votes
I think the point is that the syntax is much simpler, and the code will be more understandable.

For example, if you want nodes with type `my_type` that have a field named `field_foo` with the value `$val`, with Db\_Select, yuoll do something like :

```
$nids = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->join('field_data_field_foo', 'foo', 'foo.entity_id = n.nid')
  ->condition('n.type', 'my_type')
  ->condition('foo.field_foo_value', $val)
  ->execute()->fetchCol();

```

Which is much simpler with EntityFieldQuery :

```
$query = new EntityFieldQuery;
$entities = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_type')
  ->fieldCondition('field_foo', 'value', $val)
  ->execute();

```

# Answer
> 14 votes
I think that the main reason prefering `EntityFieldQuery` over `db_select` is that you don't have to know about the lower-level structure, in other words: how stuff is stored in the database. This improves loose coupling.

# Answer
> 3 votes
EntityFieldQuery (EFQ) will only return entity IDs. If you want to access entities data, you'll have to call `entity_load()`, which, among loading the data, will make sure that all underlying stuff you normally do not care about (such as loading fields, calling other modules hooks etc.) are made. Of course, this result in **two** SQL queries and a lot of overhead, but this is the price to pay for the abstraction.

As for the EFQ syntax being more clear, I think it's much more a question of personal preferences. I, for instance, do **not** think that EFQ is clearer. Notice that a working `db_select()` replacement with EFQ must include the return value test and subsequent `entity_load()` call, and this adds a lot of noise to the code, IMHO:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_type')
  ->fieldCondition('field_foo', 'value', $val)
  ->execute();
if (!empty($entities['node'])) {
  $nodes = entity_load('node', array_keys($entities['node']));
} else {
  $nodes = array();
}

```

So, answering your question: use EFQ if your entities are full-featured (e.g. are fieldable, can be used by other modules, etc.) and/or you think that its syntax is clearer. If other cases, use may use `db_select()`.

# Answer
> 1 votes
*EntityFieldQuery* is far more limited than *`db_select()`*, so you should have a really good reason to not use *`db_select()`* (see bart answer), which is readable enough and far more flexible.

For example, `entityFieldQuery` use *innerJoin* to fetch fields. If you need a leftJoin for whatever reason, you're trapped... http://drupal.org/node/1226622

---
Tags: 7, entities
---


# Question
Title: Image module custom image style changes image link
I am using Drupal 7.32, and I enabled the Image module.

I have created a custom "Image Style" so that I could add Bootstrap 3 "img-responsive" class to my image in my view, but adding that custom style to the image field for my view causes Drupal to change the URL where the image is placed and then not resolve the image.

This is the "Image" styles user interface. Notice at the bottom I added my own custom style.

This is is my custom image style definition.

This is my Image field in my view. Here I set the Image style to my custom Image style that I created.

This is the view displaying the content for that view. It is not resolving the images because it is changing the title to http://localhost/system/files/styles/center\_block\_responsive\_image/private/images\_content/news/latin.america.night\_.jpg?itok=1yvjqDtY. This would resolve but it is adding styles/center\_block\_responsive\_image/private to the URL for the image, when the URL should be `http://localhost/system/files/images_content/news/latin.america.night_.jpg?itok=1yvjqDtY`.

The content type's image field saves the image to the private file system. Does anyone know why the Image module would rewrite the image like this? I have a default image that I am using for each piece of content.

The image resolves for the default content type, despite the fact that it is also adding styles/center\_blow\_responsive\_image/private to the URL, as in http://localhost/system/files/styles/center\_block\_responsive\_image/private/default\_images/elaw.jpg?itok=BpkGqQJ-.

If I change the "Image Style" on the view field back to "none" it retrieves the image just fine.

Does anyone know why the Image module is adding this extra text to the URL which causes it to not resolve properly?

# Answer
> 0 votes
I found a fix by adding

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

to my settings.php file

I found the solution from this drupal stack exchange posting: Drupal 7.20 Image Styles return a url with Access Denied

I'll hold off on accepting my answer here as the accepted answer for a bit in case someone informs me that I should not be solving the problem this way.

---
Tags: 7, media, theming
---


# Question
Title: Get node ID that field belongs, in field.tpl.php being displayed in a block on any page
I have a 'Gallery' content type that has an entity reference field, which I use to reference other nodes of the 'Gallery Item' content type. When creating a 'Gallery' I use the nodeblock module to automatically create a block with this content.

So when I place this block in any page, let's say the homepage, I have it displaying the 'Gallery' title and a body on top, and below that, each 'gallery item' using the 'rendered entity' field formatter.

**What I also need, is to somehow display the node id of each 'gallery item'**.

I've tried editing the entity reference field template by creating a custom field.tpl.php template for it, but I can't find a way of accessing the node ID of each corresponding item.

Please help!

# Answer
> 0 votes
Found my solution! I was trying to access the node id from the field.tpl.php template because I wanted to add a CSS ID (using the node id) to the field outer wrapper (a div). Which was in this field template.

What I ended up doing was removing this div wrapper from the field template, and just adding the CSS id to the div wrapper in the node.tpl.php template.

Since I only needed this CSS id in certain a view mode, I created a node template for my specific view mode.

---
Tags: entities, nodes
---


# Question
Title: Add description and title field to each image
I am creating an image Album. For this I have created one content type with "Album Title"(title), "Album Description"(body) and Image field which can take unlimited number of images. Now I want to add a title and description to each image. Please help me to short it out.

# Answer
> 1 votes
Using the Media module, you can add fields to images, such as description or caption. https://drupal.org/project/media

Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.

# Answer
> 4 votes
You can add the title field and alt field, but not sure about the description field.

Go to `admin/structure/types` and then click **manage fields** for the particular content type and then click **edit** under operations for image field you want and then check the title field as shown in the below image.

# Answer
> 1 votes
In addition to what Bala said, you can use the image field caption module

> Adds an extra text area for captions on image fields.
>
> Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

In case you need to style the caption, copy the image\_field\_caption.tpl.php file and place it in your theme's directory

# Answer
> 0 votes
If you didn't find the solution for the problem you are facing by now, this is how I did it. Within your Content type element that you created, say GALLERY, in the manage fields section add another field and call it "image\_title". Within the manage display section of the same, make it visible and in line with the image you are using as your gallery element. Save your work.

Once you create a new Gallery content you will need to add the title of each image youa re adding to it. After that titles of the images should be visible in your colorbox galery. That was the thing that you were missing?

I hope this helps.

Best regards

KuzmaN

---
Tags: entities, media
---


# Question
Title: How to apply a Views filter to show fields if a radio button is not FALSE?
I have a custom field that is a radio button (from CiviCRM), and I made it available as a filter by implementing `hook_views_data()`.

I'd like to apply a filter to show fields if the radio button is set to *true*; in other words, `if not == false`.

I feel like this should be possible without using the Views PHP module, but I have hit a wall.

# Answer
> 1 votes
Often these kind of things come back to deciding how best to bend your requirements to suit the available logic. If I understand correctly, you have a radio button with the value of true, but no other options.

My immediate thought is to change it from a radio to a checkbox and set a default value as false (unchecked).

That way you just need to check for if true or if false and you don't need to concern yourself with *if not false* which does get tricky.

---
Tags: views
---


# Question
Title: Views: How to list nodes that are referencing to nodes, pointing to the current node
I have 3 contenttypes where 2 of them have reference entity fields. Each their own entityfield.

Contenttype C is the parent. Type B points to type C. Type A points to B.

On every Node of type C i want to display a view that lists the nodes of type A pointing to B, that points to C. Is this possible?

Help appreciated.

# Answer
Create a view that filters C nodes. Go to view advanced options and add a relationship with the field in B which references A and choose Referencing entity. Give a name name "children" to this relationship. Then create another relationship based on the field in A that references B. For this relationship use the previous relationship. Name this one grandchildren. Last add fields you need from the A nodes and dont forget to use relationship grandchildren for each one.

Alternatively use node A as base table and use the referring entity relationship type. Now you want to check require relationship to emulate an inner sql join and thus filter out B and C nodes with no references
> 1 votes

# Answer
I can't easily think of a way offhand. I see 2 options. I would try option 2 first (it's a bit easier).

1. Try to use the Relation module and attached fields to relation(s) and use the Relations within Views.
2. Another option I did for something similar is use Computed Field to store meta-data I needed to make Views reporting a little easier. For example in your scenario I might add a Computed Field on `Node Type C` that stores a list of related Node Ids in a comma seperated list like: `"234,543,875"`. You would write `custom PHP code` that could use an `EntityFieldQuery` to find the NIDs of the related content you want and save that list as a string of IDs. Then you could add a field of Views Field on Node Type C that renders a View of related content that passes as an argument the NID list as a `token` from the computed field.

Your example (lists of related, related things) is something I always find tricky to do -- through trial and error I have come to see trying to add meta-data to my relationships (like option 1 or 2 above) make working with the data easier.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Is There a Generic Theme Duplication Module or Drush Command
As I understand there are Drush commands for Adaptive Theme, Omega, Zen and maybe other themes for creating subthemes, but is there a more generic module/way to create/duplicate a theme? It would be nice to give clients a way to mirror their theme within the interface.

# Answer
No but you can copy the theme folder and then replace the name of the theme in all hooks and of course rename yourtheme.info to yourcopy.info. in order not to miss any hook you may use a prog like wingrep and search-replace the yourtheme string
> 1 votes

---
Tags: theming
---


# Question
Title: My php is showing a numeric value for my list field...Why?
In a form I'm trying to take a value a user selected from a radio button and compare it with what's in the database. The value for the radio button is stored in $form\_state\['storage'\]\['level'\].

The list field in my resource type for this set of items is set as follows:

Novice|Novice Experienced|Experienced Professional|Professional

And yet, when I echo out the value in $form\_state\['storage'\]\['level'\] it just gives me what appears to be the delta and not the value of the field. Would someone please enlighten me as to how the value is obtained in php code?

# Answer
Try using `$form_state['values']` instead of `$form_state['storage']`.

Check out the $form\_state keys for a bit more information.
> 1 votes

# Answer
If you try to compare a field value to hide or alter other filds field dependecies module might help you
> 0 votes

---
Tags: forms, database
---


# Question
Title: Organic Groups let users with a particular role Edit/Delete content only in the group(s) they belong to
I am using Organic Groups and have a custom role say "A". I want users with "A" role to be able to "edit/delete" any content only in the groups they belong to.

I have tried setting up with base System and OG permissions and also using Field Permissions, OG Role Override modules, but can't get exactly what i want.

Any direction on this is appreciated.

Thanks!

# Answer
Mark a content type as og group and the rest as og group audience
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: What causes 'You are not authorized to access this page' during create/edit of any menu?
I got a very odd error for "new" admin user on Drupal 7. There are a few admin users in this site but only the "new" one that is unable to create, edit or list links on any menu. The error message is like so:

> You are not authorized to access this page

But this new admin user has the same role as other admins.

Does anyone know what can causing this?

# Answer
> 0 votes
Make sure you flush caches and rebuild permissions (from status page) and run cron. If these fail check if any custom module implements hook\_node\_access A rogue Rule could also be the culprit

---
Tags: 7, routes, users
---


# Question
Title: How to translate entity in the views footer
I am creating a multilingual site. I have views and when it was created, I added to the footer entity (node/22). Next, I created a translation of this content and now changed id (node/45). How to specify the settings views to display different node corresponding to the user's language?

# Answer
With views php module you could add php in footer instead of entity. Sample untested code:

global $language; if ( $language-\> language='en'){ $n=node\_load(22); echo $n-\>title; //or any other field } else ...

A more elegant way is to use a view attachment and put another view in the footer
> 0 votes

---
Tags: views, entities, i18n-l10n
---


# Question
Title: drupal_mail sending wrongly encoded special characters in mail subject
I am using `drupal_mail()` function to send email. I have PHPMailer module with Mime Mail. It works perfectly, embedding images, sending HTML code, but for some reason, the subject line is pledged with bad characters, all the special chars of other languages do not display, a 'X' character display instead, but in the body of the message, it appears perfectly.

```
function mymodule_mail($key, &$message, $params) {

    $message['headers']=array(
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=UTF-8; ',
        'Content-Transfer-Encoding' => '8bit',
        'Return-Path' => $params["from"],
        'Reply-To' => $params["from"],

```

# Answer
There are no bugs. Maybe lazy code from the developers.

Just simply put this line

mb\_encode\_mimeheader($params\["subject"\],"UTF-8", "B", "\n");

for the subject and works in all languages and codifications (chinese, etc.). It is tremendous that phpMailer class in itself handles perfectly, but when you use the phpMailer module, this encapsulating dissapears and you have to hard-code in the mymodule\_mail() function.

Sincerely, Drupal is not suited for big projects.
> 1 votes

---
Tags: emails
---


# Question
Title: Add custom operator for condition() in search_api
I am trying to implement `hook_search_api_multi_query_alter` but it seems 'IN' operator does not work here. I have to check condition on array. Any pointers for start building custom operator.

```
function my_module_search_api_multi_query_alter(SearchApiMultiQueryInterface $query) {
$indexes = $query->getIndexes();
dpm($query->getFields());
if (isset($indexes['solr_content_index_dev'])) {
  $query->condition('solr_content_index_dev:nid', array(2918, 2367), 'IN');

}
}

```

# Answer
> 0 votes
Maybe this trick will help you. You can go upstream and implement hook\_query\_alter instead

```
function yourmodule_query_alter(&$query) {
if ($query->hasTag('search_api_db_search')) {
        $is_search = FALSE;
        $tables=$query->getTables();
        //dpm($tables);
        //only run for the query that really matters to you. Try to find something unique in this
          foreach ($tables as $table) {
            if ($table['table'] == 'search_api_db_your_important_table'  ) {
              $is_search = TRUE;
            }
          }

          if ($is_search) {
            //use query functions normally eg.
            $query->innerJoin('search_api_db_your_table', 'custom_table', "custom_table.item_id = t.item_id");
          }
  }
}

```

---
Tags: search, database
---


# Question
Title: How can I count how many times a node appears in a view?
I would like to keep a count of how many times a node is displayed in a view. For example, in my home page I have a view that displays a list of 20 products. I can count how many times users click on it. I can also count full node views.

But what I would like to do is to count how many times this product is displayed in this view. I use a random system to show users different products each time the home page is reloaded.

I have searched a lot, with different statistics modules, for example radioactivity, node view count, and entity view count but I'm just not able to find something that do what I want.

The answer should work with caching of the view enabled as well.

# Answer
> 3 votes
This can be done by tracking events with the help of Google Analytics Drupal provides module for it https://www.drupal.org/project/google\_analytics

Events can be tracked by event tracking module https://www.drupal.org/project/google\_analytics\_et

Will need to write custom js for making this event tracking, see documentation of google analytics event tracking module

I'm adding a code sample for tracking click on social media share icons:

```
    $('.facebook_popup', context).click(function (e) {
    // First register an event in Google Analytics
    if (typeof ga != "undefined") {
      if (jQuery(e.target).closest('.node-social-media').length) {
        ga('send', 'event', 'social-side-bar', 'fb-share', window.location.pathname);
      }
      else if (jQuery(e.target).closest('#block-menu-menu-share').length) {
        ga('send', 'event', 'social-shares-top', 'fb-share', window.location.pathname);
      }
    }

```

This might help you creating google analytics events

# Answer
> 1 votes
Add the node id as a hidden field to the result set. Add a jQuery script that collates all the node ids into one array (frequency summarised or raw), and then makes an AJAX call to the server, passing the node ids along. The server can then update any tables as necessary.

This will work with caching enabled as well.

In more detail:

**VIEW:**

Give the hidden nid field a class in views.

**jQuery:**

Add your jQuery in preprocess\_page (check for correct view url). Your jQuery will then have a selector looking for that class. It will loop over the selector result, passing each item to an inline function. The function will add the nid as a key to an array (if it does not already exist), and increment the value of that key by 1. This will build up the array of frequencies with the keys of the nodes.

**Server:**

When this is done, you call the drupal AJAX path, passing along the JSONified array. Your server will then convert the JSON param back to an array. It will be faster to just load the field for all the nodes in one db\_select (using IN) directly from the field's table (instead of loading nodes). You then loop over the result and do your additions, and finally write the field back for each node using db\_update/db\_merge.

If you have n different nodes that need updating, then it is n+1 database queries. Also look at optimising the SQL update/merge by perhaps using INSERT ... ON DUPLICATE KEY UPDATE. Perhaps best would be to ask another question on how best to do multiple inserts in one query in Drupal.

# Answer
> 0 votes
If you just want to display the number of items listed in the view, there are two possibilities, depending on your needs. I think that these are both part of Views itself.

There is a `Global: Result summary` item you can add to either a *Header*, *Footer* or *No Results Behavior*. The output is for display only and cannot be used as input to any other fields (it seems). See the image below for the @tokens that can be displayed (@total is what you're looking for):

There is also a `Global: View result counter` field that, when added to your view's list of fields, adds a column that displays a running count of displayed records in that column. Unfortunately, if you use a `Global: Text area` in a *Header* to output that field, you can only output the value from the first row.

If you need to save the value, let me know and I'll think about it some more.

>

# Answer
> 0 votes
Simple but you have to code here is a simple code for you

```
     function yourmodule_name_views_pre_render(&$view){
             if ($view->name == 'your_view_name') {
                if ($view->current_display == 'your_block_name') {
//to get the field in view pre render
     $fieldname = isset($view->result->_field_data['uid']['entity']->field_fieldname) && !empty($row->_field_data['uid']['entity']->field_fieldname['und'][0]['value']) ? $row->_field_data['uid']['entity']->field_fieldname['und'][0]['value'] : "";
                 //use your code create a custom table with count filed and update the count field by +1  so here when ever the view_pre_render is called this so you can select from  there your count
                }
          }

        }

```

in this you can select what node field you want and add that condition here and if the node is there update the count

you can print **`$views->result`** to take any field from that view.

if you want the node type in result add content type in the views field will give you that field it will help you to find node of that type

# Answer
> 0 votes
I was interested to see what kind of non-js solution I coul come up with that still works with caching so...

The main caching we have to deal with is:

* Views results cache.
* Views output cache.
* Drupal page cache.

The main hooks we have available are:

* hook\_views\_pre\_execute() is too early to know about results so it's out.
* hook\_views\_post\_execute() happens after we have results and it runs on both cached and non-cached results so it is a viable choice.
* hook\_views\_pre\_render() doesn't run if we are displaying cached output so it's out.
* hook\_views\_post\_render() happens after we have results and runs on both cached and non-cached output so it is a viable choice.

So you could use hook\_views\_post\_execute() or hook\_views\_post\_render() to handle your main logic. It's really up to you which to use. I would probably use hook\_views\_post\_execute() since I'm dealing more with results than display but if you wanted to run after other hook\_views\_post\_render() implementations or something the post\_render would be better.
For example if you had custom code that modifies the view output so that not all results are actually shown to the user then you might want to put your logic in post render so that you can account for that.

For this example I will use post\_execute.

```
/**
 * Implements hook_views_post_execute().
 */
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYNAME') {
    // Since we're dealing with a single view & display we don't need to work
    // out the entity type but there are ways you could make this more generic.

    // Loop through the results and log the views.
    if ($view->result) {
      foreach ($view->result as $row) {
        // The view I'm using is a node view using teaser as display.
        // You may need to adjust how entity ID is obtained in other cases.
        MYMODULE_log_view($view, 'node', $row->nid);
      }
    }
  }
}

```

Then have something like this to write to the table (you can work out the schema I was playing with from this):

```
/**
 * Log an user's viewing of an entity in a view's results.
 */
function MYMODULE_log_view($view, $entity_type, $entity_id) {
  $count = db_query("SELECT *
                       FROM {TABLENAME}
                      WHERE view_name = :view_name
                        AND view_display = :view_display
                        AND entity_type = :entity_type
                        AND entity_id = :entity_id",
    array(
      ':view_name' => $view->name,
      ':view_display' => $view->current_display,
      ':entity_type' => $entity_type,
      ':entity_id' => $entity_id,
    ))->fetchObject();

  // If we didn't get a count create a new one, otherwise increament.
  $primary_keys = array();
  if (!$count) {
    $count = new stdClass();
    $count->view_name = $view->name;
    $count->view_display = $view->current_display;
    $count->entity_type = $entity_type;
    $count->entity_id = $entity_id;
    $count->view_count = 1;
  }
  else {
    $count->view_count++;
    $primary_keys[] = 'id';
  }

  // Write the data.
  drupal_write_record('TABLENAME', $count, $primary_keys);

  // @todo: Save to a cache table based on path so we can load it again when
  // drupal serves a cached page.

  return $count;
}

```

That successfully logs how many times each node is displayed.
That works with views result & output caching on.

Then you have to deal with the views page cache.
As you can see I have left a todo in the above code for that to store a record of the nodes displayed on this page.
Along with that you could need some code to read our cache and log the views for cached pages. Something like this:

```
/**
 * Implements hook_boot().
 */
function MYMODULE_boot() {
  // Check to see if we are loading from the cache.
  if (drupal_page_get_cache(TRUE)) {
    // @todo: Get our cache entries for this page and log the views.
  }
}

```

I'm pretty confident that would all work out to handle the drupal page cache.

After that you have external caches like varnish.
Then you're in trouble and you'll need to go to an ajax request to log the views, which could basically pass in the page url and save like the hook\_boot() example above.

I have no time now but I will flesh this out some more a little later and finish the @todos.
I may also make a sandbox module and see how generic I can get it, for supporting other entities, integrating with views UI, etc.

Anyway, it works :)

Then you could add views support for the custom table and build reports etc.
Also notable is that this only stores a total count per entity. If you wanted to go really hard core you could adapt it to save each view separately with a timestamp and then you could do reporting based on date ranges too.

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


# Question
Title: How to define the time-range for the Time Field in Webform 4.x
is it possible to change the selectable time range in a time-field in Webform? I don't want the users to have the choice to select between 00:00 and 23:59. I only want them to choose between 15:00 and 23:00.

Webform validation doesn't work on time fields. Is there any other way?

Thanks in advance.

# Answer
> 0 votes
You can check with Clientside Validation Module. Otherwise you can alter the webform to add validation.

You may refer https://stackoverflow.com/questions/6785882/how-do-i-apply-webform-validation-in-drupal-7 link for a reference.

---
Tags: webforms
---


# Question
Title: Rewrite empty Fields on Feeds periodic Import
I have set up a periodic feed importer in drupal which imports nodes and updates existing nodes.

Lets assume the imported xml consits of two fields: the title and a long text field.

I import the nodes in the morning with the following content:

```
title   long text field
1       long text 1
2       long text 2
3       long text 3

```

So three nodes were correctly created with the two fields. But if I import later and the content of the xml has changed to the following:

```
title   long text field
1       long text 1
2
3       long text 3

```

As you can see the long text field of the second node is empty, but feeds doesn't update the field. The value after reimport is still 'long text 2'.

I haven't found an option or a module to achieve this. I have tried to manipulate the input data via

```
hook_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  // replace empty results with ' ' (one space), so they gets replaced
  for ($i=0; $i < sizeof($result->items); $i++) {
    for ($o=0; $o < sizeof($result->items[$i]); $o++) {
      if (empty($result->items[$i]['xpathparser:'.$o])) {
        $result->items[$i]['xpathparser:'.$o] = ' ';
      }
    }
  }
}

```

But feeds only jumps into the function if it detects changes in the xml, but i think empty fields don't get considered.

# Answer
> 2 votes
Yes, this is a known problem of feeds. However, there is a patch for it and will be included in the next release as I know. You can already apply the patch now yourself:https: www.drupal.org/node/1107522 It is #161 in the link above.

I am using it for a while and tested it too, it works for your scenario above. There is one problem with email and URL fields: Feeds still creates the field when the import is empty and this results in empty fields shown.

---
Tags: 7, importing-exporting, feeds
---


title: How to show a list of article titles

text:
# Question
Title: How to show a list of article titles
I am a bit confused. I understand what teaser does(shows the title and a preview and maybe some other things of an article). How do I not show a preview of the article.

I just want title and possibly author. My aim is to have a frontpage/homepage that only shows a list of titles.

I don't like the look of the article preview.

Still sorta new to Drupal hoping for an in depth explanation as well.

# Answer
If literally all you're trying to do is not show the body in a teaser, Views is totally overkill if you're not already using it elsewhere.

Go to `admin/structure/types/manage/CONTENT_TYPE/display/teaser` and hide the body.
> 0 votes

# Answer
Your best option is the Views Module:

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently.
>
> You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
>
> You use /tracker, but you want to restrict it to posts of a certain type.
>
> You like the idea of the 'article' module, but it doesn't display articles the way you like.
>
> You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'.
>
> You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that,
>
> but those are some of the obvious uses of Views.

* create a new view as a Page with Fields
* add whichever fields you want displayed
* assign that page address as the front page under /admin/config/system/site-information
> 2 votes

---
Tags: views, nodes
---


# Question
Title: Where do I put and How do I use form_state['redirect']
The documentation says to put `$form_state['redirect']` in your code when you want to send the form to a new page. However, when I use it in the third page submit handler of my multi-page form it doesn't work. Here's my ENTIRE code below...see near the bottom for the third page submit handler and the redirect function it calls.

Note: I NEED $form\_state\['rebuild'\] set to TRUE and $form\_state\['storage'\]\['step'\] to call the function (otherwise it breaks my script). For example, if I put $form\_state\['rebuild'\] to FALSE and remove the $form\_state\['storage'\]\['step'\] line in the else statement and replace it with the $form\_state\['redirect'\] line (currently in the non-working function below the submit handler, then it redirects just fine...HOWEVER, it then breaks the ability of the form to go BACK...and in such case if you go BACK from the third page it takes you all the way back to the first page again and the form no longer remembers your answers. But I also need to redirect users and send them to a processing page to display database results...what do I do?

```
<?php

function pathfindertool_menu() {
  $items['pathfinder'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Pathfinder Tool',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('pathfindertool_form'),
    'access callback' => TRUE,
  );
  $items['pathfinder/recommendations'] = array
  (
    'title' => 'Recommendations',
    'page callback' => 'pathfindertool_recommendations_page',
    'access callback' => TRUE,
  );
  return $items;
}

// create wrapper form and submit handler
function pathfindertool_form($form, &$form_state) {
      // Check to see if anything has been stored.
      if ($form_state['rebuild']) {
        $form_state['input'] = array();
      }
      if (empty($form_state['storage'])) {
        // No step has been set so start with the first.
        $form_state['storage'] = array(
          'step' => 'pathfindertool_first_form',
        );
      }

      // Return the current form
      $function = $form_state['storage']['step'];
      $form = $function($form, $form_state);
      return $form;
    }

    /**
     * Submit handler for the multiform wrapper.
     *
     * @see pathfindertool_primary_form().
     */

    function pathfindertool_form_submit($form, &$form_state) {
      $values = $form_state['values'];
      if (isset($values['back']) && $values['op'] == $values['back']) {
        // Moving back in form.
        $step = $form_state['storage']['step'];
        // Call current step submit handler if it exists to unset step form data.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
        // Remove the last saved step so we use it next.
        $last_step = array_pop($form_state['storage']['steps']);
        $form_state['storage']['step'] = $last_step;
      }
      else {
        // Record step.
        $step = $form_state['storage']['step'];
        $form_state['storage']['steps'][] = $step;
        // Call step submit handler if it exists.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
      }
      return;
    }

    /**
     * First of three.
     */

    function pathfindertool_first_form($form, $form_state) {
      if(!empty($form_state['storage']))
        $values = $form_state['storage'];
      $form['level'] = array(
        '#prefix' => '<div class="question-intro-text">[WE NEED AN INTRO PAGE] To get your recommendations we need to know three things: your experience level, your role, and the topics that interest you. Begin by letting us know how you consider your experience level in your field.</div>',
        '#required' => TRUE,
         '#type' => 'radios',
         '#title' => t('What is your experience level? (pick one)'),
        '#default_value' => isset($values['level']) ? $values['level'] : NULL,
        '#options' => array(
        t('Novice'),
        t('Intermediate'),
        t('Advanced'))
    );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
      );
      return $form;
    }

function pathfindertool_first_form_validate($form, &$form_state) {
  if (!($form_state['values']['level'])){
    form_set_error('level', t('You must select an experience level.'));
  }
}

    /**
     * Submit handler for the first form.
     *
     * @see pathfindertool_first_form()
     */
     function pathfindertool_first_form_submit($form, &$form_state) {
      $values = $form_state['values'];

      // Save values to the form storage, add the next step function callback
      $form_state['rebuild'] = TRUE;  // This is very important to have!
      $form_state['storage']['level'] = $values['level'];
      $form_state['storage']['step'] = 'pathfindertool_second_form';
    }

function pathfindertool_second_form($form, &$form_state) {
   if(!empty($form_state['storage']))
    $values = $form_state['storage'];
  $form['role'] = array(
    '#required' => TRUE,
    '#type' => 'radios',
    '#prefix' => '<div class="question-intro-text">Now, select your role in your organization.</div>',
    '#title' => t('What is your role? (pick one)'),
    '#default_value' => isset($values['role']) ? $values['role'] : NULL,
    '#options' => array(
        t('Grant writer'),
        t('Nonprofit Administrator'),
        t('Nonprofit Founder'),
        t('Consultant'))
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('pathfindertool_second_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
  );
  return $form;
}

/**
 * Submit handler for the second step.
 *
 * @see pathfindertool_second_form_start()
 */
function pathfindertool_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['role'])) {
      $form_state['storage']['role'] = $input['role'];
    }
    $form_state['storage']['step'] = 'pathfindertool_first_form';
  }
  else {
    $form_state['storage']['role'] = $values['role'];
    $form_state['storage']['step'] = 'pathfindertool_third_form';
  }
}

/**
 * Form that is called third
 */
function pathfindertool_third_form(&$form, &$form_state) {
   if(!empty($form_state['storage']))
    $values = $form_state['storage'];
  $form['topic'] = array(
    '#type' => 'radios',
    '#required' => TRUE,
    '#prefix' => '<div class="question-intro-text">Finally, select the topics that interest you.</div>',
    '#title' => t('Which topics do you want to learn about in the grant lifecycle? (pick one)'),
    '#default_value' => isset($values['topic']) ? $values['topic'] : NULL,
    '#options' => array(
        t('Grant writing'),
        t('Grants Research'),
        t('Grants Management'),
        t('Strategic Planning'))
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('pathfindertool_third_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  $form['#submit'][] = 'pathfindertool_third_form_submit';

  return $form;
}

// where I start having problems...
function pathfindertool_third_form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $form_state['rebuild'] = TRUE; // need this set to TRUE, see explanation above

  if (isset($values['back']) && $values['op'] == $values['back']) {
  $input = $form_state['input'];
    // The user pushed the back button.
    if (isset($input['topic'])) {
        $form_state['storage']['topic'] = $input['topic'];
    }
    $form_state['storage']['step'] = 'pathfindertool_second_form';
  }
  else {
    $form_state['storage']['topic'] = $values['topic'];
    $_SESSION['level'] = $form_state['storage']['topic'];
    $_SESSION['role'] = $form_state['storage']['role'];
    $_SESSION['topic'] = $form_state['storage']['topic'];
    $form_state['storage']['step'] = 'redirect page';
  }
}

// not working although I can echo things out here with no problem
function redirect_page() {
    $form_state['rebuild'] = FALSE;
    echo 'something'; // gets called
    $form_state['redirect'] = 'pathfinder/recommendations'; // does NOTHING
}
*/

// function to return results from DB based on what user entered, not finished - works when called
function pathfindertool_recommendations_page() {
    $output = '';
    $result = db_query("SELECT nid, type, title FROM {node} WHERE type = :type", array(':type' => 'resource',));
    if ($result) {
        while ($row = $result->fetchAssoc()) {
            $title = $row['title'];
            $output .= '<div>' . $title . '</div>';
        }
    }
    return $output;
}

```

# Answer
> 1 votes
You can't rebuild AND redirect a form. The redirect property determines where the form should go once it's finished. Setting rebuild means it's not finished. This is why we use `&$form_state['storage']` to determine what is to be displayed, save data that needs to persist across steps, etc (note: you should not be using `$_SESSION`).

> ok, I got what you suggested to work on its own. But as for using it with my 3 page form...it still continues to work fine (I rebuilt it line by line) until I get to the FINAL step in the third page submit handler ( can have 1 of the following lines but not both...and I need both): $form\_state\['storage'\]\['step'\] = 'something'; $form\_state\['redirect'\] = 'pathfinder/recommendations'; –

If it's the third and final step, why would you need to rebuild it? In this case, would it not be complete? If you set rebuild to FALSE, it should go to the page you have in redirect.

# Answer
> 1 votes
With what you have define above, the function `pathfinder_recommendations_page` would not take in `$form` and `$form_state`. You should change it up so that this function is just a regular page callback. You can return a string and then test the path to make sure that the page callback is working.

Then to get your form\_state redirect to work, create a submit handler for the form and inside of the submit handler change use the form\_state redirect.

\[EDIT\] I guess it's a bit unclear what exactly you are wanting to achieve here. My assumption was that you wanted the redirect to occur when you submit the form. As I mentioned above, right now your page callback for pathfinder\_recommendations\_page is not setup to take in the $form and $form\_state arguments.

```
function pathfindertool_menu() {
  //
  $items['pathfinder'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Pathfinder Tool',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('pathfinder_primary_form'),
    'access callback' => TRUE,
  );
  // define that path
  $items['pathfinder/recommendations'] = array(
    'title' => 'Recommendations',
    'page callback' => 'pathfinder_recommendations_page',
    'access callback' => TRUE,
  );
  return $items;
}
function pathfinder_recommendations_page() {
  // this is the destination page
  return 'anything you like';
}

function pathfinder_primary_form($form, &$form_state) {
  //define form here
}

function pathfinder_primary_form_submit($form, &$form_state) {
  //redirect here
  $form_state['redirect'] = 'pathfinder/recommendations';
}

```

# Answer
> 1 votes
Try putting it in hook\_form\_alter.

Per drupal.org's explanation of that item:

> Redirects the user to a URL after a form has been processed.

So you need to slide it in before the form is processed, which is what hook\_form\_alter is for.

You should be able to do something like:

```
function mymod_form_alter(&$form, &$form_state, $form_id)
  {
    if($form_id == 'form-to-change'){
      $form_state['redirect'] = "path";
  }
}

```

# Answer
> 1 votes
Instead of

`$form_state['storage']['step'] = 'redirect_page';` // This is for storage only and redirect\_page works as string here.

write this :

```
$form_state['redirect'] = 'pathfinder/recommendations';

```

**Note:** $form\_state is reference here.

---
Tags: forms
---