# Question
Title: Right way to add a field to be used as a filter in Views with ranges?
I need to add a field to a content type which is going to used as a exposed filter in Views.In this filter the visitor will see ranges. I've done this in the past and ended creating 2 fields to set both limits of a range. I need to remake this and I think this can be done in a smarter way.

What I need is:

1) create the content type: **flat**

2) add the field **price** to the content type **flat**

3) create a view **Flats**

4) create a **exposed filter** to filter by the field price but using ranges, e.g: "From 100 000 to 200 000", "From 200 001 to 300 000" and so on. I need these options to be a Select dropdown list.

Then my questions are:

* about point 2): I would create a integer type field for this, is this right and enough?
* about point 4): How do I do to create the ranges that I need? Maybe a module for this?

# Answer
> 0 votes
This module might help: Views Contextual Range Filter

Module Page Description:

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range. Numeric, alphabetical (string) and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on the "created" (posted) and "updated" (last modified) node properties is also supported, provided you use the correct format as dictated by Views. So, YYYYMMDD for full dates or one of the shorter formats, i.e. year+month, year-only, month-only, week-only or day-only. You may use the OR operator (i.e. +) and the negate operator. You negate by ticking the "Exclude" box on the Views Contextual filter configuration panel, in the "More" section.

---
Tags: views
---


title: Computed Field display only if below 0

text:
# Question
Title: Computed Field display only if below 0
In my computed field I'm trying to make it display the field and it's label only if the value is negative. If it is above 0 it should not display anything, not even field label.

So far in "Display Code (PHP)" I have:

```
if $entity_field_item['value'] < '0' { ;
$display_output = $entity_field_item['value'] . '%';
}else{$display_output = ''};

```

But it just returns the label with no value.

The classic

```
$display_output = $entity_field_item['value'] . '%';

```

works fine though.

# Answer
Try this:

```
if ($entity_field_item['value'] != 0)
 {
 $display_output = $entity_field_item['value'] . 'pkt';
 }
 else($display_output = NULL);

```
> 1 votes

# Answer
One issue that I can see is in the if condition `$entity_field_item['value'] < '0'`

You should remove the quotes from `$entity_field_item['value'] < 0` this should make the if condition as expected. But the Label would still be visible.

To remove that you would need to use the patch from the below link

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

---
Tags: entities
---


# Question
Title: SQLSTATE[42000]: Syntax error or access violation (db_insert Function)
I try to build new module in drupal 7 I try to insert some data in some where inside the code it was working in many functions but suddenly when I try to do the following

```
  db_insert('payment_request')
    ->fields(array(
      'payment_item' => $data['payment_item'],
      'change' => $data['change'],
      'via' => $data['via'],
      'userlist' => serialize($userlisthidden),
      'startdate' => strtotime($data['startdate']),
      'enddate' => strtotime($data['enddate']),
      'hash' => $hash
    ))->execute();

```

it gives me an error

```
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, via, userlist, startdate, enddate, hash) VALUES ('2', '1', '1', 'a:1:{i:' at line 1

```

I checked the table and the fields and the values every thing are correct

so I decide to insert static data like the following :

```
  db_insert('payment_request')
    ->fields(array(
      'payment_item' => 'qq',
      'change' => 'qq',
      'via' => 'qq',
      'userlist' => 'qq',
      'startdate' => 'qq',
      'enddate' => 'qq',
      'hash' => 'qq'
    ))->execute();

```

But it gives me the same error so, what i miss here, please help me

# Answer
> 9 votes
`CHANGE` is a reserved word in MySQL. PDO doesn't have a built-in function for quoting identifiers (just string literals and dates), so presumably Drupal simply hasn't tried to implement this on PDO's behalf.

Using a different column name would be the simplest solution.

# Answer
> 3 votes
Reserved Word are permitted as identifiers if you quote them.

For example:

instead of using keyword `interval` like this:

```
CREATE TABLE interval (begin INT, end INT);

```

You could try

```
CREATE TABLE `interval` (begin INT, end INT);

```

---
Tags: database
---


title: Get Views object from entity template

text:
# Question
Title: Get Views object from entity template
I have a Views, that renders nodes as "Rendered entity" with custom display mode - "cover". In template (or preprocess function) for this specific theming case, I need to get the Views object, that calls this render process, especially its arguments. How can I do this?

# Answer
> 1 votes
The "Rendered entity" row type comes from the Entity API module.

When using the node view row type the views module adds the view object to the node in views\_plugin\_row\_node\_view::render(), however the entity module doesn't do anything similar for its row type, so there is no easy way to get the view object when themeing the entity.

If your view is using a page display you can use views\_get\_page\_view() but this doesn't work with other display types, like block views for example.

Note that there is a feature request for the entity module to add the view object to the entity but it is still in development and the module maintainer wants to use a different approach.
So you could use that patch and then when a newer patch comes along you will likely need to make some minor tweaks to your custom themeing code, or you could make a new version of that patch as per the maintainers comments and then use that and possibly avoid having to change your custom code in future.

If you are comfortable updating the patch I would recommend that approach, otherwise I would recommend using the current patch and updating your custom code in future.

---
Tags: views, theming, entities
---


# Question
Title: How to prevent other roles from publishing content
I am new to Drupal. I am working on a website where I have 2 user roles: Site admin and editor.

The site admin has all permissions. I want the editor to only have the permission to edit content but not to publish or edit them. He can view his edited content but cannot publish them.

Different people suggested me different options, like use this module, use that module, but no body is showing me a neat and proper solution.

# Answer
Override Node Options overrides this functionality and it's pretty straight forward.

> The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form.
> 0 votes

# Answer
You can use Workflow,

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.

with or without Revisioning.

> Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

Revisioning contains a slightly old tutorial on using both together on its doc pages.
> 0 votes

---
Tags: users
---


# Question
Title: Get the title attribute into a lightbox frame
I've been exploring and getting somewhat close to what I want (getting the value of the title attribute into my lightbox frame) by reading documentation and this topic here at *Drupal Answers*.

I'm working with a `custom tpl.php` file with the following code (copied from elsewhere):

```
   if($id == 'field_afbeelding') {
            $samples = explode(';', $fields['field_werken_afbeelding_sampl']->content);
            $originals = explode(';', $field->content);
            for($i = 0; $i < count($samples); $i++) {
                print l($samples[$i], $originals[$i], array('html' => TRUE, 'attributes' => array('rel' => 'lightbox')));
            }
        }

```

From what I gathered in the documentation, it appears that I need to insert the `lightmodal[][]` array-thing into my code right at the end, where it says `array('rel' => 'lightbox')`.

In the *Drupal Answers* topic, the question starts off about how to insert a CCK field (or a caption or whatever) into a lightbox, but ends about how to get the title attribute.

The very last comment says - I quote : 'Type `<pre><?php print_r($node); ?></pre>` in node.tpl.php to see what's available in the node object (what fields, how formatted, etc.) and then take what you want and output it to the lightbox. I hope that's what you need..'

In my case, it's a view, so I went with devel module, going `<?php global $field; dpm($fields);?>`

Now as for 'take what you want and output it to the lightbox', the problem is I don't recognize out of these clickable Krumo blocks what I need. I do get these Krumo blocks that the devel module shows where you can click in the them and explore those elements/objects/whatever you want to call them.

I've been expanding all of the arrays and been seing 'title' in nested arrays. I guess the question boils down to what exactly must I put in this `lightmodal[][]` array if I'm right about the lightmodal thing?

And, before you ask, I made sure than in CCK, when editing the image field, I have alt and title attribute checkboxes checked and also given values to the images at hand.

# Answer
> 1 votes
There are multiple issues for Lightbox about your problem. Atm your best chance is indeed to override the relevant `tpl.php` file. This would be in the form of `views-view-field--viewid--fieldname.tpl.php`. The variables exposed in there that are of interest are the following:

* $output: The processed output that will normally be used.
* $row: The raw SQL result that can be used.

The first one indeed contains a string in the form of:

```
<a
  href="http://www.example.com/sites/default/files/styles/large/public/img.png?itok=Tn9Y1Pyo"
  rel="lightbox[field_image][]">
    <img
      typeof="foaf:Image"
      src="http://www.example.com/sites/default/files/styles/lines_thumbnail/public/img.png?itok=shRRK" alt="" />
</a>

```

The above should become something like this:

```
<a
  href="http://www.example.com/sites/default/files/styles/large/public/img.png?itok=Tn9Y1Pyo"
  rel="lightbox[field_image][<p>CAPTION</p>]">
    <img
      typeof="foaf:Image"
      src="http://www.example.com/sites/default/files/styles/lines_thumbnail/public/img.png?itok=shRRK" alt="" />
</a>

```

in order to have a caption in your lightbox.

You could of course use a replace function in order to achieve this, such as your attempted solution.

What I recommend is to use the `$row` variable to obtain the data itself and construct the output however you wish, for instance to add a title in `<a>` as well and why not solve the empty `alt` attribute value issue as well for the sake of SEO:

```
<?php
  //print $output;
  //dpm($output);
  //dpm($row);
  $caption = $row->taxonomy_term_data_name, // HERE use your field of choice
  print l(
    theme_image_style(array(
      'style_name' => 'thumbnail',
      'path' => $row->field_field_image[0]['raw']['uri'],
      'alt' => $caption,
      'attributes' => array('typeof' => 'foaf:Image'),
      'width' => NULL,
      'height' => NULL,
    )),
    image_style_url('large', $row->field_field_image[0]['raw']['uri']),
    array(
      'attributes' => array(
        'title' => $caption,
        'rel' =>
          'lightbox[field_image][<p>' . $caption . '</p>]',
      ),
      'html' => TRUE,
    )
  );
?>

```

# Answer
> 0 votes
You're using Views 3, Drupal 7 and creating a view with a fields format so you want to be using the `views-view-fields--VIEWNAME` template for row style output (all of which looks good so far). The change is that because you're using fields and not node, you won't have access to your `$node` variables within the views template and you want to use the $fields array.

Assuming that the title you want to add to the lightbox attribute is the same as the title of your node (and assuming you probably want the plain text version) you could access it as:

```
print $fields["title"]->raw;

```

If that's not the field you want, you can scan the fields array using devel with this:

```
dsm($fields);

```

---
Tags: 7, javascript
---


# Question
Title: theming a rendered entity in a view header
I reference a node into a view header (rendered entity). I need to do some changes in the output of this referenced entity.

Does anyone know the filename for the needed template?

# Answer
When an entity is rendered an entity view mode is picked. Each entity view mode can have different dispaly configuration. So, you may add a new View mode to your entity and set up the appropiate display config in the entity display page.

Then, in your view, seleect this view mode when configuring the rendered entity.

If you need further output customization you can define your own template for your View mode.

To add anew view mode you can check this question: How to add additional display(view mode) for node?

To set up a template file for your custom VIewmod you can check this question: How to provide template for particular view mode?

You can also use the full view mode, but this affect all rendered entities of this type.
> 0 votes

---
Tags: 7, views, entities
---


title: edite content type style

text:
# Question
Title: edite content type style
I clone content type by using bundle copy module, but the view of the content type never the same as the first one, how can I clone the style too

# Answer
Copy the template also. For example if you have a `node--old-content-type.tpl.php` file you'll need to copy it to `node--new-content-type.tpl.php`.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: Removed default login by mistake and logged out. Can't login
I made the mistake of removing the user login block through the web interface, and logged out.

Now, I don't have the login interface anymore. Does anyone know how to solve this or is re-installing the only solution?

Furthermore, when I access example.com/user, the log-in form is shown, but it doesn't accept my credentials anymore.

---

I think I have found the "issue": The login page on mysite/user is the default login page for mysite; however, the default login block that is displayed on the front page is the login for the Drupal 7 web interface. These two are completely separate, that is why my credentials weren't working on mysite/user.

So in conclusion, if you removed the default login block and logged out of the drupal 7 web interface, then you are in troubles.

Please correct me if I'm wrong.

# Answer
Jimajamma's answer is correct, but the real question here is: How do I hack a new password for user 1, given that I lost/corrupted/forgot my old one?

If you haven't turned off user registrations, create a new user. Now you have a password hash in your database for a known password. You could come up with some SQL to move this hash to user 1's password column, couldn't you? :-)

Then log in, change the password if you need to, delete the user you created, etc. And write it all down. :-)
> 2 votes

# Answer
You can reset the password in the database. Make sure that you hash it correctly using /scripts/password-hash.sh (or manually if you're comfortable). Just as an example...

1. `cd /site/root`
2. `./scripts/password-hash.sh "test password goes here"`

This should return something like:

`password: test password goes here hash: $S$Dq18FZ8uh1pMdNYE3YMw3wWytBULp8a54T/ixwnrn3IyeQL/bopi`
3. `drush sqlc`

This step uses drush to connect to your database. If you don't use drush, connect to your database in whichever way you are comfortable. I suggest trying drush. It is very powerful and will make many problems easier to solve and solutions easier to realize.
4. `UPDATE users SET pass='$S$Dq18FZ8uh1pMdNYE3YMw3wWytBULp8a54T/ixwnrn3IyeQL/bopi' WHERE uid=1;`

You should then be able to log in as user 1 using password `test password goes here`.
> 2 votes

# Answer
Try `http://www.yoursite.com/user`.
> 1 votes

# Answer
I dont know the reason why your credential are not working.But you can update password through the phpmyadmin. To reset your password,

1. Go to users table in your db
2. find the username root and click edit for edit that row
3. Then in the password field give your new password
4. And DON'T FORGET to use MD5 function to encript your password

If the above way is not easy to you then,

```
<?php
   db_query("UPDATE users SET pass = MD5('newpwd') WHERE uid=1");
?>

```
1. create a page and set the text format as PHP code
2. Then paste the above code with replacing new password and click preview or save
3. It will update the admin user password Here is the code
> 0 votes

# Answer
I had the same problem today , and I solved it by updating some fields in drupal's database. I went to ***Block table*** in ***drupal's database***. and executed this query :

"***update block set status = 1 , region = 'any-visible-block-name' where theme = 'current-theme-name' and module='user' and delta='login';*** "

then I returned to my website, and the authentification block appears in 'any-visible-block-name' that I specified in previous query.

Good luck and hope it help you :)
> 0 votes

# Answer
I solved the same problem by reseting the default theme to Bartik using drush:

* first, i navigated to /var/www/website\_folder and run
*drush vset theme\_default bartik*
* after that, i went to my website page and manage to login as admin
* than went to *Appearance* and set back old theme (the one that i was using when problem happend) and in *Structure* -\> *Blocks* enabled *User login* block

That worked for me.
> 0 votes

---
Tags: blocks, users
---


# Question
Title: Replacing a certain character pattern in a textfield when saving an entity
I got an entity type containing a long text field. If a user types in a certain character pattern ("xX" for example), this string "xX" should replaced with "×" (the proper symbol for multiplication) after saving the entity. I looked at hook\_field\_presave and hook\_field\_attach\_presave but don't know how to use correctly.

This is the code i tried in a custom module:

```
function replace_multiplication_symbol_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['name'] == 'field_technical_description') {
    foreach ($items as $delta => $item) {
      if (isset($item['value'])) {
        $items[$delta]['value'] = str_replace('xX', '×', $items[$delta]['value']);;
      }
    }
  }
}

```

# Answer
> 1 votes
So, hook\_field\_presave, according to the documentation, "Defines custom presave behavior for this module's field types." So unless your defining a field type in your module, this is the wrong hook to use.

Instead, your gonna want to use hook\_field\_attach\_presave. $entity\_type will contain the type of entity the save is being called from (node, user, etc). $entity is the full entity object, which you can just go ahead and edit.

For example, a very basic function like so:

```
function replace_multiplication_symbol_field_attach_presave($entity_type, $entity){
  if(!empty($entity->field_field_technical_description['und'][0]['value'])){
  $entity->field_field_technical_description['und'][0]['value'] = "test";
  }
}

```

would, whenever an enity is save, check for the field `field_field_technical_description` and switch it's value to "test," if it's value was not null.

---
Tags: entities
---


title: Creating a page per bundle

text:
# Question
Title: Creating a page per bundle
I am trying to create multiple bundles for a given entity.

However, when I'm doing this, all of my manage field and manage displays are on the same page, and it doesn't appear like any of the other pages are working.

Here's one of the bundles:

```
  $info['gov_data'] = array(
    'label' => t('Government Data'),
    'base table' => 'gov_data',
    'entity keys' => array(
      'id' => 'gid',
      'label' => 'type',
    ),
    'module' => 'gov_data_entities',
    'access callback' => 'gov_data_access_callback',
    'fieldable' => TRUE,
    'bundles' => array(
      'bill' => array(
        'label' => t('Bills'),
        'admin' => array(
          'path' => 'admin/structure/gov-data/bill',
          'real path' => 'admin/structure/gov-data/bills',
          'access arguments' => array('administer site configuration'),
        ),
      ),
  'committee' => array(
    'label' => t('Committee'),
    'admin' => array(
      'path' => 'admin/structure/gov-data/committee',
      'real path' => 'admin/structure/gov-data/committee',
      'access arguments' => array('administer site configuration'),
    ),
  ),
),
    'admin ui' => array(
      'path' => 'admin/structure/gov-data',
      'controller class' => 'EntityDefaultUIController',
    )
  );

```

There are about 6 or 7 more exactly like that.

Why are they all showing up on the main entity page?

How do I organize this so that it looks like content types?

EDIT: Here's my hook\_menu() for the person asking:

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

  $items['admin/config/services/gov-data'] = array(
    'title' => 'Government Data settings',
    'description' => 'Configure settings for Government Data',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('gov_data_admin_settings'),
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

```

# Answer
> 1 votes
> Why are they all showing up on the main entity page?

This is the easy part. I had the same issue with https://www.drupal.org/node/2299755, but I was dealing with several modules that were each defining a single entity. Your configuration is a bit more complicated.

You are seeing the UI elements for Manage Display and Manage Field at admin/structure because admin/structure/gov-data doesn't exist. admin/structure is inheriting everything you've defined after admin/structure/gov-data like admin/structure/gov-data/bill/fields and admin/structure/gov-data/bill/display, First you need to define a menu path for admin/structure/gov-data in your module, but this will only push all of the fields and display tabs up to that level. You'll also need to either define a redirect for each entity so admin/structure/gov-data/bill goes to admin/structure/gov-data/bill/fields or alter the admin/structure/gov-data/bill/fields and display menus so they aren't tabs.

> How do I organize this so that it looks like content types?

This is a bit more complicated. The display of node types found at admin/structure/types doesn't just automagically appear. It is defined in the Node moduels's menu hook http://cgit.drupalcode.org/drupal/tree/modules/node/node.module?h=7.x#n2004. To get something that looks like the content type list, you'll need to create a customized version of the node\_overview\_types() function found in http://cgit.drupalcode.org/drupal/tree/modules/node/content\_types.inc?h=7.x#n8

So for your configuration, alter your hook\_menu to add something like...

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

    $items['admin/config/services/gov-data'] = array(
        'title' => 'Government Data settings',
        'description' => 'Configure settings for Government Data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('gov_data_admin_settings'),
        'access arguments' => array('administer site configuration'),
    );

    // returns list of entities with menus "under" gov-data.
    $items['admin/structure/gov-data'] = array(
        'title' => 'Manage Government Data Entities',
        'description' => 'Links to manage field and display of entities',
        'page callback' => 'gov_data_overview_types',
        'access arguments' => array('administer gov data'),
        'weight' => -50,
    );

    return $items;
}
/**
 * Displays an entity type admin overview page.
 * Borrow from node/content_types.inc
 */
function gov_data_overview_types() {
  // This requires a lot more work
}

```

There is a lot of code you can repurpose from node\_overview\_types(), but that is something you can figure to meet your specific needs. You biggest issues here are undefined menu paths being displayed at a level you didn't expect because the deeper, custom menu paths aren't defined anywhere.

---
Tags: entities
---


title: Problem with custom token

text:
# Question
Title: Problem with custom token
Below is the code I am trying to get implemented for a custom token module. The purpose of the token is to work in conjunction with the \[field\_display\_name\] token for the comment author's name for a recent comment block (created be Views). I am using tokens in the rewrite results option of (Author) User:link Field in the View. The plan was to add this new token to the comment tokens so that it would show up in the View field's rewrite results replacement patterns. The token replacement pattern would be \[field\_display\_name\]\[commenter-count\], with the intended final output being one of the following options:

No additional commenters -\> just the comment author's name i.e. "John Smith" One additional commenter -\> "John Smith & 1 other" More than one additional commenter -\> "John Smith & 2 others"

I have enabled the module, and I am not getting the new token showing up in the replacement pattern options. I'm not sure if this is a code issue or a Views settings issue. I am suspicious that the argument ($nid) for the commenter\_count API function to perform the query is not being passed in from the current node. Any help would be appreciated.

Thank you in advance.

```
<?php
/**
* @file
* Extends the comment modules tokens to include a token (commenter-count).
* To be used in conjunction with the [comment:author] token.
*
* When Enabled this module creates a token that counts all commenters
* of a node and returns one of 4 possible strings:
*
*  Case 1 - No commenter   - returns False.
*  Case 2 - 1  commenter   - returns Null.
*  Case 3 - 2  commenters  - returns string: "and 1 other".
*  Case 4 - 2 commenters  - returns string: "and # others".
*/

/**
* Get number of commenters for a specific node.
*
* @param $nid
*  Node-id to count commenters for.
* @return $commenter_count result an integer, or FALSE on error.
*/
function commenter_count($nid) {
  if (isset($nid)) {
    // Retrieve the number of commenters for the current node-id.
    $results = db_query('SELECT COUNT(DISTINCT uid) FROM {comment} WHERE nid = :nid',  array(':nid'=> $nid))->fetchField();
    if ($results->uid < 1) {
      $commenter_count = '';
    }
    elseif ($results->uid == 1) {
      $commenter_count = t('& 1 other');
    }
    else {
      $commenter_count = t('& @num others', array('@num' => $results->uid));
    }
    return $commenter_count;
  }
  else {
    return FALSE;
  }
 }

/**
* Implements hook_token_info().
*/
function commentor_count_token_info() {
  $info['tokens']['comment']['commenter-count'] = array(
    'name' => t('Commenter count'),
    'description' => t('This token counts the number of commenters of a given node.')
  );
}

/**
* Implements hook_tokens().
*
*/
function commenter_count_tokens($type, $tokens, array $data = array(), array $options =      array()) {
  $url_options = array('absolute' => TRUE);
  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }
  $sanitize = !empty($options['sanitize']);
  $replacements = array();
  if ($type == 'custom') {
    foreach ($tokens as $name => $original) {
      switch ($name){
        case 'commenter-count':
           $replacements[$original] = commenter_count($node->nid);
          break;
      }
    }
  }
  return $replacements;
}

```

# Answer
A token like \[field\_display\_name\] in the rewrite results option for the display of a Views field is not the same as a token everywhere else in Drupal, so hook\_token\_info() and hook\_tokens() won't help you. On behalf of Drupal, Views, and the million or so other available words in the English language, i apologize.

Instead you need to extend a Views field handler class and override the document\_self\_tokens() and add\_self\_tokens() methods. You can instruct a field to use your custom field handler via hook\_views\_data\_alter() (thanks to Daniel Wehner for this info, and very likely the hook itself).

You can see example code from my need for adding a Views field replacement pattern / token.

If you need help adapting it for your need above let me know and i'll write that here, but the remember to list in your .info the file with your field handler extending class so that Drupal registers it, and it'll work fine.
> 1 votes

---
Tags: tokens
---


# Question
Title: How to create a view displaying a list of users who have logged-in user's preferences
How does one create a view that filters users so as to display those with preferences of the logged-in user (the one viewing them)? I'm using Drupal 7.34, Views 3.

E.g. A user selects a preference on sign up, such as "**i'm interested in a man**". How do you create a view that will show this user a list of users who selected "**I'm a man**" on their own signups. Think of it as matchmaking.

I came across this discussion but didnt figure out this comment. All the articles out there don't seem to address this clearly.

I'm certain there is a contextual filter move I'm missing. Please help.

# Answer
> 1 votes
I had same issue but solved by using this custom code in view. I was using profile2 module for registration so as per sex field, I was done this :

```
global $user;
$profiles = profile2_load_by_user($user);
foreach ($profiles as $profile) {
  if ($items = field_get_items('profile2', $profile, 'field_seeking')) {
    break;
  }
}
   return $items[0]['value'];

```

Please check my Post **HERE**.

As per my post I was do this :

```
global $user;
    $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile)
    {
        if ($items = field_get_items('profile2', $profile, 'field_sex'))
      {
            break;
          }
    }

    $i_am=$items[0]['value'];

    if($i_am=='sdmale' || $i_am=='sbmale')
    {

    $looking='smfemale+sbfemale';
    }

    if($i_am=='smfemale' || $i_am=='sbfemale')
    {
    $looking='sdmale+sbmale';
    }
    return $looking;

```

---
Tags: views
---


title: Custom Page Create

text:
# Question
Title: Custom Page Create
I create page--hospital.tpl.php file. To call this page, then I create Basic Page and Page title is "Hospital". I provided on the Menu Link and I typed "hospital" in URL path alias. Then, Save the file.

The problem is that when I click on the "Hospital" menu link it only shows the basic page content and it **doesn't show up** my page--hospital.tpl.php file. Please,help me !

Thanks.

# Answer
To understand how to use Theme Hook Suggestions, please refer to the documentation at: Drupal 7 Template (Theme Hook) Suggestions

> **node--\[type|nodeid\].tpl.php**
>
> base template: node.tpl.php
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> node--nodeid.tpl.php
>
> node--type.tpl.php
>
> node.tpl.php
>
> **page--\[front|internal/path\].tpl.php**
>
> base template: page.tpl.php
>
> The suggestions are numerous. The one that takes precedence is for the front page. The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for. Keep in mind that the commonly-used Pathauto module uses path aliases.
>
> The front page can be set at "Administration \> Configuration \> System
>
> > Site information." In Drupal 6, at "Administrator \> Site configuration \> Site information." Anything set there will trigger the suggestion of "page--front.tpl.php" for it.
>
> The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:
>
> 1. page--node--edit.tpl.php
> 2. page--node--1.tpl.php
> 3. page--node.tpl.php
> 4. page.tpl.php

It can be done in a variety of ways (at the page level as well). You can also provide your own suggestions in a preprocess function.

In your case you have not defined a new content type, but have used the Basic Page type, and you want to do it for a single page only. You therefore need to get the node id of your page, and then override as follows:

```
node--nodeid.tpl.php

```

or

```
page--node--nodeid.tpl.php

```

In your case, as you indicated that you wish to override the page.tpl.php file, it will be the latter.
> 4 votes

---
Tags: theming, path-aliases
---


title: Receiving http status code 406

text:
# Question
Title: Receiving http status code 406
I have created a custom module in Drupal 8 and added the routing table to mymodule.routing.yml. Whenever I am trying to hit a particular path, I am receiving the HTTP response "406 (406 Not Acceptable)."

What is causing this?

# Answer
You need to return a Response object or a render array from a controller.
> 3 votes

# Answer
I got the answer either use #markup as key e.g

$element\['#markup'\] = "hello world";

2nd option :

$content = array(); $content\['fruits'\] = 'Apple'; $content\['vegetable'\] = 'Onion'; $content\['message'\] = "Hello every one this First template of Drupal 8 ";

```
 return array(
   '#theme' => 'hello_show',
   '#content' => $content,
 );

```
> 0 votes

---
Tags: 8, routes
---


# Question
Title: How to show both currencies at once in the node page for price field
I am using Drupal commerce kickstart, Here I have two types of currencies like $ and INR. In the node page I am showing INR currency by default. Using Curreny Selector Module I am showing Dropdown to select the currency. If currency selected by user then calculated $ currency is showing fine. But here I need to show both prices at once. For example, "Rs.1205 & $20" at once without selecting the currency from dropdown. I am loading this node page programmatically. So I want to load the currency programmatically which is converting through European Bank. Any Suggestions please.

# Answer
Commerce Multicurrency does exactly that.

> This module enhances some of the multi-currency capabilities of Drupal Commerce.
>
> Current features:
>
> 1. UI for fine granular definition of exchange rates. (Every currency combination can be defined separately if needed) Synchronization of currency exchange rates directly from the European Central Bank (ECB).
> 2. UI to specify which rates shall be synchronized and which are handled manually.
> 3. Generation of currency specific price fields inclusive generation of rule-set to handle them.
> 4. hooks for easy integration of custom currency exchange rate sources.
> 0 votes

---
Tags: commerce
---


# Question
Title: Sandbox module doesn't show any download link
I've recently developed a module, Drupal to SugarCRM Lea', and decided to contribute to community. I've followed every steps on drupal.org to do so. I have managed to upload all my code to the sandbox, but my project page is not showing any download links for my module.

What did I forget to do?

# Answer
> 1 votes
Sandbox projects may not have releases.

There is a "Has project releases" checkbox, in the "Releases" vertical tab when you edit your sandbox, but it will be automatically cleared.

Thus it is not possible, but if you wish, you can apply for full project access.

---
Tags: community-official-site
---


# Question
Title: Rendering field groups (not individual fields)
I am using Field Group to group my fields. Purpose of this is to have better control when rendering them inside the node.tpl.php file. Specifically, I want to designate in the node.tpl.php where in the html document I want specific groups of fields rendered, while sorting fields and designating what fields belong to what group inside the UI.

Do you think Field Group is a good way of achieving this? If grouping fields using Field Group, how do you then render that group in the template file?

Edit: I am steering towards template solutions, avoiding the likes of Panels and DS.

# Answer
> 3 votes
I ended up using `hide()` on content elements I wanted place independently before `print render`ing the rest of content. As I have learned the way drupal renders/prints makes this very easy. Example:

```
<?php hide($content['product:title']); ?>
<div>
  <?php print render($content); ?> <!-- $content['product:title'] is not output -->
</div>
<div>
  <?php print render($content['product:field_image']); ?>
</div>

```

# Answer
> 1 votes
In Drupal 7 it's easy to render group or individual field of groups in template file for theme

If want to render full group with subgroup then `print render($content['group_cruiseline_ships'];`

If want to render only subgroup then `print render($content['group_shop']['product'];`

If want to render only specific field of subgroup or group then `print render($content['group_shop']['product']['field_keyboard'];`

thanks.

# Answer
> 0 votes
I use field groups' div type with display suite to stack my fields for better CSS control. No need to go into template files.

Here you can see how I have wrapped the fields in field groups with divs https://www.evernote.com/shard/s272/sh/976bd05c-8b35-41d3-aad1-107ede26de09/a0d68b931e6093b9ea27a1cd5d952420

Here is the html-code: https://www.evernote.com/shard/s272/sh/0e695fad-6a47-4249-9110-2c79a1999c73/aa7f981b606e977a38b70d61cf94dd6c

---
Tags: entities, theming
---


# Question
Title: using hook_user() to capture user actions
I am trying to create a method to log the actions of users, specifically when they log in and out. I am using `hook_user()` method to do this. This is my code.

```
function mymodule_user($op, &$edit, &$account, $category = NULL) {
     switch ($op) {
        case 'login':
            //log to db
           break;
         case 'logout':
           //log to db
            break;
    }
}

```

There are two problems with this code, and I can't figure out how to fix them.

When a user password is expired, and they attempt to log in, they are redirected to their profile page to change their password. In this event, `$op` is never "login" and, as such can never be loaded. Instead, $op = "load" but it is useless to log this as this hook gets called nearly 50 times (storing that much data would be to much). Is there a better way to capture this event?

Second, when a user logs out (`$op = 'logout'`) all the other information about the user is lost: The `$account` array only has empty values (and I need the user ID). Is there a way to capture the logout event and know the user ID?

# Answer
hope you are trying for drupal 7, there are hook for login and logout, hook\_user\_login and hook\_user\_logout respectively. the user id available for logout hook so you can populate the data you want about user.
> 0 votes

---
Tags: 6, hooks, users
---


title: Create a template file for view field?

text:
# Question
Title: Create a template file for view field?
How do I create template file for view field, My view machine name is *page\_search* and field name is *room type*.

# Answer
* First look into Theme information in views:

* In Row style output, copy one of the template names:

* This lists all available **.tpl for your views** and now Create an empty php file with your chosen template name in your **themes template folder**.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Allow non-admin users to view an EntityForm submission
I've created an EntityForm wich authenticated users can submit.

Then I've created a view wich list every entityForm submissions and everyone can see this view.

Now I want to add a field to this view. This field will contain a link to this specific EntityForm submission.

2 solutions: -Display the direct link "Entityform Submission: Link" -Display an URL "Entityform Submission: URL"

As an admin:

Those solutions both work, but only as an administrator!

The link is invisible for non-admin persons. The URL leads to a "Access denied - You are not authorized to access this page."

As a non-admin:

Question : How can I allow non-admin users to access entityForm submission pages?

Thanks!

# Answer
> 0 votes
By creating a new permission maybe ? Then create the access page via an menu item with the new permssion you created Give this permission to non authenticated users then.

---
Tags: views, entities
---


title: Turning View into flashcard

text:
# Question
Title: Turning View into flashcard
I am working on a requirement to display a 2 column (question and answer ) view into flashcard . question should appear on front and on flipping the answer should appear . I am not sure whether such kind of thing can be done with view , If there is any custom module that needs to be written , what should be the approach taken for such requirement.

Thanks for any pointer on this

Pks

# Answer
Views can render both question and answer. Beyond that you need jQuery and CSS for the hide/show/flip effects.
> 0 votes

---
Tags: views, javascript
---


title: Drupal 8 field API vs. $form_state

text:
# Question
Title: Drupal 8 field API vs. $form_state
I am creating a field with Field API, and having it shown on user registration form. However, I need its value in order to make validation. For that purpose, I've used `dpm($form_state)` which gave me the dreadful, dreadful memory exhaustion error. I then used `file_put_contents(' sites/default/files/debug.txt', print_r($form_state, TRUE));` which did not produce anything at all. I also tried a few suggestions made on IRC, among which are \`$form\_state-\>getValue(\['field\_tckn'\]). It seems I can't get what my field's value is, no matter what I do; and all I get is that the field is required when I fill it in; and I'm all out of ideas. Can you recommend anything else?

# Answer
Taken from http://www.drupal.org/node/2350819:

If you import a field, it automatically goes into the disabled section because the fact that a field is shown or not is now stored in the entity display config entities, which fields do not now anything off. I should check what our default behavior is, but this is probably by design - which makes sense actually. And if not, it'll be a feature request.
> 1 votes

# Answer
You should be able to inspect all values in $form\_state with the getValues() function. I was able to successfully inspect with the following after also running into the Out of memory error:

```
dpm($form_state->getValues());

```
> 0 votes

# Answer
It seems there is a bug with the field system. I'll try again when it is fixed. The bug in question is http://www.drupal.org/node/2350819.
> 0 votes

---
Tags: entities, 8
---


# Question
Title: How to add form fields dynamically using webform
Using webform 3 module, is there a way to dynamically add more fields or do these fields have to be created in the database first? Currently that's what I am doing and with javascript toggling the css display attribute to show or hide fields.

# Answer
See this question and the accepted answer over at Stack Overflow: https://stackoverflow.com/questions/13592932/drupal-6-x-add-more-module-no-end-to-adding-more

Basically, the answer is no. This issue (354381) addresses the problem. From the module's author:

> \[...\] there is no progress on this subject. The ability to support multiple values requires a tremendous amount of re-architecting, including changes to the way CSVs are generated, analysis, the database structure, and the UI (both for administrators and users). I wouldn't expect this feature to be added any time soon.

A possible workaround is provided at the StackOverflow question linked above. In summary, you could create a content type (or, for Drupal 7, a block type using BEAN might be slightly more appropriate). And then give anon users permission to create that entity - simulating a webform.
> 0 votes

# Answer
You can use Webform Add More module to dynamically add more fields in webform. The project page says:

> Webform Add More enables selected fieldsets to be initially hidden and progressively shown with an Add more button, mimicking CCK multiple fields. This module adds a checkbox setting to webform fieldset components to select which should have Add more functionality, as well as an advanced setting to override the button label per Webform
> 0 votes

---
Tags: 7, webforms
---


title: Get the views filter's value

text:
# Question
Title: Get the views filter's value
I'm building a views that has a PHP field with SQL queries.
I wondering if I can get the date filter value to use it in my select statement?

# Answer
Take a look at hook\_views\_query\_alter(). You can grab exposed filter values by inspecting `$_REQUEST` and grabbing the appropriate value from that array. I usually implement hook\_views\_query\_alter and just wrap the query in a `dpm()` call (from the Devel module) so I can browse the array.

If using AJAX in your views, you'll need to refresh the page after you filter your view before Devel can print the array in your messages.
> 0 votes

# Answer
I think you can use hook\_views\_pre\_view() for that. That hook runs early and you can get filters, fields, arguments... and so.

1. Get the view object at hook\_views\_pre\_view() time.
2. Get the filter (date) and the field (php code) using get\_item() from the view. You can take a look at views\_object\_tyes to see all kind of items you can get.
3. Look for date values and modify the php field.
4. Update the view items (in this case the php field) using set\_item() .

I wonder if you should better add the php code field (sql queries) programatically, using add\_item() function.

```
<?php
function my_module_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_view_display') {
    // $view_filters = $view->get_items('filter', $display_id); If you want to take a look at all the view filters
    // $view_exposed_filters = $view->exposed_input; If you need them.
    // $view_contextual_filters = $view->get_items('argument', $display_id); If you need them;

    $my_date_filter = $view->get_item($view->current_display, 'filter', 'my_date_filter');
    $my_sql_query_field = $view->get_item($view->current_display, 'field', 'my_php_field');

    // Do some stuff like:
    // Look for your values in $my_date_filter
    // Set some values in $my_sql_query_field

    // Tell drupal about the changes you've made.
    $view->set_item($view->current_display, 'field', 'my_php_field', $my_sql_query_field);
  }
}

```

I have never tried with date filters, but I think it should work.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Temporary files directory not fully protected .htaccess
I've been getting this error on my status page since I updated to 7.24 (I'm on 7.34 now).

I do have my other files directories protected. I just am having a real hard time figuring how to shut this one off. I've checked at admin/config/media/file-system for the temp file directory, and it's set to /tmp. I think that's the default. But I checked /tmp, no file of that name exists, nor is it in my sites/default/files.

Nothing seems to be broken, at least with file manipulation and storage, so it seems like Drupal is handling things fine, I just am not sure where this folder is supposed to be, or if it's supposed to be a physical file, and if not, how can I protect it with a .htaccess file if it's not a physical folder.

# Answer
Ugh, so I just realized that the directory was /tmp, not tmp. Meaning that directory is at the root of the file system, not at my site's root. I checked at / and low and behold, there is my tmp folder. Now I know where to place this .htaccess file.
> 0 votes

---
Tags: 7, security
---


# Question
Title: Why are we getting anonymous account creation on a site where this is turned off?
On one of our Drupal 7 sites (it's at v. 7.32) we're getting occasional 'bot based account creation requests. This is an information-only site where regular users will never log in, only administrators should be allowed to create accounts and only administrators and content creators can log in.

In Configuration under People "Who can register accounts?" is set to "Adminstrators only." Is that not sufficient to stop this from happening?

The accounts are being created but the admin email is being contacted to approve them, so these users are not actually able to log in, but we'd like to stop this account creation altogether.

Has anyone ever seen this?

# Answer
> 0 votes
Does your drupal version is up to date ?

Versions before 7.32 need a fix to protect your Drupal from SQL injection ...

https://www.drupal.org/SA-CORE-2014-005

Theres a link to a patch if you cant do the full update

---
Tags: users
---


# Question
Title: How do I use "drush make" modules with a local module code?
I got to love the workflow "drush make" gives us. I am sure there are others who would want their development code to be put into a make file with it not being ready for drupal.org, for example, deploying a new development testing instance of the site quickly with a bash script or from what I have seen in Aegir.

It seems the current workflow that may suit this would be to utilize a git repository of your development code. However, my development machine is Windows 7, and I would like to use "drush make" in a virtual box with an Ubuntu server instance.

# Answer
> 10 votes
Drush make also supports file:/// protocol

```
projects[my_proj][type] = "module"
projects[my_proj][subdir] = "custom"
projects[my_proj][download][type] = "git"
projects[my_proj][download][url] = "file:///path/to/my_proj.git"
projects[my_proj][branch] = "dev"

```

Use sshfs to mount the repository inside virtualbox. Guide here - https://help.ubuntu.com/community/SSHFS

# Answer
> 10 votes
You can set up local domains and local git repositories or tarballs like so:

```
projects[my_module][type] = "module"
projects[my_module][download][type] = "file"
projects[my_module][download][url] = "http://localhost/my_module.tgz"
projects[my_module][subdir] = "contrib"

```

Then in your build script you could just recreate the tgz

# Answer
> 1 votes
You can install make\_local, which extends `drush make` capabilities to also source modules from directory trees. Use it like this:

```
projects[my_proj][type] = "module"
projects[my_proj][subdir] = "custom"
projects[my_proj][download][type] = "local"
projects[my_proj][download][source] = "../relative/path/to/my_proj_dir"

```

**Advantages over "normal" `drush make`:** **(1)** In contrast to `file://` URLs, you can use relative paths. **(2)** You do not need to package your module into a `.tar.gz` beforehand, or to source it from a git repo directory. A normal directory is enough.

The directory with the module *could* be a git repo of course, but does not have to. (In your case, a Windows 7 host OS directory that is accessible via VirtualBox shared directories would do. No need to install `git` inside the VM.)

# Answer
> 0 votes
in case you drush-make a distro from a gitweb site via build makefile take care to quote the url as it contains semicolons, my question about that was here on drush make on local gitweb raw url

---
Tags: drush, version-control
---


title: Rules > Send mail to product's creator?

text:
# Question
Title: Rules > Send mail to product's creator?
I tried to use a rule found in another topic (https://www.drupal.org/node/2050565), but it doesn't work. I want to send an automatic email to the product's creator, when the product is sold.

```
{ "rules_send_email_to_product_owner" : {
"LABEL" : "Send email to product owner",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "data_is" : {
      "data" : [ "commerce-order:commerce-line-items:0:type" ],
      "value" : "product"
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:commerce-line-items:0:commerce-product:creator:mail" ],
      "subject" : "Test mail",
      "message" : "Test mail nr 1",
      "from" : "Sender",
      "language" : [ "commerce-order:state" ]
    }
  }
]

```

} }

Any help would be greatly appreciated :)

# Answer
> 1 votes
# You need to debug the rule!

This is not a direct answer but can help you find the problem. And it is too long to post as a comment. You should follow these steps regardless of other similar rules working (a teeny tiny difference can be causing the rule to fail).

# Required tools

Install the devel module. but **NOT** on production site, only on your development site. It will add an extra action to rules `debug a value` under *devel* section.

# Is the rule actually triggered?

**Method 1:** Add a simple action, `display a message` and enter a simple text. Do the required actions actually needed to fire the rule (buy a sample product). Is the message displayed or not?
**Drawback:** If the message is not displayed, you wont actually know if the action is not triggered OR there is some error in rule definition, preventing the rule engine from executing it.

**Method 2:** Go to `admin/config/workflow/rules/settings` On your site, there is a checkbox to enable rules debugging. It's something like `dpm()` but for rules only with helpful information. Whenever a rule is triggered, all the thing happening (or failing) will show up in the debugging area. If something has failed it will be printed in red so you can easily find it.
**Drawback:** Can get annoying going through the rule stacktrace :|

**If it's not firing:**
There should be something wrong with the event/conditions you have set, Or a fatal error in the rule action definition. If the later find it with method 2 above.

# Are the data you are using not null and valid?

* Temporarily remove the condition `commerce-order:commerce-line-items:0:type`. Since you are working on development site this should not be a problem. In the actions (**Important:** *In the beginning, as the first action*) add the action `debug a value`. the value to debug would be `"commerce-order:commerce-line-items:0:type`. Go and buy the sample product, the rule should fire, and *devel's debug a value* would print the `type`. Check if it is set and is what you want it to be.
* Do the same for `commerce-order:commerce-line-items:0:commerce-product:creator:mail`.
* Do the same for `"language" : [ "commerce-order:state" ]` --\> **However this sounds fishy!** why would you set the language as the state?!! You should read the language from user entity (the creator).

Have fun debugging rules!

---
Tags: commerce, rules
---


# Question
Title: form validation messages are not rendered immediately
I have a form, with multiple (ajax) components. I have added a simple button in the middle of this form, to validate custom fields.

```
$form['fieldset_2']['forward'] = array(
  '#type' => 'button',
  '#value' => t('Forward'),
  '#name' => 'btn_forward',
);

```

As expected, button call validation function in which I check if all values are correct.

1. The validation messages are not rendered immediately. I have to refresh page to get the error messages. The button doesn't use ajax.
2. I have a field type radios and form\_set\_error doesn't color the element with red or something.

# Answer
> 5 votes
The problem is that Drupal has already finished setting messages for the current request when it gets to processing your form. To get things working properly call `drupal_get_form` in template\_preprocess\_page:

```
function myThemeOrModulename_preprocess_page(&$variables) {
  // For node templates.
  // $variables['node']->my_form = drupal_get_form('form_name');
  // For page templates.
  $variables['my_form'] = drupal_get_form('form_name');
}

```

Then render the form in your template file:

```
<?php print render($my_form); ?>

```

There was another issue for which I don't know the cause of currently, but adding `$variables['messages'] = theme('status_messages');` (see theme\_status\_messages) inside the same `preprocess_page` function solved it.

# Answer
> 0 votes
I've run into similar situations when trying to render webform blocks from within TPL files. One solution is to create a unique region for your form. Then assign a block (webform block, custom module block or create a PHP block with your drupal\_get\_form() code) to the new region for the specific node only. Render your new region in your page.tpl and you should be good to go.

---
Tags: ajax, forms
---


title: Commerce and Attribute Quantities

text:
# Question
Title: Commerce and Attribute Quantities
## Our Goal

We're creating a book product. It comes in a variety of sizes (ex. 5x5, 8x8, 10x10) with 20 pages included. We're using the size as an attribute field. Customers can order a standard book, or add additional pages up to 100 total pages. Additional pages are priced /page and /size; for example 5x5 = $1.00/page, 8x8 = $1.50/page etc. The "Add to Cart" section should look something like this:

===========================

## BOOK

* Size \[5x5\]
* Pages \[ enter amount \]

**Total:** $75.00 **\[Add to Cart\]**

===========================

The simplest solution would be to add a pricing option with its own quantity field, except that functionality doesn't seem to be available.

## I've considered the following:

* **Commerce Option I:** Creating a pricing attributes option (select list or radio button styles as a slider). The only caveat is the admin on adjusting pricing for 4000 options (50 books with 80 page options each) is a usability nightmare.
* **Commerce Option II:** Creating a pricing attributes integer field (acting as a quantity field) and using Rules to do the math and adjust the pricing. Unfortunately the variables and math did not seem to be available to Rules.
* **Commerce Product Bundle:** Creating a pages product variation and using page size as an attribute field. That would allow us to leverage the quantity field in the bundle's add to cart display. The problem in this case is two fold:
    1. Having to create 3 product variations, then having to create at least 2 products (book and book/pages bundle; 3 if you have different papers or page pricing needs to vary) each time you add a new book to your collection. This very quickly creates something close to an administrative hell for the shop owner.
    2. Commerce Product Bundle is still in Alpha, and has been for 2 years. No commits have been made in over a year. The module, even though it often works well, is buggy and doesn't play well with Commerce Option; which we leverage quite substantially.
* **Custom Line Item:** Using Randy Fay's "custom line item custom discount technique" leveraging an integer field and rules. I added an integer field to the product variation for cost per page. Then created an integer field which needed to be exposed to the customer. Using the combination of both I attempted to create a rule which calculated the additional price based on the product of the those fields. It does not appear that this is possible using Rules.

## Conclusion, and request for additional brain power

I've gone around multiple circles trying to figure this one out and am about to go completely bonkers. Perhaps I'm missing something completely simple, or I'm approaching this problem from the wrong angle. Has anyone been able to do something similar? How did you achieve it?

# Answer
Commerce by default supports line item fields that can appear on the Add to Cart form. If you only sell this one type of product on the site and will always need that "additional pages" field, then you could just add the field to the default product line item type. If you have other needs, you'd use a custom line item type either defined in code or created via https://drupal.org/project/commerce\_custom\_product.

Once you have customers putting in their custom number of pages, it's up to you to adjust the price accordingly. Pricing rules receive the full line item object for price manipulation, including the values of any line item fields present on the Add to Cart form. You can construct a variety of rules that look at the referenced product to determine how much to charge for additional pages and work it out using the Rules actions to create data values.
> 1 votes

---
Tags: commerce
---


title: Changing url of exposed filter

text:
# Question
Title: Changing url of exposed filter
When I used an exposed filter the filter selection is passed as name/value pair in the url, for example:

```
members?field_a=valuea&field_b=valueb

```

How can I set it up to use more of a "pathauto" style url:

```
members/valuea/valueb

```

# Answer
A colleague of mine created a module called path data a while back. His intentition was to solve this very problem. Unfortunately it has turned out that it conflicts with regular path aliases, so it will work on a site like drupal.org that doesn't use aliases, but *will* break links on a path-alias using site.

Currently, it's my belief that the only generic way to solve this issue is either manipulating the URLs at the httpd layer, or using hook\_url\_inbound\_alter and hook\_url\_outbound\_alter. You can read a bit more about the mentioned hooks at this question.

However, if I were to give this another shoot myself, I would attempt a Views specific solution instead, as this problem is common enough that it could be justified to have a module for this.

In hook\_views\_pre\_build, one could take data from a url like "members/valuea/valueb", push these values into $\_GET\['q'\], let views build it's query seeing the get arguments "in the url", then possibly remove them again in hook\_views\_post\_build.
> 9 votes

# Answer
There is a module, Query Parameters To URL, that I recently released that addresses the issue you are describing:

> This module provides the ability to rewrite URL query parameters into Clean URL components on specified paths.

You can configure which paths should have their query arguments rewritten as clean URL components using a simple regular expression, or by implementing a module hook.

That way you can transform a Views exposed filter URL like

http://example-site.com/events?field\_category\_id\[0\]=100&field\_category\_id=101&field\_author\_name\[0\]=John&field\_author\_surname\[0\]=Doe

into http://example-site.com/events/p/field\_category\_id/0\__100--1\__101/field\_author\_name/0\__John/field\_author\_surname/0\__Doe

Underneath it uses hook\_url\_inbound\_alter, hook\_url\_outbound\_alter, and hook\_init with redirects where necessary.
> 4 votes

# Answer
From the programatically perspective, you can always use hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter() hooks for that.

You can give a try to Query Parameters To URL module or if you're using Search API and Facets, you may use Facet API Pretty Paths.

You can also convert your view to use arguments in your path and use Redirect module.

Apart the above, there is no easy way to achieve that, as there is still pending feature for Drupal 8; see Allow query strings in URL aliases.

When you're using panels which uses views and in example better exposed filters, you can do some few hacks like (URL example: /panel\_url?category=123):

```
/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path) {
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}

```

For more information, please see Passing Argument from URL in Panel to View Pane or Block.

Finally, you can use hook\_menu() to define your custom menu callbacks and load your view programmatically.
> 1 votes

# Answer
Exposed filters are forms, which means that the place where they are redirecting ("action" attribute), needs to be known before user will choose any option. So we cannot redirect him to any pretty URL that contains information about his choice. The workarounds:

1. JavaScript. Use JavaScript to alter on the fly "action" attribute of exposed filter form based on options that user chose, and set "action" to URL of proper view with proper contextual filters configured. But I doubt it would be "SEO friendly" then (please someone correct me if I'm wrong).
2. Do double redirect. By using hook\_form\_alter, after getting the form, redirect user to url of proper view, with proper contextual filters configured, based on his input. This may actually need a user confirmation on some browsers, so it may be extremely annoying.

In both above methods, you would need to use https://drupal.org/project/views\_expost to change method of those forms to POST, so variables won't pollute users URL.

The bottom line is that if you need to have pretty urls with exposed filters - you are probably doing something wrong. Because I think they are just for filtering data, and should not be used to define new pages on website. If you need that - you can create a view configured to be a menu, and urls in that menu, would redirect user to the same view he is now, but with different contextual filters.
> 1 votes

# Answer
You could use the following code.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "abcd") {
    $form['#submit'] = array('custom_search_redirect');
  }
}

function custom_search_redirect($form, &$form_state) {
  $form_state['redirect'] = "members/valuea/valueb;
}

```
> -1 votes

---
Tags: 7, views
---


# Question
Title: FlexSlider, Media Galleries, & Nodes (entity reference)
If this has been asked before I apologize.

I'm somewhat new to Drupal but I know enough to dig myself a hole trying to find a solution to an idea.

I would like to use entity reference to display a media gallery and have the gallery formatted as a FlexSlider with thumbnail navigation.

I have tried both Flexslider Fields and FlexSlider Entity Reference but I can't seem to get either to work properly with Media Galleries.

Any suggestions?

I need it to be a simple interface a non-tech content creator can use without issue.

# Answer
I can recommend the ”Entity Reference Views Formatter" module.

https://www.drupal.org/project/entityreference\_views\_formatter

You then have full flexibility of views to output your Entity reference fields!

Here is a good thread on how to use the Entity reference views formatter module, setting up the correct Relationship and Argument can be a bit tricky. https://www.drupal.org/node/1889358
> 0 votes

---
Tags: nodes, media, javascript
---


title: how to allow span inside p (ckeditor)

text:
# Question
Title: how to allow span inside p (ckeditor)
I have a paragragh which has 3 font colors throughout it, however every time I try to add the spans inside the paragraph CKEditor takes it upon it's self to remove them on me. How do I get the spans to stay inside the paragraph?

I save this:

```
<p>Have <span class="lt-blue-txt">TROUBLING SYMPTOMS</span> and health concerns taken over your life? <span class="white-txt">Muse can help</span>.</p>

```

but it turns into this:

```
<p>Have TROUBLING SYMPTOMS and health concerns taken over your life? Muse can help.</p>

```

# Answer
Did these links not help:

https://stackoverflow.com/questions/18349048/ckeditor-strips-span-and-style-attributes

"If you are using the CKeditor module then there is an option in Advanced Options that is also mentioned in the module homepage where you should set"

or: Prevent WYSIWYG+CKEditor from stripping html classes "There is an issue with CKEditor 4.1+, which has a feature called Automatic Content Filter (ACF) that will automatically strip attributes not defined for the editor"
> 0 votes

---
Tags: wysiwyg
---


title: Solr can't find lib files

text:
# Question
Title: Solr can't find lib files
I have been trying to install the search\_api\_solr module. I installed tomcat and Solr according to the instructions on the module's project site and the INSTALL instruction in the module. However, I am stuck.

According to the INSTALL.txt instructions:

> NOTE: The Solr 4.3+ example application is currently not completely supported with the configuration files included in this module, due to a slight change in the directory structure. To fix this, simply copy, move or symlink the contrib/ directory from the top level of the extracted Solr package one level down to example/.
>
> *(For other directory structures: the contrib/ directory has to be in the directory two levels up from the one which includes the conf/ directory. For help, just start the Solr server and check the log files for WARN messages – they should state in which place Solr expects the directory to be.)*

I checked an sure enough Solr is reporting the following warnings:

> 00:15:45 WARN SolrResourceLoader Can't find (or read) directory to add to classloader: ../../../contrib/extraction/lib (resolved as: /usr/local/tomcat/solr/drupal/../../../contrib/extraction/lib).
>
> 00:15:45 WARN SolrResourceLoader Can't find (or read) directory to add to classloader: ../../../contrib/clustering/lib/ (resolved as: /usr/local/tomcat/solr/drupal/../../../contrib/clustering/lib).

The question is how to resolve this? I am using SolrL ver 4.6.1

# Answer
> 1 votes
I was having the same issue.

I ended up copying the contrib folder into: /usr/local/tomcat So I had: /usr/local/tomcat/contrib/ and: /usr/local/tomcat/solr/drupal/

That error about contrib/extract/lib went away, but now I'm getting: "Failed to load file /usr/local/tomcat/solr/drupal/solrconfig.xml"

As seen on the logging screen: http://screencast.com/t/MqtSNpqUljI

**UPDATE**: I went to the admin section on Solr and tried to add the core called drupal. So it tried to process the solrconfig.xml and found an error: http://screencast.com/t/EEmU4P9M I had the useCompoundFile twice. I fixed it and added the core. After that, it was working fine. I hope this helps out someone. I installed solr on centos by following the lullabot guide: http://www.lullabot.com/blog/article/installing-solr-use-drupal

# Answer
> 0 votes
I would not use a tomcat install but the jetty based example included with Solr. You can find it in the solr/example directory. Try running the start.jar with "java -jar start.jar", does it work?

https://cwiki.apache.org/confluence/display/solr/Running+Solr+on+Jetty "Solr comes with an example schema and scripts for running on Jetty, along with a working installation, in the /example directory. It is stripped of all unnecessary features and its config has had some minor tuning so it's optimized for Solr. It is recommended that you use the provided Jetty server for optimal performance. For more information about the Jetty example installation, see the Solr Tutorial and the basic installation instructions"

---
Tags: search
---


title: Rewrite Views field result using code

text:
# Question
Title: Rewrite Views field result using code
How do I rewrite views field result programmatically? I want to change the link basing on another field value.

I have a field called room typ,e which is a reference to taxonomy terms (Bedroom / Meeting Room). The second field is the node ID, which I want to use to give the link of the page (there are two different page: Enquiry and Booking). If the selected term is *Bedroom*, I want to link the Booking page; if the selected term is *Meeting room*, the link should be Enquiry. I want to change the link text for *Meeting room*: It should be *Enquire Now* and *Book Now*.

# Answer
You could add news fields to your vocabulary for the link text ('Enquire now') and for the href ('Enquiry')

You'll add these new fields to your view, and then you will be able to format your link like nandhana said. And the reference will do the rest ...

But be sure that the 'nid' is the lower field among all others, so that you can access to all others fields
> 1 votes

# Answer
For Example : You give title link for images:

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

```
> 0 votes

---
Tags: views
---


title: Form_state empty after ajax callback

text:
# Question
Title: Form_state empty after ajax callback
Im struggling with my form since yesterday ... I can't find a way to retrieve values from form\_state in my form function.

heres my different pieces of code :

```
    function mymodule_menu() {
  $items['mypath'] = array(
      'title' => 'Bienvenue',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_form'),
      'access callback' => 'mymodule_checkID',
      'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_form($form, &$form_state) {

        if(!empty($form_state['values']['rows'])){
            $cmdeData=$form_state['values']['rows'];
            watchdog("TEST","TEST-OUI",array(),WATCHDOG_ALERT);
        }else{
        watchdog("TEST","TEST-NON",array(),WATCHDOG_ALERT);         $cmdeExiste=checkCmde($cmdeID);
            if($cmdeExiste){
                //On récupère les données de la commande via SQL et on les stocke dans un tableau
                $cmdeData=recupCmde($cmdeID);
            }else{
                if(isset($_GET['D1'])){
                    $cmdeData=recupIntentionCmde(explode('|', $_GET['D1']));
                }
            }
        }

      if (empty($form_state['num_lignes'])){
        if(!$cmdeExiste && (!isset($cmdeData) || empty($cmdeData[0]))) {
            $form_state['num_lignes'] = 1;
        }else{
            $form_state['num_lignes'] = count($cmdeData);
        }
      }

      $lignes=array();
      $lignes['#tree']=TRUE;
      for ($i = 0; $i <= $form_state['num_lignes']; $i++) {

        $lignes['r'.($i+1)]=array();

        $lignes['r'.($i+1)]['ref'] = array(
          '#type' => 'textfield',
          '#size' => 7,
          '#maxlength' => 7,
          '#required' => TRUE,
          '#default_value' => ( $i<count($cmdeData) ? $cmdeData[$i]['ref'] : '' ),
          '#disabled' => ( $i<count($cmdeData) ? TRUE : FALSE ),
        );
        $lignes['r'.($i+1)]['qte'] = array(
          '#type' => 'textfield',
          '#size' => 3,
          '#maxlength' => 3,
          '#required' => TRUE,
          '#default_value' => ( $i<count($cmdeData) ? $cmdeData[$i]['ref'] : '' ),
          '#disabled' => ( $i<count($cmdeData) ? TRUE : FALSE ),
        );
        $lignes['r'.($i+1)]['des'] = array(
          '#type' => 'item',
          '#size' => 60,
          '#default_value' => ( $i<count($cmdeData) ? $cmdeData[$i]['ref'] : '' ),
        );
        $lignes['r'.($i+1)]['pge'] = array(
          '#type' => 'item',
          '#size' => 3,
          '#default_value' => ( $i<count($cmdeData) ? $cmdeData[$i]['ref'] : '' ),
        );
        $lignes['r'.($i+1)]['tot'] = array(
          '#type' => 'item',
          '#size' => 7,
          '#input' => FALSE,
          '#default_value' => ( $i<count($cmdeData) ? $cmdeData[$i]['ref'] : '' ),
        );

        if($i < count($cmdeData)){
            $lignes['r'.($i+1)]['btn_supp'] = array(
            '#type' => 'button',
            '#value' => t('Supprimer'),
            '#name' => t('Supprimer_'.($i+1)),
            '#ajax' => array(
                'callback' => 'cmde_tlv_deleteRow_ajax_callback',
                'wrapper' => 'lignes_articles',
            ),
            );
        }else{
            $lignes['r'.($i+1)]['btn_supp'] = array(
                '#type' => 'item',
            );
        }
      }

    $form['table'] = array(
    '#theme' => 'cmde_tlv_form_table',
    '#header' => array(t('Référence article'), t('Quantité'), t('Désignation'), t('Page'), t('Total')),
    'rows' => $lignes,
    '#prefix' => "<div id='lignes_articles'>",
    '#suffix' => "</div>",
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Valider la saisie',
    // '#submit' => array('cmde_tlv_submit2'),

  );

 return $form;
}

function cmde_tlv_deleteRow_ajax_callback($form, &$form_state) {

unset($form['table']['rows'][$form_state['triggering_element']['#parents'][1]]);

$form_state['num_lignes']--;
//$form_state['rebuild'] = TRUE;

return $form['table'];
}

```

From the drupal API I've read that the 'drupal\_get\_form' function was reseting the form\_state array.

Ive tried to add a HOOK\_form\_alter function but ive got the same problem. heres the code :

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

    if($form_id=="mymodule_form"){

        watchdog("TEST",print_r($form_state, TRUE),array(),WATCHDOG_ALERT);
    if(!empty($form_state['values'])) watchdog("TEST","TEST2",array(),WATCHDOG_ALERT);
    }

}

```

Here what' inside the form\_state array :

> Array ( \[build\_info\] =\> Array ( \[args\] =\> Array ( ) \[form\_id\] =\> cmde\_tlv\_form ) \[rebuild\] =\> \[rebuild\_info\] =\> Array ( ) \[redirect\] =\> \[temporary\] =\> Array ( ) \[submitted\] =\> \[executed\] =\> \[programmed\] =\> \[programmed\_bypass\_access\_check\] =\> 1 \[cache\] =\> \[method\] =\> post \[groups\] =\> Array ( ) \[buttons\] =\> Array ( ) \[input\] =\> Array ( ) \[num\_lignes\] =\> 2 )

Note 1 : I can't post the content of 'form\_state' from the callback function, but it has 'values' and 'triggering\_element' and all normal stuff

Note 2 : I did try to uncomment `$form_state['rebuild'] = TRUE;` in the callback function and did a lot of test to see if form\_state was still empty (default) ... and it still was ...

# Answer
I did find why my **$form\_state** array was reset: The **required** attribute was the problem. Adding `'#limit_validation_errors' => array()` to my delete button did the trick.
> 1 votes

---
Tags: forms
---


title: Webforms module breaks MySQL database

text:
# Question
Title: Webforms module breaks MySQL database
I've got 'Webform 7.x.3.20" installed on my Drupal 7 and it works perfectly, apart from it seems to have 'broken' the MySQL database. I first noticed this when I tried to use the 'Backup and Migrate' module - I got the following error: Additional uncaught exception thrown while handling exception.

> Additional uncaught exception thrown while handling exception.
>
> Original
>
> PDOException: SQLSTATE\[HY000\]: General error: 2013 Lost connection to MySQL server during query: show table status; Array ( ) in backup\_migrate\_source\_db\_mysql-\>query() (line 435 of /home/example.com/public\_html/sites/all/modules/backup\_migrate/includes/sources.db.mysql.inc).
>
> Additional
>
> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> php \[:db\_insert\_placeholder\_2\] =\> %type: !message in %function (line %line of %file). \[:db\_insert\_placeholder\_3\] =\> a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:112:"SQLSTATE\[HY000\]: General error: 2013 Lost connection to MySQL server during query: show table status; Array ( ) ";s:9:"%function";s:39:"backup\_migrate\_source\_db\_mysql-\>query()";s:5:"%file";s:96:"/home/example.com/public\_html/sites/all/modules/backup\_migrate/includes/sources.db.mysql.inc";s:5:"%line";i:435;s:14:"severity\_level";i:3;} \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> http://example.com/admin/config/system/backup\_migrate \[:db\_insert\_placeholder\_7\] =\> http://example.com/admin/config/system/backup\_migrate \[:db\_insert\_placeholder\_8\] =\> 82.29.92.127 \[:db\_insert\_placeholder\_9\] =\> 1409596675 ) in dblog\_watchdog() (line 160 of /home/example.com/public\_html/modules/dblog/dblog.module).
>
> Uncaught exception thrown in session handler.
>
> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db\_condition\_placeholder\_0) AND (ssid = :db\_condition\_placeholder\_1) ); Array ( \[:db\_condition\_placeholder\_0\] =\> Zy8B5O3kHHKb5uIZnFFODRyXl9C\_a82Ek-o9why5wNU \[:db\_condition\_placeholder\_1\] =\> ) in \_drupal\_session\_write() (line 209 of /home/example.com/public\_html/includes/session.inc).

I then went to look on phpMyAdmin to find that if I clicked on the database itself, it showed that there were no tables and has started logging me out of phpMyAdmin almost immediately. However, if I click on the '+' to the left of database name on the left hand side, I can view all of the tables in the database and even browse them individually.

Finally, I have used `mysqlcheck` over SSH and found that all the tables are OK until it reaches any belonging to webforms, and then I get "Got error: 2013..." again. I know for definite it is the module because I tried removing the tables for the database, and everything goes back to normal.

Any ideas why this is happening and how this can be fixed? The webform module is excelllent and I do make good usage of it, however I'm going to have to find an alternative if this continues as I can't even update Drupal core or backup the database at the minute!

# Answer
I would expect this is more related to the backup and migrate module.

The addition of the webform module's data may have pushed your setup over its limit when doing large amounts of processing like backup and migrate would be doing.

I would suggest checking your MySQL configuration's max\_allowed\_packet setting, it may be too low.

I would usually recommend setting it to 64M for Drupal 7 and then restarting the MySQL service and see if that resolves the issue.
> 0 votes

# Answer
In my experience this is either max packet size (as above) or timeouts

have a look here: http://dev.mysql.com/doc/refman/5.0/en/gone-away.html

which gives details of common causes of the mysql has gone away error it refers to among others wait timeout and max packet size
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How do I pass a PHP variable to Drupal.settings global javascript?
Javascript works fine, but i need to get **my\_var** variable from module. At the moment its not working.

Clear my page cache and browser cache several times.

The variable 'my\_var' is showing value on front end but not on backend/admin side.

Front end theme is Bartik; the admin theme is Seven.

All other variables are available on Admin side from Drupal.settings, except the one I pass from my custom module.

This works well on both themes.

```
alert(Drupal.settings.basePath);

```

This is my code.

### MY\_MODULE.module

```
/**
 * Implements hook_page_build().
 */
function MY_MODULE_page_build(&$page) {
    ctools_include('modal');
    ctools_modal_add_js();

    // HERE it is calling the js
    drupal_add_js(array('MY_MODULE' => array('my_var' => 'MY_VALUE'),), 'setting');
    drupal_add_js(drupal_get_path('module', 'MY_MODULE') . '/js/MY_MODULE.js');
}

```

### MY\_MODULE.js

```
(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context) {
        alert("test");
        alert(Drupal.settings.MY_MODULE.my_var);
    }
  }
})(jQuery);

```

On front end, it alerts with *test* followed by *MY\_VALUE*, but on admin side, it shows *test*; Firebug then shows me:

> Uncaught TypeError: Cannot read property 'my\_var' of undefined

How can I fix this?

# Answer
> 1 votes
calling drupal\_add\_js in hook\_init is a fairly standard response to this kind of question, as is hook\_boot.

hook\_init is used for setting up things required by the page - but doesnt run on cached pages.

hook boot is used for code that has to run on cached pages as well as uncached pages.

The way I usually debug this kind of thing is with the javascript console. In chrome, open the console and type

```
Drupal.settings

```

hit enter and it should print out the whole settings object for you to inspect. This will let you see what you have.

I suspect the problem may be down to when hook\_page\_build gets fired on admin pages if Im reading your question correctly.

```
Uncaught TypeError: Cannot read property 'my_var' of undefined

```

means that

```
Drupal.settings.MY_MODULE

```

evaluates to undefined. It could be at any level. so try the javascript console trick and see what you find (is Drupal there.. is drupal.settings there).

you could also try

```
(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context,settings) {
    alert("test");
    alert(settings.MY_MODULE.my_var);
   }
  }
})(jQuery);

```

which is more keeping with how it is documented for behaviours on drupal.org

# Answer
> -1 votes
your problem is here

```
    drupal_add_js(array('MY_MODULE' => array('my_var' => 'MY_VALUE'),), 'setting');

```

you should wrote

```
drupal_add_js(array('MY_MODULE' => array('my_var' => 'MY_VALUE')), array('type','setting'));

```

---
Tags: 7, javascript
---


# Question
Title: How to save POST variables securely using entity api
I am creating a module that connects Drupal Commerce to Shipworks (a shipping management system). They communicate with each other using HTTP POSTs via a single endpoint URL on Drupal. One aspect I am trying to understand is how to handle the POST variables returned from Shipworks in a secure manner.

For example, when a shipment is created in Shipworks the corresponding order id ($\_REQUEST\['order'\]) and tracking number ($\_REQUEST\['tracking'\]) are posted to Drupal at the endpoint. How do I save the tracking number in a secure manner using the entity api? Can I use the following code?

```
if (is_int($_REQUEST['order'])) {
  $order_id = $_REQUEST['order'];
}
else {
  _outputError(40, "Not a valid order id.");
}

$order = commerce_order_load($order_id);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$tracking = $_REQUEST['tracking'];

$tracking_number = str_replace(' ', '', strtoupper($tracking));

$order_wrapper->field_tracking_numbers->set($tracking_number);
$order_wrapper->save();

```

# Answer
It really depends on how ShipWorks works. If it lets you specify a URL when it downloads the order data, you could use a secret key appended to the URL that you can use to authenticate a request as Ayeshk mentions. If it allows the merchant to specify a URL in a configuration form, at least you can set the secret key once and have the merchant copy it, kind of like how Drupal appends a secret key to the cron URL.

I also have a project upcoming that requires ShipWorks. Are you sharing the code publicly anywhere?
> 0 votes

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


# Question
Title: Why do I get "Page not found" with my code?
I just created a new module but I can't manage to access it.

Here is the home.info.yml

```
name: Home
description: Ownzones Homepage
type: module
core: 8.x

```

Here is home.routing.yml

```
home.oztest:
  path: '/oztest'
  defaults:
    _content: '\Drupal\home\Controller\HomeController::oztest'
    _title: 'Ownzones'
  requirements:
    _permission: 'access content'

```

And here is the HomeController:

```
namespace Drupal\home\Controller;

use Drupal\Core\Controller\ControllerBase;

class HomeController extends ControllerBase {
  public function oztest() {
    $element = array(
      '#markup' => 'Hello, world',
    );

    return $element;
  }
}

```

I don't see what I'm doing wrong, and when I try to access /oztest I get a message saying *The requested page could not be found*.

# Answer
> 3 votes
\_content is no longer used, wherever you found that is outdated. Use \_controller instead.

---
Tags: 8, routes
---


# Question
Title: AJAX returns response code 200, and displays error messages in callbacks
I'm running Drupal 7.34 with quite a few modules (relevant because unfortunately I did not notice when the problem first started and it would take ages to look through them all one by one) and I have some quite strange behaviour. Whenever I try to fill in an autocomplete text field, manually check for updates or do anything else that involves AJAX really, I get an error message with the HTTP Response Code 200 and the response text is actually the HTML of the user profile page. One exception to this is in a custom module I wrote which uses callbacks, and strangely when the callback is outputted any persistent messages (i.e operating in maintenance mode) are also displayed in the same place. I have tried disabling and deleting this module but it did not change anything.

Also, I suspect it could be related that my messages log is filled with warnings saying:

```
Warning: Cannot modify header information - headers already sent by (output started at /home/site.com/public_html/includes/common.inc:2725) in drupal_goto() (line 697 of /home/site.com/public_html/includes/common.inc).

```

Does anybody have any idea what could be causing this?

# Answer
> 0 votes
Thanks to some brilliant and generous help from @thedotwriter, I believe I have found the cause of this problem and a solution.

In turns out that the root of the redirection to the user profile page, which meant that the AJAX response text was the code of that page, was some PHP code similar to the following, in one of my nodes:

```
if(!user_is_logged_in()){
   drupal_goto("user");
}

```

At first, this seemed odd because the node was in no way related to AJAX. To complicate the issue further, if the line was removed and then re-added once the node had been updated, AJAX worked again... for a few hours.

Looking in the log, I noticed that just before the error returned Cron had run. This made sense - sort of - because then I found that when I ran Cron manually it never completed but ended up on the user page, which can be explained by the fact that Cron would have evaluated the above code due to the fact that it runs as an anonymous user.

Here my answer falls down a bit because I'm not quite sure how this all affects AJAX. I'm assuming that it's due to caching and/or the fact that part of Cron indexes the site so therefore because Cron was being redirected the index was corrupt/incomplete. I don't have any solid evidence, but it can be backed up by the fact that before the site would only ever get up to being 82% indexed, but without that code it is now 100% indexed. If anyone would like to offer there thoughts on this answer however, please feel free to do as I really would like to confirm 'the missing piece of this puzzle'.

There are a few ways to avoid this issue. One would be to check to see if the script that is accessing the node is cron so that you know not to do any redirects (see here). However, the method I chose was to move this 'functionality' into a rule. I do so for many reasons, but most importantly because it is not recommended to use PHP codes in nodes at all and I think that this incident illustrates why.

---
Tags: ajax, http-request
---


title: Can I use PHP 5.5?

text:
# Question
Title: Can I use PHP 5.5?
With the feature freeze for PHP 5.5 long past, I figured it was time I post an update to the popular PHP 5.4 and Drupal 7 question.

So, can Drupal run on PHP 5.5?

# Answer
> 21 votes
In short, if your site runs on PHP 5.3, it will run on 5.5 as well, go upgrade! (Your dev environment, until a real release is out)

With the short answer out of the way, here are some more details.

With regard to "Does Drupal work on it", very little changed from PHP 5.3, to 5.4 to 5.5. The one issue that showed up under PHP 5.4 was really just PHP being better at telling developers when they were doing something wrong, rather than an incompatibility introduced by PHP. The details of that are well covered in PHP 5.4 and Drupal 7.

No similar new warnings show up with PHP 5.5 though, and while some things have changed, they are highly unlikely to have negative impact on your Drupal site.

One performance concern that was raised with running 5.4 was that APC was lagging behind in support. This will not be an issue this time, as 5.5 now includes a replacement for APC Optimizer+

Drupal 6: By now, most things work well with PHP 5.3, meaning it should work well on 5.5 as well. I have yet to test this myself.

Drupal 7: Runs smoothly, I've encountered no problems what so ever, largely because Drupal 7 was developed more with PHP 5.3 in mind, and any problems discovered on 5.4 have long since been fixed.

Drupal 8: Requires 5.3 from the start, so will work well. I will update the answer when I've tested it myself.

# Answer
> 3 votes
Updates to letharion's answer:

* Drupal 8 now requires PHP 5.4.2 (probably even higher by the time we release it), and 5.5 is supported, although not required
* Drupal 6 support for 5.3 is already good although issues still remain, handled as bugs because D8 migration from D6 will rely on PHP 5.3 being supported by D6.

# Answer
> 1 votes
Whilst installing a fresh version of Drupal 7.26 in a PHP 5.5 environment, I was getting the "Set-up database" screen load twice. On the 2nd submission of the form, I would then get a WSOD. Loading the site from the root path gave a 404.

I tracked down this patch (comment #45) which solved the problem for me. As you'll read there, it was due to the way the new PHP caching system works and the caching of the settings.php which stores the database credentials.

# Answer
> 1 votes
Adding the following lines to the main htaccess file can help.

```
php_value date.timezone America/New_York
php_value error_reporting E_ALL
php_value display_errors 1
php_value display_startup_errors 1
php_value memory_limit 256M

```

# Answer
> 0 votes
I have hit a snag trying to install Drupal 7.26 on Ubuntu 13.10 (php 5.5).

```
Fatal error: Call to undefined function field_attach_load() in /var/www/d7/includes/entity.inc on line 316

```

I had to apply this patch - https://drupal.org/comment/7721819#comment-7721819.

Deleted existing database for this install.

Re-created the database and then ran `install.php`.

The problem for me was fixed with that patch.

# Answer
> 0 votes
Fresh install of drupal-7.26

Ran PHP 5.5.9 -got error: "...entity.inc on line 316"

In server-control-panel I changed my Drupal folder to use "PHP 5.4.25". Then hit back in browser, re-entered the install-data, and voila -\> up and running...

Installed themes, some modules, created pages; changed back to PHP 5.5.9 -\> still working...

# Answer
> 0 votes
**Drupal 7:** Check all issues with tag php 5.4 or php 5.5 to be sure you are not using any of the modules that still have issues with those versions: https://drupal.org/project/issues/search?text=&projects=&assigned=&submitted=&project\_issue\_followers=&&&&issue\_tags\_op=%3D&issue\_tags=PHP%205.4%2C%20PHP%205.5.

If your site has any of those modules installed I think it is better to stick to php 5.3 for Drupal 7.

**Drupal 6** Add the php 5.3 tag too as some less used or maintained modules still have issues with php 5.3.

---
Tags: updating
---


title: Permissions not saving

text:
# Question
Title: Permissions not saving
I'm working on a development site. Up until recently I haven't had any trouble with saving permissions, everything was working fine, until I added the different user roles for the site. After I added them all, I went back, and started to assign the correct permissions to the correct users types. I hit save, and... nothing.

No error message, no message at all. And the save didn't take effect. I'm starting my head over why it suddenly just isn't working when it was working before. Is there a limit the the amount of users types that Drupal allows?

# Answer
> 8 votes
This sounds a lot like a php runtime issue. PHP has a configuration called max\_input\_vars, which you can use to set a limit on the number of input vars php will accept. This will affect the number of $\_POST and $\_GET variables that can be fed into php. The default is 1000, and I suspect, if you have lots and lots of user type, you're hitting up against this ceiling.

# Answer
> 4 votes
I've had a similar problems with permissions in that it won't even render the page, probably because we use roles to differentiate our clients and therefore have more than 100 of them.

Try going directly to `admin/people/permissions/roles`, and edit the permissions for a single role, it works for me.

My guess is it is a memory issue, you could potentially fix it by upping your script allowance in php.ini but that would have repercussions.

---
Tags: users
---