# Question
Title: Require specific access for certain pages with only one input field
For certain pages i have to require a login first (custom form with 1 input field).

* When you try to reach the URL of one of those pages you are redirected to a login-page
* They have to fill-in a number of 11 digits. If the filled in field contains 11 digits they are redirected to the protected page(s).

It's not an age gate. It's for doctors the have to fill in a 11-digit code. If the code contains 11 digital characters they can see the protected page(s).

How (which modules) are best practices to built this functionality?

# Answer
so the characters can be random or need to be verified against some database table entries?

best thing would be to have a custom code/solution for this, use ctools popup and custom javascript to check for the right cookies on the selected pages, we can add a field defining the setting whether the page requires verification or not, and overridden node tpl (template) for that particular content type which can contain drupal\_add\_js or inline javascript based on the field condition. Adding a module and customising will add more pain in my opinion.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How do I use it in a system with 2 PHP-versions?
On my server there are two versions of PHP: 5.4 and 5.6. Using the shell PHP 5.4 is the standard and it can't be changed because of PLESK/ODIN. The websites I'm administering are using PHP 5.6 via PLESK, so Drupal 8 works fine. Drush doesn't, because it uses the shell.

I have installed Drush with the following commands:

```
php drush.phar core-status
mv drush.phar /usr/local/bin/drush
drush init

```

How can I change this to use PHP 5.6 in /opt/plesk/5.6?

# Answer
> 3 votes
Drush has an environment variable `DRUSH_PHP` to set the php executable. You can set it in your .bashrc or directly on the command line:

```
env DRUSH_PHP=/opt/plesk/5.6/php drush status

```

# Answer
> 2 votes
Unless I'm missing something, what you need to do is, for your local shell, to have the system use the php5.6 executable rather than the php 5.4 one?

You need to find (or install) the php you need: for example, say the 5.4 version is in /usr/bin/php; the later one might be in /usr/local/bin/php

If you can't do that, you may be able to install your own version of php in your home directory (i.e. under /home/joeby/php/... ) though that is unfortunately not as simple as it might be.

Once you've located the correct php executable, do one of two things:

1) \[This is the preferred solution:\] Modify your shell PATH: e.g. in .bashrc a line like:

```
PATH=/usr/local/bin:${PATH}

```

where the /usr/local/bin is the folder you found the correct php in. It matters that this precedes the ${PATH}. Because the system searches for the php binary in the path, and you have only changed the path for your own shell (not for the system), it should mean you run the php you want, but the system sees the version it wants.

2) modify the drush php file. To do this you'd need to install drush as separate files, rather than a .phar file, and then find the file 'drush' and replace the first line. Normally it should look like this:

```
#!/usr/bin/env php

```

you can change it to:

```
#!/usr/local/bin/php

```

that is, the complete pathname of the executable you want to use. Once this is done remove write permission for yourself, so it is non-trivial for an update to replace the modified file:

```
chmod a-w /usr/local/bin/php

```

---
Tags: 8, drush
---


title: How do I export my site structure?

text:
# Question
Title: How do I export my site structure?
Since Drupal 8 is days away from release, I've started experimenting with rebuilding my personal site on it. The one feature I am really looking forward to is configuration management in code.

Unfortunately, my taxonomy terms are not exported by the config module. From what I've found googling on the subject, neither are menu items.

Which leaves me stumped. The natural way to set a sites structure (or information architecture) is a combination of content types, taxonomy vocabularies and their terms, and a set of menus. Or, at least, that seems to be the natural way to me.

While googling, I could not find any discussion on this subject.

So, how do I export the taxonomy terms and menu items that define my sites structure?

### Edit to add some details:

Assume the site is a magazine. It has Fiction, World Events, Technical, and Letters sections. There will always be a /fiction, a /world-events, a /technical, and a /letters menu items. There are several kinds of content types, each can go into various sections.

So I create a vocabulary for the sections.

```
sections
- fiction
- world events
- technical
- letters

```

A taxonomy reference field is added to each content type.

Thus, when content is created it is tagged with the appropriate section terms.

If the site deploys without one of those sections, it is broken. Thus the menu items, and taxonomy terms should be considered configuration. Not content.

From what I've read, the main problem is that terms and menu items can collide if you try to move them between instances. Terms have a incrementing tid. Menu items also have an incrementing id. Though I do see the taxonomy\_term\_data and menu\_link\_content tables which seem to map uuid's with term and menu item ids. So, couldn't that be used to make exporting them feasible?

Also, isn't one of the main uses cases for taxonomies defining a site's structure?

I guess what I'm stuck on is that some menu items and some taxonomy terms really should be considered as configuration, not data. As in, if I were coding this instead of using Drupal, I'd hard code them. Thus, they should be exportable so that they can be committed to version control.

And that's why I'm asking "How do I export my site structure?"

# Answer
> 1 votes
For install content, you can use Default Content for D8 (also on GitHub). For ongoing content syncing Entity Pilot is expected to enter public beta this week and there is an active initiative around Deploy module.

Disclaimer: Entity Pilot is my project.

# Answer
> 0 votes
For a deployment that you are planing, you should use features, that packs it all into a module. To add menus you can use yml-files and basic content like taxonomy terms can be added in module\_install(). Or wait until UUID Features is ported to drupal 8.

# Answer
> -1 votes
Managing configuration in Drupal 8 states:

> The Configuration Manager module in Drupal 8 provides a user interface for importing and exporting configuration changes between a Drupal installation in different environments, such as Development, Staging and Production, so you can make and verify your changes with a comfortable distance from your live environment.
>
> You can import, export, and synchronize configuration in your site via Manage \> Configuration \> Configuration Synchronization (admin/config/development/configuration).

Aparently it supports many types, including taxonomy and menus:

---
Tags: 8, configuration
---


# Question
Title: Using computed field to format phone numbers?
I am trying to create a computer field that automatically formats phone numbers like so: xxx.xxx.xxxx

The numbers come from user input, and they will be displayed on each user page (I've added fields to Drupal's user profiles so that they include contact info)

How do I do that? Never used computed fields before, but I believe it's the solution to what I'm trying to do....

# Answer
> 1 votes
Try Masked Input module. It allows you to create a text field with mask that you can setup custom (e.g. 999.999.9999). When user enters info into the field with masked input, the information entered is formatted automatically and stored into database with that exact format. So the output of formatted information becomes that much easier.

One drawback of this module is that it provides formatting only if user has JS enabled in the browser. If JS is disabled, you will rely on user to enter info in the desirable format. You can also ask the user to provide info in specific format by entering field description as a fallback (e.g. "Enter your phone number as follows - xxx.xxx.xxxx). I've used this module on websites with big user base, and I can tell that users very rarely have JS disabled when they fill up forms.

---
Tags: 7, entities
---


title: field_view_field geofield_map

text:
# Question
Title: field_view_field geofield_map
I'm doing the following

```
field_view_field('node', $node, 'field_geo',
    array(
      'label' => 'hidden',
      'settings' =>
        array(
            'format_type' => 'geofield_map_map'
        ),
    );

```

`field_geo` is a geofield. `geofield_map` module is enabled (output is fine for this field in other instances where I am not calling `field_view_field()`

In looking through geofield\_map.module, there is every indication in hook\_field\_formatter\_info() that I should be using "geofield\_map\_map", but I don't get the map output. Anyone have any idea why?

# Answer
> 1 votes
Found the problem ... I was defining the output type in the settings array vs directly in the display array.

```
field_view_field('node', $node, 'field_geo',
    array(
      'label' => 'hidden',
      'type' => 'geofield_map_map'
    )
);

```

Hope this helps someone else.

---
Tags: entities, location
---


# Question
Title: Is it possible to redirect user to another form depending on values entered in the first form
I have 3 Webforms named A, AA and AB, In form A there are few question with Yes and No options.

I am looking for a way to direct user depending on the selected options, If user select all the options as Yes and press submit the form should direct the user to form AA else to form AB.

Is there any easy way/Module to check the Form A and direct user to either AA or AB depending on the selected options

I assume rules could be a choice, but i can't figure out.

# Answer
Finally I Manage to redirect user to anther form base on entered values.

1. Install Rules module and Webform Rules
2. Create new rule
3. From React on event select After a submission draft has been submitted
4. Add a new condition, select Webform has name, Select form\_id from Data selector, and select the form name from Weforms value
5. Add a new condition select Execute custom PHP code
6. Add the custom code

if ($data\['components'\]\['1\_are\_you\_aged\_18\_to\_50\_years\_of\_age\_'\]\['value'\]\[0\]=='Yes') { return TRUE; } else { return FALSE; }

Change the field name 1\_are\_you\_aged\_18\_to\_50\_years\_of\_age\_' and Yes value to your own field name and value 7. Add an action, select Page redirect and add the URL.

8. Click save, And click save again.
9. Go to /people/permissions
10. Allow all the user type to Execute PHP code "Please note allowing users to execute PHP code is not recommended due to security risk".
> 1 votes

# Answer
Yama gets close, but, instead of using custom PHP in your rule, try this patch to the webform\_rules module that exposes form data that's been submitted directly to the rules UI, without requiring you to write custom PHP code.

More importantly, step 10 in the answer from Yama creates a potentially serious security problem on your site. They aren't kidding when they say "Please note allowing users to execute PHP code is not recommended due to security risk". It is a permission that should never be granted to anonymous or untrusted users.
> 0 votes

---
Tags: webforms, redirection, rules
---


# Question
Title: How to overwrite modules by default with DRUSH?
I am using a module list from Drupal 7 to populate a Drupal 8 site.

Some modules are now included in core, so there are a lot of confirm overwrite messages like this:

```
 Install location C:\drupal-8.0.1//modules/imagecache_actions already exists. Do
you want to overwrite it? (y/n):

```

What is the command for default Y or N ?

Now I use this command:

```
 drush en module -y

```

But I would like to set default answer to "overwrite yes" if module is already enabled or already exists and downloaded so I don't have to manually enter Y everytime

# Answer
**Overwrite** Allows the project to be installed in a directory that is not empty. If not specified this is treated as FALSE, Drush make sets an error when the directory is not empty. If specified TRUE, Drush make will continue and use the existing directory. Useful when adding extra files and folders to existing folders in libraries or module extensions.

```
projects:
  myproject:
    overwrite: TRUE

```
> 0 votes

---
Tags: drush
---


# Question
Title: How can I change the drupal form action based on Radio button selected?
I have developed a custom form in my module. Now I have to change the form action based on radio button selected. Suppose if I have 3 radio buttons saying 1. ABC 2. DEF 3. XYZ

If i select ABC and submit form, my result should display on www.domainname.com/abc

Thanks.

# Answer
You can change the Form action in submit function

```
    function your_form_name_submit($form,&$form_state){
          if($form_state['values']['radion_button_name'] == 'abc') {
         $form_state['redirect'] = url('path/to/redirect');
        }
    else{
       $form_state['redirect'] = url('path/to/redirect');
     }
}

```

hope this will help you!!
> 1 votes

# Answer
There may be following options to change the form action based on radio option selection.

**1. Using ajax callback**

Create menu item

```
/**
 * Implements hook_init().
 */
function YOUR_MODULE_menu(){
  $items = array();
  $items['stack-exchange'] = array(
    'title' => 'Stack exchange',
    'description' => 'Stack exchange.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stack_exchange_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

// form callback
function stack_exchange_form($form, &$form_state){
  $form = array();
  $options = array('abc' => t('ABC'), 'def' => t('DEF'), 'xyz' => t('XYZ'));

   $form['submitto'] = array(
    '#type' => 'radios',
    '#title' => t('Submit to'),
    '#options' => $options,
    '#description' => t('Select a option to submit the form to specific location.'),
    '#ajax' => array(
      'callback' => 'alter_form_action',
    ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  return $form;
}

// ajax call back
function alter_form_action($form, $form_state){
  $commands = array();
  $action = $form_state['values']['submitto'];
  switch($action){
    case "abc":
      $submit_to = 'your-path/' . $action;
      break;
    case "def":
      $submit_to = 'your-other-path/' . $action;
      break;
    case "xyz":
      $submit_to = 'your-again-other-path/' . $action;
      break;
  }
  $commands[] = ajax_command_invoke('form#stack-exchange','attr', array('action', $submit_to));
  return array('#type' => 'ajax','#commands' => $commands);
}

```

**2. Using jquery**

```
// attach js file in from callback
$form['#attached']['js'] = array(
    drupal_get_path('module', 'dev') . '/js/stack_exchange_form.js'
  );

```

and put following js code into

```
(function($) {
  Drupal.behaviors.YOUR_MODULE = {
    attach: function (context, settings) {
      $("form#stack-exchange-form input[name=submitto]:radio").change(function () {
        var action = $(this).val();
        var submit_to = '';
        switch(action){
          case "abc":
            submit_to = 'your-path/' + action;
            break;
          case "def":
            submit_to = 'your-other-path/' + action;
            break;
          case "xyz":
            submit_to = 'your-again-other-path/' + action;
            break;
        }
        $('form#stack-exchange-form').attr('action', submit_to);
      });
    }
  };
})(jQuery);

```

Note: you need to change the hook name and element selector accordingly
> 1 votes

# Answer
You can do this stuff in your form submit.

```
function yourmodule_form_submit($form, &$form_state) {
 // do your submit stuff
 if($form_state['values']['radion_button_name'] == 'abc') {
   drupal_goto('abc path');
 } else if ($form_state['values']['radion_button_name'] == 'efg') {
   drupal_goto('efg path');
 } else {
   drupal_goto('default path');
 }
}

```
> 0 votes

# Answer
**You can apply this code it will work for you:**

```
 <?php

function formalter_menu() {
$items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
'title' => 'Example Form', //page title
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
'page arguments' => array('formalter_form'), //put the name of the form here
'access callback' => TRUE
);

return $items;
}

function formalter_form($form, &$form_state) {

$form['price'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'What is Your Price?',
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
);
$form['topic'] = array(

 '#type' => 'radios',
 '#title' => t('Topic'),
 '#options' =>          array('Movie'=>t('Movie'),'Songs'=>t('Songs'),'Ads'=>t('Ads'),'Tv

Serials'=>t('Tv Serials'),'Others'=>t('Others')),
    );
  $form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Click Here!'),
  );

  return $form;
 }

 function formalter_form_validate($form, &$form_state) {
 // dpm($form);
//dpm($form_state);
  if($form_state['values']['topic'] == "Movie")
   {
  $form_state['redirect'] = url('http://www.google.com');
     }
    else{
      $form_state['redirect'] = url('http://www.yahoo.com');
      }
  }

  function formalter_form_submit($form, &$form_state)
{
drupal_set_message('warning',"Thanks for submitting the form");

  }

 ?>

```
> 0 votes

---
Tags: 7, forms
---


title: How can I use entity save in drupal 8

text:
# Question
Title: How can I use entity save in drupal 8
I'm installed drupal 8 in local and created a content type named as **Project** with minimal fields. And implemented form API to collect data in custom module.

Here how can I save the data as node content? or How can I use entity save in drupal 8

# Answer
if you only want save node type. You can use code example below

```
<?php

use Drupal\node\Entity\Node;
$node = Node::create([
  // The node entity bundle.
  'type' => 'article',
  'langcode' => 'en',
  'created' => REQUEST_TIME,
  'changed' => REQUEST_TIME,
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  // An array with taxonomy terms.
  'field_tags' =>[2],
  'body' => [
    'summary' => '',
    'value' => '<p>The body of my node.</p>',
    'format' => 'full_html',
  ],
]);
$node->save();

```
> 1 votes

---
Tags: forms
---


# Question
Title: How to pass metatags from a node into a view?
I'm sending the information of my node into an external application and I need to be able to send the meta tags of that node as well. Unfortunately, I do not see the meta tag fields.

My question is...

* How can I send my meta tags into a view?

**NOTE: I'm using the Metatag module, I have seen few posts that suggest using the metatags\_quick module to add this functionality. However, I need to be able to do it with the instead Metatag module**

# Answer
> 1 votes
There is a sandbox project call Metatag Views Field, which provide metatags as a field into Views.

---
Tags: 7, views, entities, meta-tags
---


title: How do I add CSS files?

text:
# Question
Title: How do I add CSS files?
Here is an example of my \*.info file.

Why the page cannot load the CSS that I add myself?

# Answer
> 6 votes
You Need to create a separate `*.libraries.yml` and declare it in your theme's `*.info.yml` file.

Note:

If your theme is named **"smart"**, then the file name should be `smart.libraries.yml`

**Attaching to all pages:**

To attach a library to all the pages on the site that use your theme, declare it in your theme's `*.info.yml` file.

```
name: smart
type: theme
core: 8.x
libraries:
  - smart/cuddly-slider

```

**Defining a library**

```
cuddly-slider:
  version: 1.x
  css:
    theme:
      css/cuddly-slider.css: {}

```

# Answer
> 3 votes
In Drupal 8, you need to define a "library" to add your custom CSS/JS

> The general steps for loading assets (CSS/JS) are:
>
> 1. Save the CSS or JS to a file.
> 2. Define a "library", which can contain both CSS and JS files.
> 3. "Attach" the library to a render array in a hook.
>
> But in the case of themes, there is an alternative to step 3: themes can choose to load any number of asset libraries on all pages.

More details in the online documentation here: https://www.drupal.org/theme-guide/8/assets

# Answer
> 0 votes
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

> In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes, for everything: asset libraries. Asset libraries can contain one or more CSS assets, one or more JS assets and one or more JS settings.
>
> ### Defining a library
>
> To define one or more (asset) libraries, add a \*.libraries.yml file to your module folder. (If your module is named fluffiness, then the file name should be fluffiness.libraries.yml). Each "library" in the file is an entry detailing CSS and JS files (assets), like this:

```
cuddly-slider:
  version: 1.x
  css:
    theme:
      css/cuddly-slider.css: {}
  js:
    js/cuddly-slider.js: {}

```

In other words you need to create a library.

---
Tags: 8, theming
---


# Question
Title: Can I use Drupal 7's CSS/JS cache buster/token programmatically?
By default Drupal adds a cachebuster to CSS and JS resources:

```
<style type="text/css" media="all">
@import url("http://example.com/modules/system/system.base.css?o0xoqx");
@import url("http://example.com/modules/system/system.menus.css?o0xoqx");
@import url("http://example.com/modules/system/system.messages.css?o0xoqx");
@import url("http://example.com/modules/system/system.theme.css?o0xoqx");
</style>

```

Is there a way to use the cache token (`o0xoqx`) programmatically in the template?

I'd like an easy way to add the same token to some other resources later on (namely: the whole lot of modern favicons), so I could "refresh" them more easily.

# Answer
> 9 votes
You certainly can, it's just a variable:

```
$current_token = variable_get('css_js_query_string', '0');

```

---
Tags: 7, caching
---


# Question
Title: Views table doesn't set fields next to each other
I got a content type with 7 fields. Each field can contain unlimited inputs. Like:

* Field Type/DN got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
* Field L got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

When I make this in a view table I get this:

```
Type/DN       L
1             1
1             2
1             3
1             4
1             5
1             6
1             7
1             8
1             9
1             10
1             11
2             1
2             2
2             3
2             4
2             5
2             6
ETC.

```

What I want is

```
Type/DN       L
1             1
2             2
3             3

```

The fields are imported from a CSV file by feeds importer.

Here some images to show my settings:

# Answer
I made the excel import input all the fields. And make a node for every row in the xls file, then i made a extra field with the product name in the xls file so every node could reconize on what tabel they had to add the rows.

bit messy with a lot of tables but the out put works.
> 1 votes

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


title: Custom login for specific role

text:
# Question
Title: Custom login for specific role
On a site there are some pages from a Content-type. Some of those pages (for the Belgium language only) need to be **only** accessible for Dokters.

So when you try to reach the `URL` of one of those pages you are redirected to a login-page.

But the role 'dokters' needs to have an extra login-field. **Or only this field to login is even better if thats possible!** It should be a field with 11 digits. Or if this is to complicated (Username, Password, 11-digit field).

How (which modules) are best practices to built this functionality?

**UPDATE:**

Now i managed to do a workaround with Content Access module. I made a role 'doctor'. And now **only** users with role 'doctor' can access those pages.

But is there something to do like when the Doctors visit those restricted pages they are redirected to a custom login-page. On this page you have a small form: *Fill in your 11-digit code to access this page.*

Because all doctors have their own 11-digit code. We don't have to send all doctors the *username* name and *password* for role 'doctor', instead they can access the content directly, with their 11-digit code! The only validation should be that the field contains 11 digits.

How do i manage this in the simplest/best way?

# Answer
> 0 votes
First, create a custom permission:

```
/**
 * Implements hook_permission().
 */
function MY_MODULE_permission() {
  return array(
    'access doctor content' => array(
      'title' => t('Access content for doctors'),
    )
  );
}

```

If the restricted content is a custom page you can do this:

```
/**
* Implements hook_menu().
*/
function MY_MODULE_menu() {
  $items = array();
  $items['doctor_page'] = array(
    'title' => 'Doctor page',
    'page callback' => '_doctor_page_content',
    'access arguments' => array('access doctor content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

```

If the restricted content is a node make sure there is a reliable way to filter that content in your code (e.g. by adding a checkbox 'Protected' to the node). Set access restrictions on nodes like this:

```
/**
 * Implements hook_node_access().
 */
function MY_MODULE_node_access($node, $op, $account) {
  // Check if the content is protected.
  if (!empty($node->field_protected_content[LANGUAGE_NONE][0]['value'])) {
    // If so, check if the user has access to it.
    if (user_access('access doctor content', $account)) {
      // Allow access.
      return NODE_ACCESS_ALLOW;
    }
    // Deny access.
    return NODE_ACCESS_DENY;
  }

  // Handle the default restrictions.
  return NODE_ACCESS_IGNORE;
}

```

Don't forget to add your custom permission to the user role via the permissions page (`admin/people/permissions`).

---
Tags: 7, users
---


# Question
Title: How do you clear a field value with entity_metadata_wrapper()?
Suppose I have an entity with a field `field_foo` on it and I want to clear that field's value.

What should I pass to `$wrapper->set()`?

I have tried `NULL` and `array()` and both produce an error message.

# Answer
> 24 votes
The problem is that you must set an empty value that is compatible with the data type of your field. If you do not, you will get an exception raised. Passing `NULL` or `array()` when a string is expected will therefore raise an error.

Another thing to keep in mind is that the data you pass will also depend on whether your field is a single value, a multi-value field, or a field with multiple properties.

If your field is a single value (and thus the wrapper for the field is an instance of EntityValueWrapper) then you should assign it an empty value *compatible with the data type in question*. For instance the two following methods are equivalent:

```
$wrapper->title = '';
$wrapper->title->set('');

```

However the following three examples will raise an exception, because the data types are not compatible with the `title` field:

```
$wrapper->title->set();
$wrapper->title->set(NULL);
$wrapper->title->set(array());

```

If your field is a field with multiple properties (for instance a formatted text field, which defined both a `value` and `format` property) and thus an instance of EntityStructureWrapper, then `array()` or `NULL` will be the correct empty value. So you can do the following:

```
$wrapper->field_formatted_text = array();
$wrapper->field_formatted_text = NULL;

```

But in that case, passing an empty string would have raised an error. Note that you could have chosen to make the `value` property empty instead, in which case a string is the correct data type:

```
$wrapper->field_formatted_text->value = '';

```

Finally, if your field is a multi-value field (and thus your wrapper is an instance of EntityListWrapper) then `array` or `NULL` are the correct empty values, and the following three lines are equivalent:

```
$wrapper->field_example_multiple->set();
$wrapper->field_example_multiple = array();
$wrapper->field_example_multiple = NULL;

```

Note: Calling the `clear` method on the wrappers is not equivalent to setting the field to an empty value. When the field is set to an empty value, it then calls EntityMetadataWrapper::updateParent on the field's parent wrapper. This ensures amongst other things that the `setter callback` defined by hook\_entity\_property\_info is called. Calling `clear` does not do that.

# Answer
> 4 votes
Further to other answers and comments, if the field is multiple *and* required, as previously noted you **cannot** use

`$wrapper->field_example_multiple->set()`

`$wrapper->field_example_multiple->set(NULL)`

nor even `$wrapper->field_example_multiple->set(array())`,

but instead you can use the following if you want to clear the field of all its values:

```
$wrapper->field_example_multiple->set(array(NULL));

```

In fact, this works whether or not the multiple-value field is set to 'required', and so I'd recommend always using this, to ensure that your code is robust.

(Of course, if the field is 'required' then you perhaps shouldn't be completely clearing it anyway, but your code might be doing this as a preliminary step to deleting the whole entity or something similar, so there are times when it might just be legitimate.)

# Answer
> 2 votes
It appears that the complexities listed in the other comments are only relevant to a required field. If the field is not required, then this should be pretty simple:

```
$wrapper->field_foo = NULL;

```

You can use the wrapper to check the properties of the field:

```
$properties = $wrapper->getPropertyInfo();
$field_required = !empty($properties['field_foo']['required']);

```

Depending on the context, you can also just get the properties of the one field using:

```
$wrapper->getPropertyInfo('field_foo');

```

# Answer
> 1 votes
Another solution for this problem could be `EntityMetadataWrapper::clear`

`$entity_wrapper->field->clear()`

---
Tags: entities
---


# Question
Title: admin/config page taking around 30 seconds to load; the rest of the website loads fast
I have a new Drupal install and it works allright, everything loads fast, except for the Configuration page at admin/config. What I have done so far to try to tackle the problem: \- Disabled all contrib modules, with no success. \- Disabled the Update Manager module, no success either. \- Enabled Devel and extended query logs, besides page execution time: ordinary pages take some 300 ms to load. The admin/config page is taking around 30000 ms to load. There is no evidence in the logs that it has to do with the database queries. On the Config page, none of them is above the threshold limit.

It then occurred to me trying something else: I am inside a corporate network and there are two different ways to enter this Drupal site: by checking the internal IP false address and by checking the external IP address the IT team has set for this server (open to the world).

I found that by navigating to the Configuration page from the internal IP address, there is no delay at all, the page loads fast! By navigating into it from the external IP address, the page gets these 30 seconds delays to load.

Any ideas on how I should try to fix this issue with the IT team? I have access to the server and I can run commands on the command line and maybe check server logs. I am not a Linux specialist, but I can follow instructions and run commands.

# Answer
> 2 votes
The admin/config page can trigger a check of the site 'status report' which depending on the modules & services your site uses may check for the ability to connect to certain services. 30 seconds sounds like it is trying to use some service but throws a timeout after 30 seconds. Try checking the status report under working / not-working conditions to see if some services are being blocked.

# Answer
> 1 votes
This will happen if your watchdog table is very large. Going into the mysql backend and doing

`truncate watchdog;`

solved this problem for me.

The watchdog table contains logs, so truncating it is safe in that it will not affect the working of the system.

---
Tags: performance
---


title: Webform Localization

text:
# Question
Title: Webform Localization
I created a form in English. I used the localization webform module to translate the fields of the form. In configuration -\> Regional and Language -\> Translate interface -\> Translate. It works!

Now I'd like to translate different e-mails in several languages. For this I enabled the option: "Synchronize webform recipients e-mail across node translations."

Now what I need to do more? I wanted to set up E-mails with confirmations in different languages or even use different email. I'm a little confused on this part.

Thank you for your help.

Best regards.

# Answer
> 0 votes
If you add a select field in your webform, for example ( language ) then you can filter emails using that select field. You can rather let the user select the language or do it with a language detection script.

---
Tags: webforms
---


title: Put multiple views in one block

text:
# Question
Title: Put multiple views in one block
I want to create 3 different lists of 3 different content types. They should be displayed in one block and this block would be the only one in a particular region.

Ultimately I just want a title for this region or block respectively like news and inside three different news columns like sports, politics, business (just examples).

My ideas:

1. A Block view using fields with three attachments. Problem is I can't create an empty block view without any fields specified. But then I have this extra SQL Query and the result will be rendered in html anyway even if I mark it "exclude from display".
2. Create three different block views, assign them to the region and create a custom theme template for this region.

Are there other options. Panels? Haven't used it yet, so not sure if it would be a fit for this problem.

# Answer
> 2 votes
1. Create your first list as the block view itself and give it a title of "News".
2. Now add the other two lists as attachments to the block view and set the titles to be **blank**.
3. Finally, add a "Global: Text area" to the **Header** of each display, containing your "Sports", "Politics" and "Business" titles, perhaps inside \<h3\> tags.

# Answer
> 0 votes
Morbid's answer is good or you could look at https://www.drupal.org/project/blockgroup

However, depending on your needs, this could be the easiest and would perform best.

Add a filter to only allow the three content types. Then add the content type as an "excluded field" so it doesn't show. In the view settings, group by content type.

This will separate your nodes by type and if you have the various fields set to not show if empty, could definitely be the most manageable option.

---
Tags: 7, views
---


# Question
Title: Best practice to alter the attributes variable in a Drupal 8 Twig template
I'm creating a custom Drupal 8 theme based on Bootstrap. (NOTE. I'm aware of https://www.drupal.org/project/bootstrap, I just want some practice.)

More often than not, I find myself adding Bootstrap classes to the existing Drupal classes via the `Attribute` object already available in the template.

For instance, in Bootstrap, the main navigation menu looks like this:

```
<ul class="nav navbar-nav">...</ul>

```

What is the best practice is to add the `nav navbar-nav` classes to Drupal's `menu.html.twig` template? This template already contains the following line:

```
<ul{{ attributes}}>

```

**1) Add the classes with a preprocess function?**

I could add the following function to my `MYTHEME.theme` file to alter the `attributes` variable before it's passed to the template:

```
function MYTHEME_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['attributes']['class'][] = 'nav';
    $variables['attributes']['class'][] = 'navbar-nav';
  }
}

```

**2) Add the classes directly inside the Twig template?**

First, I'd create a template named `menu--main.html.twig` to override only Drupal's main menu.

Then, I'd alter the line with the `<ul>` to:

```
<ul{{ attributes.addClass(['nav', 'navbar-nav']) }}>

```

I find #2 a little less clean but it keeps all the markup in the same place.

What do you think?

# Answer
> 3 votes
If it is your theme then I would do it in a template. Drupal Core converted a lot of preprocess/template to work like that, e.g. the node template.

The advantage is that everything is together as you said and it's a lot easier change it later.

Also if you're a module that defines a template, then someone can just copy that, adjust it and have full control over the classes.

---
Tags: theming, 8
---


title: Why is hook_schema() called twice?

text:
# Question
Title: Why is hook_schema() called twice?
I'm working with entities and, in trying to troubleshoot another issue, I noticed that `hook_schema()` is called twice each time the module is installed. This happened even with a bare bones test module containing only a `hook_schema()` definition. My questions are:

* Is it normal for `hook_schema()` to be called twice on module installation?
* Why would `hook_schema()` be called twice on installation?

# Answer
It seems to be normal. Looking at the hook\_schema documentation, you see that it is invoked in `drupal_get_complete_schema()` in includes/bootstrap.inc and in `drupal_get_schema_unprocessed()` in includes/common.inc. The main difference is that the latter does not invoke `hook_schema_alter()` after the hook\_schema is invoked. The first of those functions seems to be called on practically every page load. The second function is called from `drupal_install_schema()` during the module install process.

Concluding, looking at the code it seems to me that:

* It is normal
* It happens because during installation, Drupal needs the un-altered schema definitions
> 3 votes

# Answer
Actually, `hook_schema()` is not just used when a module is installed, and Drupal creates the database tables the module needs. It is also used from other functions or methods that need to know the fields a database table contains. For example, EntityFieldQuery::propertyQuery() and drupal\_write\_record() use it.

Then, when a module is enabled/installed, Drupal (via `module_enable()`) invokes `hook_schema()` twice:

```
  // Refresh the schema to include it.
  drupal_get_schema(NULL, TRUE);
  // Update the theme registry to include it.
  drupal_theme_rebuild();
  // Clear entity cache.
  entity_info_cache_clear();

  // Now install the module if necessary.
  if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
    drupal_install_schema($module);

    // Set the schema version to the number of the last update provided
    // by the module.
    $versions = drupal_get_schema_versions($module);
    $version = $versions ? max($versions) : SCHEMA_INSTALLED;

    // If the module has no current updates, but has some that were
    // previously removed, set the version to the value of
    // hook_update_last_removed().
    if ($last_removed = module_invoke($module, 'update_last_removed')) {
      $version = max($version, $last_removed);
    }
    drupal_set_installed_schema_version($module, $version);
    // Allow the module to perform install tasks.
    module_invoke($module, 'install');
    // Record the fact that it was installed.
    $modules_installed[] = $module;
    watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
  }

```
> 2 votes

---
Tags: 7, entities, database
---


# Question
Title: Can I temporarily stop update notifications for one project only?
Is there a way I can tell Drupal not to notify me about a particular version of a module? For example, if it isn't security related and I choose not to update one module but would like to receive notifications about other modules (or future versions of the module in question)?

The Drush command from one of the answers to this question is close to what I want except if there are future security updates I would still like to know about it, just no more notifications for this particular version.

```
drush pm-updatecode --lock=module_to_ignore

```

# Answer
> 3 votes
See Update Advanced module:

> Extends the administrative interface for Drupal core's "Update status" module. In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.

---
Tags: security, notifications
---


title: Can this be achieve by attributes?

text:
# Question
Title: Can this be achieve by attributes?
I am thinking of setting a product that is only valid from a period of time eg:

product a from 15january2016 til 15january 2018, upon this setup it will be available from that period of time.

also when creating the product a, I can set the time of the product available more of like a timeslot like : 9:00am - 10:00am - 3booth 10:00am -11:00am - 3booth etc

user will be able to choose more than one.

example :

A buy 9am-10am - 3booth A also buy 10am-11am - 1booth

so A can buy 3stock from a timeslot and also buy another timeslot with only 1 stock. and how do we proceed with this option? can product attributes help?

this product is going to be available daily.

more of like selling practice session.

my question are : can this be achieve by attributes? for timeslot? and since there is only 3 classes, and this each class can only be taken by one person 1hour, is there any solution for validation of stock?

I am brainstorming of doing custom attributes but can not get away of thinking how to handle the stock of the class available or not?

some ideas would be great

thank you!

# Answer
The following four fields would be easily possible for making "timeslot" products:

1. **Start** \- date field, single date (not a range)
*You want a single date field because views will be more straightforward when not dealing with ranges on one field. It's much easier to do two fields and have two filters than it is to have one field with a range filter (date supports both use cases).*
2. **End** \- date field, single date (not a range)
3. **Timeslot** \- Product title would be easiest **OR** taxonomy reference
*The taxonomy route would allow you to make the timeslots fieldable and help you connect products of the same timeslot (if it is helpful to have all 9am - 10am products in a single list).*
4. **Stock** \- You could use commerce\_stock to create a single stock availability **OR** you could just disable the product on checkout.

So, the simplest route would only include a "start" and "end" date field with the product title being the "timeslot" and using the "status" of products as a simple "single availability" flag.

Hope that helps!
> 1 votes

---
Tags: commerce, entities
---


# Question
Title: Rules scheduled email empty when using php variable, but not when hardcoded
I'm using rules scheduler (on D7) to set up a reminder email based on a time specified within a commerce order (more specifically a line item in the order). I was able to get everything set up correctly using these instructions, so that the email is scheduled and send out. However, I am having a problem with the actual content of the email appearing correctly.

Just to clarify the rule setup, the flow is

1. Line item is updated
2. Rules scheduler schedules a component to run based on line item's date field
3. When the scheduled time is hit, the component is triggered
    1. A view that serves the list of users is loaded
    2. Component loops through list of users in the view
        * Email is sent to each user

The content of the email is defined by another view, which I am embedding using:

```
<?php
$id = $line_item->line_item_id;
print views_embed_view('commerce_checkout_page_for_email_embed', 'block_4', $id);
?>

```

The $id above is used to pass the line item's ID into the view to filter results by the current line item.

In my testing, when triggering the component directly on Line Item Update instead of at a scheduled time, everything works perfectly. The email is sent, and the body of the email contains the proper view filtered by the current line item.

However, when the email is sent by rules scheduler, the body of the email is empty. When I hard code `$id` (`$id=1776` instead of `$id = $line_item->line_item_id`) the body of the email is exactly as it is supposed to be. I can only assume that this means that for some reason, the scheduled rule is not able to access the variable I'm passing to it. I also tried passing the token for the line item id, but you cannot pass token in PHP, so that was a bust.

Does anybody know why this might be, or have any suggestions?

# Answer
> 0 votes
Instead of scheduling a rule to execute and send an email with no context, you could use commerce\_messages to create a message entity with all the data saved and then schedule the message\_notify rule to send an email.

Messages: https://www.drupal.org/project/message

Commerce Message: https://www.drupal.org/project/commerce\_message

Message Notify: https://www.drupal.org/project/message\_notify

---
Tags: views, commerce, tokens, rules
---


title: Where do I put the Houzz Badge code?

text:
# Question
Title: Where do I put the Houzz Badge code?
I'd like to add a Best of Houzz badge on our site. I have the code, but don't know where to put it.

Is it Admin --\> structure --\> ... then what?

Since the site was built by someone else and now I'm maintaining it, I really don' want to mess anything up by poking around and "experimenting."

# Answer
> 1 votes
Go to: *YOUR\_SITE/admin/structure/block/add* and fill the info like this:

In *Block body* field you must put the code of the badge and go to the bottom of the page to *Save block*.

Then in the YOUR\_SITE/admin/structure/block page search your block, in this case the name is "*Best of Houzz badge*" then select the region where the block will be displayed (in this case `Sidebar first`)

Go to the bottom of the page and click in the *Save blocks* button.

And you will see the block in your site.

---
Tags: theming, blocks
---


title: Feeds Import - Entity Reference mapping

text:
# Question
Title: Feeds Import - Entity Reference mapping
I have a "Buildings" content type. Within that content type I have a building\_id field, which contains the building ID.

I have an "Employee" content type. Within that content type I have an entity reference to the Buildings content type.

I have a CSV file for employees but it does not have the building label or the node id, only the building\_id.

So my issue is that when I run the employee feed import, I cannot add the building since I only have the building\_id.

How would I map the building\_id in my csv to match the building\_id in the building content type so that it knows which building node it is referencing?

I hope that makes sense :)

Thanks!

# Answer
In the past I used Views Data Export to build a spreadsheet in Views that contain the NID and the plain text field I needed to use as a reference.

Then in Excel, you can use VLOOKUP to join 2 excel files based on a common column (building\_id) so that way you can obtain the entity referenced nid you need for your import.
> 2 votes

---
Tags: entities, feeds
---


# Question
Title: Access argument string for all administrators to access menu
I have implemented a hook\_menu method in a module i'm writing.

The problem i'm facing is, i'm not able to pass an access argument that grants access to all the administrators.

The only one able to access the page is the admin account that was made upon installation.

Any help would be appreciated. This is the code.

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

    $items['admin/config/people/raffle'] = array(
        'title' => 'Raffle',
        'access callback' => 'user_access',
        'access arguments' => array('administer site configuration'),
        'file' => 'raffle_admin.inc',
        'page callback' => 'raffle_abc_view',
    );
    return $items;
}

```

# Answer
Defining your module in hook\_menu is not enough. You need to define hook\_permission() too. You can do something like this

```
function raffle_permission() {
   return array(
    'administer site configuration' => array(
      'title' => t('Administer Site Configuration'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```
> 2 votes

---
Tags: routes, users
---


# Question
Title: How can I index all remaining items programatically?
I'm just using the stock Drupal 7 search. Is there a function to index all the unindexed content from my module? And re-indexing? I haven't found this yet if it exists.

# Answer
One way to do it is `exec("drush search-index");`.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Drush syntax error, unexpected T_FUNCTION in webform.module
When I try to run drush right now I get this error:

```
-bash-4.1$ drush pm-list
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected T_FUNCTION in
<site location>/sites/all/modules/webform/webform.module,
line 4654

```

Here is the function where the error occurs:

```
/**
 * Get a list of all available component definitions.
 */
function webform_components($include_disabled = FALSE, $reset = FALSE) {
  static $components, $enabled;

  if (!isset($components) || $reset) {
    $components = array();
    $disabled = array_flip(webform_variable_get('webform_disabled_components'));
    foreach (module_implements('webform_component_info') as $module) {
      $module_components = module_invoke($module, 'webform_component_info');
      foreach ($module_components as $type => $info) {
        $module_components[$type]['module'] = $module;
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
      }
      $components += $module_components;
    }
    drupal_alter('webform_component_info', $components);
    uasort($components, function($a, $b) {
      return strnatcasecmp($a['label'], $b['label']);
    });
    $enabled = array_diff_key($components, $disabled);
  }

  return $include_disabled ? $components : $enabled;
}

```

Line 4654 is the one that starts with "uasort" (near the bottom). I'm using

* PHP 5.6.15
* Drupal 7.41
* Webform 7.x-4.12

Drush was working for the whole project (up till now) and webform was installed near the start of the project.

# Answer
> 1 votes
It's seems to be a problem with the anonymous function. I read some post that talk about a problem with eAccelerator and the PHP version. The recomendations are:

* disabling eAccelerator and opcode caching
* replacing eAccelerator with Zend's opcache
* reverting to PHP 5.3

You can read more at:

---
Tags: 7, webforms, drush
---


# Question
Title: How to use the table header instead of an exposed dropdown to sort a Views table?
I have a view where the format display is a Table.

I exposed some field for sorting. The problem with that is, instead of activate the Table Header for the choosen sorting field in order to sort, that's created a dropdown where the user can choose the sorting field.

Is there a way to use to Table Header for sorting instead of this generated dropdown.

# Answer
> 3 votes
Go to Table ***Setting*** and check the column ***Sortable*** of the field (like the image) and then click the ***Apply*** button and ***Save*** your view.

You will see the link in the table header

---
Tags: 7, views
---


# Question
Title: Views Long query execution time serious problem
I got some serious issue with the views performance. I am just fetching 9 items using the Tagadelic list with 3 filters and 3 sorting criteria. It says query build long query execute time like 46147.48 m, Which is really frustrating.

Query build by view is as below:

Can you please help??

# Answer
There is no one line answer for you question as there are multiple things that can affect a query running slowly.

What you should do is enable slow query log in MySQL and try to debug from that point why your query is taking so long to execute. Things you can do are,

1. Tune your MYSQL.
2. Turn on slow query log.
3. Use the Explain command to find more info on how your query is executing, http://dev.mysql.com/doc/refman/5.7/en/using-explain.html.
4. Watch out if the tables are correctly indexed.
5. Last but not least, you can use hook\_views\_query\_alter if you feel views is not creating the query optimally.
> 2 votes

---
Tags: views
---


# Question
Title: Is there a way to add a Captcha to Ubercart?
After some fraud attempts, I've been requested to add a Captcha to an Ubercart store in Drupal 7 and am surprised that in my searching I can't find any information on how to do this. Has anyone achieved this?

# Answer
> 1 votes
I am assuming you are talking about the add to cart form. Please share on what page or place you need captcha?

If you cannot find a module, then you need to do exactly what the captcha module does,

1. Write hook\_fomr\_FORM\_ID\_alter for the form for which you need to add the captcha.
2. Look for articles online explaining how to add captcha programmatically on a form in Drupal, ex: How do I add reCaptcha to a custom form?, https://www.drupal.org/node/743056.
3. Enable your custom module containing this code, and the captcha module.

You should have your captcha on ubercart's add to cart or any other form with a submit button.

---
Tags: ubercart, captcha
---


title: Ordering fields in template.php file

text:
# Question
Title: Ordering fields in template.php file
I am trying to theme the user s profile edit form. I Have added a class to the form and the look changed. However i am still struggling to find out how to order the fields in the way i want directly in the template.php file. Here is my code :

```
if ($form_id == 'user_profile_form') {
//dsm($form);
//kpr($form);
$form['#prefix'] = '<div class="nano-ui">

<h1 class="formtitle"> Modifer vos informations</h1>
';
    $form['#suffix'] = '<div style="margin-bottom:100px"></div></div>';

    $form['field_civilite']['#prefix'] = '<div style="margin-bottom:10px">

<div class="notification info  margin" style="margin-top:25px" >
        <h1>Informations personnelles du membre</h1>
      </div></div>
';

$form['field_nom'][und][0][value]['#attributes']['class'] = array("nui-input");
$form['field_prenom'][und][0][value]['#attributes']['class'] = array("nui-input");
$form['field_personne_morale'][und][0][value]['#attributes']['class'] = array("nui-input");

$form['locale']['#prefix'] = '<div style="margin-bottom:10px">
<div class="notification info  margin" style="margin-top:25px" >
        <h1>Preferences compte </h1>
      </div></div>
';

$form['account']['current_pass']['#attributes']['class'] = array("nui-input");
$form['account']['mail']['#attributes']['class'] = array("nui-input");
//$form['field_civilite']['#suffix'] = '<span class="radio"></span>';
$form['field_pays_users'][und]['#attributes']['class'] = array("select");
$form['field_profession'][und]['#attributes']['class'] = array("select");
$form['field_conditions_enregistrement'][und][0][value]['#attributes']['class'] = array("dislaynone");
$form['field_conditions_enregistrement']['#prefix'] ='<div class="dislaynone">';
$form['field_conditions_enregistrement']['#suffix'] = '</div>';

$form['actions']['submit']['#attributes']['class'][] = 'nui-button green';
$form['actions']['cancel']['#attributes']['class'][] = 'nui-button red';

}

```

Is there a way to override UI that manages the fields display for drupal users ?

# Answer
> 0 votes
Firstly, why template.php for reordering the fields of an entity edit form? You should put this logic in a module and not a theme, look up hook\_fomr\_alter and hook\_form\_FORM\_ID\_alter.

Secondly, if the profile is the default user profile in D7 or you have created one using profile2, you can go to the manage fields section of the entity and reorder the fields just by dragging them. That should change the order on both view page and edit page of the entity, no?

Can you try it out and see if it works! You might not need to write code at all!

---
Tags: theming
---


# Question
Title: Rule not being triggered when node is created programmatically
In my project, i created a node programmatically using the following code

```
    function create_my_node() {

$node = new stdClass();
  $node->type = 'custom_content';
  node_object_prepare($node);
  $node->uid = 1;
  $node->title    = 'new node';
  $node->language = LANGUAGE_NONE;
  $node->field_period [$node->language][0]['value'] = $period;
  $node->field_numbers[$node->language][0]['value'] = $number;
  $node->field_numbers[$node->language][0]['format'] = NULL;
  $node= node_submit($node);

  node_save($node); }

```

This works fine.

I then added a rule in the Rules module that says: "After saving new content" and content is "custom content", display a message on the site.

This works fine when I create content from the drupal admin interface, but it doesn't trigger the rule when the node is created through my code.

Please what could i be missing?

# Answer
It might be a `permission` related issue, one post I found on drupal site https://drupal.org/node/929936 contains the discussion about the same.
> 0 votes

# Answer
@seyi I just checked your codes on my local installation with some changes as few we do not required to make this test,so code with which I test is.

```
function save_my_node() {
  $node = new stdClass();
  $node->type = 'page';
  node_object_prepare($node);
  $node->uid = 1;
  $node->title    = 'new node';
  $node->language = LANGUAGE_NONE;
  $node->body = "test";
  $node= node_submit($node);
  node_save($node);

  // setting message using drupal_set_message();
  drupal_set_message("your node is created");
}

```
* As you see use of dupal\_Set\_message();
* it is working in my case.
* Also I tried creating a rule with

+ Event as "After saving new content of type Basic page"
    + Condition as none.
    + Action as "Show a message on the site" the message provided in the actions is alsomworking fine in my case.

I'll recommend debugg codes for node saving,try using jook\_node\_insert(); to custom track of node save process and debug it.
> 0 votes

# Answer
Did you try to enable debug mode in Rules. ? It might help in debugging if there is any issue on Rules side.
> 0 votes

---
Tags: rules
---


# Question
Title: How do I edit the response of successful register.json?
How can you edit the Services' json response of successful register.json to include the user's OR system's auto-generated password, plus any token?

I've tried a variety of combinations of the commented code below..

```
function logintoboggan_process_login($account, &$edit, $redirect = array()){
  global $user;

  $user = user_load($account->uid);
  watchdog('login debug', json_encode($edit)); // AT THIS POINT I CAN VERIFY WE HAVE THE PLAIN-TEXT PASSWORD
  //user_login_submit(array(), array('uid' => $account->uid));
  user_login_finalize($edit);
//  $user = user_load($account->uid);
//  $user->token = drupal_get_token('services'); //WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK.
//  user_login_finalize($edit);
//  module_invoke_all('hook_user_login');
//  module_invoke_all('tripchi_user_login');
//  module_invoke_all('logintoboggan_user_login');

```

and even also tried hacking the drupal core on line 3888 of "/modules/user/user.module":

```
elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
      global $user;
      $user = user_load($account->uid);
      watchdog('login debug', json_encode($edit));  // AT THIS POINT I CAN VERIFY WE HAVE THE PLAIN-TEXT PASSWORD AND TOKEN AVAILBABLE!
      //user_login_submit(array(), array('uid' => $account->uid));
      user_login_finalize($edit);
    //  $user = user_load($account->uid);
    //  $user->token = drupal_get_token('services'); //WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK IN TERMS OF SESSION PERSISTANCE
    //  user_login_finalize($edit);
    _user_mail_notify('register_no_approval_required', $account);
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
    drupal_set_message(t('Registration successful. You are now logged in.'));
    $form_state['redirect'] = '';
  }

```

if one of my test lines don't break the call altogether, on success the call just replies:

```
{
    "uid": "499",
    "uri": "http://localdrupal.tripchi.com/drupalgap/user/499"
}

```

# Answer
> 2 votes
I was never able to get back the raw text password without hacking on the logintoboggan / user modules themselves (similar to what is shown in my question).

However, I solved my same purpose of providing immediate-login-upon-registration for Services/API calls using the services\_token\_access module. This code only hooks onto a success registration then ads the services\_token to the response which is now the only thing my client now needs for validation.

```
function HOOK_services_request_postprocess_alter($controller, $args, &$result) {

if ( gettype($result) == 'array' && isset($result['uri']) && isset($result['uid'])) { // THIS CONDITION MATCHES THE DEFAULT RESPONSE OF A SUCCESSFUL REGISTRATION.
        $user = (object)$result;
        $user = user_load($user->uid);
        $user = HOOK_services_account_object_alter($user);
        $result = array('token'=>$user->services_token, 'user'=>$user);
    }
    return $result;
}

function HOOK_services_account_object_alter(&$user) {
    $user->services_token = services_token_access_update_token($user->uid, FALSE); // essential for logging in later
    $user->specialstuff = 'whatever else you need';
    return $user;
}

```

(The services\_token\_access module is not particularly popular and barely supported, but worked for me.)

---
Tags: 7, users, services, sessions, authentication-authorization
---


title: form_submit hook not firing

text:
# Question
Title: form_submit hook not firing
The title says it all. I've created a form, but the submit hook isn't triggered once the form is submitted.

```
    <?php

//Create raffle form
function raffle_create_form()
{

    //Basic raffle info
    $form['#method'] = 'post';
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "<h5>Raffle information</h5><hr>",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "How many people can join this raffle?",
        "#required" => TRUE
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#prefix" => "<h4>Prize information</h4><hr>",
        "#title" => "Prize type",
        "#required" => TRUE
    );

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        "#required" => TRUE
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';
    return $form;
}

function raffle_create_form_validate()
{
    //validation logic
}

function raffle_create_form_submit()
{
    print_r($_POST);
}

```

Isn't the submit hook supposed to fire automatically?

What i'm doing now is i've set an action to a particular URL, made the menu hook call drupal\_form\_submit and passed the raffle\_create\_form\_submit as an argument.

```
    <?php

//Create raffle form
function raffle_create_form()
{

    //Basic raffle info

    $form['#action'] = url('/admin/config/people/raffle/create/post');
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "<h5>Raffle information</h5><hr>",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "How many people can join this raffle?",
        "#required" => TRUE
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#prefix" => "<h4>Prize information</h4><hr>",
        "#title" => "Prize type",
        "#required" => TRUE
    );

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        "#required" => TRUE
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';
    return $form;
}

function raffle_create_form_validate()
{
    //validation logic
}

function raffle_create_form_submit()
{
    print_r($_POST);
}

//Menu hook

```

function raffle\_menu() { $items = array();

```
$items['admin/config/people/raffle'] = array(
    'title' => 'Raffle',
    'access callback' => 'user_access',
    'access arguments' => array('Manage Raffles'),
    'file' => 'raffle_admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('raffle_admin_page')
);

$items['admin/config/people/raffle/create'] = array(
    'title' => 'Create Raffle',
    'access callback' => 'user_access',
    'access arguments' => array('Manage Raffles'),
    'file' => 'raffle_admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('raffle_create_form')
);

$items['admin/config/people/raffle/create/post'] = array(
    'title' => 'Creating Raffle!',
    'access callback' => 'user_access',
    'access arguments' => array('Manage Raffles'),
    'file' => 'raffle_admin.inc',
    'page callback' => 'drupal_form_submit',
    'page arguments' => array('raffle_create_form_submit')
);
return $items;

```

}

Is this the way it should be done?

# Answer
> 1 votes
@Haider Ali, Drupal form need to be defined with the $form, $form\_state arguments

```
  function your_form_name($form, &$form_state) { }

```

For validate and submit function, you need to define them with function name following \_validate and \_submit respectively. So your validate function should be like

```
  function your_form_name_validate($form, &$form_state) { }

```

and submit function:

```
  function your_form_name_submit($form, &$form_state) { }

```

If form, and related functions are defined in this way, then only validate and submit function will be called by default. Else they will not be called.

---
Tags: hooks, forms
---


# Question
Title: What's the usage difference between element_validate and validate hook?
From what i've learned today, there are two ways one can go about validating input.

One is the #element\_validate field which is passed along the form hook, and the other is the validate hook.

Why use the validate hook if input can be validated with the #element\_validate field? Is it a necessity to implement the validate hook in this case?

Or is it a method that should be implemented for complex validation while all simple validation(is number, is date, is url) can be done via the #element\_validate option?

# Answer
@Haider Ali with ***#element\_validate***, we can add our own custom validation functions to a **field** or we can pass the validation functions provided by Drupal, e.g., **element\_validate\_integer\_positive()**, **element\_validate\_number()**, etc.

This #element\_validate works only on the field we added it to.

When we want to add custom validation to multiple fields, we add it in form **validate hook**, so that we do not need to add separate function to each field and call multiple validate functions.
> 1 votes

---
Tags: hooks, forms
---


title: Implement like on image

text:
# Question
Title: Implement like on image
I create gallery list from views 7.x-3.11 with display image and title. When click on title go on content page, its works fine.

I want to display like button on gallery list page of every image.

I try on **flag** with **dlike** module and add field in views of `GLOBAL: PHP` and write code `print flag_create_link("machine_field_name", $row->title)`, Display Label fine but when click on Label, display popup with A https 500 error occurred.

I also try with Like Button module but. It show like button only one in one page, i want to like every image.

**My question is how to display like button of every image in page when create page with views.**

# Answer
> 0 votes
I'm almost certain that adding global: text and using the php text format works.. I remember having trouble with this ages ago so that could be it.

# Answer
> -1 votes
While using Like Button module, ***in view***:

**Add the field (you created using likebtn widget) to *Fields section* of the view, it will add like button to each image(each content).**

---
Tags: 7, views
---


title: How to handle hook_node_validate?

text:
# Question
Title: How to handle hook_node_validate?
I am using some contirb module and in which `hook_node_validate` is used. I am overriding the function passed in hook by running `CUSTOM_MODULE_node_validate`. But the contrib module validate also keeps running, is there any way that I can stop it running and let only mine one to run?

```
function CUSTOM_MODULE_node_validate($node) {

  $nodep = 'object' == gettype($node);
  $isrelevantp = _anonymous_publishing_relevantp($node, $nodep);
  if ($isrelevantp) {
    custom_anonymous_publishing_cl_content_validate($node); // function replaced with my custom for validation
  }

}

function custom_anonymous_publishing_cl_content_validate($node){
  ..........
}

```

ALREADY RUNNING IN MODULE:

```
/**
 * Implements hook_node_validate().
 *
 * The validate function will handle the honeyfield.
 */
function anonymous_publishing_cl_node_validate($node) {
  $nodep = 'object' == gettype($node);
  $isrelevantp = _anonymous_publishing_relevantp($node, $nodep);
  if ($isrelevantp) {
    _anonymous_publishing_cl_content_validate($node);
  }
}

function _anonymous_publishing_cl_content_validate($node){
  .......
}

```

# Answer
You can remove a module's implementation of a hook like so:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_validate' && isset($implementations['anonymous_publishing_cl'])) {
    unset($implementations['anonymous_publishing_cl']);
  }
}

```
> 4 votes

---
Tags: 7, nodes, hooks
---


title: Create an entity within an entity

text:
# Question
Title: Create an entity within an entity
Hopefully there is something out there to do what I want. I imagine my terminology is off hence why my googling is failing.

I have two content types.

Album & Track.

I want to create a new Album. When creating an Album I want to be able to reference tracks to it. I know I could create the tracks first then use the entityreference module to add those tracks to the album.

What I want to do is to create the Tracks on the fly. So have an Add track button, fill in the fields for track and then for it to be associated with the album.

For my purpose Track does not need to be it's own content type but I need to able to capture more than one field when pressing the add button.

Any ideas if there is anything out there for this?

If not I can try hacking together something in code.

# Answer
> 2 votes
You want to use references and something like the Inline Entity Form module.

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

# Answer
> 0 votes
https://www.drupal.org/project/entityreference\_autocreate could be an option. Never had to use it but have it bookmarked for when I eventually will. Can't help with instructions.

---
Tags: 7, entities
---


# Question
Title: Node is flagged, flag has node reference field, how to show list of referenced nodes to author
This is a little convoluted, so I'll try to be as clear as possible by using concrete examples.

It's basically a "relevant job suggestion" system. It works like this:

* A "candidate" user creates a "CV" node.
* An "employer" creates "job" nodes.
* There is a flag set up that is attached to CVs.
* This flag has a node reference field.
* When an employer flags the CV, they choose a job node to reference (suggest)

I want to display a view of all job nodes suggested for that candidate - visible only to them (the author of the flagged node).

I hope that makes sense. I think the part I'm struggling with is getting the relationships & contextual filters right, so any pointers there would be appreciated.

# Answer
I would have an entity reference field for the user where their CV node is referenced. (Using rules on node creation). Helps in many ways.

In views, the contextual filter would be getting those CV nodes using the entity reference filter.

Then in the relationships, you would pick the appropriate flag and it should display the relevant job postings.

I'll test this tomorrow as its very similar to something i did before. I might be off on the contextual filter but i think you should definitely use entity reference from the beginning.

Edit: I'm actually quite certain you should be able to do this without entity reference or rules. Filter the view using Job content type. Then two relationships, one for node authored and flag.
> 0 votes

---
Tags: views, nodes, flags
---


# Question
Title: Using Views: how to display all node edits made by user X while excluding the "first time created" nodes (original node revision)
For my content type I have enabled support for revisions. When I make view it displays the revisions along with nodes created by user. Is there any way to get only the list of edited nodes. If user created node and then edited it, I just want to show users edits only. please suggest?

**UPDATE EXPORT VIEWS CODE :**

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'tetstststst';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Header: Global: Result summary */
$handler->display->display_options['header']['result']['id'] = 'result';
$handler->display->display_options['header']['result']['table'] = 'views';
$handler->display->display_options['header']['result']['field'] = 'result';
$handler->display->display_options['header']['result']['content'] = 'Displaying  @total';
/* Relationship: Content revision: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content revision: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'node_revision';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['label'] = '';
$handler->display->display_options['fields']['title_1']['alter']['path'] = '[link_to_revision] ';
$handler->display->display_options['fields']['title_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title_1']['link_to_node_revision'] = TRUE;
/* Field: Content: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'node';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
$handler->display->display_options['fields']['changed']['date_format'] = 'long';
$handler->display->display_options['fields']['changed']['second_date_format'] = 'long';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'link' => 'link',
);

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

```

**EXPORT VIEWS CODE** \[**updated** \- taken from oksana-c's example\]:

```
$view = new view();
$view->name = 'content_revisions';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node_revision';
$view->human_name = 'Content Revisions';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Content Revisions';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'view revisions';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'timestamp' => 'timestamp',
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'timestamp' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content revision: Content */
$handler->display->display_options['relationships']['vid']['id'] = 'vid';
$handler->display->display_options['relationships']['vid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['vid']['field'] = 'vid';
/* Relationship: Content revision: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content revision: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node_revision';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node_revision'] = TRUE;
/* Field: Content revision: Updated date */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'node_revision';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['timestamp']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content revision: Updated date */
$handler->display->display_options['sorts']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['table'] = 'node_revision';
$handler->display->display_options['sorts']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Post date */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'node';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['relationship'] = 'vid';
$handler->display->display_options['filters']['created']['operator'] = 'empty';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');

```

**RESULTS FROM UPDATED VIEW**

# Answer
> 2 votes
**UPDATE:** Original answer was completely overridden as the embedded view export did not produce desired results. Below is the View Export that produced desired results and some insight on

> how to display all node edits made by user X while excluding the "first time created" nodes (original node revision).

Here's a little **PROLOGUE**:

Every time the node is edited - a new revision is created (you can bring your revisioning methods one level up by installing Revisioning module). So essentially each edit is a revision including the original node version, which also has it's own revision number. Even though revision info ais accessible through Views, there is no default method to differentiate the Original Revision (revision where node was created first) from other revisions in Views. This is because there are no fields that you can query that will tell you that the revision is the original node version. The only field that one can use for differentiating original version from revisioned version is "Node's Created Date". Unfortunately we cannot query this field in Views when we use revisioning and the only way to filter out the original versions of nodes from a View is to compare "created" date and "updated date".

**SOLUTION:** This task requires a custom Views filter, which will query "created date" of each node and compare it with "updated date" from the node's revision.

The quick way of doing this is to install Views PHP module and use Global:PHP filter in View to query and compare dates. ***Warning:*** *Views PHP may affect View performance significantly depending on the amount of results that should be processed.*

The right way of doing this is to create custom Views filter handler. Some info on it here and here.

So here it is - the updated View Export that displays all revisions + dates of user X while filtering out Original Node Version. This View requires Views PHP module.

```
    $view = new view();
$view->name = 'content_revisions';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node_revision';
$view->human_name = 'Content Revisions';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Content Revisions';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'view revisions';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'timestamp' => 'timestamp',
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'timestamp' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content revision: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Relationship: Content revision: Content */
$handler->display->display_options['relationships']['vid']['id'] = 'vid';
$handler->display->display_options['relationships']['vid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['vid']['field'] = 'vid';
/* Field: Content revision: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node_revision';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['link_to_node_revision'] = TRUE;
/* Field: Content revision: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node_revision';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['exclude'] = TRUE;
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Field: Content revision: Updated date */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'node_revision';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'custom';
$handler->display->display_options['fields']['timestamp']['custom_date_format'] = 'm/d/y H:i:s T';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: Content revision: Updated date */
$handler->display->display_options['sorts']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['table'] = 'node_revision';
$handler->display->display_options['sorts']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'vid';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Global: PHP */
$handler->display->display_options['filters']['php']['id'] = 'php';
$handler->display->display_options['filters']['php']['table'] = 'views';
$handler->display->display_options['filters']['php']['field'] = 'php';
$handler->display->display_options['filters']['php']['use_php_setup'] = 0;
$handler->display->display_options['filters']['php']['php_filter'] = '$node = node_load($row->nid);
$timestamp_original = $node->created;
$timestamp_edit = $row->timestamp;
if ($timestamp_original != $timestamp_edit) { return FALSE; }
else return TRUE;';

```

---
Tags: 7, views, nodes
---


# Question
Title: Unlike other rules my custom Commerce Fees rule is executing on every cron job
I have the following Commerce Fees rule:

```
{ "rules_setup_fee" : {
    "LABEL" : "Setup Fee",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce License Billing" ],
    "REQUIRES" : [ "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "commerce-order:commerce-line-items:0:line-item-label" ] } },
      { "AND" : [
          { "text_matches" : {
              "text" : [ "commerce-order:commerce-line-items:0:line-item-label" ],
              "match" : "VS"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "setup_fee",
          "amount" : "999",
          "currency_code" : "USD"
        }
      }
    ]
  }
}

```

which is working just fine, however it is the only rule that shows in the log messages way too frequently:

```
Type    rules
Date    Thursday, January 14, 2016 - 17:50
User    drupal
Location    http://drupal/admin/config/system/cron
Referrer    http://drupal/admin/config/system/cron
Message Rules debug information:
" Reacting on event Apply a fee to a given order.
0 ms Reacting on event Apply a fee to a given order.
2.988 ms Evaluating conditions of rule Setup Fee. [edit]
3.538 ms The condition data_is_empty evaluated to TRUE [edit]
3.547 ms AND evaluated to FALSE.
3.563 ms Finished reacting on event Apply a fee to a given order.
Severity    notice

```

It seems like while other rules execute only when necessary, this one does on every cron run. What kind of condition I should add to the rule to make it execute only when someone tries to actually tries to put something in the shopping cart?

# Answer
> 0 votes
I take from the rule export that you're using Commerce License Billing? Well, if you are, then likely it is applying the fees whenever doing it's billing calculations.

Commerce Fees defines it's own rules event that fires off when an order refresh occurs. Order refreshes are done by calling `commerce_cart_order_refresh()`. When you load an order, a `hook_commerce_order_load()` gets invoked and `commerce_cart` has a `commerce_cart_commerce_order_load()` hook that refreshes orders if certain criteria are met:

1. The order hasn't been refreshed in this request.
2. The order is a shopping cart.
3. The order is the latest revision.
4. The order can be refreshed. (Commerce 1.9 added new rules to add performance by regulating this better.)

Long story short: It sounds like your install is working fine and in general unless you have thousands of rules firing on every page request, there is little to worry about. Rules are effectively just a wrapper around plan PHP functions. Your cron is running and a new order is being generated or refreshed in some way and so the rule fires.

---
Tags: commerce
---


title: Where do I import a panels variant?

text:
# Question
Title: Where do I import a panels variant?
In the Panels UI, when you are editing a variant, you have the option to **Export** the variant, and the tooltip says "*Export the variant into code to import into another page*."

This is exactly what I would like to do, but where do I paste the code to import it? When I choose **Add variant**, I don't see an option to import, and I don't see an import option in the Page Manager UI (admin/structure/pages) either.

# Answer
> 7 votes
If you are not the super admin (user id = 1) on your drupal site.

You need to give the permission for "Use CTools importer" to be able to import a variant.

# Answer
> 2 votes
there should be an import button at the top of the page beside the Add Variant:

---
Tags: panels
---