# Question
Title: Installing updates through the UI does not work
This is what I get when trying to install any update from `/admin/reports/updates/update`

It stays stuck like that and progress bar doesn't move. I even set permissions in sites/all and sub dirs to 777.

E.g. the update.php works. I upgraded from 7.34 to 7.41 and ran update.php no problem, but cannot update a single module.

EDIT: Actually it crashed after 20 minutes. This is the error:

```
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: http:///corporate/authorize.php?batch=1&id=41&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {queue} WHERE (item_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 202 ) in SystemQueue->deleteItem() (line 273 of /modules/system/system.queue.inc).Uncaught exception thrown in shutdown function.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {batch} SET batch=:db_update_placeholder_0 WHERE (bid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => a:12:{s:4:"sets";a:1:{i:0;a:15:{s:7:"sandbox";a:0:{}s:7:"results";a:2:{s:3:"log";a:1:{s:13:"jquery_update";a:3:{i:0;a:2:{s:7:"message";s:27:"Error installing / updating";s:7:"success";b:0;}i:1;a:2:{s:7:"message";s:114:"File Transfer failed, reason: /jquery.ui.datepicker-nl.js is outside of the /domains//public_html/corporate";s:7:"success";b:0;}s:6:"#abort";b:1;}}s:5:"tasks";a:0:{}}s:7:"success";b:0;s:5:"start";d:1451383853.52180004119873046875;s:7:"elapsed";i:0;s:5:"title";s:18:"Installing updates";s:12:"init_message";s:40:"Preparing to update your site<br/>&nbsp;";s:8:"finished";s:38:"update_authorize_update_batch_finished";s:4:"file";s:35:"modules/update/update.authorize.inc";s:16:"progress_message";s:29:"Completed @current of @total.";s:13:"error_message";s:22:"An error has occurred.";s:3:"css";a:0:{}s:5:"total";i:1;s:5:"count";i:1;s:5:"queue";a:2:{s:4:"name";s:17:"drupal_batch:41:0";s:5:"class";s:10:"BatchQueue";}}}s:16:"has_form_submits";b:0;s:11:"current_set";i:0;s:11:"progressive";b:1;s:3:"url";s:46:"http:///corporate/authorize.php?batch=1";s:11:"url_options";a:0:{}s:10:"source_url";s:0:"";s:8:"redirect";s:38:"http:///corporate/authorize.php";s:5:"theme";s:5:"seven";s:17:"redirect_callback";s:11:"drupal_goto";s:2:"id";s:2:"41";s:13:"error_message";s:120:"Please continue to <a href="http:///corporate/authorize.php?batch=1&amp;id=41&amp;op=finished">the error page</a>";} [:db_condition_placeholder_0] => 41 ) in _batch_shutdown() (line 537 of /includes/batch.inc).

```

EDIT2: If you click go to error page:

```
Notice: Undefined index: log in update_authorize_update_batch_finished() (line 187 of /modules/update/update.authorize.inc).
Warning: Invalid argument supplied for foreach() in update_authorize_update_batch_finished() (line 187 of /modules/update/update.authorize.inc).
Notice: Undefined index: log in update_authorize_update_batch_finished() (line 236 of /modules/update/update.authorize.inc).
Update failed! See the log below for more information.

```

# Answer
> 1 votes
To answer the question, there are generally two things that go wrong during updates. Either the update cannot be downloaded, or there is some other process clogging the batch operation.

If the update fails to download, check the `Administer > Site configuration > File system` page and make sure the temporary directory listed there exists and is writable by your fileserver. For linux generally `/tmp` (temporary files directory in the OS root) is generally good, for Windows it is often better to create a folder somewhere (`C:\Windows\temp` often does not work).

If the queue is clogged, there might be a function throwing errors preventing the other processes from continuing. This way the queue and batch tables can fill up rapidly without ever doing something. Make a database backup, truncate the `batch` and `queue` tables and see if it makes a difference.

The second error you are seeing is because the process did not complete, and is not the cause but the result of the error.

---
Tags: 7, updating, installation
---


# Question
Title: Is it possible to POST more than one article at once?
How do I POST two or more articles at once?

Something like follows:

```
{
"_links":{ "type":{ "href":"http://drupal8/rest/type/node/article" } },
"title":[{"value":"Title 1"} ],
"title":[{"value":"Title 2"} ]
}
Result: Status Code: 400 Bad Request "Syntax error"

```

It is even possible for a single request to add more than one article?

# Answer
> 0 votes
As far as I know there is now way to create multiple nodes in one request. You can send multiple requests instead.

The JSON format need not to to be that much complex(as you mentioned in your POST).

You can use the following JSON format to create a node.

> **URL :** http://www.example.com/d8/entity/node
>
> **Method:** POST
>
> **Headers:**
>
> **Name:** X-CSRF-Token
>
> **Value:** TPlhcaO\_KESksKPye805T86j0-ja9rhyfaaqi6zpA8

You can get user session token by requesting the following URL

URL: http://www.exmaple.com/rest/session/token

JSON format to create a node (Article) for **D8**

```
{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hi World"}],
}

```

I've tested this on my D8 instance. It's working fine. Hope it helps

---
Tags: 8
---


# Question
Title: How to get Final SQL query when using Views?
How do I get complete SQL query from Views, the one I could run in mysql directly.For example biggest stumbling block is fields part. Like below

```
SELECT users_node.uid AS users_node_uid, node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail, 'user' AS field_data_field_first_name_user_entity_type, 'user' AS field_data_field_last_name_user_entity_type, 'node' AS field_data_field_purchase_date_node_entity_type, 'node' AS field_data_field_serial_number_node_entity_type
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid
WHERE (( (node.status = '1') AND (node.type IN  ('product_registration')) ))
ORDER BY node_created DESC
LIMIT 50 OFFSET 0

```

this lines are problematic field\_data\_field\_first\_name\_user\_entity\_type, field\_data\_field\_last\_name\_user\_entity\_type etc

They are not real fields in DB, they somehow get rewritten somewhere, but I can't find where and how. How to get the FINAL query to DB in drupal when using views?

p.s. in image, you can see what I get for those fields in phpmyadmin if I run query. Not really useful.

# Answer
Try the Views Show Query module

> This module shows real SQL query in Views UI during live preview.
>
> 'Real query' means it is rewritten by query\_alter hooks. For instance, node access checks are added, so this requires selecting the user on behalf of which the query is supposed to be executed. So the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.
>
> This module makes it possible to show SQL query not only during live preview, but when the view is executed normally. You can add footer to the view with the following PHP code:

```
<?php
$rows = array();
$view->exposed_input['views_show_query_uid'] = 1;
views_show_query_views_preview_info_alter($rows, $view);
drupal_set_message($rows['query'][0]);
?>

```
> 0 votes

---
Tags: database, views
---


# Question
Title: Is there a CKeditor / Drupal module that allows for a one-button image upload (without requiring Flash)?
**Background:** I'm looking to add an image upload button to CKeditor. Ideally, I'd like to automated the click responses to start IMCE and jump right to the IMCE Upload button. In fact, I'd like to put the IMCE upload button on CKeditor's tool bar.

**My Question:** Is there a way to put the IMCE Upload button directly onto the CKEditor tool bar just like we have here in side of StackExchange?

**What I've seen/tried:** I've seen other methods recommending One Click Upload but this uses SWFloader. The Media module is great but people want a direct upload from inside the editor. They don't want to jump to another screen.

# Answer
The Insert module should be perfect for this https://www.drupal.org/project/insert

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
>
> This module was previously known as FileField Insert.
> 2 votes

---
Tags: 7, wysiwyg, files, media
---


# Question
Title: Dev version connects to the live site database despite settings.php
I've made a dev copy of the site to perform some tests and bug fixes:

1. copied site files to the separate directory
2. copied database under the same user, so I'm able to see both DBs in the phpmyadmin
3. edited settings.php to point dev to the copied database
4. created new nginx conf to serve dev.mysite.com

BUT, the dev version is still communicates with the production DB somehow.

Server configuration: Ubuntu, Varnish front, Nginx back, MariaDB, opcache

Site configuration: Drupal7, single-site setup

And of course, I've double checked settings.php

Christmas mystery?

# Answer
> 0 votes
You did not edit your sites.php file or name the new site directory in such a way that Drupal can discover it.

# Answer
> 0 votes
It's Nginx misconfiguration: dev domain was pointed to the production directory

---
Tags: database, configuration
---


# Question
Title: How to add indexed:has taxonomy term id(with depth) in the contexual filter of view?
I have created a view and added indexed fields to that view to show content.

I want to show content related to taxonomy "related place" as well as its related child taxonomy content. For selecting child taxonomy I used simple hierarchical module, but the problem I am facing is that I'm not getting any option to select Indexed:has taxonomy term id(with depth) in contexual filter to show content .

The propose of using indexed fields in views for filtering content using facet api.

I've tried everything to achieve this, but no result.

# Answer
> 0 votes
In custom module

* you can use hook\__views\_pre\_view to change contextual filter,
* add children terms till depth to the contextual filter,
* function taxonomy\_get\_children\_all() defined below, will fetch all child terms till depth:
* In view, don't forget to allow multiple value contextual filter for contextual filter.

```
function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
       foreach ($below as $nt => $nd){
         $result[$nt] = $nd;
       }
    }
 }
 return $result;
 }

 function formalter_views_pre_view(&$view, &$display_id, &$args){
 if($view->name == "category_view") { // && $display_id == "page") {
   $vid = <Your vocabulary id>;

   $t = $args[0];

   $tt = taxonomy_get_children_all($t,$vid);
   foreach($tt as $k => $v) {
     $a = (string)$k;
     $args[0] = $args[0] . "+" . $a;
   }
 }
}

```

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


# Question
Title: Can we make template for contextual filter?
Can we make template for contextual filter, because while I am writing php code in it, it is not supplying true values. I am writing these code in php code of contextual filter:

`<?php
 $children = array_keys(taxonomy_get_children($handler->argument, $vid=1));
 if(!empty($children)) $handler->argument .= '+' .implode('+', $children);
?>`

I need to apply these code in template file so that get satisfactory result over there and can apply some custom code too.

# Answer
> 0 votes
There is no such template, but to override contextual filters you can follow the following approach:

In a custom module

you can use hook\__views\_pre\_view to change contextual filter, add children terms till depth to the contextual filter, function taxonomy\_get\_children\_all() defined below, will fetch all child terms till depth: In view, don't forget to allow multiple value contextual filter for contextual filter.

```
function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
       foreach ($below as $nt => $nd){
         $result[$nt] = $nd;
       }
    }
 }
 return $result;
 }

 function formalter_views_pre_view(&$view, &$display_id, &$args){
 if($view->name == "category_view") { // && $display_id == "page") {
   $vid = <Your vocabulary id>;

   $t = $args[0];

   $tt = taxonomy_get_children_all($t,$vid);
   foreach($tt as $k => $v) {
     $a = (string)$k;
     $args[0] = $args[0] . "+" . $a;
   }
 }
}

```

---
Tags: 7, views
---


# Question
Title: How to assign credit hours to user account once the content is marked completed by admin
I have a custom content type "course" and it has an entity reference to username. ( the username is basically an instructor who is suppose to teach the course )

I have created a field "Course Completed" in course content type and admin changes it to "completed" manually. The content type also has a filed "Number of hours"

What i need is, when the node is marked as completed, the "Number of hours" is taken from node and added to user account. ( i can create a field using profile2 and name it as "user credit hours")

How would i do this? is there any module which will work similar to what is needed ?

thanks

# Answer
> 0 votes
i managed to do it with rules and adding some action code in a custom module.

After adding a condition, i had a make a custom action and then i was able to add that action in to the created rule.

You can send value to your custom action and then load user and update its field.

```
$user = user_load($user_trainer_id);
$obj = entity_metadata_wrapper('user', $user);
$obj->field_earned_credit_hours = $new_custom_value;
$obj->save();

```

---
Tags: nodes, rules, users
---


# Question
Title: How do you re-direct an alias at a scheduled time?
I am using Drupal 7(.40 or .41) and what I am trying to achieve is to completely change a pages content at a specific time & date (00:00:01 01/01/2016 to be specific)

Because the content changing is about 90% of the page, I presumed that I could set a node to unpublished at 23:59:59 with the alias and then publish the new node at 00:00:01 with the same alias. However it throws up an ***alias is in use*** error.

There is nothing obvious in my URL Alias config (`/admin/config/search/path`) that would indicate this is possible so I am probably looking at it the wrong way, short of using a different URL.

Thoughts and methods would be welcome.

# Answer
I would use the Rules module for this. But you can't "rely" on the *Rules Scheduler* in this case, if you want the redirect to start happening as of `00:00:01 01/01/2016` (sharp).

# Redirect old path to new path

Here is the rule you'd need for it (in Rules export format, just use copy/past to import it in your own setup):

```
{ "rules_redirect_an_alias_at_a_scheduled_time" : {
    "LABEL" : "Redirect an alias at a scheduled time",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "AND" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "the_old_path" } },
          { "data_is" : {
              "data" : [ "site:current-date" ],
              "op" : "\u003E",
              "value" : 1451602800
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Please note that the old path (= the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

```

A few more tweaks to make it fit your exact scenario:

* change all occurences of `the_old_path` to the path to be used **until** `00:00:00 01/01/2016`.
* change all occurences of `the_new_path` to the path to be used **starting from** `00:00:01 01/01/2016`.

Whenever such redirect actually happens, the user will also receive an informational message like so:

> *Please note that the old path (= `/the_old_path`) is no longer in use, you will be redirected automatically to its corresponding path (= `/the_new_path`)*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the exported rule above.

**Attention**: this exported rule uses UTC times ... if your question is about another timezone, make sure to also tweak the value of `1451602800` to fit your needs.

# Redirect new path to old path

If you don't want to have the new path be shown yet BEFORE `00:00:01 01/01/2016`, then just create a similar rule like the previous one, in which you swap the `the_old_path` and `the_new_path`, and reverse the test on the `site:current-date`.
> 3 votes

# Answer
You need to set rules which schedule node to be published on specific time after cron run it would automatically be published.
> 0 votes

---
Tags: 7, nodes, redirection
---


# Question
Title: Form element validation #element_validate not working
I am porting this contrib module to D8 and need some help.

The module is shipped with a custom node type. Certain elements options in the node\_form will be populated dynamically. Also other modules needs to able to provide options for these fields.

`hook_form_FORM_ID_alter` calls the wrapper class `MyModuleManager` that performs several helper duties. All is going well except that I can not get the custom element\_validation to work.

Upon form validation a warning is generated

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'FilebrowserManager' not found in Drupal\Core\Form\FormValidator->doValidateForm() (line 282 of core/lib/Drupal/Core/Form/FormValidator.php).

```

together with the fatal error:

```
Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /var/www/drupal8/core/lib/Drupal/Core/Field/WidgetBase.php on line 376 and defined in Drupal\Core\Field\WidgetBase->massageFormValues() (line 511 of core/lib/Drupal/Core/Field/WidgetBase.php).

```

The fatal error occurs exactly when validating `$form['my_field']`

```
class MyModuleManager implements MyModuleManagerInterface {
  use StringTranslationTrait;

  public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
    ...

    return $form;
  }

  public function addFormDefaultOptions(array $form, FormStateInterface $form_state) {

    // Replace MyModule_hook by Events
    // ...
    // Events returns dynamic $options

    $form['my_field']['widget']['#options'] = $options;
    $form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

    return $form;
  }

  public function myModuleValidateTrue() {
    return;
  }

}

```

As the warning tells it can not find the callback in FormValidator I suspect the problem might be the way I wrapped my code in this class. Being new to OOP I would appreciate all help.

# Answer
> 0 votes
It's probably this line:

```
$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

```

Which should be this, without parentheses in the method name:

```
$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue'));

```

See PHP: Callbacks / Callables for the full story.

---
Tags: forms
---


title: How do I fix a shipping rule?

text:
# Question
Title: How do I fix a shipping rule?
I have some rules to set the shipping rate depending on weight and address, but I can't make them work properly. The shipping rate is loaded, but there aren't changes with the weight.

```
{
  "rules_atacama" : {
    "LABEL" : "Atacama",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules",
      "commerce_physical",
      "commerce_order",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-shipping-service" ],
          "value" : "costos_envio"
        }
      },
      { "OR" : [
          { "commerce_physical_rules_order_weight_comparison" : {
              "commerce_order" : [ "commerce-line-item:order" ],
              "operator" : "\u003E=",
              "value" : "0",
              "unit" : "g"
            }
          },
          { "commerce_physical_rules_order_weight_comparison" : {
              "commerce_order" : [ "commerce-line-item:order" ],
              "operator" : "\u003C",
              "value" : "1500",
              "unit" : "g"
            }
          }
        ]
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:order" ],
          "field" : "commerce_customer_shipping"
        }
      },
      { "OR" : [
          { "commerce_order_compare_address" : {
              "commerce_order" : [ "commerce-line-item:order" ],
              "address_field" : "commerce_customer_shipping|commerce_customer_address",
              "address_component" : "administrative_area",
              "value" : "AT"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "3350",
          "component_name" : "flat_rate_costos_envio",
          "round_mode" : "0"
        }
      }
    ]
  }
}

```

Can anyone help me?

# Answer
> 2 votes
If you're taking the pure rules route, you'll need a single rule per rate. So if you have two (2) zones and three (3) weight tiers, you'll need six (6) total rules. For example:

1. Northeast
2. Rest of the US

And

1. 0-5 lbs
2. 6-10 lbs
3. 11+ lbs

Will be 6 total rules:

1. Northeast (0-5 lbs)
2. Northeast (6-10 lbs)
3. Northeast (11+ lbs)
4. Rest of the US (0-5 lbs)
5. Rest of the US (6-10 lbs)
6. Rest of the US (11+ lbs)

You may also find it worth your time to review Commerce Shipping Postal Code Weight and Commerce Shipping Weight Tariff.

---
Tags: 7, commerce, rules
---


# Question
Title: Clean URLs disabled even though module-rewrite is on
I have a manually installed LAMP environment on Ubuntu 15.10 **Desktop** and when I came to install Drupal 8 on it i've seen that clean URLs are disabled, so I turned on the Apache2 (2.4.12) rewrite module in the terminal via:

```
sudo a2enmod rewrite

```

Than I got:

```
Module rewrite already enabled

```

And yet when I cleared the browsers' cache and refreshed the installation page I still get:

> Clean URLs Disabled.
>
> Your server is capable of using clean URLs, but it is not enabled. Using clean URLs gives an improved user experience and is recommended.

So, if I turned on the rewrite module, why Drupal 8 still can't use them?

# Answer
I was having the same problem, I opened the `/etc/apache2/apache2.conf` file and located this portion of the file

```
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

```

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done.
> 10 votes

---
Tags: uri
---


# Question
Title: Ckeditor and IMCE not working with Plupload
When I use IMCE with CKeditor as a WYSIWYG for my website it works fine:

However when I add the Plupload module which would allow me multiple files selection it breaks!

If this can't be fixed, is there any other alternatives similar to Plupload that I can use with CKeditor?

# Answer
> 0 votes
Use Insert module instead of IMCE

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

# Answer
> 0 votes
Check the module IMCE Uploader. It depends on IMCE and Plupload.

> Besides that, It also provides the Plupload uploader as a plugin (in this module) to allow uploading multiple files at a time. If you want to use it, just select "IMCE Uploader - Plupload" the module list and enable it

---
Tags: 7, wysiwyg, files, media
---


# Question
Title: Convert exposed dropdown filter to links Drupal Views
So I have a date filter for my view which filters the view by post date(year). I already used BEF(Better Exposed Filters) but the only available options there is Default select list or jQuery Date Picker. I've attached some pics here, the first one is what's the filter looks like currently and the second one is how it should look. Need to convert the dropdown to look like the second pic. Thanks!

# Answer
> 1 votes
You can use something like this:

Add a contextual filter to your view for 'Content:created year"

Add a Header Global Text Area (Full HTML) with this in it:

```
<ul>
<li><a href="by-date/2012">2012</a></li>
<li><a href="by-date/2013">2013</a></li>
<li><a href="by-date/2014">2014</a></li>
<li><a href="by-date/2015">2015</a></li>
</ul>

```

by-date is my view's path. Yours will be different.

Style it.

Looks like this without styling:

If you don't want a contextual filter you could create your date links with a query parameter like this:

```
by-date?date-filter=2015

```

Then use a views hook to read the query paramter and add the filter in code.

# Answer
> 1 votes
```
<code>
Please go through the following steps to display the select list as year links
//hook_theme
function mymodule_theme($existing, $type, $theme, $path){
    return array(
        'list_items' => array(
            'template' => 'list_items', //tpl to display them as list
            'path' => $path . '/templates',
            'type' => 'module',
            'variables' => array(
                'list' => NULL,
                'current' => NULL
            ),
        ),
    );
}
/*
hook_form_alter
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'views_exposed_form') {
     $current = '';
     $ranges = explode(':',$form['date_filter']['value']['#date_year_range']);
    foreach($ranges as $key => $range) {
       $ranges[$key] = date('Y', strtotime($range.' years', strtotime(date('Y-m-d H:i:s'))));
    }
    $startYear = $ranges[0];
    $endYear = $ranges[1];
    if($ranges[0] > $ranges[1]) {
        $endYear = $ranges[0];
        $startYear = $ranges[1];
    }
    $items = array();
    $endYear = (int)$endYear;
    $startYear = (int)$startYear;
    if(empty($_REQUEST['date_filter']['value']['year'])) {
    $items[] = 'All years';
    } else {
       $items[] = l('All years', current_path(),array('query' => array("date_filter[value][year]" => '')) );
    }
for($i=$endYear; $i>=$startYear; $i--) {
        if($_REQUEST['date_filter']['value']['year'] == $i) {
         $items[$i] = $i;
        } else {
         $items[$i] = l($i, current_path(), array('query' => array("date_filter[value][year]" => $i)));
}
}
$list = theme('list_items', array('list' => $items, 'current' => $_REQUEST['date_filter']['value']['year']));
       $form['html'] = array(
        '#type' => 'markup',
        '#markup' => $list,
    );
    }
}
/*
templates/list_items.tpl.php
*/
<ol><?php foreach($list as $key => $value) { if($current == $key || empty($current)) { ?><li class="active"><?php print $value; ?></li>
<?php } else { ?>  <li><?php print $value; ?></li>
 <?php } } ?></ol>
//mymodule.info
name = Filters customization
description = Filters customization
version = VERSION
core = 7.x
dependencies[] = date
</code>

```

---
Tags: views
---


title: Loading taxonomy term custom field data

text:
# Question
Title: Loading taxonomy term custom field data
I have a vocabulary "holiday\_types" with taxonomy terms "ski" and "beach". I have a custom field on these taxonomy terms "field\_activityid" which relates to a legacy system.

I want to load all these terms so that as I loop through a list of regions I can add the taxonomy\_term ID to an entity reference field, and I need to get the legacy activityid to query an external API.

I'm having issues with entityQuery not recognising 'holiday\_types' as a bundle of taxonomy term, I tried 'type' too. I'm also not getting entityQueryAggregate working either so thought I'd pose the question here to see if there's a 'proper' way of querying custom fields on taxonomy terms.

Adding example here which produces "QueryException: 'bundle' not found"

```
$holidayTypesQuery = \Drupal::entityQueryAggregate('taxonomy_term');
$holidayTypesQuery->conditionAggregate('bundle', 'holiday_types');
$ids = $holidayTypesQuery->execute();
$storage = \Drupal::entityManager()->getStorage('taxonomy_term');
$entities = $storage->loadMultiple($ids);

```

If I change 'bundle' to 'vid' it errors with the following:

```
    Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]:
Syntax error or access violation: 1305 FUNCTION purkidev.holiday_types does not exist:
SELECT holiday_types(taxonomy_term_field_data.vid)
AS vid_holiday_types
FROM {taxonomy_term_data} base_table
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data
ON taxonomy_term_field_data.tid = base_table.tid
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_2
ON taxonomy_term_field_data_2.tid = base_table.tid
HAVING (holiday_types(taxonomy_term_field_data_2.vid) = :db_placeholder_0); Array ( [:db_placeholder_0] => )
in Drupal\purkitest\Controller\PurkitestController->simple() (line 89 of /Users/steve/Sites/purkidev/modules/purkitest/src/Controller/PurkitestController.php).

```

Trying without Aggregate:

```
$holidayTypesTIDs = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid', 'holiday_types')->execute();
$taxonomyTermStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
$holidayTypes = $taxonomyTermStorage->loadMultiple($holidayTypesTIDs);
foreach ($holidayTypes as $holidayType) {
  dpm($holidayType);
}

```

This works but when I dpm($holidayTypes) I don't get anything in the fields:

```
[fields:protected] => Array
    (
    )

```

...hence why I was trying aggregate as I thought it brought together the fields.

So, can I access the value of my field\_activityid from here and if so how? Have tried various random things like

```
dpm($holidayType->field_activityid->value())

```

which produces

```
Call to undefined method Drupal\Core\Field\FieldItemList::value()

```

Following berdir's comments here's the latest whole function... which now works - thanks all for helping my syntax!

```
public function simple() {

$holidayTypesTIDs = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid', 'holiday_types')->execute();
$taxonomyTermStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
$holidayTypes = $taxonomyTermStorage->loadMultiple($holidayTypesTIDs);

$markup = '';
foreach ($holidayTypes as $holidayType) {
  $markup .= "<p>Holiday Type: ";
  $markup .= $holidayType->getName();
  $markup .= "</p><p>TID: ";
  $markup .= $holidayType->id();
  $markup .= "</p><p>ActivityID: ";
  $markup .= $holidayType->field_activityid->value;
  $markup .= "</p><p>";
}

return array(
  '#markup' => $markup,
);

```

}

# Answer
Your entity query works fine (without aggregate). `dpm()` doesn't work in D8 for content entities, try kint() instead, but that will also be misleading.

Your last attempt was almost correct: `->value` is a property (a magic property, actually), not a method. So this should work fine:

```
$holidayType->field_activityid->value

```

As referenced already in a few questions, have a look at http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet; it's a bit old but it's still a great overview of the Content Entity (Field) API.

If you do want to use `dpm()`/`kint()`, then always run it on `$entity->toArray()`. That will give you an array structure of the fields, you can translate that 1:1 to object properties and it will work fine. For deltas, use `$holidayType->field_activityid[1]->value`; not providing it defaults to delta 0.

And, no, you definitely don't want an aggregate query. You need that if you want to COUNT() or SUM() some values of your entities.
> 2 votes

---
Tags: entities, taxonomy-terms, 8, database
---


# Question
Title: How to print the path alias without "/" in views
I would like to print the path of a node in a view, but without the "/".

With "Content:path" the trailing slash before the alias is always there.

ie:

```
path-of-node

```

in stead of `/path-of-node` Any suggestions, pls?

# Answer
If you have a custom module of your own, you can use the function below. To find the exact structure of the data you want to modify, you can use dpm or just simply print\_r.

```
function hook_views_pre_render(&$view) {
    if($view->name == "MY_VIEW"){
        foreach($view->result as $key => $r){
           $view->result[$key]->path[0]["rendered"]["#markup"] = substr($view->result[$key]->path[0]["rendered"]["#markup"], 0, -1);
    } //if
 } // function

```

As for a direct way, I was trying and I think I even post a question, but to no success. Surely it is much simpler but don't know how to.
> 1 votes

---
Tags: views, path-aliases
---


title: Empty e-mail body using drupal_mail

text:
# Question
Title: Empty e-mail body using drupal_mail
I'm using drupal\_mail for sending eMails from a custom module. This is the code:

```
function changeme_node_update($node) {
...
$to = "receiver@example.com";
$from = "sender@example.com";
$subject = 'sampletext ' . $nodedate;
$body = "Dear " . $user_name . "! \r\nSome more text\r\n\r\n" . $nodetitle . "\r\nDate:" . $nodedate . "\r\nTime:" . $nodetime . " h";
$body .= "\r\n\r\nSome more text here";

//call mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
);
drupal_mail('changeme', 'information', $to, "de", $params, $from);
...
}

function changeme_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
    break;
    }
}

```

I'm receiving emails with the subject but the message is missing. Also, where to change the encoding?

Thanks!

# Answer
> 3 votes
Try this :

```
function changeme_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
    break;
    }
}

```

`$message['body']` is supposed to be an array as defined here so I changed `$message['body']` to `$message['body'][]`

# Answer
> 3 votes
I was having the same issue. The following worked for me. The code below should replace what you have set in the case statement
`$message['body'][] = check_plain(t($params['body']));`

```
    function changeme_mail($key, &$message, $params) {
     switch ($key) {
       case 'information':
         $message['subject'] = $params['subject'];
         $message['body'][] = check_plain(t($params['body']));
       break;
      }
    }

```

# Answer
> 0 votes
The reason you are getting an empty string for body is that Drupal is expecting an array, not a string. In fact, the function that formats the message, `DefaultMailSystem::format()`, contains the following code.

```
  // Join the body array into one string.
  $message['body'] = implode("\n\n", $message['body']);
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = drupal_wrap_mail($message['body']);

```

If you pass two strings to `implode()`, the function will return `NULL`, which (in the context of strings) is then converted to an empty string. (See one of the comments in the PHP documentation page.)

---
Tags: emails
---


# Question
Title: How to Filter view by comparing 2 fields. If field-a < field-b
I have a product content type that has 2 price fields.

I want to create a view that shows all products where price-A is less than price-B.

I was hoping I could just add a filter and select price-A then choose operate less than and set the value as price-B, however you can't do that.

I have looked into using a views hook, mainly hook\_views\_query\_alter but haven't had any luck.

I've also tried using the Views PHP module and been unable to get it to work.

Does anyone know the best way to achieve this?

# Answer
What you're looking for is the filter criteria `Global: Fields comparison`:)
> 12 votes

# Answer
Welcome to the Drupal Answers Stack Exchange ! There is no straight forward way to achieve this in Drupal views as of now, and as i know.

You can do this using Views PHP module. Enable this module and add a filter PHP filter which you can select from views filter Global Category once you install above module.

Add php code some thing like below in the PHP code section of filter.

```
$node = node_load($data->nid);

$field_a = field_get_items('node', $node, 'field_price_a');
$price_a = field_view_value('node', $node, 'field_price_a', $field_a[0]);

$field_b = field_get_items('node', $node, 'field_price_b');
$price_b = field_view_value('node', $node, 'field_price_b', $field_b[0]);

if ($price_a >= $price_b) {
  return TRUE;
}

```

Change the field\_price\_a with your Price A field name and field\_price\_b with your Price B field name.

I tested and it worked for me ! Hope you can crack it too :-)
> 4 votes

# Answer
This functionality is now included in Views starting with version 7.x-3.8. See https://www.drupal.org/node/699252#comment-7513087 for more.
> 0 votes

# Answer
http://drupal.org/project/views\_dependent\_filters is pretty useful...

The add-button of "Filter Criteria" has new submenues. Selfexplaning once you try it...

EDIT: sorry, but not for \> or \<, but for filtergroups which can be seperated by OR
> -1 votes

# Answer
If price is a field in your content type, in Drupal 7 views you can automatically, and easily choose a field com-parer. I guess this should work.
> -2 votes

---
Tags: 7, views, commerce
---


title: Generating URL to taxonomy term (tag)

text:
# Question
Title: Generating URL to taxonomy term (tag)
I am trying to insert tag url and page title in breadcrumb path. With page title everything is Ok, however I can't find any info how to get tags, or how to generate url for them. I think I am getting tag how I am supposed to, but this returns object of `Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem` without id (?). So How could I gennerate Url from this object?

```
function theme_preprocess_breadcrumb(&$vars) {
  $node = \Drupal::request()->attributes->get('node');
  $title = $node->getTitle();

  $tag = $node->field_tags->first();

  $vars['breadcrumb'][] = [
      'text' => $title
  ];
}

```

# Answer
Yes, I agree with Ivan.

Here is a blog post that recommends creating a new breadcrumb builder service. https://www.palantir.net/blog/d8ftw-breadcrumbs-work

The key pieces are extending BreadcrumbBuilderBase and defining the service in a yml file.

```
 # mymodule.services.yml
 services:   mymodule.breadcrumb:
   class: Drupal\mymodule\NewsBreadcrumbBuilder
   tags:
     - { name: breadcrumb_builder, priority: 100 }

```

While data can be manipulated in the preprocess layer it should be used for visual changes rather than behavioral changes.

Now to answer your more direct question of how to actually generate the links. I think what you want is something like

```
$node->field_tags->referencedEntities()[0]->id();

```

I recommend looking at BookBreadcrumbBuilder both for the Breadcrumb specific parts and the link construction. There you'll see links constructed like this:

```
$links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', array('node' => $parent_book->id()));

```
> 2 votes

# Answer
This is the object of the first term entity in the fielditemlist of `field_tags`:

```
$node->field_tags->first()->entity

```

You can access all propterties of the term, for example the label or id:

```
$node->field_tags->first()->entity->id()
$node->field_tags->first()->entity->label()

```

Or the url:

```
$node->field_tags->first()->entity->url()

```
> 1 votes

---
Tags: entities, taxonomy-terms, 8, uri
---


title: Viewing statistics for content types

text:
# Question
Title: Viewing statistics for content types
I am trying to use the Google Chart Tools module to display graphs with data regarding content types inside a view (Views module). For example, lets say I have a content type called Car that has a field called Color. I would like the graph to display, say, the number of Cars that are blue, red and green.

Is there a way to do this using only the the Google Charts, Views, and Core drupal modules or do I have to download a seperate module? Is there another Charts module that would do what I am asking for more easily than Google Charts?

# Answer
### Step 1: Getting started

To create charts in Drupal, you can (also) use the Charts module. It comes with a sample view which will give you a chart for each of your content types.

Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.

For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.

### Step 2: Create the tabular format of the view

A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the ***Bonus tip*** within Steps to create charts using the views UI, i.e.:

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. **It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.** ...

### Step 3: Add the chart to your view

Do not try to start this step if you didn't first complete the prior step.

Just use the views display format "Charts", and select the various options that fit your needs. Refer to Steps to create charts using the views UI for detailed instructions about this.

Disclosure: I'm a (co-)maintainer of the Charts module.
> 1 votes

---
Tags: 7, views, entities, nodes, charts
---


title: Define relationship with a field?

text:
# Question
Title: Define relationship with a field?
Is it possible to create a relationship based on a field?

In a field settings, I want to set the Relationship to be referencing another field. Does this make sense? I want to turn a field into a relationship.

An example: An integer field is meant to contain version id numbers. So have a relationship from the integer field to the node\_revision table.

# Answer
> 0 votes
Per hook\_views\_data\_alter, I came up with code along the lines of the following which seems to work for my example in the question:

```
$data['field_data_FIELDNAME']['dummy_name'] = array(
  'title' => t('Map field to other db column'),
  'group' => t('Custom mapping'),
  'relationship' => array(
    'base' => 'node_revision',
    'base field' => 'vid',
    'field' => 'FIELDNAME_value',
    'handler' => 'views_handler_relationship',
    'label' => t('Map field to db column'),
    'title' => t('Field to db map'),
  ),
);

```

---
Tags: 7, views
---


# Question
Title: Why is it considered improper to directly add an `onclick` attribute to an HTML element?
From a Drupal perspective, why is it considered improper to directly add an `onclick` attribute to an HTML element instead of using a Javascript behavior?

# Answer
There's a good answer in the JavaScript subreddit on reddit here. To summarise, here are the reasons provided:

> * tight coupling between presentation and behavior
> * code runs in the global scope
> * makes testing and debugging difficult
> * defies progressive enhancement
> * quickly becomes hard to maintain
> * also it will unbind any previously assigned click handlers which might be an unwanted side effect

Maintainability and testability are the major killers for me here.

There's not much more to add to give a Drupal specific answer. The only two things that comes to mind are the following:

1. Behaviours are automatically re-applied to any content loaded via AJAX, so if you have an AJAX powered view the click handler will be rebound for you without having to have the function in the global scope.
2. You don't have to try and locate templates, or hack away at anything just to add a new attribute to an element. For example, if you want a click handler on a node title link, you have to update the template. If you then add a new view mode, but still want to have the click handler listening, then you need to ensure the `onClick` is on that element as well - this increases the maintenance time and risk of error. If you just use a behaviour, then you can hook onto the title link class and it'll work everywhere.
> 4 votes

---
Tags: javascript
---


# Question
Title: Installation error in Ubuntu - The settings.php file does not exist
I've installed Drupal 6\7\8 in WAMP environments for about a hundred times, but I don't recall ever having the following instllation error, which I encountered only in Ubuntu desktop 15.10, Apache2 (2.4.12), Drupal 8:

> **The Settings file does not exist**.
>
> The Drupal installer requires that you create a ./sites/default/settings.php as part of the installation process. Copy the ./sites/default/default.settings.php file to ./sites/default/settings.php. More details about installing Drupal are available in INSTALL.txt.

As the error suggest, I've tried to create it myself from the default.settings.php as the install error suggests and there was no change. I could surly import it from another Drupal 8 site in my WAMP environment, but I would thank any Drupal developer who would shed some light on why this would even happen?

Maybe it happened due to the fact that in the first time there was an install attempt, the folders permissions were not 777 (now they are - changed recursively for the site's folder only and at least temporarily).

Will thank you for your help,

## Update

# Answer
> 4 votes
go to the folder where you installed drupal. Ex:

```
cd /var/www/drupal

```

then

```
sudo chown www-data -R sites

```

Now try installing again.

---
Tags: 8, installation
---


# Question
Title: Flag state as contextual filter in views
Please help me and provide a little explanation about the following thing:

**1) What I have:<br>**

* a content type called "word"
* a flag for this content type called "learned".
* a view display with "word" nodes

**2) What I want to achieve:**

* filter view results with "learned" flag state (to get only flagged, or not flagged, or all of them) for current user via contextual filter.

I've added a relationship on **"Flags: Content flag"** where i can limit results to those nodes, which are already flagged by current user. But honestly I don't understand how to connect this relationship with contextual filter to get a possilibily to receive different results basing on the flag state (flagged, unflagged, all).

Actually, I want to get the same result as if I use an exsposed filter on a Flag state. But I don't want to use an exposed filter as well as I'm using an ajax call to load this view display with predefined options.

Any help?

# Answer
> 1 votes
Not with contextual filter, in views I think it's posible with a normal filter (not exposed) since you have already the flag relationship, first add your flag as a field (don't display it if you want) then just filter your nodes with the flag status (flagged). Then you clone the view and change flag status on filter (now to unflagged) and you will have an opposite view (non-flagged) content.

---
Tags: views, flags
---


# Question
Title: "Aggregate and compress CSS files" and "Aggregate JavaScript files" in performance settings, is not working
This thread contains the most information I've been able to find about this: #986558: "Aggregate and compress CSS files" and "Aggregate JavaScript files" in performance settings, is not working

I have 2 d7 sites. One is in public\_html/ on my server and has no problems. The other is in a sub-directory, and breaks when turning on Aggregation/Compression of css & js files (in admin/config/development/performance ).

When I turn on js performance, my js doesn't work. When I turn on css performance, no css loads on my site in Firefox or Chrome, but does load in Safari. According the the above-mention issue, it's because of Drupal & my server sending compressed info to the browser, which can't decompress it and thus, I get no js or css.

Following a recommendation, I disabled these in my .htaccess file:

```
#Header append Content-Encoding gzip
#Header append Vary Accept-Encoding

```

What that did, however, was break some of my css, and load a "skip to content" area in the top of my website (which, if you do theming, you might be familiar with seeing that as a hidden html element that is loaded).

I'm not sure what to do to fix this. I encountered it the first time I built this site, but was using D7-rc1. I rebuilt it hoping new core/module updates would fix it, but this site is running on D7.7 now.

Please help. Thanks.

# Answer
Well, this issue is ongoing at http://drupal.org/node/986558 . The Drupal-7.9 should have fixed it, and it did fix my css, but I am still having issues with js.

Note: if you have this problem and upgrade to Drupal-7.9 , make 100% sure you replace all of your .htacess files.
> 2 votes

# Answer
You could use the following free tools from Online-Code.

I've been using them for a long time and have had no performance issues.
> 0 votes

---
Tags: performance
---


# Question
Title: Gmap click marker should zoom the map and display other markers
I have two content types: **City** and **Place**. Both of them use a `location` field which has lat long fields enabled.

The *Place* content type has a node reference field to *City* content type.

I want to display a google map, which will display the *City* nodes markers. Clicking on any marker will zoom the map and will display the place nodes markers in that city.

And then clicking the place marker which will open its detail page.

Is it possible with gmap and views or any other module? Or a custom script will be used?

# Answer
> 1 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
>
> And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
>
> Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
>
> Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it.

---
Tags: 7, views, google-maps
---


title: Is using SQL table prefixes necessary?

text:
# Question
Title: Is using SQL table prefixes necessary?
During an upgrade, there is a setting for the table prefixes to use for the database table.

Is it a must to use table prefixes? What does using that setting help with?

# Answer
It means that if you were to install another Drupal, 7 or 8 on the same database (zentech0\_Benia), using prefix will prevent causing confusion/collision.

Ex:

having two tables named accesslog is confusing.

while having site1\_acesslog, site2\_acesslog you know which accesslog belongs to which site.

In conclusion, if you don't plan on installing another Drupal 7 or 8 in zentech0\_Benia, (having 2 websites in the same database) then you don't need table prefixes.
> 2 votes

---
Tags: 8, upgrading
---


# Question
Title: how to hide view block when other view block not giving any search result?
I have created a view(ABC) in which search criteria: **"country type content"** and other filter is **"promoted to front page"**."Promoted to front page" filtering content using cck boolen field(yes/no).

Another view(XYZ) has search criteria: **"country type content"** only.

When promoted to front page cck field is empty or null my first view(ABC) will hide same as I want to hide second view(XYZ) If first view is hidden.

Both the views i placed at same region **"Header"**.

How to hide (XYZ) view, if (ABC)view has no content or hidden?

# Answer
For such cases, when visiblity of one view need to be dependent on another view, we may ***alter the view***, or we can use ***hook\_views\_pre\_render*** or ***hook\_views\_pre\_render*** to control the view through custom code.

Here as you are **using block**, so you can also use block configuration "***Show block on specific pages***" instead of coding in some custom module.

Then you can select option "***Pages on which this PHP code returns TRUE***" there.

After doing so, you can use the following code in the textarea:

```
<?php

$view = "<Your dependee view's machine name on which other view is dependent>";

$display = "<Your dependee view's display ID>";

$all_row = views_get_view_result($view, $display);

if(count($all_row)>0) {
  return TRUE;
}
?>

```
> 1 votes

---
Tags: views, hooks
---


# Question
Title: How can I add a menu link to a page with a form in DrupalGap?
I made a custom page that has a form on it. How can I add a menu link to the authorised user menu? There is this very useful documentation http://docs.drupalgap.org/7/Menus/Adding\_Links\_to\_Menus but **how do I get the path to the custom page with the form?**

In settings.js I have added this and the new link shows up.

```
drupalgap.settings.menus['user_menu_authenticated'] = {
  options: menu_popup_get_default_options(),
  links: [
{
  title: 'My Account',
  path: 'user',
  options: {
    attributes: {
      'data-icon': 'user',
      'class': 'ui-btn ui-btn-icon-right'
    }
  }
},
{
  title: 'Logout',
  path: 'user/logout',
  options: {
    attributes: {
      'data-icon': 'delete'
    }
  }
}, //NEW LINK
 {
  title: 'Buy points',
 // path: 'user/logout', // what path?
 page_callback: 'drupalgap_get_form',
  page_arguments: ['my_module_payment_form'],
  options: {
    attributes: {
      'data-icon': 'delete'
    }
  }
}
  ]
};

```

In my\_module.js I have added the form like so and it shows up:

```
function my_module_menu() {
  try {
  var items = {};
  items['in-app'] = {
    title: 'get points',
    page_callback: 'drupalgap_get_form',
    page_arguments: ['my_module_payment_form']
};
return items;
}
   catch (error) {
      console.log('my_module_menu - ' + error);
    }
 }

```

# Answer
Figured it out finally:

```
path: 'in-app'

```

Comes from the hook\_menu items array.
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: Newly contributed theme not showing in Project Application issue queue
I have contributed a theme (Auro) in Drupal.org and assigned for "Needs review" but the project not showing in Project Application issue queue.

Why doesn't my theme appear in the Project Application queue? What did I do wrong?

# Answer
It doesn't appear because you didn't create an issue in the Project Application issue queue, but in the issue queue for your theme.
To create a issue in that queue, go to https://www.drupal.org/project/issues/projectapplications and click on *Create a new issue*.

Since I am a Drupal.org webmaster, I have already moved the issue in the correct queue; you don't need to do anything more.
> 1 votes

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


title: Entityform Submissions in a view

text:
# Question
Title: Entityform Submissions in a view
I have an **EntityForm** referenced on a node and I need to show **submissions** on a **view** where :

* Node Author can view all submissions
* Submitter view his own Submission (for edition purpose)

How can I do so?

# Answer
> 1 votes
Ended up using two blocks with contextual filters, one that shows up for the node author and the other for Submitters.

---
Tags: 7, views
---


# Question
Title: How to generate a styled image with out actually creating it?
There is a content type in my website called `image` and it has an *image* field. There are about 16GB images in my website and people have uploaded very high quality images.

There is an image style in my website which uses the original image plus a watermark. This causes double space consuming. People are only allowed to download this version. The number of images in my website is growing very fast and it needs lots of space.

I need to show the styled version to the user with out creating it in `\styled` directory.

Is there any way to handle this problem? Is there anyway to keep the site working like now, but instead of creating a separate copy of the original image, display the styled image and generate download link to the user in any other way?

Thanks.

# Answer
The only way would be to use CSS and put a div with a background transparent image of the watermark overlay on top of the actual image using the `z-index:` attribute.

You would risk that people could inspect element or view page source and find the direct link to the image, or use a tool to strip all css and then save the image.

For total security, I'm pretty sure there is no other way than having the watermark on the image itself.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Migrating disqus comments into drupal comments
After having refactored my site disqus comments do not match with their original nodes (despites they share the same path alias) and I am considering leaving disqus, as I didn't manage to fix the problem.

I would like to migrate from disqus to drupal and although I have seen that disqus offers an export feature that generates a xml file (https://help.disqus.com/customer/portal/articles/472149-comments-export). Unfortunately I haven't been able to import that file into drupal, as the disqus module had this functionallity on D6 only and this sandbox project is abandoned and does not work (I guess disqus changed their API)

Maybe migrate module or feeds module could handle that, but I haven't found any documentation on how to proceed.

Any help would be appreciated. Thanks.

EDIT: The following code shows disqus' xml structure:

```
<?xml version="1.0" encoding="utf-8"?>
<disqus xmlns="http://disqus.com" xmlns:dsq="http://disqus.com/disqus-internals" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://disqus.com/api/schemas/1.0/disqus.xsd http://disqus.com/api/schemas/1.0/disqus-internals.xsd">
    <!-- First defines the threads = drupal nodes -->
    <thread dsq:id="3225849642">
        <id>node/400</id> <!-- This nid has changed after migration-->
        <forum>carloscamara</forum>
        <category dsq:id="670543" />
        <link>http://carloscamara.es/blog/2014/11/15/experiencia-como-usuario-de-un-fairphone</link><!-- This path is the same after migration-->
        <title>Experiencia como usuario de un Fairphone</title>
        <message />
        <createdAt>2014-11-14T23:52:16Z</createdAt>
        <author>
            <email>some email</email>
            <name>some name</name>
            <isAnonymous>false</isAnonymous>
            <username>ccamara</username>
        </author>
        <ipAddress>some IP</ipAddress>
        <isClosed>false</isClosed>
        <isDeleted>false</isDeleted>
    </thread>

    <!-- Posts are like drupal comments are later defined and related to threads referencing their thread dsq:id -->

    <post dsq:id="2247159473">
        <id />
        <message><![CDATA[<p>Estoy muy interesada en comprarme el Fairphonr 1, y espero no llegar tarde. ¿Dónde puedo comprarlo?</p>]]></message>
        <createdAt>2015-09-10T23:05:08Z</createdAt>
        <isDeleted>false</isDeleted>
        <isSpam>false</isSpam>
        <author>
            <email>Another email</email>
            <name>Another name</name>
            <isAnonymous>true</isAnonymous>
        </author>
        <ipAddress>Another IP</ipAddress>
        <thread dsq:id="3225849642" />
    </post>

    <!-- This comment is a child of another comment -->
    <post dsq:id="2247642804">
        <id />
        <message><![CDATA[<p>Hola, pues siento decirte que los Fairphone 1 se agotaron y no van a hacer más, así que me temo que solo quedan dos opciones: o comprar el Fairphone 2 (mucho mejor, pero también más caro) o comprar uno de segunda mano.</p>]]></message>
        <createdAt>2015-09-11T07:45:30Z</createdAt>
        <isDeleted>false</isDeleted>
        <isSpam>false</isSpam>
        <author>
            <email>some email</email>
            <name>some name</name>
            <isAnonymous>false</isAnonymous>
            <username>ccamara</username>
        </author>
        <ipAddress>some IP</ipAddress>
        <thread dsq:id="3225849642" /> <!-- This is the parent's node -->
        <parent dsq:id="2247159473" /> <!-- This is the parent's comment -->
    </post>
</disqus>

```

# Answer
You will need Feeds Comment Processor and Feeds XPath Parser because your xml does not use the typical rss title, author, and url tags.

Here is an example on how to set up the xpath parser.
> 1 votes

---
Tags: 7, migrations, comments
---


# Question
Title: Give permission to dealer_user_role to create users and profile2 fields
I have situation as follows:

I have three types/roles of users.

* AdminRole
* Dealer Role
* CustomerRole

I have given permission to "Dealer Role" to create/add "Customer Role" user. That works fine for me.

But my daunting task is as follows:

I am using "Profile2" module for "Customer Role" user.

I have created one profile\_type in Profile2 module in which 6 fields are there with separate page for editing profiles page.

Also i have enabled UNIQUE REGISTRATION Path.

Although i have access to the unique registration path when none of the user is logged in system and administrator is log-in.

I want to give "Profile2" module permission in a way that "Dealer Role" having permission to create/add data to the "Customer Role".

In simple, when "Dealer Role" is logged in system, dealer can manage "Customer Role" user.

Thanks Same

# Answer
global $user;

$uid = $user-\>uid;

$accessRoleArr = '';

if(in\_array('Admin',$user-\>roles) || in\_array('Dealer',$user-\>roles) || in\_array('Customer',$user-\>roles))

{ return FALSE; }
> 0 votes

---
Tags: users, 7
---


# Question
Title: Do PHP static variables persist across Batch API batch items processing?
Do PHP static variables, which do persist during a normal page request, persist between progressive Batch API runs? What about during non-progressive (command-line) batch execution? Does &drupal\_static come into play in any way?

In my application, I want to take advantage of in-memory caching across batch processes.

# Answer
No they do not.

I had a similar question some time ago: https://drupal.stackexchange.com/a/59274/1899

PHP static variables do not persist between requests.

In your batch operation, you receive an array argument as the last argument. Call it `&$context` (pass by reference), and then you can have persistent variables.

* `$context['sandbox']` preserved between iterations of the same batch task. Useful for progressive batch OPs.
* `$context['results']` preserved throughout the entire batch progress.
> 3 votes

# Answer
Static variables exist per request, so no, they won't persist across separate batch runs.

If you need to cache data across requests in memory just use redis/memcache/etc, there are contrib modules available for each that hook into the core caching stays so you can use a familiar API
> 4 votes

---
Tags: caching, batch-operations
---


# Question
Title: Bootstrap: Responsive tables with WYSIWYG text format
I use WYSIWYG as text format and inserted tables under the filed using MYSIWYG are not responsive and make the site unresponsive.

It looks really bad in mobile phones.

**Website without table:**

**Website with table:**

Things I tried so far and didn't work:

1. Zurb responsive tables
2. Responsive Tables Filter
3. Responsive Tables
4. After adding table with WYSIWYG I changed the text format to Full HTML and didn't work

# Answer
> 1 votes
# Option 1: Use Responsive Tables

To have more control over table columns, use the Responsive Tables module. Some details about it (rom its project page):

> Adds a library to allow tables to function better in responsive layouts.
>
> You can manually add the library to any table on the site. You also have the option of using the Better Views Tables module to configure the responsive table controls through the Views UI.

# Option 2: Use a responsive theme

You should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "*is designed from the ground up as a mobile-first responsive theme*". However that has like 5 module dependencies ...

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

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

---
Tags: 7, wysiwyg, theming
---


# Question
Title: Views fields configuration is not working
I set a few fields as *FIELDS* section of a view. the problem is when I click on the fields the `Style settings` ,`No results behavior` , `Rewrite results` and `More` links are not collapsible . this is the screenshot

what it is like that?

# Answer
> 3 votes
Apparently you're not the only one to encounter this issue. Here are some similar situations:

It appears that no one has found out the solution yet. It doesn't seem to come from jQuery Update or backend theme. However, these advices show up each time:

* Make sure that the needed JavaScript file is loaded in the header of the node (`collapsible.js`)
* Perhaps a conflict with another module that would use Views hook. Disable enabled modules one by one and test.

If you find which module interferes with Views or why JS file is not loaded, I think you will make more than one happy people.

# Answer
> 0 votes
This mostly happens when you have a javascript error, or using a custom admin theme which doesn't play well with the accordion/fieldset behaviors.

Open Javascript console (Usually F12) to see if there's any errors reported there.

If you're using a custom admin theme, try switching back to **Seven** theme

# Answer
> 0 votes
I've had same problem.

I have custom module in which I have override javascript of contrib module Field group like this:

```
$javascript[drupal_get_path('module', 'field_group') . '/multipage/multipage.js']['data'] = drupal_get_path('module', 'create_events') . '/js/multipage.js';

```

When I realized that I've added condition to override js file only on add content type event page or on edit page.

```
/**
 * Implements hook_js_alter().
 */
function create_events_js_alter(&$javascript) {
    if (request_uri() == '/node/add/event' || node_type_get_name(node_load(arg()[1])) == 'Event') {
        // override default multipage javascript to change button output
        $javascript[drupal_get_path('module', 'field_group') . '/multipage/multipage.js']['data'] = drupal_get_path('module', 'create_events') . '/js/multipage.js';
    }
}

```

So maybe you can check if you are implementing hook\_js\_alter function and try to comment that out and try again.

Hope this will help someone.

---
Tags: views, entities, javascript
---


title: Problem when visiting users profiles

text:
# Question
Title: Problem when visiting users profiles
In my website, users can connect, see their profiles, update their profiles and **visit other users profiles**

So for each users, I created a profile page `user-profile.tpl.php`

But I've some troubles when I'm visiting other users account.

For example in my account profile page, there is a link who's redirecting me to the edit page.

I wrote this code for showing the edit link :

```
<?php
  global $user;
  print l(t('Update my profile'), "user/{$GLOBALS['user']->uid}/edit");
?>

```

When I'm visiting a random user page, this link appears. **But I want it to appear only on my profile page**

And it's the same for my profile picture, when I'm visiting a random user page, my picture is always showing.

```
<?php
    $user_item = user_load_by_name($user->name); // or user_load( $user->uid )
    print theme('user_picture', array('account' =>$user_item));
?>

```

I have no idea how to fix theses problems, that's why I need your help (I'm new to Drupal btw)

(I'm using Profile2)

Thanks

# Answer
> 2 votes
You can get the user id from url using `arg()` function. for the first part you can do something like this.

```
global $user;
$user_id = arg(1);
if($user->uid == $user_id) {
// means it is logged in user profile - so show edit link

}

```

For the second part you are loading profile of logged in user, that is why it is always showing your picture you need to do the following instead.

```
$user_item = user_load($user_id); // user id we got from arg()
print theme('user_picture', array('account' =>$user_item));

```

---
Tags: theming, users
---


# Question
Title: How do I create a route to a raw text file
I'm working on a Drupal 8 module, and I would like to include a couple of text files, each of simulated json data, as examples. How would I include these files in my module and create a route in the module.routing.yml file that would tell Drupal that when a visitor comes to mysite.com/examples/json1 to just print the text file (json data) as-is?

# Answer
There might be a clever solution for this, but a simple straight forward solution would be to:

1. Make a Controller and use that in your routes.
2. In the method on the controller, load the contents of the file (or just hardcopy it into your controller method)
3. Return a JSON response in your controller.

I haven't gone into details on how to code this, there are plenty of code examples and documentation on this on drupal.org
> 3 votes

# Answer
Create a route in your module.routing.yml and add the following route

```
route_name:
  path: 'examples/route_path'
  defaults:
    _controller: '\Drupal\module_name\Controller\JsonController::renderJSON'
  requirements:
    _permission: 'access content'

```

Then create Controller with the name JsonController and inside that create a function renderJSON like the following

```
 /**
   * RenderJson.
   *
   * @return json string
   *
   */
    public function renderJSON() {
       // read your json content here.
       //encode your json using JsonEncoder class and return it

    }

```
> 0 votes

---
Tags: 8
---


# Question
Title: Remove all previous cart if have same product creator
Thanks a lot joshmiller, but I need this rule on before add product to cart react event, not after save commerce order.

I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.

With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.

Any suggest how to solve this using rule?

# Answer
You simply need to create a rule that reacts on order creation, searches for existing orders for that user, and cancels those orders.

Next, add the condition to make sure you won't pull all anonymous orders. If you allow anonymous orders, you might have to implement some sort of custom session searching for orders.

Next, add an action that brings in a list of entities (we're going to pull a list of orders based on owner).

Then, select Commerce Orders

This is what the full action looks like when you've set it up for selecting by order owner's user id:

Next, you want to add a loop based on the orders you've pulled:

Next, you want to add an action inside that loop that changes the status of the orders:

Finally, set the order status to canceled:

Here's an export of the rule:

```
{ "rules_cancel_previous_orders" : {
    "LABEL" : "Cancel previous orders",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_order", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:uid" ], "op" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "uid",
            "value" : [ "commerce-order:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "canceled" } }
          ]
        }
      }
    ]
  }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Does Drupal strip out style and span tags?
I was trying use span and style tags in pages, rather than in CSS and it seems that Drupal is configured to strip them out whether the input format is *Filtered HTML*, i.e. they are applied to *Full HTML*.

Is that something which can be fixed only by editing the core files, or are the some modules or settings in Drupal's admin settings that can override that?

# Answer
> 4 votes
Go to Configuration -\> Content Authoring -\> Text formats. Here you can configure what tags are allowed.

All unallowed tags are stripped out, is always stripped out.

Check out https://www.drupal.org/project/wysiwyg\_filter for more advanced filtering.

# Answer
> 1 votes
Are you using a WYSIWYG module like "CKEditor - WYSIWYG HTML"?

It appears to be this module or the CKEditor itself that is wrongly stripping out correct HTML such as inline styles, not Drupal.

There is a bug report open here https://www.drupal.org/node/778200

My current workaround is to disable the editor when adding these types of HTML so that I edit and save while in source mode.

You could also try using a different WYSIWIG editor besides CKEditor. This module allows several different editors to be used: https://www.drupal.org/project/wysiwyg

# Answer
> 1 votes
As authtentictech noted above, disabling the editor can work (I create a text format of Full HTML-No Editor) to deal with the edge cases where this can pop up. Here, it's only straight code that is put in--no WYSIWYG editor is allowed for that format).

It can get really annoying when having to collaborate with editors, though (if they don't know how to code). If at all possible, it may be better for you to create HTML classes, since CKeditor is actually trying to help you avoid adding bad code and non-conforming visual design to your layouts.

Sometimes, the solution can be simple, as well--for instance, I use a custom icon font, and span classes are used to display icons in text. Per the developer's instructions, adding it to HTML text would be `<span class="[class name]"> </span>`. CKedtior interprets that space between the span tags as irrelevant, and strips it out. Adding ` ` in place of the space fixes it, and no changes to settings are required.

# Answer
> 0 votes
To configure Text Formats you can go to /admin/config/content/formats

> A text format contains filters that change the user input, for example stripping out malicious HTML or making URLs clickable. Filters are executed from top to bottom and the order is important, since one filter may prevent another filter from doing its job. For example, when URLs are converted into links before disallowed HTML tags are removed, all links may be removed. When this happens, the order of filters may need to be re-arranged.

See here for more information on text filters and input formats.

---
Tags: 7, input-formats
---


# Question
Title: How to hook into core's "log in to comment" link
I'm running Advanced Forums on D7, and when an anonymous user views a forum post (lets say nid 101) there is link under the post that says "Log in or register to post comments".

The problem is it is supposed to point to 'user/login?destination=node/101#comment-form' but the url encoding causes it to become 'user/login?destination=node/101%23comment-form'

I looked inside core's comment module, under function theme\_comment\_post\_forbidden line 2387 says:

```
$destination = array('destination' => "node/$node->nid#comment-form");
return t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination))));

```

but I think it should make the #comment-form a url fragment:

```
$destination = array('destination' => "node/$node->nid");
$fragment = 'comment-form';
return t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', array('query' => $destination, 'fragment' => $fragment)), '@register' => url('user/register', array('query' => $destination, 'fragment' => $fragment))));

```

How I can create a hook to this and change the link?

# Answer
> 0 votes
I found the solution with the help of this SE post. Using MYMODULE\_node\_view\_alter(&$build) and MYMODULE\_comment\_view\_alter(&$build) in my custom module, I was able to change the values using:

```
$build['links']['comment']['#links']['comment_forbidden'] = str_replace('%23','#', $build['links']['comment']['#links']['comment_forbidden']);

```

---
Tags: 7, comments, redirection
---


title: Add 2 form elements to Form via AJAX

text:
# Question
Title: Add 2 form elements to Form via AJAX
I am newbie into Drupal.

I want to add 2 form elements dynamically to existing form via AJAX based on particular condition. But in the examples I saw till now the AJAX callback defined returns only one element to form. I tried to achieve this by adding these two fields in fieldset and returning fieldset as a single item. But this replaces my container div completely. This works only at first time and then the contents returned by callback replaces the container.

```
function new_registration($form, &$form_state) {
    $form['select-reason'] = array(
        '#type' => 'select',
        '#title' => t('Reason'),
        '#options' => array('' => 'Select') + _global_reasons(),
        '#description' => t('Reason.'),
        '#ajax' => array(
          'event' => 'change',
          'callback' => 'is_true',
          'wrapper' => 'options',
          'method' => 'replace'
        ),
      );

    $form['options'] = array(
        '#type' => 'container',
        '#prefix' => '<div id="options">',
        '#suffix' => '</div>'
      );
    }

function is_true(&$form, &$form_state) {
      $product_quality = $form_state['values']['select-reason'];
      if(_belongs_check($product_quality)) {
          $form['a-add'] = array(
              '#type' => 'fieldset',
              '#collapsible' => FALSE,
              '#collapsed' => FALSE,
          );
          $form['a-add']['detail'] = array(
              '#type' => 'textfield',
              '#title' => t ( 'Details' ),
              '#description' => t ( 'Enter product name.' ),
              '#maxlength' => 400,
              '#size' => 100,
              '#required' => TRUE,
          );
          $form['a-add']['num'] = array(
              '#type' => 'textfield',
              '#title' => t ( 'Number' ),
              '#description' => t ( 'Enter number.' ),
              '#maxlength' => 400,
              '#size' => 100,
              '#required' => TRUE,
          );
      } else {
            //remove 2 fields added in IF block
      }
      return $form['a-add'];
    }

```

I also tried to return HTML structure of these two and place it in #markup type of form element. But I am not convinced with this way as theming might be complicated. Can anybody help? Thanks in advance.

# Answer
> 0 votes
You need to change the AJAX method from `replace` to `html`, so that the container won't be replaced by the ajax callback, instead the content of the container will be updated.

Please update your code as follows:

```
$form['select-reason'] = array(
  '#type' => 'select',
  '#title' => t('Reason'),
  '#options' => array('' => 'Select') + _global_reasons(),
  '#description' => t('Reason.'),
  '#ajax' => array(
    'event' => 'change',
    'callback' => 'is_true',
    'wrapper' => 'options',
    'method' => 'html', // Update this line
  ),
);

```

# Answer
> 0 votes
Add the additional form elements in the build function. The build function is rerun on every ajax request. If you don't have other things to do as modifying the form structure, then the ajax callback can be empty and you only need to return the new ajax container.

So you need to change this:

Put the new form elements inside the ajax container (in the first function):

```
$form['options']['a-add'][...]

```

And then return the whole container in the ajax callback (second function):

```
return $form['options'];

```

You always have to return the outside ajax div, otherwise the ajax callback will not work a second time.

---
Tags: forms, ajax
---


# Question
Title: Video host URL different in full content page links than in View links
**Background:** Site in question has a custom content type "video record" containing many custom fields including a URL to brightcove.com-hosted video. (Note, the site is *not* using any Brightcove-specific modules.) A thumbnail image activates the link in both the full content view of a page and also in a View displaying a smaller selection of the fields from this content type. In both cases, the link is opened in a modal window generated by the module "lightbox2."

**Problem:** Thumbnail links from the View work as intended. Links from the full content page *do not* work, although they were working at an earlier point in site development. Unfortunately we don't know at what exact point, in the course of core or module updates, this functionality was lost.

**Additional Info:** Looking at the links in Firebug, we see an obvious difference: The ones that work (from the View of fields drawn from this content type) include a string beginning with "bcpid1235797793001?bckey= ..." and ending with a string of type "&secureConnections=true&secureHTMLConnections=true" that exists in the URL field of every node of this type. The ones that don't work are lacking both strings.

**The Question:** The link in the View and the one in the full content page must draw from the same URL field, as there is only one such field for each content item. In the case of the full content type, why might it be stripping out parts of the original URL and delivering a result that doesn't work?

# Answer
> 0 votes
The solution was to install the Dev version of module Image Link Formatter (7.x-1.0+6-dev). It now seems clear, this module (the current recommended version) was invisibly rewriting the URL, as there is no other way it could be specified to be rewritten in the standard interface options for the content type's fields. Although there was no documentation found for this issue in the issue queue or in documentation about the Dev version, apparently it is a bug that was fixed.

---
Tags: uri
---


# Question
Title: Using fivestar_get_votes() to show the votes on a node
I need to display a multi-axis review system using Fivestar in node.tpl.php in Drupal 7.

I created the content type according to this tutorial, which is for Drupal 6, and I need to know how I can call `votingapi_select_results()` and `fivestar_theme()` in Drupal 7.

Initially, I tried the following code.

```
$design_rating = votingapi_select_results(array('entity_id' => $node->nid, 'tag' =>'design', 'function' => 'average'));
print_r($design_rating );

```

It caused a fatal error.

Later, I used `fivestar_get_votes()` as in the following code.

```
$design = fivestar_get_votes('node', $node->nid, 'design', NULL);
print_r($design);

```

I got an array.

```
  Array (
    [average] => Array (
      [vote_cache_id] => 128
      [entity_type] => node
      [entity_id] => 18
      [value] => 80
      [value_type] => percent
      [tag] => design
      [function] => average
      [timestamp] => 1332162918
    )
    [count] => Array(
      [vote_cache_id] => 127
      [entity_type] => node
      [entity_id] => 18
      [value] => 1
      [value_type] => percent
      [tag] => design
      [function] => count
      [timestamp] => 1332162918
    )
    [user] => Array(
      [vote_id] => 8
      [entity_type] => node
      [entity_id] => 18
      [value] => 80
      [value_type] => percent
      [tag] => design
      [uid] => 1
      [timestamp] => 1332162918
      [vote_source] => 122.164.241.37
      [function] => user
    )
  )

```

I don't know how to use it to show the result shown from the Fivestar module. How can I do it?

i tried with below code in node.tpl.php and it displayed result as '3' not a fivestar widget.

```
$variables=array('rating'=>60,'stars'=>5,'tag'=>'design');
echo theme('fivestar_static',$variables);

```

Am i missing anything in it? or is there any other procedure to call theme function in node.tpl.php in drupal 7?

# Answer
> 4 votes
Fivestar module for Drupal 7 implements fivestar as a field. Assuming the field name is `field_fivestar_awesomeness` you can print it anywhere with:

```
$fivestar = field_view_field('node', $node, 'field_fivestar_awesomeness');
print render($fivestar);

```

There are some display and language options, see more in the api docs.

# Answer
> 0 votes
You can use `fivestar_custom_widget()` from the Fivestar module

1. Create rate from node

```
$rating = votingapi_select_single_result_value(
 array(
    'entity_id' => $node->nid,
    'entity_type' => 'node',
    'tag' => 'vote',
    'function' => 'average',
));

```

2 Create form

```
$vote = drupal_get_form('fivestar_custom_widget', array('average'=>$rating), $settings);

```

where

```
$settings = array( 'stars' => 5, 'tag' => 'staff_vote');

```

see more in `fivestar.module`

---
Tags: rating
---


# Question
Title: Include content on module install of a custom block
I'm using Features for creating a custom module that installs and places blocks on my site, but Features doesn't export content and in this case the block contents will be needed.

I'm trying figure out how to include custom block's content somewhere in my module to my custom blocks appear with some content (to allow editing in 'custom library page') or somehow populate my custom blocks after module install with a automate tool.

PS: From now, I've putting content after module install using mysqldump (export site A, insert site B), but its not safe procedure.

Any hints are appreciated.

# Answer
> 0 votes
Use https://drupal.org/project/default\_content for install time content. For ongoing content, there is Entity Pilot (disclaimer: my product) https://drupal.org/project/entity\_pilot.

---
Tags: blocks, 8
---


title: Using a Variable in a Rules Calculation

text:
# Question
Title: Using a Variable in a Rules Calculation
I'm attempting to calculate an estimated shipping date on products with a turn-around time. Using a variety of fields on separate entities I've been able to get about 75% if the way. I run into a problem when attempting to perform the final calculation on my rule component. For some reason my calculated variable is not available on *Input value 2* of the calculation when enabling *data selection*.

**This is what my component looks like:**

```
+ Set a data value:
  Parameter: Data: [order:field-due-date], Value: [site:current-date]
+ Add a variable:
  Parameter: Type: Date, Value: now
  Provides variables: Shipping Date (shipping_date)
+ Loop:
  Parameter: List: [order:commerce-line-items]
  List item: Current Line Items (line_item_list)
    + Apply an interval to a date:
      Parameter: Interval number: [product-display:field..., Interval period: Days, Date: [site:current-date]
      Provides variables: Line Item Date (line_item_date)

```

At this point I try to add an action "Calculate a value" to the loop; like this:

```
+ Input Value 1
  Data selector (Select data of the types Decimal number, Date.)
  -- line-item-date --
+ Operator
  Value
  -- max --
+ Input Value 2
  Data selector (Select data of the type Duration.)
  -- shipping-date --

```

I calculate this in order to overwrite the shipping date with the highest "line-item-date" in order to display an estimated shipping date based on the product with the longest turn-around time.

Here's my problem: the "shipping-date" variable is not available in "Input Value 2". I don't understand why the "select data of type" is "Duration" and not "Decimal number, Date"; although I assume that's where the problem is.

# Answer
> 1 votes
I ended up using a slightly different approach. Just in case somebody else is interested in this I'm posting my final solution here.

**PROBLEM**

"Estimate" a ship date based on the turnaround times of all the products in cart whenever a product is added or removed from the cart and at checkout (just in case the customer decides to check out days after adding the products).

**Additional modules and fields:**

* Using the interval field module I added a "Turnaround Time" field to the product variation type.
* I also added a date field to the order entity - "field-due-date".

**RULES**

I created 3 items under rules.

**Reaction Rule: Set the estimated shipping date**

```
+ Events
    + After adding a product to the cart
    + After removing a product from the cart
    + Completing the checkout process
+ Actions
    + rule set: Set the estimated shipping date
        // these settings ensure that you run through each and every line item, instead of just the current item; spend a long time doing that - over and over. :(
        + Line Item
          Data Selector: commerce-order:commerce-line-items:0
        + Order
          Data Selector: commerce-order
        + Commerce Product
          Data Selector: commerce-product

```

**Ruleset: Get Line Item Turnaround Value**
rules\_get\_line\_item\_turnaround\_value
This rule gets the integer value of each line-item's turnaround time (in days in my case) and writes it to "line-item-turnaround-time" variable which is passed along to the next ruleset. I could probably have used a regular Rule instead of a Rule Set here.

```
Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter
    Integer, Line Item Turnaround Time, line_item_turnaround_time, provided

+ Rule: Get the Line Item Turnaround Time as a Number
  Provides variables: Line Item Turnaround (line_item_turnaround)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
    + Elements
        + Add a variable
          Parameter: Type: Integer, Value: [line-item:commerce-product:field-turnaround-time:interval]
          Provides variables: Line Item Turnaround (line_item_turnaround)
          //pulls the turnaround time as an integer
        + Set a data value
          Parameter: Data: [line_item_turnaround_time], Value: [line-item-turnaround]
          //write's the turnaround time to the "line_item_turnaround_time" variable

```

**Ruleset: Set the estimated shipping date**
rules\_set\_the\_estimated\_shipping\_date
This rule pulls the turnaround time from a list of the line items in the current order, compares them and uses the largest value to adjust the estimated delivery date. Again, I could probably have used a regular Rule here instead of a Rule Set.

```
Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter

+ Rule: Calculate the estimated shipping date
  Provides variables: Order Turnaround Time (order_turnaround_time), Conversion result (conversion_result), New Estimated Shipping Date (new_estimated_shipping_date)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
        + Entity has field
          Parameter: Entity: [order], Field: field_due_date
          //exposes the current order to the rule
    + Elements
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [site:current-date]
          //set the order's due date to the site's current date. This does two things: 1. ensures that the shipping date is based on the exact time the order is completed, as opposed to a previously calculated value, or the order creation date. 2. rules fail if no value is set
        + Add a variable
          Parameter: Type: Decimal number, Value: 0
          Provides variables: Order Turnaround Time (order_turnaround_time)
          //set the base turnaround time to 0 so we have something to compare our line item turnaround times to
        + Loop
          Parameter: List: [order:commerce-line-items]
          List item: List of Line Items (list_of_line_items)
          //loop through a list of the current order's line items
            + rule set: Get Line Item Turnaround Value
              Parameter: Line Item: [list-of-line-items], Order: [list-of-line-items:order], Product Display: [line-item:commerce-product]
              Provides variables: Line Item Turnaround Time (line_item_turnaround_time)
              //runs the "Get Line Item Turnaround Value" and pulls the "line_item_turnaround_time" for the current loop line item
            + Calculate a value
              Parameter: Input value 1: [line-item-turnaround-time], Operator: max, Input value 2: [order-turnaround-time]
              Provides variables: Calculation result (result)
              //check to see if the current loop line item's turnaround time is larger than the value of the order-turnaround-time
            + Set a data value
              Parameter: Data: [order-turnaround-time], Value: [result]
              //if the current loop line item's turnaround time is larger than the value of the order-turnaround-time write it as the new "order-turnaround-time" otherwise keep the old value
        + Convert data type
          Parameter: Target type: Integer, Value to convert: [order-turnaround-time], Rounding behavior: Always up (9.5 -> 10)
          Provides variables: Conversion result (conversion_result)
          //converts the order-turnaround-time to an integer, just in case it's not, so we can apply it as an interval
        + Apply an interval to a date
          Parameter: Interval number: [conversion-result], Interval period: Days, Date: now
          Provides variables: New Estimated Shipping Date (new_estimated_shipping_date)
          //add the new "order-turnaround-time" to the "site:current-date[field-due-date]" to calculate the estimated shipping date
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [new-estimated-shipping-date]
          //write the new estimated shipping date to the field-due-date field on the order

```

Hope that saves someone a couple of hours.

---
Tags: commerce, rules
---