# Question
Title: Allow Anonymous user to Subscribe while site under maintenance mode
The title says it all. I have customized the Maintenance mode page, to Coming soon!! how i want to enable the visitors of the website to Subscribe So they'll will be notified when the website is officially lunched. how can i Achieve this, am developing the website in Drupal in 7.

# Answer
> 2 votes
Maintenance mode is not really for this.

I would recommend using a custom theme for "Coming soon". That way you can have them come to a home page with information and sign up/register for the site.

When you're ready to put the real site up, change themes.

# Answer
> 0 votes
Don't put your sie in permanent "maintenance mode". Instead use the Rules module to achieve the same goal.

All that's needed is some tuning of the "Custom rule" I suggested also as an answer to the question about "How can I put a Drupal Commerce site in 'Shop Closed' mode, similar to Drupal's maintenance mode?".

In your case you'd probably want to block mostly every URL being visited, except the "User registration" page.

# Answer
> -2 votes
I have prepared a step by step guide for allowing the anonymous user to subscribe for the node update.

Visit this link for a complete guide: http://c.pachabhaiya.com/blog/2013/08/drupal-how-to-make-anonymous-user-subscription-on-a-particular-node-update/

* Possibility for the anonymous users to subscribe to particular node.
* Send email notifications automatically to the subscribed users when
that particular node is updated.

---
Tags: maintenance-mode, notifications
---


title: Sign up using google account

text:
# Question
Title: Sign up using google account
I am trying to add a 'Login using Google' type login page. But I cant find any module that does it out of the box. Could anyone help me proceeding in the right direction as to creating a module that would allow user to sign up with their google account?

# Answer
I have found a module called openid selector that does exactly what I am looking for.
> 2 votes

# Answer
After my long trial and error with many modules, I can recommend Hybridauth -- the module is maintained and working admirably well.
> 2 votes

# Answer
you can use the Janrain module and service. The service is free for small site
> 1 votes

# Answer
You could use the Google Friend Connect module.

> Google Friend Connect (GFC) provides simple user authentication using any OpenID account, including Google, Yahoo and AIM. Instead of filling in yet another profile form, your users can connect to their existing identities, showing current profile pictures. By making login easier and connected to existing identity, you'll see increased engagement and comment activity.
> 1 votes

# Answer
The OAuth Connector module for Drupal 7 claims to be supporting signing up and logging in through OAuth 2 API:s in general and Google+ specifically.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to know node/entity ID from a submit handler?
How to know node/entity ID from a submit handler of a form created with hook\_form()?

I need to make db\_update() query on a single row from submit handler called by admin/structure/video/manage/% form created with Forms API.

# Answer
I would recommend *not* to use extra submit handlers on node forms. Forms are not the only way that you can create a node. Modules like Feeds, Migrate, etc can create nodes programatically.

If it's a node, and you don't want to alter data that the node itself, implement `hook_node_insert` and you have access to the whole `$node` object! `$node->nid` would be the node ID if you name your function's first argument as `$node`.

If you prefer an extra submit handlers, you can access node or entity that is being created/updated in $form (I can't remember the exact key name though).

Install Devel module. Then, you can see what's in the `$form` array in your submit handler like this:

```
function mymodule_extra_submit_handler($form, &$form_state) {
  dpm($form); // pretty-prints the entire form.
}

```

Usually `$form['#node']` is the node object, so `nid` is `$form['#node']->nid`
> 2 votes

# Answer
~~$form\['build\_info'\]\['args'\]\[0\]\['id'\]~~

$form\_state\['build\_info'\]\['args'\]\[0\]-\>id;
> 2 votes

# Answer
might be you are using $form\['#submit'\]\[\] = 'custom\_submit\_function';

use this code:

```
$form['actions']['submit']['#submit'][] = 'custom_form_submit';

```

Definitely you will get `nid` on `print_r($form_state);`

e.g

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

if ($form_id == 'portfolio_node_form') {
   // $value = $form['nid']['#value'];
   $form['actions']['submit']['#submit'][] = 'ita_custom_form_submit';
}

return $form;
}

function ita_custom_form_submit($form, $form_state) {
      $val = array();
    $val = $form_state['values'];
    print"<pre>";
    print_r($val);
    //exit(); // do uncomment to see form_state object
//coding
}

```
> 0 votes

# Answer
I used

```
$form['#submit'][] = 'custom_submit_handler';

```

to add my submit handler to run after the default submit handler.

Then in my custom handler function, I found the entity ID in the $form\_state variable:

```
$form_state['values']['entity']->id

```

I hope this helps someone!
> 0 votes

---
Tags: forms, entities
---


# Question
Title: Get rid of classes from views root container
Looking for a way to clear all unnecessary in terms of semantic classes from top-level div for a view:

```
<div class="view view-comments-count view-id-comments_count view-display-id-entity_view_2 view-dom-id-f2370f55bf76844fef6e17764e8a5058">
      <div class="view-content">
        ROWS
    </div>
</div>

```

want to become:

```
<div class="view">
      <div class="view-content">
        ROWS
    </div>
</div>

```

I have tried Semantic Views and Fences but they all deal only with view content (field or rows) but not with the top-level div config.

I know that some bits can be changed with `views-view.tpl.php` however you can only clear all classes from it but I want to use css class from Views configuration.

# Answer
> 2 votes
You can use template\_preprocess\_views\_view function and remove needles classes from `$vars['classes_array']` array.

```
function mymodule_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view') {
    $vars['classes_array'] = array('view', $vars['css_class']);
  }
}

```

---
Tags: views, 7
---


title: How to add new item in menu_local?

text:
# Question
Title: How to add new item in menu_local?
I'm using Drupal commons and I want to add new item next to View link, so I used hook\_menu to create this.

```
function manage_child_menu() {
  $items['node/%node/demo'] = array (
    'title' => 'Demo',
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'manage_child_auction_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

```

Well, it didn't work at all. Please help

# Answer
> 1 votes
In my case using hook\_menu will never work. Then i have to use hook\_menu\_local\_tasks\_alter to make it work. Here is how.

```
function manage_child_menu_local_tasks_alter(&$data, $router_item, $root_path) {
   if ((arg(0) == 'node' || arg(0) == 'groups') && arg(2) == '') {
   $nid = arg(1);
   $node = node_load($nid);
   if ($node->type == 'project_auction') {
     $link = menu_get_item("node/$nid/demo");
     $link['title'] = 'Auction List';
     $link['weight'] = 10;

     $data['tabs'][0]['output'][] = array(
       '#theme' => 'menu_local_task',
       '#link' => $link,
     );

     $data['tabs'][0]['count'] = $data['tabs']['0']['count'] + 1;
  }
 }
}

```

# Answer
> 0 votes
If you want to add it in main menu. Then you need to add `'menu' => 'main-menu'` . Or else when you are adding menu, Clear all the cache first and then try to render your desire result.

---
Tags: routes, 7
---


# Question
Title: I'm using Mobile Navigation but does not load the dropdown menu after installing jQuery Update
After installing the module jQuery Update not shown the Menú Mobile. Why?

# Answer
> 0 votes
You have to set the correct ***Default jQuery Version*** in configuration. May be that causes this problem..

---
Tags: navigation
---


# Question
Title: How to alter the value used to sort a view?
I have properties that have a rental price. The rental price is a field collection with a value ***(price)*** and ***period*** (per month, per week). You can sort the properties by price (low to high, or high to low) using an ***exposed filter***. The problem is that if someone enters 2000 per month it is being registered as more expensive than a property that is 600 per week (2400 per month). So I want to divide the monthly values by 4 in order to have equal calculation.

**What hook do I need to use in order to process the value field just before it is used to sort the properties?**

# Answer
you can change query of view by this **hook\_views\_query\_alter(&$view, &$query)**

This hook is a core hook of views api but you can override it in you custom moduel like **MYMODULENAME\_views\_query\_alter**

In this hook you can get parameters by exposed filter's and change views query based on these parameters.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to speed up performance of taxonomy hierarchical select drupal
I have a taxonomy that have **35(States)** -\> **650(Districts)** -\> **6500(Blocks)** -\> **650000(Villages)** taxonomy terms using hierarchical select module

when i filter it on my content type form then it's performance is very slow. so, i want to know that how to increase it's performance when filtering.

i have installed taxonomy manager module but we can't use it as CCK Field of Taxonomy Term.

# Answer
> 1 votes
Using High-performance JavaScript callback handler will speed up it a bit while i recommend using Simple hierarchical select rather than Hierarchical Select , cause it is much faster in queries (off course less user friendly) .

this is the description High-performance JavaScript callback handler :

> JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc. This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.

---
Tags: performance
---


title: Changing node/%/edit title

text:
# Question
Title: Changing node/%/edit title
I have created custom content type for upload the details. I have used hook\_form\_alter to set the node title as "Upload". When I edit the node in node/%/edit the title remains "Upload". I want the title to be "Edit" .How to do this?

# Answer
Please try this:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'form-id') {
   if(arg(0) == 'node' && arg(2) == 'edit'){
     drupal_set_title('Upload Edit');
    }
    else{
     drupal_set_title('Upload'); }

  }
}

```
> 4 votes

# Answer
After searching finally found the answer. Place this code in your template.php

```
if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'YOUR FORM ID') {
  if (arg(0) == 'node' && arg(1) == 'edit') {
    drupal_set_title(t('Edit Content');
  }
  else {
    drupal_set_title("Upload Content");
  }}

```
> 0 votes

# Answer
Try this..

```
$node = node_load(your nid);
$node->title = 'new title';
node_save($node);

```
> -2 votes

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


# Question
Title: Feeds: use custom field as unique field for mapping
I am using D7, Feeds, XPath Parser. For mapping, I need to use a custom field as the unique field. I am retreiving data from booking.com and the unique value their is the hotel id, so i need to save this hotel id from the user as well as retrieve data from booking.com bsed on this unique field and map to my contents based on this unique field.

In the documentation of feeds i found this - Use field other than nid as unique node field in feeds for 7.x-2.x

It says you need to apply a patch from this comment - http://drupal.org/node/661606#comment-5921904

This patch applies to a file called field.inc in the mappers folder of feeds. However this file is not even present there. The patch also applies to another file, however running the patch gives errors.

* Is field.inc actually present in feeds/mappers?
* Am I making some mistake in applying the patch?
* Is there any other way of achieving - custom field as unique field for mapping?

Any help on this would be greatly appreciated. Thank you.

# Answer
Answering my own question -

Using patch from - http://drupal.org/node/661606#comment-6481214 on the feeds module and a patch from - http://drupal.org/node/1705386#comment-6481224.

Hence using Feeds with Field Validation. First a validation for unique must be added to the required field. In the mapping for just like title can be set as unique even this field will have the setting to be set as unique.
> 2 votes

# Answer
This tutorial works for me:

How to configure unique fields in Drupal feeds importer ?

See also the official documentation, which states that you can either use the Field Validation module, or write a custom solution implementing `hook_feeds_processor_targets_alter()`.
> 10 votes

# Answer
If you will only be using one Feeds importer (i.e. only importing from a single XML source), you can do this without applying any patches. In the importer mappings, just map the hotel ID field to GUID and set it as unique. If you need to use hotel ID in your content type, map it to another field as well.

From your description, it *sounds* like your needs might be more complex (i.e. importing from multiple sources into the same content type)? If so, you can use Field Validation module to set your field as unique. Note that last time I used it, this also required a patch \- but it may be committed now. This Field Validation issue provides some more info.

I think the method you referred to (using Unique Field module) is a little outdated now.
> 4 votes

---
Tags: 7, feeds
---


title: Remove Classes from Menu

text:
# Question
Title: Remove Classes from Menu
I know that this isn't a really big priority but with the default Drupal menu you get css classes like `.first` or `.last` or `.active`.

`.first` and `.last` are being provided by CSS3 and `.active` only needs to be on the `<a>` link not on the `<li>` due to the way my CSS works.

All these classes are unneeded and I'd like to remove them, so I can create a clean and efficient template.

Does anyone have any ideas how to do this (and if possible provide a small code sample)?

Thanks :)

# Answer
> 0 votes
Basically you're going to have to alter you're theme to provide an alternate function to provide an entry point into menu\_tree\_output. This means finding the block or function that renders the menu, overriding that function, and each that it calls until you get to menu\_tree\_output.

After that copy a changed version of menu\_tree\_output into your theme's template.php and modify it as necessary. You may even have to override theme\_menu\_link to prevent options from showing up on both the li and a elements.

For the most part though, I think you answered your own question at:

> only needs to be on the 'a' link not on the 'li' due to the way my CSS works.

Obviously, a CMS cannot readily accomodate the needs of all possible combinations of CSS. I often have to add classes due to the complex needs of the navigation for crazy designs. I would count myself lucky if I didn't have to add classes, and just had extra classes available in the markup.

# Answer
> 3 votes
if you wanna kill off all the classes that comes out with the menu list look after the theme\_menu\_link() thats where the

```
<li class="first leaf menu-mlid-305">

```

comes from

if you really wanna kill all the classes you can do something like this :

```
function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

dump that dunction into you template.php and you the classes that the menus comes with will go kaboom - you will also remove the active classes etc, but hey the li tags are goddamn clean

# Answer
> 0 votes
It really depends on how you render the menu.

If the menu is rendered via menu\_tree(), you can strip all classes from menu tree like that:

**Solution 1** template\_preprocess\_menu\_link():

```
function MYMODULE_OR_THEME_preprocess_menu_link(array &$variables) {
  // Unset all the classes.
  unset($variables['element']['#attributes']['class']);
}

```

**Solution 2** theme\_menu\_tree():

```
function MYTHEME_menu_tree($variables) {
  // Strip all classes from menu tree.
  $variables['tree'] = preg_replace('/class="[^"]*"/i', '', $variables['tree']);
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

```

You can do the same with `MYTHEME_preprocess_menu_tree()`.

**Solution 3** theme\_menu\_link() as @mortendk suggested.

---
Tags: routes, theming
---


# Question
Title: Bootstrap.inc error appearing on website
When I go to my database website at kctd.org/community, I get this error:

> Fatal error: require\_once() \[function.require\]: Failed opening required '/home/kctd/public\_html/community/sites/all/modules/views/modules/translation/views\_handler\_filter\_node\_language.inc' (include\_path='.:/usr/lib/php:/usr/local/lib/php') in /home/kctd/public\_html/community/includes/bootstrap.inc on line 3069

I have no idea what that means. The last action I did was extending the result of my view filter to include user's email. When I clicked save, this popped up. I cannot log in to even switch to maintenance mode.

What can I do?

# Answer
> 1 votes
The problem seems to be that `views_handler_filter_node_language.inc` was moved from `views/modules/translation` to `views/modules/locale`. I guess you have updated the views module but not rebuilt you registry. You should be able to solve this by flushing the cache. Here's a issue, addressing the same problem.

Notice that whenever you update a module you should also call the update script located at `example.com/update.php`.

To flush the cache using drush use the following syntax: `drush cc all`.

You could also try to clear the `cache_bootstrap` table using:

```
mysql -uusername -ppassword -hhostname database -e"DELETE FROM cache_bootstrap WHERE cid='system_list';"`

```

or

```
drush sql-query "DELETE FROM cache_bootstrap WHERE cid='system_list';"

```

**Backup your database before trying the above**

If you still have trouble, you could also try to disable the views module using something like this:

```
mysql -uusername -ppassword -hhostname database -e"UPDATE system SET status='0' WHERE name='views';"

```

or

```
drush dis views

```

You might need to clear the cache as in the previous step for this to take effect.

Here you can find more information about disabling a module manually: Disabling modules manually in the database

# Answer
> 1 votes
For me it was simply a case of having moved module folders in sites/all/modules to sites/all/modules/CONTRIBUTED - I was trying to clean up my folder structure a bit.

The issue resolved as soon as I moved the module folders back to their original placement.

# Answer
> 0 votes
I would do two things.

Restart Apache and make sure your APC has enough memory. Errors about require and/or include can be indicative of APC not having enough memory.

If that doesnt fix things, download the registry rebuild module for drush, and run it. Take a database backup first as a precaution.

# Answer
> 0 votes
1. How I got Here; I tried to update some modules using the 'available updates' option in the modules configuration menu
2. The solution in my own case; First I had to download the following files; views, views\_block\_area, views\_slideshow again which can be found here http://drupalmodules.com/ or https://drupal.org/
3. Next, I unzipped both files and connected to my host-machine using ftp, then I navigated to ../sites/all/modules and overwrite the directories
4. further I also made backups of the aforementioned directories in case I may have to roll back configuration

---
Tags: views
---


# Question
Title: Remove 'Your Name' field from comments display
I want to hide/remove the "Your Name" field from the comments on a Drupal 7 site.

I am using the bamboo theme and Drupal 7.

I have seen a few threads for the but most are about removing the subject line, or are about Drupal 6 etc. I have tried a few different methods I have seen, but have not succeeded in getting this to work on Drupal 7 as of yet. Any advice?

# Answer
> 1 votes
The name input is not a required field, so the easiest thing would be to hide it using CSS.

Try the following:

```
.comment-wrapper .form-item-name { display: none; }

```

You could also use hook\_form\_alter(). Check for the $form\_id for the comment form, then set: `$form['FIELD NAME GOES HERE']['#access'] = FALSE;`

# Answer
> 1 votes
Found a solution to this that worked for me.

If you're theme has a comment.tpl.php file, if you search this file somehwere there will be a `<?php print $author; ?>` piece of script. Removing this worked for me. It's a bit of a hack, but stops the username still appearing in the developer tools, which means you can have authenticated users post anonymously.

# Answer
> 1 votes
Had the same problem and solved it based on jdu's method. Insert following code into your themes template.php file inside your hook\_form\_alter() function:

```
if ($form_id == "comment_node_article_form") {
  $form['author']['#access'] = FALSE;
}

```

This needs to be done for all node types with comments enabled.

IMO this method is better than using css, since css only hides it from display, not from the rendered html.

---
Tags: 7, entities, theming, comments
---


# Question
Title: Upload Data From Excel Sheet to taxonomy
I have 4 Excel sheets like:

**First (35) Records**: State Code | State Name

**Second (650) Records**: State Code | District Code | District Name

**Third (6500) Records**: State Code | District Code | Block Code | Block Name

**Fourth (650000) Records**: State Code | District Code | Block Code | Village Code | Village Name

I want to upload from Excel sheet based on *State Code* or sequence hierarchical records to taxonomy.

Adding them one by one is very difficult task.

I have a module for Excel import, but matching of record of parent is necessary like : **State -\> District -\> Block -\> Village in taxonomy**

So how to upload these records to taxonomy (with no headache)?

# Answer
Try Taxonomy CSV import/export

> This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.
> 0 votes

---
Tags: taxonomy-terms, importing-exporting
---


# Question
Title: Drupal Multiupload Filefield Widget conflict with mutiselect ajax dropdown
I have created a multiupload field in my node using **Multiupload Filefield Widget**. I am using the code below to alter the default node form.

There is an ajax based dependent dropdown field in the form i.e city dependent on country.When I select a single country the form work fine. But when I select multiple values form the country list I get the follwing error:

*An illegal choice has been detected. Please contact the site administrator.*

I get this particular error when there is the multiupload form element present. When I remove the element from $form its works fine with multiple selected values.

Please help me out to solve this problem.Thanks in advance!

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'mynode_node_form':
            $country_list = load_countries();
            $selected_country = (isset($form_state['values']['country'])) ? $form_state['values']['country'] : key($country_list);

            $form['countries'] = array(
                '#type' => 'select',
                '#title' => t('Select Your Country'),
                '#options' => $country_list,
                '#default_value' => $selected_country ,
                '#ajax' => array(
                    'callback' => 'city_dropdown_callback',
                    'wrapper' => 'city_wrapper',
                ),
                '#multiple' => TRUE,
                '#required' => TRUE,
            );

            $cities_list = load_cities($selected_country);
            $selected_cities = (isset($form_state['values']['cities'])) ? $form_state['values']['cities'] : key($cities_list);
            $form['cities'] = array(
                '#type' => 'select',
                '#title' => t('Select Your City'),
                '#prefix' => '<div id="city_wrapper">',
                '#suffix' => '</div>',
                '#options' => $cities_list,
                '#default_value' => $selected_cities,
                '#multiple' => TRUE,
                '#required' => TRUE,
            );

    }
}
function city_dropdown_callback($form,$form_state){
    return $form['cities'];
}

```

# Answer
Solved by issues by updating jquery.form.js to version 3.51.

Found the solution at : https://www.drupal.org/node/153774#comment-9202403
> -1 votes

---
Tags: 7, ajax
---


# Question
Title: Default theme css wrongly included in another theme
I have 2 themes enabled on a Drupal 7 installation. The have one css file each included in their .info files:

sites/all/themes/themeA/css/screen.css sites/all/themes/themeB/css/screen.css

The default themeA is the default theme. Using hook\_custom\_theme, I'm setting the theme to themeB for a certain section of the website based on path. The theme changes successfully and the page renders using themeB when it should.

There is something strange that happens though and the css file from themeA loads as well, breaking parts of the page.

I am checking in hook\_css\_alter in themeB and there is no mention of themeA/css/screen.css. I am checking in hook\_css\_alter in themeA and it is never executed.

I have solved this by removing the file from themeA.info and adding it in themeA\_css\_alter(). I would prefer though and it would be interesting as well to find out why this happens, so that I can put back the the file inclusion where it should normally be.

Any insights?

# Answer
The issue was happening on form pages that had CKEditor-enabled fields. The CKEditor module has a configuration option to specify additional CSS to load. By default, it loads the default theme's CSS. After changing this option, everything works as expected.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Views content pane not showing in panel for some users
I have a view content pane displaying a node of a certain content type. This content type contains entity reference fields which are rendered as nodes on in the view field settings. On this view, I have a contextual filter of type "Content: NID" with "Provide default value" selected and "Content ID from URL" selected in the drop-down.

I created a panel page over-riding the node template, and a variant with 2 selection rules: 1) Node being viewed is this content type, and 2) "Node: accessible - Logged in user can view Node being viewed."

I am using two users to test - the admin user, and a test user.

* When I view this panel page as an admin, with 'bypass node access' permission, I can see the panel with the content pane, and the node and the referenced nodes that are present in the view.
* In the node access table, the node is listed with the correct realm and gid.
* Debugging output shows that my test user has the correct grants (at least one grant contains realm and gid that matches the node\_access records), and should be able to view the node.
* If I disable the panel, my test user CAN access the node directly, as well as the nodes referenced in the entity reference fields.
* I made a copy of the content pane display (as a view page, with url), and my test user CAN access the view, and all nodes on the view.
* When my test user tries to view the panel page, he sees the OTHER panes on the panel (which I assume tells me that "logged in user can view node being viewed" is TRUE, as the variant IS being displayed).
* One strange thing that I noticed, is that when I try to preview the view by manually adding the NID argument, I get nothing - no query being displayed, and no content being rendered, but this is for the content pane, not the view page display with url.

However, the test user can **NOT** see the views content pane embedded in the panel, while the admin user can. The pane simply does not render, and the "No results behaviour" of the view, which is set to display a message, does not render, either. It is just blank.

Anyone know why the content pane would not render? Is there some permission that I'm missing, or some setting on the views content pane screen? Or some setting on the panel variant configuration, or the pane configuration? I don't see anything that should hide this pane.

# Answer
> 1 votes
The issue that I was having had to do with the fact that I was using Views PHP to enter PHP code as the contextual filter validator. It should have been on only one display, but it was saved in the master, and was added to all displays, including ones which were over-ridden. I removed it entirely, from the master, but it still didn't fix it. It appears that there is a bug in either the views php module, or the view module (or possibly ctools), in which the validation stayed in the views cache, even after removing it, saving the view, and clearing cache.

To fix this, I exported the view, manually removed the validation code, and re-imported.

Hope that helps the next person who might run into this very obscure problem.

---
Tags: views, panels, users
---


# Question
Title: Custom 'Who's Online' View - How to filter User View by whether logged in
I have a User View that is trying to replicate the 'who's online' block. It currently has 3 filters:

* A custom user\_profile field (Must be **False**)
* User: Active (Yes)
* User: Current (Yes)

For some reason the filter works on when using the first two but when I introduce the User: Current filter it filters the entire view by the active user.

What I need to do is be able to filter the view by **all** current logged in users.

# Answer
You need the User Stats module.

> Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
>
> * days registered; -join date;
> * days since last login;
> * days since last post;
> * post count;
> * login count;
> * user online/offline;
> * IP address;

Once you install this module, you will get an option online user as filter. That's it.
> 1 votes

---
Tags: views
---


# Question
Title: How do I get the password from form API to use to log into external site?
I have these functions, one is for the Form API and the other, git pull, is called on a cron hook. The password is coming up blank and therefore the git pull is not working.

```
function cronmonitor_admin_form($form, &$form_state) {

  $form['cronmonitor_account'] = array(
  '#title' => t('Github Account'),
  '#type' => 'textfield',
  '#description' => t('Github ID'),
  '#default_value' =>  variable_get('cronmonitor_account'),
  );

  $form['cronmonitor_pass'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#maxlength' => 64,
  '#size' => 15,
  );
 ...more form elements....
}

function git_pull(){

  $localRoot        = variable_get ...
  $localRepoName    = variable_get ...
  $localRepo        = "{$localRoot}/{$localRepoName}";
  $username         = variable_get('cronmonitor_account');
  $password         = variable_get('cronmonitor_pass');
  $remoteRepoName   = variable_get ...
  $remoteRepo       = "https://{$username}:{$password}@{$remoteRepoName}";
  if( file_exists($localRepo) ) {
      shell_exec("cd {$localRepo} && git pull");
  }
  else {
      shell_exec("git clone {$remoteRepo} {$localRepo} ");
  }
}

```

# Answer
I went with the Encrypt Form API module.
> 0 votes

---
Tags: forms, users
---


title: Rename nodes based on field

text:
# Question
Title: Rename nodes based on field
Basically, I want the name of a node to be replaced with the value of a certain field. So if I have a field type called field\_new\_name, I want the title field to be changed to that field's value.

I found this link http://dropbucket.org/node/823 but I don't quite understand what it's doing. Is this what I want?

If so, as I run this script, is there a way to build to keep track of changes? Because some nodes reference others via hrefs so I'd wanna go back and change those references as well.

# Answer
Had this question once, came along this Generating node title from node fields

In the reactions, there's a little gem in the comments: https://www.drupal.org/project/auto\_entitylabel You can use Tokens and al kind of this stuff ;-). When your field is *field\_foobar* then you'll have the tokens \[field\_foobar-formatted\] and \[field\_foobar-raw\]
> 1 votes

# Answer
Basically, this was easier than I thought. I ended up using Pathauto to create alias' based on the field I wanted and then installing Global Redirect so that the previous urls and aliases all redirected to this new alias. With the Aliases I didn't need to parse and replace references in the html page.
> 0 votes

---
Tags: nodes
---


# Question
Title: Module to import github content onto local drupal server
I want to be able to put content from github into the sites/default/files folder of drupal so I was wondering if there was a way to do this.

# Answer
> 0 votes
I made my own module. You can see part of the code here. I put that code on a cron\_hook.

---
Tags: version-control
---


# Question
Title: How to add a confirmation form upon submission of user profile form
I have previously added a confirmation dialog to my own forms using a technique like http://blog.purdy.info/2014/04/how-to-work-with-confirmform-in-drupal-7.html. However this assumes that you have control of the form builder and submit functions. I now want to add a confirmation to the user profile form which is of course defined in the user module.

Any suggestions ?

Thx

# Answer
> 0 votes
You can add your own submit handler in front the of the predefined submit handler using hook\_form\_alter().

The #submit property is an array of submit handlers and it allows multiple values. Use array\_unshift() to put your handler in front of the predefined handler.

Your code will look something like this:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if ($form_id = 'target_form') { // make sure it's the right form
    // add my handler
    array_unshift($form['#submit'], 'my_submit');
  }
}

function my_submit( $form, &$form_state ) {
}

```

When the form is submitted, it will run `my_submit()` before the predefined submit handler.

---
Tags: forms
---


# Question
Title: Can Joyride Jquery Button take us to another page?
```
<li data-button="Welcome! Let's Start">
<h2>Stop #1</h2>
<p>We will see this on first stop(Ask saheel what to be written   here).     Any valid HTML will work inside of Joyride.</p>
</li>
<li data-class="pane-update-and-events-panel-pane-1 .pane-title" data-button="Next: Upcoming Events" data-option="tipLocation:top;tipAnimation:pop">
<h2>Update Events</h2>
<p>We will see is some random things about Upcoming Events Here too.</p>
</li>
<li data-class="pane-upcoming-events-panel-pane-1 .pane-title" data-button="Move Forward" data-option="tipLocation:top">
<h2>Final Closing</h2>
<p>If it works fine, we have Achieved Level 3</p>
</li>
<li data-class="pane-article-panel-pane-1 .field-content" data-button="close" data-option="tipLocation:bottom;tipAnimation:fade">
<h2>Recent Article</h2>
**<p>We will see whether this page would take us there.<a href="******">Go to Desired Page</a></p>**
 </li>

```

I have written this code but what I want is, jquery Joyride should take the user to another page when the last pop up has appeared and user clicks on it's button where an automatically triggered action would run. So far I am unable to do that. Is it even possible? PS: \****** would be replaced by the desired page address.

# Answer
I'm not sure about joyride but you could write some javascript to listen for when the last popup has appeared and afterwards use

```
window.location.href = 'someurl.com';

```

Or some such to move the user to a new page.
> 0 votes

---
Tags: javascript
---


# Question
Title: Sending data via post and redirecting user
So I made a module that needs to gather some data and redirect user and that data to a payment site.

```
function payment_upload_form($form, &$form_state){

$form = array();
$form['#action'] = 'www.somepaymantsite.com';
$form['#method'] = 'POST';
$form['CustomerFirstName'] = array(
    '#title' => t('First name'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#size' => 25,
);

$form['CustomerLastName'] = array(
    '#title' => t('Last name'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#size' => 25,
);
etc....

$form['customersubmit'] = array(
        '#value' => 'Pay now',
        '#type' => 'submit',
        '#submit' => array('wspay_submit'),
    );

return $form;

}

function payment_submit($form, &$form_state){
$option = array(
        'ShopID'=>'xzy',
        'ShoppingCartID' => $temp_cid,
        'TotalAmount'=> $amount,
        'Signature' => $signature,
        'ReturnURL' =>'http://some_sitecom',
        'CancelURL' => 'http://some_site.com',
        'ReturnErrorURL' => 'http://some_site.com/1',
        'CustomerFirstName' => $form_state['values']['CustomerFirstName'],
        'CustomerLastName' => $form_state['values']['CustomerLastName'],
        ....
        );

$options = array(
  'method' => 'POST',
  'data' => drupal_http_build_query($option),
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$response = drupal_http_request('www.somepaymantsite.com', $options);
 $response->redirect_url = 'www.somepaymantsite.com';

```

The problem is that it does not redirect me on the first go, but when I use the same ShoppingCartID it redirects me and I get an error because the ID is the same(it need's to be different every time), but the data is in the URL . So my question is why does it not redirect the user with the data to the site when he clicks Pay now.

---------------------- EDIT -------------

How can i create a middle page in drupal that has this data and sends it like that, meaning a confirmation page :

```
        <form name=“pay“ action=“https://to.the.shop.something“ method=“POST“>
    <input type=“hidden“ name=“ID“ value=“some_value“>
    <input type=“hidden“ name=“ID2“ value=“some_value“>
 <input type=“hidden“ name=“ID3“ value=“some_value“>
    <input type=“submit“ value=“Pay now“>
    </form>

```

# Answer
> 0 votes
Your submit function name is wrong , your submit function not called at all, In Drupal if you have form name x then the submit should be x\_submit, so in your case the submit function should be

payment\_upload\_form\_submit

---
Tags: redirection, forms
---


title: How to Edit a contributed module

text:
# Question
Title: How to Edit a contributed module
I am using the Feedback Module, and I need to add an email field to the feedback form. How can I make the necessary edits to the Feedback Module in such a way that they stay when the module is updated?

# Answer
@Chances G is right but in cases that you need to make a new feature or make a change that you can't handle via Drupal's hook system you should create a patch and submit it to the community.
> 0 votes

# Answer
You should never edit core or contributed modules if it can be helped (which it almost always can). I haven't used Feedback, but the general Drupal way of extending forms is to use hook\_form\_alter from your own custom module.

Basically create a simple module. All it needs is a mymodule.info file and a mymodule.php file inside of a folder in /sites/all/modules. Here is some more info on creating a module.

Then in your mymodule.php file, add a function that looks something like this:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FEEDBACK_MODULE_FORMID') {
    $form['custom_email'] = array(
      '#type' => 'textfield',
      '#title' => 'Email',
      '#required' => TRUE,
    );

    $form['#submit'][] = '_mymodule_feedback_form_submit';
  }
}

```

This will add a new field to the form, and register a submit callback for the form.

Finally write the `_mymodule_feedback_form_submit` function to actually do something with the value when the form is submitted.
> 4 votes

---
Tags: 7
---


title: Render a webform to another node

text:
# Question
Title: Render a webform to another node
I have a new text format sample\_page with the filter sample\_page, I've created using hook\_filter\_info(). In the callback, I am rendering a webform using depending on the token in the node body, for webform I'm planning to use a token \[block:webform:webform-client-form-2423\].

I could render the blocks created programmatically, system blocks. But not the blocks created by other modules, I have tried \[block:user:login\] from http://mine.local/admin/structure/block/manage/user/login/configure to render to login blocks too. But these blocks didnt seems to work. Here is my callback for filter.

System blocks that worked for me, I used the token \[block:block:25\] from http://mine.local/admin/structure/block/manage/block/2/configure and for blocks created programatically by my own module, suppose my module is my\_module, I have used the token \[block:my\_module:block\_name\] from the url http://mine.local/admin/structure/block/manage/my\_module/block\_name/configure

```
preg_match_all('/\\[([a-zA-z0-9_\-]+:[a-zA-z0-9_\-]+)+\\]/m', $text, $match);
$matches = $match[0];
foreach ($matches as $token) {
  $token_name = str_replace(array( '[', ']' ), '', $token);
  $type = explode(':', $token_name);
  if ($type[0] == 'block') {
    $module = $type[1];
    $bid = $type[2];
    $block = block_load($module, $bid);
    $replacement = render(_block_get_renderable_array(_block_render_blocks(array($block))));
  }
}

```

Can any one look into the problem. Any help would be appreciated...

# Answer
You can add the webform using hook\_page\_alter().

```
/**
 * Implements hook_page_alter().
 */
function my_module_page_alter(&$page){

  // Get the webform's nid that you want to display on the current page.
  $webform_nid = my_module_webform_to_display();

  // Load the webform node.
  $webform = node_load($webform_nid);

  // Render the webform using my custom view mode.
  $markup = drupal_render(node_view($webform, 'my_custom_view_mode'));

  // Add the markup to the page element.
  $page['content']['system_main'][] = array(
    '#markup' => $markup,
  );
}

```
> 1 votes

---
Tags: nodes, blocks, theming
---


title: Drupal Node view modes

text:
# Question
Title: Drupal Node view modes
I have setup multiple new view modes for a specific node. Full,Teaser,New Teaser,Custom Display.

Is there a way to view the same node with different URLS for the different view modes. Please let me know if i need to explain further.

Hopefully this makes some kind of sense.

# Answer
If you would be okay with having a parameter in the url control your view mode then you can add this code to your custom module using hook\_entity\_view\_mode\_alter().

For example:

http://www.yoursite.com?view\_mode=Full

http://www.yoursite.com?view\_mode=Teaser

.....

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function my_module_entity_view_mode_alter(&$view_mode, $context) {
  // If there is a view_mode parameter in the url change the view mode to it.
  if (isset($_GET['view_mode'])) {
    $view_mode = $_GET['view_mode'];
  }
}

```
> 2 votes

# Answer
You can do this with View Mode Page

> Create separate pages for different view modes for a given content type.
>
> On the manage display page for a given content type, you can assign patterns for view modes so that they will become a page at the given path. For instance, if you want to show the teaser at a specific URL, you could do node/%/teaser. If you also use Display Suite or other modules that allow you to create new view modes, you can use these modes to display one or more fields from a node at a separate URL.

Or you can use Panels also.

Or a custom module could do this as well but no sense in reinventing the wheel :)
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Drupal Webform not submitting sometimes right after clearing cache
I add a webform node to another node via hook\_page\_alter() or in a block. Sometimes when submitting this form it doesn't submit the data and redirect to the Custom URL set in the settings. Right after I see the the form give me this issue I notice that the submitted data does not appear under Results -\> Submissions. It only happens right after clearing the cache. Once it happens if you refresh the page or go to another page that has the form it doesn't happen. If I go to the actual node that is the webform I can't reproduce this issue.

Below are the steps I take to reproduce this problem (FYI I can only reproduce it sometimes. I can reproduce it logged in as user 1 but I have better luck reproducing as anonymous user):

1. Flush all cache via drush cc all command
2. Refresh page with form
3. Fill out form and submit
4. Notice that the page refreshes instead of going to destination url (this happens maybe 40% of the time)

This is how I display the webform on certain nodes via hook\_page\_alter():

```
$get_my_free_download_node = node_load($nid);
$markup = drupal_render(node_view($get_my_free_download_node, 'hcp_gmfd_slide_in'));

$page['content']['sliding_panel'] = array(
  '#markup' => $script . $markup,
);

```

I am using Webform 7.x-3.24. I added debug code webform\_client\_form\_submit() and my code never gets run when this issue happens.

I'm wondering if Varnish or Memcache is causing this issue? I don't ever remember seeing this a long time ago but I don't think I ever did a test of clearing the cache and testing the form right away.

These are my Memcache settings in settings.php:

```
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array('127.0.0.1:11211' => 'default');
$conf['memcache_bins'] = array('cache' => 'default');
$conf['memcache_key_prefix'] = 'AW';

$conf['reverse_proxy'] = true;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
# Bypass Drupal bootstrap for anonymous users so that Drupal sets max-age > 0
$conf['page_cache_invoke_hooks'] = FALSE;
# Fix for admin_menu disappearing see https://drupal.org/node/442560#comment-2692220
$conf['admin_menu_cache_client'] = FALSE;

```

**Update**

I originally stated that this only happened in production but after testing locally more often I was able to replicate the issue locally.

# Answer
> 0 votes
Turns out that this issue was happening to me locally so it wasn't Memcache or Varnish that was causing this issue. It turned out to be a webforms module.

Because I was embedding the form on another node the '#action' value was incorrect. I didn't run into this issue in the past because the code was updated on a newer version of webforms.

One fix is to use hook\_form\_alter() to change the action:

```
if ($form["#node"]->type == "stage_one_form" && !path_is_admin(current_path())) {
  $alias = "/" . drupal_get_path_alias("node/{$form['#node']->nid}");
  $form['#action'] = $alias;
}

```

Another fix is to run the patch I created here.

---
Tags: 7, webforms
---


# Question
Title: Metatags trimmed body in description/summary
I am using the Metatag Module. Everything works as expected, till I checked the description for each node and saw that it is empty.

Since there is no output with \[node:summary\] I changed it to \[node:body\] which works, but now the whole node is in the description field... I checked the available tokens \[\*:summary, \*:value, \*:format\] with no success.

Any suggestions how to use the \[node:body\] in a trimmed version?

# Answer
You can use any field with Metatag, so simplest way would be to use Computed Field, that

> lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields

In your custom php code for field computation, use code like this:

```
$body = $entity->body['und'][0]['value'];
$width = 160;
$body_trimmed = substr($body, 0, strpos(wordwrap($body, $width), "\n"));
$entity_field[0]['value'] = $body_trimmed;

```

It will truncate on the word boundary, giving you no more than `$width` characters. More about truncating on StackOverflow.

Then, simply feed this computed field to Metatag.
> 3 votes

# Answer
Thanks @Molot!

I was looking for a way to put a trimmed description field into another field called summary. You would think Drupal would do this automatically but the summary field is only populated if a user enters it manually.

My code looked like this:

```
$desc = $entity->field_prj_desc['und'][0]['value'];
$width = 140;
$desc_trimmed = substr($desc, 0, $width);
$entity_field[0]['value'] =  $desc_trimmed;

```
> 0 votes

---
Tags: 7, tokens, meta-tags
---


title: hide a field in webform components

text:
# Question
Title: hide a field in webform components
I want to hide the field `"form key"` in all of the webform components. I tried doing it with `"*hook_form_alter*"` and with "*\[#access\] = false*" but I can't succeed in this. I also tried to use `"*hook_webform_component_load*"`.

But in all of those, i can't understand exactly what I need to do to hide the form key field in all of the components in all of the webforms. I can't even hide one component's "form key" field. I don't understand which is the field that i need to modify.

p.s - im using form\_builder too.

I'm doing something wrong.

any help will be appreciated. thanks, alexandra.

# Answer
> 1 votes
The webform\_civicrm module does this (actually it disables it rather than hiding it)

You can see the relevant code here (note this function runs in the context of hook\_form\_alter).

You could hide it by doing something similar but setting `$form['form_key']['#type'] = 'hidden';`

# Answer
> 0 votes
Although I have no experience with the Webform Locked Fields module myself, it sounds like the module does exactly what you are asking for (so no custom code needed).

> With this module you can lock fields in a webform so that those fields cannot be deleted or modified except by administrators with appropriate permissions.
>
> Users who have the "administer webform locked fields" permission will see a checkbox titled "Webform creator can modify" when they edit a webform component. If that box is unchecked, the component can only be modified or deleted by users who have the the "administer webform locked fields" permission. Other users who have webform creation permission will be taken to a page that says "Not allowed" if they attempt to edit or delete that component.

---
Tags: webforms
---


# Question
Title: Two Factor Authentication for admin/OAuth2 for REST API
I am building a "headless" Drupal application. The front-end is in AngularJS using OAuth2 to authenticate to the REST API that I have built. A client did a security audit and wanted additional security on the Drupal administration interface. I implemented the TFA module using Google Authenticator and Twilio SMS. All is good.

Except, calls to the API are requiring TFA completion/validation. This is noted in the documentation. It states to develop a custom plugin that will handle web services connections.

I don't have a problem doing this, but I was wondering if anybody has run into this issue and has the plugin ready for sharing. I have exhausted plenty of time searching to no avail.

# Answer
There's no public plugin for this as far as I'm aware of (note, I'm author of the drupal.org TFA module).

I do think it's a quick write, depending somewhat on how your REST API is authenticating the request and particularly whether you create a Drupal session and invoke the user login process.

You can allow a REST call to skip the TFA process very similar to how the TfaTrustedBrowser works. The loginAllowed() method on this plugin (implementing TfaLoginPluginInterface) will be invoked and you can check the request headers/global scope (user UID) and return TRUE to tell TFA to not block the login action.
> 1 votes

---
Tags: users, services
---


# Question
Title: Get current node's count (rank/order?) from node.tpl in a View which renders a list of nodes
I have a `view` that lists multiple `article nodes`. Now for each rendered node, I want to be able to know its rank/order from the list of displayed nodes.

Here's a visual representation:

```
[view]
    [node.tpl] $count=1 [/node.tpl]
    [node.tpl] $count=2 [/node.tpl]
    [node.tpl] $count=3 [/node.tpl]
    [node.tpl] $count=4 [/node.tpl]
    ...
[/view]

```

For the first rendered node, I will be able to access a variable called `$count` whose value is set to `1` because it's the first and so on.

Btw, I'm using Rendered entity so I'm using `node.tpl` not `views/rows` templates

# Answer
Ok it looks like there's a similar thread but worded differently.

How to add classes to every X number of node in a array
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to make table-responsive in drupal views
I have created the views which renders table. I want to make table responsive without any contrib module. Is it possible?

# Answer
Consider the Views Responsive Grid module. Here is a quote about it (from its project page):

> ... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
>
> Features:
>
> * Horizontal or vertical grid layouts
> * Custom classes for use with responsive themes

Of course, this requires the use of a contributed module (which is something you want to avoid as per the edited version of your question).

Assuming that it's OK to use a contributed "theme", you may should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "*is designed from the ground up as a mobile-first responsive theme*". However that has like 5 module dependencies ...

For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

> All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.
> 3 votes

---
Tags: 7, views, theming
---


title: Error on Insert Map

text:
# Question
Title: Error on Insert Map
I am using Drupal 7 and the Google Map Field module. When I click on the *Insert Map* button, the Firebug console shows this:

> TypeError: `$(...).prop` is not a function

It seems like I need `jQuery.noConflict()`, but why is this happening?

# Answer
> 1 votes
Because Drupal ships with jQuery 1.4 and `prop()` was added in 1.6.

You could mess about with a second version of jQuery and `noConflict`, or you can just install the jQuery Update module and let it handle things for you.

If that won't work (e.g. it produces other conflicts with existing scripts), try jQuery Multi instead.

---
Tags: javascript
---


title: Views PDF Change Table Layout Setting

text:
# Question
Title: Views PDF Change Table Layout Setting
I am using **Views PDF** Module in my project.

This module provide only limited settings for table layout i want to generate pdf according to custom design as given below:

The pdf file generated through **views PDf module** currently as below:

so, please tell me how to design my pdf table in Views PDF Module.

# Answer
> 2 votes
I done this before using global text field and html. Add all needed fields into view and exclude them from display. Then create an html layout using field replacement patterns according to your requirement using a **Global:Text** field. Then generate **PDF**.

Hope this helps you.

---
Tags: views, files
---


# Question
Title: Adding a dropdown list to the Registration Form. Drupal 7
How would I go about adding a dropdown list to the user registration form? Also, is there a limit as to how many dropdown items you can have?

# Answer
You can do this via the UI by going to (admin/config/people/accounts/fields) and then adding your new field. There is no limit to how many fields you can have.
> 2 votes

# Answer
One way of adding a dropdown list has already been stated. However, if you wish to add a dropdown of taxonomy terms, you can incorporate the following piece of code:

```
//get the list of locations from taxonomy to use in the dropdown
$dropdown_source = taxonomy_get_tree(2);
$dropdown_array = array('0' => '--none--');
foreach ($dropdown_source as $item) {
$key = $item->tid;
$value = $item->name;
$dropdown_array[$key] = $value;
}

//location filter dropdown
$form['filterset']['locationfilter'] = array(
  '#weight' => '1',
  '#key_type' => 'associative',
  '#multiple_toggle' => '1',
  '#type' => 'select',
  '#options' => $dropdown_array,
  '#title' => 'Filter by location',
);

unset($dropdown_array);

```

It will also rule out problems on encountering non-relevant taxonomy terms.

You may also check out taxonomy\_form
> 0 votes

# Answer
//Here is the function for getting list dynamically from database(here i uses taxonomy). In this function '$vocabularyName' as parameter is taxonomy\_machine\_name, which we created for our project then query for getting the id from taxonomy\_term\_data (drupal default table) of above name, and fetching the data from drupal default table taxonomy\_vocabulary.

```
    function getList($vocabularyName) {
      $query = db_select('taxonomy_term_data', 'f');
      $query->innerjoin('taxonomy_vocabulary', 'b', 'b.vid = f.vid');
      $query->fields('f', array('name', 'tid'))
            ->condition('b.machine_name', $vocabularyName);
      $result = $query->execute()->fetchAll();

      $keyarray = array();

      foreach ($result as $key => $value) {
      $keyarray[$value->tid] = $value->name;
     }

     $options = $keyarray;
     return $options;
   }

```

//code for hook\_form()

```
$form['city'] = array(
'#type' => 'select',
'#title' => t('City'),
'#options' => getList('taxomomy_machine_name'),
);

```

Note : Answer with the consideration of drupal7
> 0 votes

---
Tags: users
---


# Question
Title: How to do integrate javascript in drupal way
I want to integrate this Flex Slider code to drupal but without success. Please help. here is the code

```
if($('#homeSlider').length > 0) {

    var hIndex = 0;
    var $hCap = $('#homeSlider').find('.captions').children('li'), $hSlides, $hPrev, $hNext;

    $('#homeSlider').flexslider({
        animation: 'slide',
        animationLoop: true,
        slideshow: true,
        slideshowSpeed: 7000,
        smoothHeight: false,

        controlsContainer: $('#homeSlider').find('.thumbs'),
        keyboard: true,
        controlNav: false,
        start: function(e){

            $hPrev = $('#homeSlider').find('.flex-prev');
            $hNext = $('#homeSlider').find('.flex-next');
            $hSlides = $('#homeSlider').find('.slides').children('li');

            $hPrev.append('<img src="' + $hSlides.eq(e.count).data('thumb') + '" />');
            $hNext.append('<img src="' + $hSlides.eq(hIndex+2).data('thumb') + '" />');

            $hPrev = $hPrev.find('img');
            $hNext = $hNext.find('img');

        },
        before: function(e){

            $hCap.eq(hIndex).fadeOut(200);

            var prev = hIndex - 1 < 0 ? e.count-1 : hIndex - 1;
            var next = hIndex + 1 > e.count-1 ? 0 : hIndex + 1;

            hIndex = e.data('flexslider').animatingTo;
            $hCap.eq(hIndex).fadeIn(500);

            changeThumbs(prev, next);

        }
    });

    function changeThumbs(prev, next){
        $hPrev.prop('src', $hSlides.eq(prev).data('thumb'));
        $hNext.prop('src', $hSlides.eq(next+2).data('thumb'));
    }

}

```

# Answer
The Managing JavaScript in Drupal 7 guide provides the information to add JavaScript to Drupal. The techniques presented there apply to both themes and (custom) modules:

Add a scripts\[\] = somescript.js to your module or theme's .info file Use drupal\_add\_js() in your module or theme's code Use the #attached\['js'\] property in a From API or renderable array. Note that Drupal already include jQuery, jQuery UI and a bunch of other libraries so you don't, and shouldn't, add them yourself. Instead you should use drupal\_add\_library() or the #attached\['library'\] property.

The Working with CSS guide provides the information to add CSS to Drupal. Again, the techniques presented there apply to both themes and (custom) modules. With an exception: addition of style sheets from an .info files only works for a theme and not a module.

Add stylesheets\[all\]\[\] = somestylesheet.css to a theme's .info file. Use drupal\_add\_css() from module or theme's code. Use #attached\[css\] property in a From API or renderable array.
> 0 votes

# Answer
In some\_name.js file replace $ with jQuery. For e.g.

```
 $('#homeSlider').flexslider({
       //code
    })

```

with

```
    jQuery('#homeSlider').flexslider({
       //code
    })

```
> 0 votes

---
Tags: javascript
---


title: Is there Page bulk manager?

text:
# Question
Title: Is there Page bulk manager?
I tried to look for bulk page manager for Drupal 7, but I wasn't successful. More specifically, I'd like to change access settings for multiple pages in one step. Something similar to what VBO provides for entities.

Any suggestions?

# Answer
# Content Access VBO

Maybe you want to look at Content Access VBO ... It's (still) a sandbox project, so not sure if you really want to consider it. Here are some details about it (quote from that link):

> ... creates an action for Views Bulk Operations to update per node content access (view/edit/delete etc). It adds a menu item to the Content menu tree and adds a new view which lists content with the VBO action as a button.

But at least it may help to get more inspiration to build your custom module to get this done.

# Combine Rules with Views Bulk Operations or Content Access

Another approach is to use the Rules module, combined with modules Views Bulk Operations and/or Content Access. Here are a few questions that may help to get more inspiration about its possibilities (the sky is the limit ...):
> 0 votes

---
Tags: chaos-tool-suite
---


title: Programatically Update a Module

text:
# Question
Title: Programatically Update a Module
Is it possible to programatically update a module in Drupal 6? In otherwords, run an update as if running from update.php. I assume so. I looked at update.php and saw the function

```
update_do_once($module, $version, &$context);

```

I can't say I understand what `$context` is, and I can't get this working even after doing a full bootstrap. I get no errors, just nothing happens.

Has anyone every done this before?

# Answer
> 1 votes
Check out hook\_update\_N().

# Answer
> 0 votes
This might now be what you were aming for with your question, but an excellent programming tool for Drupal is drush.

On your terminal you only need to run

```
 $ drush updb

```

to update modules.

# Answer
> 0 votes
I realized I can run my own hook\_update\_N() functions apart from update.php, as long as I am bootstrapped and include the module's .install file.

# Answer
> 0 votes
This should be straight forward in both Drupal 6 & 7:

```
$sandbox = array();
module_load_include('install', 'foo');
foo_update_7001($sandbox);

```

---
Tags: 6
---


# Question
Title: Insert 'select all' choice in a particular level in Taxonomy Term Reference Tree Widget
I'm using D7. And I have a big term reference tree with Term Reference Tree. There are so many terms in the tree that I'd like to put 'select all' choice in it for usability. Is it possible to put 'select all' choice in some level?

Let me show you the example of what I want to do below...

(Ex) Let's say there is a vocabulary whose name is 'Food'

**\[Food\]<br>** **-Vegetable**
--Select All
--Pumpkin
--Carrot
--Radish
--Potato
**-Fruit**
**-Fish**

So, what I want to do is...if you check the 'Select All' under the Vegetable level, the all of choices(Pumpkin, Carrot, Radish, Potato) will be checked.

I searched the way to do that but couldn't find the answer. Any tips would be appreciated. Thank you.

**Added:**
I found you can do something like I want to do by the setting below...
-Start minimized =\>Whichever
-Leaves only =\>Off
-Select parents automatically =\>On
-Cascading selection =\>On

With the setting above, you can chose all choices by checking the parent level.
**But, I also wanted to enforce users to chose the deepest level.**
With the setting above, users don't always have to chose the deepest level...
So, correctly, I'd like to say I want to put 'select all' and enforce users chose the deepest level.
I still need your help. Thank you.

# Answer
Drupal have Taxonomy Manager module where all levels and terms have checkbox options and also **add, edit, delete, move,** functionality here.

**Taxonomy Manager:**

> This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.
>
> For using the Taxonomy Manager you should have JavaScript and automatically load of images enabled in your browser.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: pager_query() - How to fetch only 100 records with a pagination 10 items per page?
```
$result = pager_query($query, 10, 0, NULL, $args);

```

Currently with above code , I am getting all **results** with **10 items** per page. But I need to display only first 100 records , with 10 items per page. Is this possible with pager\_query() or any alternate solution using plain **PHP** and **MySQL**?

# Answer
> 1 votes
You can pass a `$count_query` argument to `pager_query()`, which you can use to control the overall count:

e.g.

```
$sql = 'SELECT * FROM my_table';
$count_sql = 'SELECT COUNT(id) FROM my_table LIMIT 100';

$result = pager_query($sql, 10, 0, $count_sql);

```

# Answer
> 0 votes
Replace '$args' with '100' in pager\_query() and check.

# Answer
> 0 votes
**If you need to supply any argument to your query just add them after all the \**pager\_query** arguments like so:\**

**Example Query:**

```
$query = "SELECT heading, summary, publish_date FROM {news} WHERE category_id = %d ORDER BY publish_date DESC";

$result = pager_query($query, 100, 0, NULL, $cat_id);

```

So, for the **pager\_query** example above let me explain the arguments:

1. **1st arg ($query)** = The query to be executed.
2. **2nd arg (10)** = $limit The number of query results to display per page.
3. **3rd arg (0)** = $element The integer number of the pager we are working with.
4. **4th arg (NULL)** = $count\_query Just put NULL which is the default for this variable.
5. **5th arg ($cat\_id)** = The argument that needs to be passed to the query itself.

# Answer
> 0 votes
```
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'your_content_type')
          ->fieldCondition('field_village_schedule_state', 'value', 'your_value','=')
         $_GET['village'],'=')
           ->range(0,100)
           ->execute();

  if (isset($results['node'])) {
       $nodes = node_load_multiple(array_keys($results['node']));
       foreach ($nodes as $row)
        {
          // Your Code Here for dispaly.
        }
     }

```

---
Tags: 6, database, paging
---


# Question
Title: How to login-redirect users to their profile page on specific days only?
By using Rules Once per Day module, logged in user would be redirected to profile page on specific day. My issue is, every time when user logged in to the site, the user is redirected to profile page.

But I want this rule to work on specific days, like Monday and Thursday. How I can handle this without Rules Once per Day module?

I want to this functionality works at only once. How can I do this? Any suggestions?

# Answer
You could do it simply by rules module (no extra module required):

1. Create a new rule.
2. Select event - *user has logged in*
3. Could add in a condition, check for a role for eg. **This step is optional, and can be ignored if not required.**
4. Select an action - Page redirect, and add the url `/user` to the destination.
5. Make sure you enable the rule.
6. Test, test, and test ;-)

If you want to schedule this view to run on a particular day you could check on Scheduling rules. There is also a very good video from nodeone about the same.
> 2 votes

# Answer
Even though the Rules module is one of those amazing Drupal modules, it does have some challenges with processing dates ... (= open issues in its issue queue).

Therefor consider using an approach as detailed in the (great) answer to the question about Rule to check if a date value is a specific day of the week ...

Another option is to write your own module for this. Refer to Drupal custom Rules how to write your own events conditions, actions and custom object (+custom tokens) for a great tutorial about how to do so. The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

## Part 1: Defining the Event, Condition and Action

### Define the Rules Event

```
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

```

### Define the Rules Condition

```
/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

### Define the Rules Action

```
/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

## Part 2: Coding the custom Event, Condition and Action

### Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the `your_module_package_bought` in it):

```
  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

```

### Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function `your_module_condition_package_type` is executed using the arguments provided. Here is an example of how such function could look like:

```
function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

```

### Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named `your_module_action_change_order_status`.
> 1 votes

---
Tags: 7, rules, users, redirection
---


# Question
Title: Theming Views problem to print view fields
I was trying to edit my view theme with php in the file **views-view-field--homepage-banner--block--field-site-image.tpl.php** and try to print view fields, but values come's empty. any ideas?

Code example:

```
<?php
$link=$fields['field_site_image_link']->content;
$src=$fields['field_site_image']->content;
$link2 = '/' . strip_tags($fields['field_site_image_link']->content);
print $src;
print $link2;
?>
<a href="<?php echo $fields['field_site_image_link']->content; ?>"><?php echo $fields['field_site_image']->content; ?></a>

```

# Answer
1- clear cache
2- take the views-view-field.tpl.php source as a starting point for doing what you need also have a look at documentation at the top of the file
> 0 votes

---
Tags: views, theming
---


# Question
Title: Views with taxonomy contextual filter not working in Russian language in Drupal 7
I have a `View` which works perfectly in English. It has a `contextual filter`, with options Content: Has `taxonomy term` ID , filters by taxonomy term with term name converted to term Id.

But when I put in the URL the term in Russian, Раздел, it does not show the content. When I check the SQL, to my surprise and dismay, this is what I find: `search_index.word = 'razdel'`.

Clearly there has been a transliteration. Maybe this is why it does not work. I do not really what to do.

# Answer
> 0 votes
It's probably the collation of your fields and tables in database, try to check to see if all the tables collation is set to `utf8_general_ci`

you can google to find an script to bulk update your tables and or fields collation

---
Tags: 7, views, transliteration
---


title: Display google map based on coordinates

text:
# Question
Title: Display google map based on coordinates
I've a node with field that store coordinates (in a field with type Geofield).

Now I want to display google map block on page based on coordinates in that field. How should I do it? IS there any module that provide such functionality.

# Answer
> 0 votes
I decided to use gmap module as it provides widget to change Display format for my geofield.

---
Tags: entities, location
---


# Question
Title: colorbox does not seem to work anymore after upgrade from 7.x-1.6 to 7.x-2.9
I upgraded `colorbox` from 7.x-1.6 to 7.x-2.9 and now, I lost functionality of loading the pictures in a box. my page is http://www.quaaoutlodge.com/content/lodge and the centered picture in the middle, used to load nicely in a colorbox frame before the update but this does not work anymore now. The link looks like:

```
<a class="colorbox colorbox-insert-image" href="http://www.quaaoutlodge.com/sites/default/files/styles/gallery-cblarge/public/exterior---back-of-lodge-1200-x-800_0.jpg?itok=V55hQ0Bj" rel="gallery-all"><img alt="" class="image-large" height="200" src="/sites/default/files/styles/large/public/exterior---back-of-lodge-1200-x-800_0.jpg?itok=Q6e4P9RK" width="480"></a>

```

The link is being "auto-created" as follows: In my Content type, I have added a Field `myImage` that allows me to upload and insert the image into the content. The Format of the field, I set to `Colorbox`. I setup my image styles as follows:

```
Content image style: Hide
Colorbox image style: Original image
Colorbox gallery type: Per page gallery
Colorbox caption: None

```

And don't understand how this isn't working anymore after the upgrade... Whaty's wrong with this I'm wondering? Should I rollback to 7.x-1.6 or can I fix this?

**EDIT A**
The colorbox module is installed & enabled and it says `A light-weight, customizable lightbox plugin for jQuery 1.4.3+.` Looks like I'm using jQuery 1.4.4: `<script type="text/javascript" src="http://www.quaaoutlodge.com/misc/jquery.js?v=1.4.4"></script>`

**EDIT B**
I just copied `modules/colorbox/` to `libraries/colorbox/` but that didn't change much. You say the "JS lib" is not included on the page? I have `<script type="text/javascript" src="http://quaaoutlodge.com/misc/jquery.js?v=1.4.4"></script>` and `<script type="text/javascript" src="http://www.quaaoutlodge.com/sites/all/themes/marinelli/templates/jquery.js"></script>` in my source code, the second line refers to `jQuery 1.8`

# Answer
> 1 votes
i think you need to update the colorbox library too !

right now - the JS lib is not included in the page ...

---
Tags: javascript, upgrading
---


# Question
Title: How do I show a progressive number such as "Item 1 of termName", "Item 2 of termName"?
I have a vocabulary with 4 taxonomy terms. There is a content type with a taxonomy reference field for that vocabulary.

I have a view that is pulling a list of all these nodes on a page. My design calls for the list to display to which taxonomy term the nodes belong, along with a progressive number.

>

Each node shows *Issue #*, where the progressive number shows which node was created first for that taxonomy term.

I thought being able to use tokens in view fields would help, but it seems it isn't currently possible, reading Provide Field item that supports Text Filters.

Does anyone know of a way to accomplish this without writing custom code?

I saw Node count for taxonomy terms, but that's about showing a node count, while I want to show a progressive number.

# Answer
I know that you can set the format to html ordered list and group by the tag, but that will number the items automatically as in a standard ordered list with no control of the placement or prefixing with "Issue #". See Number items in a grouped view, resetting counter with each group, for example.

I think the views\_php module with some custom coding could possibly work. I'll admit I have difficulties in getting parameters to reset effectively at times, but perhaps your mileage will vary.
> 1 votes

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


# Question
Title: Query URL containing term name instead of term ID on Views Exposed Filters
I've got a View with an Exposed Filter that shows Taxonomy Terms that are used to filter the content that's going to be displayed as the result.

It's a View that shows recipes based on the filters chosen by the user (Type of Recipe, Type of Meat).

When I submit the form, I get the following URL:

```
/recipes-view?type-of-recipe=all&type-of-meat=22

```

The last parameter shows the number 22, which is the Term ID for the value chosen. The URL has to contain the Term Name instead of the Term ID.

Can I change it via `hook_views_query_alter()` or is it needed to create a custom handler for that?

Thanks in advance.

# Answer
> -1 votes
There's no need to do this in code. You basically need to:

1. Add relationship to taxonomy term via entity reference field (it would probably also work with term reference)
2. Add exposed filter using this relationship (search for field Taxonomy Term: Term)

It works fine and you get URL, such as:

```
recipes-view?tid=vejuu

```

If you want to have an URL key `type-of-meat`, you can set it in *More* drop-down in you exposed filter configuration. The field name is *Filter Identifier*

I experienced problems with using features trying to prevent duplicates created by joining taxonomy terms.

---
Tags: views, uri
---


# Question
Title: Date selection with price - without commerce
I need a option to let users set up dates and price when creating node with unlimited number of entries.

For example:

"from: 15/01/2015 to 20/02/2015 - Price = 50 USD"

from: 21/02/2015 to 15/03/2015 - Price = 70 USD

from: 16/03/2015 to 15/05/2015 - Price = 90 USD

It would be nice if could look user friendly too since users will make atleast 7-8 entries.

Something like "from: \__________ to \__________ : price \__________"

Instead of underline it should be date popup and for price i would use integer.

# Answer
You can accomplish this with the Field Collection module and Date module.

1. Navigate to manage fields under your node type
2. Create a new field with field type of Field collection
3. Set the number of values to unlimited under the field you created in step 2
4. Navigate to /admin/structure/field-collections and select Manage Fields under the field collection you just created in step 2.
5. Select Manage Fields
6. Add From Date Field
7. Add To Date Field
8. Add Price Field
> 1 votes

---
Tags: 7, nodes, entities, commerce, datetime
---


# Question
Title: Define available default colors for Color Field programatically
I use the Color Field as a field in a custom module from where I create the content type programatically.

By default the available colors are defined at this hook: color\_field\_field\_settings\_form

in the color\_field module.

I need to modify the list of available colors and I wanted to do at the field creation time.

At my \_slider\_installed\_instances function I have:

**EDIT**: Added the **settings** section with no results.

```
        'slider_background' => array(
                'field_name' => 'slider_background',
                'type' => 'color_field_rgb',
                'label' => $t('Slider background color'),
                'widget' => array(
                        'type' => 'color_field_default_widget',
                ),
                'settings' => array(
                        'default_colors' => array(
                                'default_value' => '#AC725E,#D06B64',
                        ),
                ),
                'display' => array(
                        'default' => array(
                                'label' => $t('Slider background color'),
                                'type' => 'text'
                        )
                ),

        ),

```

and I wonder how to define the settings for default colors so the list will be the one defined by me at my module.

I'll appreciate any hint.

Thanks in advance.

# Answer
> 0 votes
Finally to achieve I move to implement in my custom module the hook hook\_field\_info\_alter and update at this hook the $info\[field\]\['settings'\]\['default\_colors'\] list of hex color values.

I couldn't find the solution I was looking for.

# Answer
> 0 votes
You are using the following code:

```
'settings' => array(
  'default_colors' => array(
    'default_value' => '#AC725E,#D06B64',
  ),
),

```

The correct structure for the *settings* array is the following one, in your case.

```
'settings' => array(
  'default_colors' => '#AC725E,#D06B64',
),

```

---
Tags: entities
---


# Question
Title: How to set blog post under event section in Drupal commons
I use the Drupal Commons distribution. I already created **blog-post** depends under **group section** using **OG\_MEMBERSHIP**. Likewise, **blog-post** depends under content type **event**. How to achieve this?

We also have some **event section** (with particular time/date and location), which is used for maintaining some **blog-post** (content type).

Can anyone provide some insight about how to do this? I.e some procedure or modules for creating such **blog-post** (content type) under event.

# Answer
> 1 votes
# Entity reference

Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

> Provides a field type that can reference arbitrary entities

# References

Another option is to consider the References module, which provides D7 versions of the 'node\_reference' (and 'user\_reference') field types, that were part of the CCK package in D6.

# Recommended tutorials

If these module don't help for what you're trying to achieve, then reviewing the amazing set of videos to Learn Organic Groups might help somehow.

---
Tags: 7, nodes
---


# Question
Title: Adding a field to a content type for Apache Solr search and Facets
I've got a content type of Journal, and another content type of Article. All of the data associated with the Journal itself is stored on that content type, and not duplicated in the Article; the Article just has an entity reference to the Journal. So, for instance, Journal has a Year field, but Article has no Year field. (Conceptually, a Journal is a collection of Articles.)

For the most part, this entity reference relationship works great (and avoids duplicate information.) However, when doing things like searching, it can have some side effects. For example, if someone searches for a keyword, gets back a list of Articles with that keyword, they're then not able to filter that down by Year using facets, since that content type doesn't technically have a year associated with it, just a reference to a different content type that does. I'm hoping to find a way around that, but I'm not sure how to get it working.

I'm still pretty confused on the relationship between the Solr server we have and the Drupal site. It was my idea that once all was indexed, the Solr server takes the search string, and just ships back nodes/entities/etc. that match. If that's wrong or right, I'm still not sure if my problem has to do with Solr or FacetAPI.

What I've done so far is below, but it seems to have no effect on the search results. (In other words, if I search for a year, the articles aren't being returned as results; I'm not even worrying about Facets yet, even though those are the ultimate goal.)

```
function issue_archive_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id){
  if($node->type == "article") {
    // Load the journal this article is associated with, and get it's year
    // The is_ prefix is to denote a single (instead of multi-value) integer
    $journal = node_load($node->field_journal['und'][0]['target_id']);
    $document->setField('is_article_year', intval($journal->field_year['und'][0]['value']));
  }
}

function issue_archive_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // Make the indexed fields available for search results
  $query->addParam('fl', 'is_article_year');
  // Filter where 'index_field_name' = 'indexed_value'
  $query->addFilter('is_article_year', 'indexed_value');
}

```

# Answer
Figured it out. Adding the answer in case anyone else needs it. Code below...

```
function issue_archive_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id) {
  if($node->type == "article") {
    $node = node_load($node->nid);
    $journal = node_load($node->field_journal['und'][0]['target_id']);
    $document->addField('its_field_year', $journal->field_year['und'][0]['value'] + 0);
    $document->addField('itm_field_year', $journal->field_year['und'][0]['value'] + 0);
  }
}

function issue_archive_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  $query->addParam('qf', 'its_field_year');
  $query->addParam('qf', 'itm_field_year');
}

```

Using the solr\_devel module, I saw that the journal type had two fields listed in the entity/document for year, one with the its\_ prefix, and the other with the itm\_prefix. I added both of those, and added the query field (I think that's what it stands for?) parameters to the query.

This got me the exact results I was looking for.
> 0 votes

---
Tags: search
---


title: Views PHP : couldn't print dates

text:
# Question
Title: Views PHP : couldn't print dates
I'm using views php to printing, and calculate some dates in my view.but when I try to print a date (06/01/2015) in the global php field it printed like: 16831 which is the node id
Value code:

> $load=$row-\>field\_date\_loading;
> return $load;

Out put code:

> echo $value;

# Answer
> 0 votes
use

```
$load = $data->field_field_date_loading[0]['raw']['value'];
echo $load;

```

if you are using an end date as well you can get it with:

```
$data->field_field_date_loading[1]['raw']['value'];

```

---
Tags: views
---


title: Taxonomy layout on node creation

text:
# Question
Title: Taxonomy layout on node creation
I have a content type with 5 taxonomies, each with 50 terms (checkbox). All of them are available for user to choose when creating node.

It looks really long and not quite user friendly.

So i am looking a module that can make this look nice. Table, inline, anything but default would look better.

# Answer
> 1 votes
For these situations I prefer to use the Chosen jQuery plugin, which makes elements way more user-friendly. For easy intergration of this plugin with Drupal, see the Chosen module.

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


# Question
Title: Why don't links use https:// when I access the site using that protocol?
## The Problem

Accessing my site over https (the only protocol allowed) I get the content, but none of the CSS, images etc.

Drupal is creating pages in response to *https* requests that include *http* links to these resources, but it should be using *https*.

## What I've done

I have copied a site to a dev server. The site loads and basically works fine - I can log in etc. It's just that all the links drupal generates are http. The site I've copied it from also runs over https. The site does not exist on http (it would just get a Forbidden error). I've `drush cc all`.

So Apache's working - I can access the site. `.htaccess` is working (clean urls work, for example).

I'm using SNI to access the site because the server has other vhosts too, but I'm only accessing the site using the latest Firefox (and as it's a dev site and I'm the only dev, nobody else will use it).

I've done this dozens of times and am quite stumped! Why does Drupal not notice that the request came over https?

## The fix

Turns out that `.htaccess` has this to say:

> ```
> /* Base URL (optional).
>
> If Drupal is generating incorrect URLs on your site, which could
> be in HTML headers (links to CSS and JS files) or visible links on pages
> (such as in menus), uncomment the Base URL statement below (remove the
> leading hash sign) and fill in the absolute URL to your Drupal installation.
>
> ```

Sure enough, putting `$base_url = 'https://example.com';` fixed it.

**But why is this necessary?**

# Answer
I had a similar problem and ended up using `$base_url = ''`. It fixes the problem with static content. Drupal will generate relative URLs instead of absolute which is the right thing to do anyway. However, this breaks `update.php` for some reasons (running 7.38).
> 1 votes

---
Tags: 7, ssl
---


# Question
Title: How to programatically convert nodes from draft to saved
Is there a way I can convert all my imported nodes into "saved " status instead of "Draft" programmatically? Can this be done in a hook and what would the code for doing this be? If it can be done with Rules how exactly would this rule be created? This has to be something that is done without any user interaction, so Views Bulk operations is not the answer.

I am using workflow module, and it has two states, the first one is draft, the second one is "Done"

Thanks,

# Answer
> 1 votes
You can use function:

```
// If have error you need uncomment line bellow
//module_load_include('module', 'workflow', 'workflow');

// To get array nid you can use funtions
//$array_nid = workflow_get_workflow_node_by_sid(3);

function update_workflow_transition($nid) {
  // insert your node id
  // you can get array node id with db_select or function workflow_get_workflow_node_by_sid($sid)
  $entity = node_load($nid);
  $transition = new WorkflowTransition();
  $entity_type = 'node';
  $field_name = '';
  $old_sid = 2; // sid of your Draft status
  $new_sid = 3; // sid of your Saved status
  $uid = 1; // You can change with uid of author.
  $stamp = REQUEST_TIME;
  $comment = 'Your comment';
  $transition->setValues($entity_type, $entity, $field_name, $old_sid, $new_sid, $uid, $stamp, $comment);
  workflow_execute_transition($entity_type, $entity, $field_name, $transition, $force = TRUE);
}

```

You can call this function by hook\_form\_alter() when you use module feed to import node. Or you can create simple form and when submit form call this function.

**Update:** You can use hook\_feed\_after\_save

```
function YOURMODULE_feeds_after_save(FeedsSource $source, $entity, $item, $entity_id) {
  $transition = new WorkflowTransition();
  $entity_type = 'node';
  $field_name = '';
  $old_sid = 2; // sid of your Draft status
  $new_sid = 3; // sid of your Saved status
  $uid = 1; // You can change with uid of author.
  $stamp = REQUEST_TIME;
  $comment = 'Your comment';
  $transition->setValues($entity_type, $entity, $field_name, $old_sid, $new_sid, $uid, $stamp, $comment);
  workflow_execute_transition($entity_type, $entity, $field_name, $transition, $force = TRUE);
}

```

Version test Feeds 7.x-2.0-beta1

# Answer
> 1 votes
You can change Workflow status for all nodes using Views Bulk Operations module Here is a little manual how to accomplish this task:

1. Download and install Views Bulk Operations module
2. Create a view that will show content of necessary content type in table format.

3. Add in this view next fields: Content: Title, Workflow history: New state name, Workflow history: Old state name and Bulk operations: Content.

4. Open created view page, select all nodes, choose "Change workflow state of post to new state" operation and click on the "Execute" button

5. Choose new node state and click on the "Next" button

6. On the next page press on the "Confirm" button

---
Tags: nodes, rules, workflows
---


title: Drupal commenting system vs Disqus

text:
# Question
Title: Drupal commenting system vs Disqus
I like the multiple login possibility of Disqus. You can login with facebook or twitter or google etc. On the other hand, comments will exist on a 3rd party server and the package that includes the single login feature costs a lot (that mean that drupal site's users can comment without logging again at disqus system or another).

1. How I can simulate similar system on my site? How can users sign in with facebook, twitter, google, openid at my site so that they comment?
2. Is there any other feature of disqus system apart from multiple login that can be accomplished with drupal modules?

\[3. Does disqus makes site slower to load? 4. How can I move comments from Drupal to Disqus? 5. How can I move comments from Disqus to Drupal?\]

Edit: I would like an answer possibly from someone that has used both systems as advantages and disadvantages appear in the long run, and it is not easy to decide just at a fast research. I have seen sites switching from one commenting system to another because they understood the disadvantages of their choice after some months.

# Answer
Regarding question 1, there are several options to do that, for instance OpenID Selector.

Question 2: Yes. I don't know all of Discus' features so I cannot answer this for each and every one of them. However I do know that there are Drupal modules for comment notification, for instance Comment Notify.

Questions 3-5: those are quite specific, I think you'd better ask them in the issue queue of the Drupal Disqus module.
> 7 votes

# Answer
Regarding 3-5: it doesn't make page load slower. When I tried migrating my comments back from Disqus to Drupal (about a month ago), that feature wasn't working.
> 2 votes

# Answer
Might be a little late on this one, but was searching for it lately. I would recommend using Disqus commenting. I have been using drupal core commenting and ran into several issues: the major one being SPAM; while drupal core commenting system can also be extended, you need more modules (read: more server resources, more conflict possibilities, etc).

I've switched to disqus recently and have enjoyed the benefits of it. With disqus you get

1. Multi-Login
2. Spam Management
3. Simple UI
4. Comment Voting
5. Popularity based rankings
6. Comment Moderation (major one)

I wrote a full blog about it at Drupal: Best Commenting System

It's not that drupal core commenting can't do all this, but disqus does it with a single module.
> 0 votes

---
Tags: comments
---


# Question
Title: Best way to backup and restore the databases of a Drupal 7 multisite using Drush?
I'm looking for an easy way to backup (and if needed restore) the databases of a Drupal multisite using Drush.

**Drush command I use to backup all the databases:**

```
drush @sites sql-dump --result-file --gzip

```

The backup of the databases seems to work. After executing the above command, databases are automatically stored in /root/drush-backups/*DATABASENAME*/*TIMESTAMP*/*DATABASENAME\_TIMESTAMP*.sql.gz

What command can I use to restore the last backup of the databases automatically?

What is the best way to backup and restore the databases of a Drupal 7 multisite using Drush?

PS: I'm using Git, so I only need to backup databases.

Many thanks for your advice!

# Answer
This is how I do the restore on a site-by-site basis:

```
drush @site1 sql-drop -y && gunzip -c /path/to/backup/file1 | drush @site1 sql-cli

```

You could maintain a list of site aliases to database name and write a shell script to automate the process.

The database name for an individual site could be extracted as follows:

```
drush status @site1 --fields=db-name --field-labels=0

```

Unfortunately, there's no all-in-one solution for restore.

An alternate solution would be to use the Backup and Migrate module, which has drush integration. There are `bam-backup` and `bam-restore` commands which might be easier to work with.

As @Duncanmoo mentioned, it's also good to run `drush rebuild-registry` after the restore.
> 4 votes

---
Tags: drush, multi-sites, deployment, subsites
---