# Question
Title: How do I make an auto-increment field based on another field with Computed Field and Node Clone modules working together?
I have a Computed field to calculate a value (if another field has value A, count nodes with the same value, add 1 and then use the result for the computed field value, auto-increment-like). This field is then used by Rules to create the node title.

Each time I save a node, this field is calculated. Fine.

Each time I update a node, the field is not calculated. Fine.

But I also need to clone a node and each time I clone a node, the field is NOT calculated though I need it to be recalculated. Consequently, the node title is identical and the computed field value of the cloned node is wrong.

I have tried Rules but a computed field does not support writing with an action like “Set a data value”. Then I tried to abort Computed Field and use Rules to set a data value using PHP evaluation but now I have trouble with tokens. I need to call them in PHP Evaluation and did not manage to… the PHP syntax is different between Computed Field and Rules

How do I make Computed Field and Node Clone working together?

Thanks for any help.

Interesting questions :

Using computed field value in Rules

**EDIT 1 :**

I have tried to transfer my code from Computed Field to Rules and I think I am very close. But I still need an advice about tokens. How do I call a token in PHP evaluation (action Set a data value)? `token_replace`? For example, if I need the `[node:nid]`, how do I get it in a variable `$nid`? (`$node` is not available in this Rules action...)

Thanks for any tips about this PHP syntax.

**EDIT 2 :**

As requested, here is my rules export, inspired by the Computed Field code. The problem is the query to get the NID of the Entity Reference Field (`field_site_id_target_id`). I worked with `field_get_items` in Computed Field but in Rules PHP Evaluation, it does not work (?). I know that this value is available in a token (`[node:field-site-id:nid]`) but I do not know how to call it in the PHP Evaluation. I also tried to "Add a variable" to fetch this NID but still I do not know how to call it in the PHP evaluation.

I am sure that someone can solve this in this forum :)

```
{ "rules_titre_auto_sample_2" : {
    "LABEL" : "Titre auto Sample 2",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : {
      "node_insert--sample" : { "bundle" : "sample" },
      "node_update--sample" : { "bundle" : "sample" }
    },
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-sample-number-2" ],
          "value" : {
            "select" : "node:nid",
            "php" : { "code" : "$nid_site=db_query(\u0022SELECT field_site_id_target_id FROM {field_data_field_site_id}\u0022)-\u003EfetchField();\r\n$result=db_query(\u0022SELECT count(*) FROM {field_data_field_site_id} WHERE field_site_id_target_id=\u0022.$nid_site)-\u003EfetchField();\r\n$value=sprintf(\u0027%03d\u0027,$result+1);\r\nreturn $value;\r\n" }
          }
        }
      },
      { "data_set" : {
          "data" : [ "node:title" ],
          "value" : "[node:field-site-id]-[node:field_sample_number_2]"
        }
      }
    ]
  }
}

```

**EDIT 3 :**

As requested to understand the problem :

Create Node/1 with title Site A – 001 (Field Site ID = Site A, Sample Number = 001 (computed)) OK

Create Node/2 with title Site A – 002 (Field Site ID = Site A, Sample Number = 002 (computed)) OK

Edit Node/2 : title unchanged. OK

Create Node/3 with title Site B – 001 (Field Site ID = Site B, Sample Number = 001 (computed)) OK

Clone Node/3 for Node/4 with title Site B – 001 (Field Site ID = Site B, Sample Number = 001 (computed)) **ERROR** : should be Site B – 002.

Cloning the node paste the Sample number value instead of a new calculation.

Hope this helps.

**EDIT 4 :**

Answer to Pierre Vriens about the first answer and the option "Save then edit" for Node Clone.

Unfortunately it does not work for my original problem. You are right, with the option "Save then edit", the Rules is triggered if I use the After cloning Event. But still, my computed field is not **re-computed**, the field value is cloned and then the title is the same.

For my case, I only see two ways :

abort Computed Field and only work with Rules and PHP Evaluation

OR

find a way to force the re-computing of my computed field when a content is saved or updated. I know there is an option on Computed Field to recalculate but it is working every time it is displayed, giving me some weird results with non-stop increasing number...

The problem is that a computed field does not support writing... So the action Set data a value from Rules can not be used here.

Besides, with your option, it will save a clone immediately and it is not appropriate for my clients : for example, if they just want to try the cloning procedure, they will have to search for the new content and delete it and I want this as user-friendly as possible.

I will re-think my Computed field and see what happens...

**EDIT 5 :**

After a long run of different combinations between Computed field, Node Clone, Rules, Auto-Label and Pathauto, I am really close to something.

Let me sum up the question so far :

* A Field A is calculated with Computed field, each time a content is saved.
* This field A is an auto-increment one, based on another field's value (Field B). See Edit 3 for an example of the results expected.
* The Automatic Entity Labels module allows me to hide the title in content form (with no pattern for the title)
* Rules is triggered each time a content is saved or updated to build the node title (= Field B - Field A).
* Node Clone allows me to clone a content BUT the Field A is not re-computed and consequently the node title is the same.

Based on my tests and comments from Pierre Vriens, I have tried a new angle.

Computed Field has an option called "Recalculate the field value every time" and I have tried to play with it. Now, I managed to have a computed field and title when creating a node or cloning a node!

BUT I still have a last problem : when I saved a content, I get a « Page not found »...

Actually, Pathauto is working to create an URL alias for each node (`[node:content-type]/[node:title]`). Surprisingly, the node is well created with the right URL alias (available in Content Overview) but just after saving the new content (or cloning) a « Page not found » is displayed. I suppose this time I have a problem with the actions sequence.

Any idea for this last obstacle ?

As soon as everything is fine on this procedure, I will create a clear answer with each step I used.

# Answer
Finally, a solution has been found, without Computed Field.

I worked with all modules cited in Edit 5 except CF and create my auto-increment value with Rules :

* After saving new content/After updating existing content
* If Field to auto-increment is empty
* Then Execute custom PHP code (PHP Filter core module requested) to get the right value (SQL)
* Set a Data Value to rewrite the node title, using the previous calculated value (with Tokens)

To force a new calculation when cloning a node, I worked with the Rules event "After cloning a node" (as suggested by Pierre.Vriens) but do not forget to choose the option "Save as a new node then edit" in Node Clone's configuration. Then, I have built a Rule to calculate the value after cloning a node and rewrite the node title.

This issue led me to meet a new powerful module : Conditional Rules. Thanks to that fabulous module, you may add if, else, switch, while... within your Rules. Must have.
> 0 votes

# Answer
Have a look at this (extremely basic) rule, in Rules export format:

```
{ "rules_demo_of_node_cloning" : {
    "LABEL" : "Demo of node cloning",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "clone" ],
    "ON" : { "clone_node" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "bingo, a cloned node ... add any additional Rules Actions you want (after this action)." } }
    ]
  }
}

```

The above rule uses Rules Event **After cloning a node** (an event which is available if you have the Node clone module enabled). All this rule does is to show some message starting with "***bingo, a cloned node ...***" (sorry, my favorite way of unit testing any rule ...). At least that's what's supposed to happen ...

But, according to comment nr 6 in issue nr 2212039, this event is only triggered if using Node clone's configuration option "***Save as a new node then edit.***", and not if using the option "***Pre-populate the node form fields***". These options can be found at `admin/config/content/clone`. And sure enough, after changing this option, you get such *bingo*-message (so the rule gets triggered by that event).

So as a work around, you may want to use that option "***Save as a new node then edit.***", and then either add this Rules Event (= After cloning a node) to your existing rule. Or otherwise create a new rule with this Rules Event, and add appropriate Rules Conditions/Actions which are probably similar to the rule you have already working for new or updated nodes. Better still, by only changing that Node clone configuration option mentioned above, your existing rule (to create or update a node) may get triggered already (so you don't have to do anything else).
> 0 votes

---
Tags: 7, nodes, rules, path-aliases, entities
---


# Question
Title: Is possible to update a project that has been installed from the archive file?
I'm very new to composer, I've only used it to install the occasional necessary library for our D8 projects. At each Drupal update I normally run

```
drush up drupal

```

Which (among other things) replaces the vendor folder and composer.json, so on sites with library dependencies, I need to re-run

```
composer require [library]

```

Aware of the touted benefits of Composer as a dependency manager, I want to use composer to maintain our Drupal projects. However I've run into issues, namely that

```
composer update

```

or composer update drupal/core --with-dependencies both give me "Nothing to install or update". After some reading, I found this resource https://github.com/drupal-composer/drupal-project. With this unzip, if I run

```
composer install

```

I get the correct latest version of Drupal installed in ./web. But when I use the yaml from the template composer.json file in my own composer.json file I still get "Nothing to install or update".

My folder structure is identical to the .zip distribution, so /core and /vendor and /sites etc are all in the same folder, so I have obviously adjusted the composer.json file according. But it doesn't matter what I do, I just get "Nothing to install or update" "Nothing to install or update" "Nothing to install or update"

So, I'm beginning to think that composer update with or without dependencies REQUIRES YOU TO HAVE INSTALL THE DRUPAL 8 PROJECT WITH COMPOSER TO BEGIN WITH.

Is that right? If so, then I can move on. If not then I need to know what I'm doing wrong. Right now it's not a big deal and I can manage the update process, but it seems each new project requires more and more non-core libraries, so I know composer will save me a lot of time in the future.

TL;DR - Can someone give me a kickstart to configuring my EXISTING, WORKING PRODUCTION SITES so I can use composer to update them, the usual ReadMe's don't seem to work properly with sites that weren't also installed with composer.

# Answer
> 8 votes
I got this working, I was very close but removing /vendor and composer.lock was what helped in the end. Here are the steps from the top:

1. add the line "drupal/core": "~8.1" to the 'require' statement (or update it to whatever version you require - in my case ^8.0 - latest Drupal 8 release).
2. Remove the drupal/core line from the 'replace' statement.
3. Add the following line somewhere (at the end? I believe this should replace the existing repositories statement, more information here. ):

```
"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}

```
4. Remove the /vendor folder
5. Remove the composer.lock file
6. Run your core update as follows

```
composer update drupal/core --with-dependencies

```

---
Tags: 8, updating, composer
---


# Question
Title: How to correctly invalidate a cached node when a menu link content is added/updated/deleted?
I'm currently facing an issue:

By following the contrib module's(menu\_link\_attributes) functionality, I altered the menu item's form to have a visibility by path option(almost the same as in the block config form).

I am saving the input data from the form in the menu\_link\_content's options column, then unsetting the menu item in hook\_preprocess\_HOOK() if the conditions are met.

The thing is, we have cached pages which are basically nodes(only on dev environment, the local one works as expected because caching is disabled) and the menu item is unset only after a CC.

I'm trying to add a cache tag to the node so that it's invalidated after I'm done with menu items.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function prl_menu_item_visibility_preprocess_node(&$variables) {
  // Since all the pages are nodes and all of them are using footer menu, we add the menu_link_content cache tag and invalidate it
  // when a link is saved and supposed to be hidden on specific pages.
  $variables['#cache']['tags'][] = 'menu_link_content';
}

```

Unfortunately, no success.

# Answer
> 2 votes
The tag you add doesn't exists. You probably want to add the list tag from the menu link content, which is invalidated in all cases when a link item is added, updated or deleted:

```
$variables['#cache']['tags'][] = 'menu_link_content_list';

```

But there might be another problem. As I understand your idea is, if you have a cache tag somewhere on the page, the complete page gets invalidated. This is true, but it will not help you. The rebuilt page will contain the cached menu block, if the block has not the correct cache tag on its own. So if you add a cache tag from the menu link to the node you have to do the same vice versa, add a node tag to the menu.

And probably you also need a cache context in the menu block for the visibility.

---
Tags: 8, caching
---


# Question
Title: How to display all records by default on a view with exposed filters
I've managed (after a lot of struggle) to create a view with four exposed filters (all filters are taxonomy fields). My problem is that now by default no data is presented to the user whene the page loads and data appears only when a filter term is chosen. I'm trying to achieve the exact opposite: have all data presented and then filter it accordingly. how can i do it?

# Answer
> 2 votes
When editing the filter, you can choose to require it if it's a select type of filter, you can also provide a default filtering that's used (before the user inputs). My guess is that you need to tweak these settings. to make sure that the default view filter settings display all or a selection of your choosing.

# Answer
> 1 votes
I came-across this one as I had same problem too when googling for the solution. I managed to solve this with Drupal 8; for Drupal 7, it should be the same.

On any exposed filter that you set, choose *Contains any word* from *Operations*.

---
Tags: 7, views
---


# Question
Title: After logging in the user is not directed to the homepage
I noticed that when I login I get redirected to `localhost/mysite/user/1` and not `localhost/mysite` or `localhost/mysite/homepage`. Why is this and what can I do about to **make the user go to the homepage after logging in ?**

# Answer
> 0 votes
It is a default option. But you can redirect user to any page by using hook\_form\_FORM\_ID\_alter Example:

```
 /*
* Implements hook_form_FORM_ID_alter
*/

     function YOUR_MODULE_OR_THEME_NAME_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Alter login form and add own custom submit handler.
      array_push($form['#submit'], '_custom_user_login_form_submit');
    }

 /**
 * Custom submit handler for login form.
 */

    function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $parameter = 'some_value';
        // Set redirect to login form.
      $form_state->setRedirect('custom_page', ['parameter' => $parameter]);
    }

```

For the front page default front page name is view.frontpage.page\_1. So it should be

```
 function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {

          $form_state->setRedirect('view.frontpage.page_1');
        }

```

---
Tags: 8, users
---


# Question
Title: How to alter incorrect Join type generated by Views?
I am suffering from a bug in Views 7.x-3.11 detailed here in relation to filter groups. Views incorrectly adds INNER JOINs when LEFT joins would be correct.

I am trying to alter the $query object using the code ( this approach is not based on any documentation, but simply a guess ):

```
function mymodule_views_query_alter(&$view, &$query) {
  if($view->name == 'my-view' && $view->current_display == 'my-display') {
    $query->table_queue['field_data_field_listing_type']['join']->type = 'LEFT';
  }
}

```

However this change causes the View to generate an ajax error "Fatal error: Call to undefined method stdClass::build\_join in sites/all/modules/views/plugin/views\_plugin\_query\_default.inc on line 1313".

Any assistance?

# Answer
Complete operator error. For the benefit of anyone else who encounters this error check your fieldname. In my case I had misspelt the fieldname \['field\_data\_field\_listing\_type'\] so it was generating a new incompleted entry in the table\_queue array.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to create multi level subgroups in organic groups?
I Need to create multi level of subgroups in organic groups like

like a tree. I don't know how to create using organic groups. Can anyone suggest.

# Answer
Apparently, there is a module for this: Subgroups for Organic groups

According to the module description,

> This module enables a user with the proper permissions to build group hierarchies (or tree) by nesting groups under other groups. Simple or complex group hierarchies can be easily created.
> 0 votes

# Answer
Assuming you already have organic groups installed and working:

1. Lets assume your content type for organic groups is called "group"
2. Edit this content type via: admin/structure/types/manage/group
3. Click on the "Organic Groups" tab for the content type.
4. Select the "Group content" field in addition to "Group". This ensures that the "Group" content type can also now be part of a group.
5. Save the content type.

That's all you need to do.

Additionally, installing og\_groups module enables propagation of settings, permissions etc. It is only needed if you want to so do.

If you want to see the tree hierarchically, you made need to create views using somethign like views\_tree
> 0 votes

---
Tags: organic-groups, entities, group
---


# Question
Title: How programmatically create custom field type with some base fields?
I want to emphasise that I don't want to use `field_collection`.

I want to create custom field type that can be reused in different entities and bundles. This should be kept in one custom module. So when I enable it and go to 'manage fields' page on any entity type then I should be able to pick up my custom field type (e.g.: `foo`). This field should be combined with base image field and simple one line text field. I don't want to use `field_collection` module because as far as I see I can not recreate my field, even features give me ability to export it in `field_base` section. After flushing my drupal to clean instance and enabling this feature again I can not see it in 'Add existing field' in \[structure \> content types \> CONTENT\_TYPE \> manage fields\] page. Maybe I'm doing something wrong. (?)

So how can I programmatically create custom field type with existing base fields? e.g. Custom `foo` field type with image field and text field?

OR (if I done something wrong with features..)

How can I export custom field collection with sub fields, only as a **field definition** (not attached to any content type/entity) using features?

# Answer
What you want to do is create a field type with multiple properties. This is indeed more efficient than a field collection, because a property only needs one more column in the field table, while a field collection is a complete new entity in the database.

This is the documentation how to build a custom field type from scratch in a custom module:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-type

As you want to add a property to an existing field type use this tutorial

https://www.lullabot.com/articles/extending-a-field-type-in-drupal-8

and extend the class `ImageItem` for the new field type. You also need to extend `ImageFormatter` to display and `ImageWidget` to provide a form field for the new property.
> 1 votes

---
Tags: 7, entities, features
---


# Question
Title: Run second site in the same VM: Is it possible?
I would like to run all my Drupal 8 sites in one Vagrant VM instead of just one. Is this possible?

I tried to remove the default drupal site from the "web" folder and pulled(git) 2 of my current probject into it.

For any reason drush does not recongnize the drupal roots as proper drupal sites.

I am not sure how other modules react... Is it normal to create each time a new VM for each Site you are developing. Seems a bit overkill.

# Answer
> 1 votes
Yes, this is *possible*, but take it from me as a guy who did it for about 12 sites - it gets tedious fast to manage it.

Setting up and tearing down VMs is so fast and cheap, it's simply more practical to me to create one per project. It's less to manage, and it just becomes a 'part' of the project codebase (you can fetch Drupal VM with Composer now for example, or download and keep it in a 'tools' folder outside of docroot).

Also it does not sound like you are setting up Drupal VM properly... I suggest re-reading the docs or posting more information.

---
Tags: virtual-machine
---


# Question
Title: Delete unused tables from the drupal database
In my Drupal database I have so many field\_deleted\_data\_XX and field\_deleted\_revision\_XX tables. I have disable the revision entity but I want to delete these existing revision created tables, can I delete these tables directly or Is there any SQL script to delete unused tables from the database.

# Answer
You can safely remove them yes. You can use drush to delete these tables: run `drush eval 'field_delete_field("yourfield")'` and run cron afterwards with `drush cron`.
> 3 votes

---
Tags: entities, database
---


title: Db_select Condition Collate

text:
# Question
Title: Db_select Condition Collate
In drupal 7 db\_query, when i use (**LIKE**), i add (**COLLATE utf8\_turkish\_ci**) after field. Because i want to search by Turkish characters. It works fine.

But i dont know how i use this in db\_select. For example; I use that condition

```
$query->condition('title', '%' . db_like($some_text) . '%', 'LIKE');

```

And i use orderby like that

```
$query->orderBy('title', 'ASC')

```

How can i add **COLLATE utf8\_turkish\_ci** for condition and order?

# Answer
I have a solution now.

For LIKE;

```
$query->where('n.title COLLATE utf8_turkish_ci LIKE :title', array(':title' => '%'.db_like($some_text).'%'));

```

For ORDER BY;

```
$query->orderBy('n.title COLLATE utf8_turkish_ci', 'ASC');

```
> 0 votes

---
Tags: 7, database
---


title: menu get object doesn't seem to work

text:
# Question
Title: menu get object doesn't seem to work
I'm a trying to pass a var, in this case the var "$node" to the page.tpl.php. Tried everything for three days but i cannot make it work despite my code is correct apparently. Tried different ways but when i tried to check with isset if the var exists, it returns false. I really need it, so i can check pages and nodes.

This is my code:

template.tpl.php

```
  function agn_preprocess_page(&$vars) {
  $node = menu_get_object();
  if ($node = menu_get_object()) {
      $vars['node'] = $node->type;
  }
  }

```

page.tpl.php

```
<?php if (isset($node)){
   print "true";
}else{
   print "false";
}
?>

```

Thanks in advance!

# Answer
> 1 votes
$node is already available in page.tpl.php on node pages without you having to do anything. See the documentation

---
Tags: 7, theming
---


title: Show custom entity bundle field

text:
# Question
Title: Show custom entity bundle field
I created an module polls and entity poll using Drupal Console

I want to add default entity\_type on installation. Currently I added only one field to it field\_image.

I created following files

FILENAME : **field.field.poll.article.field\_image.yml**

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.poll.field_image
    - polls.poll_type.article
  module:
    - image
id: poll.article.field_image
field_name: field_image
entity_type: poll
bundle: article
label: Image
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: '[date:custom:Y]-[date:custom:m]'
  file_extensions: 'png gif jpg jpeg'
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  title_field: false
  alt_field_required: true
  title_field_required: false
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  handler: 'default:file'
  handler_settings: {  }
field_type: image

```

FILENAME : **field.storage.poll.field\_image.yml**

```
langcode: en
status: true
dependencies:
  module:
    - file
    - image
    - polls
id: poll.field_image
field_name: field_image
entity_type: poll
type: image
settings:
  uri_scheme: public
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  target_type: file
  display_field: false
  display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes:
  target_id:
    - target_id
persist_with_no_fields: false
custom_storage: false

```

Field is created but it is coming as hidden in Form. How can I show it when modules get installed.

Please suggest.

--

Thanks

# Answer
> 1 votes
Configure the field in the form display, export this file

```
core.entity_form_display.poll.article.default.yml

```

and put it in the folder /config/install. Remove the uuid line from the yaml file.

---
Tags: entities, configuration, 8
---


# Question
Title: The connection was reset when creating a new node
On a localhost environment, when I try to create a new node, I get this message:

> *The connection was reset*.

There is some issue with css, cache and/or registry since when I disable the css aggregation it works for the next node and it stops for the next node creating. In order to work again for a new node it needs enabling the Css aggregation and so on.

Also when I clear caches I get this kind of messages:

> *The following module has moved within the file system: views\_test. In order to fix this, clear caches or put the module back in its original location. For more \[warning\] information, see the documentation page. bootstrap.inc:1128*

Any suggestions? Thanks.

# Answer
There are in fact two issues in your question.

To solve *The connection was reset* issue, have you tried to run rebuild\_registry ?

```
drush dl registry_rebuild-7.x
drush en registry_rebuild-7.x -y
drush cc drush
drush rr

```

Some people also reported that with Coder Module but not only, they had to edit `httpd.conf`, increasing the Apache stack size to 8MB

```
<IfModule mpm_winnt_module>
   ThreadStackSize 8388608
</IfModule>

```

For the 2nd issue *The following module has moved within the file system*, this appeared since Drupal 7.50 release. A straight way to correct these errors is to use Module Missing Message Fixer. You'll find alternatives and full explanations in this DO post.
> 1 votes

---
Tags: debugging
---


# Question
Title: How to implement a Rules Action to loop through quantity of a products bought?
With the Drupal Commerce module, I created a new product type I use for selling points to my customers. The product has a custom field named “points” (field type integer) where I specify the amount of point to sell.

On checkout I grant the points to the user with this rule, using the Rules module (thanks to Vic, see "How do I sell points using a new product type?):

> 1. Rule Event: on payment completed Action: loop through the order line-items. Each line-item has an action to call the next component with parameters of order and the line-item.
> 2. Component Parameters: order, line-item Condition: data comparison line-item:type is Product (to expose line-item:commerce-product) Action: call next component with parameters of order and line-item:commerce-product
> 3. Component Parameters: order, product Condition: data comparison product:type is Product (to expose the product:field-points-to-add) • Action: add userpoints, number to add being product:field-points-to-add

The problem comes when the quantity of the products sold is more than 1 because the action loops only through `line-item` and not through `line-item:quantity`.

Any suggestion for looping through `line-item:quantity`?

# Answer
Consider this Rules Component (in Rules export format, use the Rules UI to import it in your own site):

```
{ "rules_grant_user_points_multiple_times" : {
    "LABEL" : "Grant user points multiple times",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "USES VARIABLES" : {
      "points_to_grant" : { "label" : "Points to grant", "type" : "integer" },
      "quantity" : { "label" : "Quantity", "type" : "integer" }
    },
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "points-to-grant" ],
            "op" : "*",
            "input_2" : [ "quantity" ]
          },
          "PROVIDE" : { "result" : { "calculated_points" : "Calculated points" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : [ "calculated-points" ],
          "tid" : "0",
          "entity" : [ "site:current-user" ],
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

Some more details about this Rules Component:

* It uses 2 parameters (both "integer"), i.e.:
    + **Points to grant**, which is like your custom field named “points”.
    + **Quantity**, which is like your quantity of the products sold.
* Rules Actions:
    + Calculate a new variable (= `calculated_points`), which is simply a multiplication of the above 2 parameters.
    + Grant user points for an amount equal to ... euh ... indeed: `calculated_points` (adapt the details of the actual transaction to fit your needs).

These User Points will be granted to the "current user". Optionally you could just make that yet another parameter for the Rules Component also. I.e. if "current user" is not the customer who bought the quantity of products (which would allow one customer to buy such points for another user should you want to allow that, similar to a gift-card).

With that, all that's left is to finds the right spot in your existing Rules logic (related to checkout), to use the above Rules Component.

***Easy, no?***
> 0 votes

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


# Question
Title: How to utilise RequireJS and still access Drupal(7) JS API?
I have a project set up with Drupal loading in RequireJS which has a jQuery dependency defined.

All is well and good until I try something like this in a RequireJS managed module:

```
    (function($, Drupal) {
        Drupal.behaviors.someModuleName = {

            attach: function(context, settings) {
               // Some functional stuff here
            }
       };
    }(jQuery, Drupal));

```

The problem is that the attach function does not get called which leads me to think that Drupal is firing off its behaviours loader before Require has loaded up its modules.

# Answer
Woops, I'm not sure how the explanation got lost!

The script include:

```
<script id="requirejs" data-rev="1485975293" data-main="main.js?rev=1485975293" src="require.js?rev=1485975293"></script>

```

Alright, so this is in my main.js (data-main) file, that requirejs uses for loading up the dependencies and all that.

I'm just posting the relevant code block here (notice the `Drupal.attachBehaviors(document, Drupal.settings);` at the end:

```
    require([
      'jquery',
      'underscore',
      'intentcontext',
      'app',
      'primary-menu'
      ], function ($, _, IntentContext, app) {
      'use strict';

       // DOM ready
      $(function() {

        // js loaded only on homepage
        if ($('body').hasClass('front')) {
          require(['homepage']);
        }

        /*
         * loaded js for foundation and intention
         */
        require(['foundation']);
        require(['intentinit']);

        // call drupal behaviors
        Drupal.attachBehaviors(document, Drupal.settings);
      }); // DOM ready
    });

```

And then example of a dependent js module (primary-menu.js):

```
    define([
      'jquery',
      'intentcontext'
    ], function ($, IntentContext) {
      'use strict';

      /*
       * constructor
       */
      var PrimaryMenu = function(context, settings) {
        var
          self = this;

        self.$elm = $(context).find('#block-system-main-menu');
        $('body').once('primaryMenu').each(function() {
          self.init();
        });
      }; // PrimaryMenu constructor

      /*
       * on document ready with drupal behaviors
       */
      (function($, Drupal) {
        Drupal.behaviors.primaryMenu = {
          attach: function(context, settings) {
            var
              primaryMenu = new PrimaryMenu(context, settings);
          }
        };
      }(jQuery, Drupal));
    });

```

Hope that helps.
> 1 votes

# Answer
If RequireJS is loading your application's modules asynchronously once the page is loaded, then there is a high chance that Drupal's own page load handler will attach behaviors before your modules had their chance at registering theirs.

Because the are attached using the jQuery ready event, you may be able to `jQuery.holdReady()` to delay jQuery's ready event processing to after your application is loaded.

Another solution would be to call `Drupal.attachBehaviors(document, Drupal.settings);` time once your application is fully loaded. Properly written behavior should no have issue being attached multiple times to the page.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How can I add this image plugin, on a new clean/new texteditor?
When I want to add a texteditor `admin/config/content/formats` 4 editors; basic,restricted,full and plain are pre installed.

The basic.HTML CKEditor is with image plugin installed

When I create a new text format, the image plugin is not enabled and there is no obvious way to open it. How do I get the image plugin when configuring a new text format?

# Answer
This can be achieved by activating the image plugin for CKEditor.

Drag the following icon from the available icons to the active toolbar:
> 1 votes

---
Tags: 8, wysiwyg
---


# Question
Title: White Screen of Death on Cron, fixed with update.php
One installation of Drupal has been fine for a long time, but has started developing a WSOD on most (maybe all) cron invocations.

Looking through Drupal's log messages, I see a few normal cron messages, and then this:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in theme_get_registry() (line 277 of theme.inc).
Warning: array_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc).
Warning: array_fill_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc)
Warning: PHP Shutdown: Argument #1 is not an array in ThemeRegistry->set() (line 457 of theme.inc).

```

I then see the following repeated many hundreds of times, once for each theme hook, it seems:

```
Theme <hook name> not found. Warning: array_key_exists() expects
parameter 2 to be array, null given in ThemeRegistry->offsetExists()
(line 421 of theme.inc).

```

So that is repeated a few hundred times, where \<hook name\> is every theme hook in the entire Drupal installation.

It has been running a custom theme, but that theme has behaved fine for ages. In fact, I have not made many recent site changes. I've only updated Drupal to 7.52.

Any ideas how to proceed?

# Answer
Looks like an issue with either a theme hook implementation, or call to a theme function. In particular seems related to `theme_block`

While it could be something else, I'd suggest making sure you have the file `block.tpl.php` in your base and sub-theme directories and then clear cache.

Other possibilities are a file permission issue, make sure the files are readable by the webserver
> 0 votes

---
Tags: 7, wsod
---


title: Drupal queue processing at cron run

text:
# Question
Title: Drupal queue processing at cron run
I use ultimate cron to fill in a queue with some nids.

To add the items in the queue, I use something like:

```
$queue = DrupalQueue::get('my_queue');
foreach($urls as $nid=>$url){
  sleep(1);
  $response = drupal_http_request($url,array('timeout'=>3,'method'=>'head'));
  if($response->code=='404'){
    $queue->createItem(array('nid' => $nid));
  }

```

This works OK.

When the time comes, another cron job is executed that deletes those nodes. This is done like:

```
$queue = DrupalQueue::get('my_queue');
for($i=0; $i<$queue->numberOfItems(); $i++){
  $item = $queue->claimitem();
  node_delete($item->data['nid']);
  $queue->deleteItem($item);
}

```

This is not working OK; there is a small issue: Everytime the second job runs, only half of the items in the queue are processed (deleted). If there are 3000 items in the queue, only 1500 are deleted. If there are 1500 items, only 750 are deleted and so on.

Why is that? Is there a way to control it?

# Answer
So you have 2 queues walking all over eachother. The `timeout` value is how long the item is `Leased` to have work done upon it. The `lease-time` does not guarantee your processing will finish it time. A `Leased` item will not be able to be `deleted` until its lease has `expired`.

So you should analyze the tasks being run and adjust your timeout to be larger than the longest processing time you have recorded as occurring. I typically do a 2x or 10x as much Lease-time as my longest evaluated processing time. Once an item has completed processing its Lease is expired (so over guessing doesn't really hurt you here).

Alternatively, instead of having 2 queues you could do all this with 1 queue. To try to get around contention. You could insert into a single queue all your NIDs with an additional value of `task`; and at the end of that queue append a new list of NIDs with an additional flag value of `delete` or `purge`. Adjust your worker function to examine a NID and the action to perform on the NID; `task` or `delete`.

For example your createItem could look like:

```
// Add all NIDs for task to be performed.
$queue->createItem(array('nid' => $nid, 'action' => 'do-task'));
// in the same list later on queue the same NIDs to be deleted.
// by setting a huuuuge lease time you will never accidently purge an
// uncompleted task.
$queue->createItem(array('nid' => $nid, 'action' => 'do-delete'));

```

You may find working with a single queue -- easier than juggling 2 queues.
> 2 votes

# Answer
I encountered this same issue. I fixed it by setting `$queue->numberOfItems()` into it's own variable and then using the variable in the foreach. If I didn't do this, I found that the number of items was decrementing for each 'for' iteration, so only half were being processed.

So change:

```
for($i=0; $i<$queue->numberOfItems(); $i++){
  $item = $queue->claimitem();
  node_delete($item->data['nid']);
  $queue->deleteItem($item);
}

```

to:

```
$numberOfQueueItems = $queue->numberOfItems();
for($i=0; $i<$numberOfQueueItems; $i++){
  $item = $queue->claimitem();
  node_delete($item->data['nid']);
  $queue->deleteItem($item);
}

```

I know I'm 4 years too late, but hope this helps the next person.
> 2 votes

---
Tags: 7, queue
---


title: Get visibility of a block

text:
# Question
Title: Get visibility of a block
I've found plenty of posts about changing the visibility of a block programatically.

My problem is the opposite. Given a block's ID/delta, how do I find out if it should be displayed at the current path?

I have a field collection that allows you to append a block using the Block Reference module (I preprocess the field collection and use my own template, so the logic has been taken away from the Block Reference module). It works, but I only want it to kick in if the "Show block on specific pages" rule says that block should be displayed.

# Answer
> 0 votes
To test the block style visibility rules, you can use `drupal_match_path`

For example, in core: `block_block_list_alter`

> Checks the page, user role, and user-specific visibility settings. Removes the block if the visibility conditions are not met.

---
Tags: 7, theming, blocks
---


# Question
Title: Can I conditionally call a library based on HTML element?
I would like to use DataTables.js for tables created by content editors in the main body field of a content type. I already have the library installed in my libraries.yml.

I had an idea that I could avoid calling the library globally, but instead have it only be called on a page that has an HTML `<table>` element rendered.

That idea came from drupal.org documentation here, which offers up this code example for the `hook_element_info_alter()` function:

```
function fluffy_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'fluffiness/fancy_table';
  }
}

```

However when I checked into the theme.api, I saw this code is intended for people making modules and indeed the documentation section I saw it in was for modules.

Can I use this same or similar bit of code in my **theme\_name.theme** file to apply to all nodes? Is there something else I should do instead?

Thanks for any advice you can offer.

# Answer
`hook_element_info_alter` won't suit in this situation because you are trying to do something based on the value of a body field, which is just 'text' as far as Drupal is concerned. `Element` in the Drupal world is different. But here is an approach to your problem.

You can implement `hook_preprocess_node` and check if the body field value contains `<table` \- and if there is a hit, then attach the library:

```
use Drupal\Component\Utility\Unicode;

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $match = Unicode::strpos($node->field_body->value, '<table');

  if ($node->field_body->value && $match !== FALSE) {
    // next line is just an example
    $variables['#attached']['library'][] = 'mytheme/libraryname';
    $variables['#attached']['library'][] = 'mytheme/datatables';
  }
}

```

This will only attach the library to a node being rendered IF the node body field has a value, and within it, there is a match for an opening table tag.

The `use` statement should go at the top of your *mytheme.theme* file.

`strpos` has a caveat:

> Note that a return value of 0 is not the same as FALSE.

So if you plan on using this a little more elsewhere, take note.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to implement Likert Scale with EntityForm?
I was using Webform, but I need to provide an autocomplete field to reference a node of a particular type. I see many recommendations to dump Webform and use EntityForm, but the first question type I need to reproduce is a Likert scale. I don't see any discussion of how to create this fundamental question type with EntityForm. Do I really need to build each Likert scale question by typing option names/ids into a select field? Would there then be a way to report on the sum of a set of items in my form?

A Likert Item is a question like "What do you think of this module? Answer 1 (strongly disagree) to 5 (strongly agree)." A Likert Scale is the sum of responses to a series of Likert Items.

Webform has a very nice implementation.

# Answer
> \[...\] you can make form elements that don't have directly corresponding elements in the FAPI. The "grid" component is a good example of this, and in this case, I think it's exactly what you're wanting. You can effectively create a likert scale by creating "options" along the top with these keys:

```
-2|Strongly disagree
-1|Disagree
0|Neutral
1|Agree
2|Strongly agree

```

Source: https://www.drupal.org/node/291658
> 0 votes

---
Tags: 7, webforms, entities
---


# Question
Title: SA-CORE-2013-003 - Files directory Not fully protected
I'm using `Pressflow` 6.38 and I'm trying to implement SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities | Drupal.org inside of `/etc/httpd/conf.d/pressflow.conf` configuration file, like following:

```
<DirectoryMatch "^/(tmp|var/www/html/current/files)">
    # Turn off all options we don't need.
    Options None
    Options +FollowSymLinks

    # Set the catch-all handler to prevent scripts from being executed.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files *>
        # Override the handler again if we're run later in the evaluation list.
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    # If we know how to do it safely, disable the PHP engine entirely.
    <IfModule mod_php5.c>
        php_flag engine off
    </IfModule>
</DirectoryMatch>

```

however still getting following message in `Status Report` page:

> Files directory Not fully protected

```
See http://drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the files directory to help protect against arbitrary code execution.

```

My environment:

```
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.8 (Santiago)
# rpm -q httpd php
httpd-2.2.15-55.el6_8.2.x86_64
php-5.3.3-48.el6_8.x86_64
#

```

# Answer
> 1 votes
quote from SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities | Drupal.org:

> Additionally, the .htaccess of the temporary files directory and private files directory (if used) should include this command:
>
> Deny from all

instead of using `.htaccess` inside of `/tmp` directory (which can be wiped), I placed following rule inside of my `pressflow.conf`:

```
<Directory "/tmp">
    Deny from all
</Directory>

```

---
Tags: 6, security
---


# Question
Title: Call to a member function getFileUri() on null in ImageItem::presave()
I have a node migration as part of a D6-\>D8 migration, and for the image field in the node, I've done a separate files migration, and then in my node migration, I just refer to the files migration to get the destination fid and write that to the image field.

```
field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid

```

The problem I'm running into is the error listed in the title. This is the presave() function:

```
public function preSave() {
  parent::preSave();

  $width = $this->width;
  $height = $this->height;

  // Determine the dimensions if necessary.
  if (empty($width) || empty($height)) {
    $image = \Drupal::service('image.factory')->get($this->entity->getFileUri());
    if ($image->isValid()) {
      $this->width = $image->getWidth();
      $this->height = $image->getHeight();
    }
  }
}

```

It seems like it's dying because there is no image for that node, because it's dying at this line:

```
$image = \Drupal::service('image.factory')->get($this->entity->getFileUri());

```

It works just fine when there is an image for the node. Shouldn't this be skipped if there is no image found in the files migration? Is there a config option in the .yml file I can use to avoid this error?

Thanks.

**UPDATE:** I found this docs page on the skip\_on\_empty process plugin, and implemented as suggested on that page:

```
field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: migration
      migration: file
      source: fid
    -
      plugin: skip_on_empty
      method: row

```

but I still get the same error, more than likely because in the pipeline, it's already errored out before it gets to the skip\_on\_empty plugin. However, if I switch things around:

```
field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: skip_on_empty
      method: row
    -
      plugin: migration
      migration: file
      source: fid

```

Then the entire blog node is skipped if there is no image. How can I just skip trying to migrate the image if there is none?

# Answer
> 1 votes
I a similar issue on a previous migration, I found that a core issue sometimes causes that error.

The patch submitted fixed the problem on my case.

---
Tags: 8, migrations, media
---


# Question
Title: How do I make a mini-panel pane a title?
I've been replicating some work, in mini-panels, that's already on my site. On one of the mini-panels there is a custom-content pane that is acting as a header. In the gear icon drop down there is a little option called 'Panel Title' that can be selected.

However, I cannot find this option for other custom panel panes I create.

The content of the already-made title page is simply a Title input.

Would anyone know how I can create this?

# Answer
> 0 votes
OK, found it.

It wasn't in the pane settings as I thought (I was looking through loads of Panel documentation). Right at the top of the Edit Mini Panel page there is a dropdown menu called Title Type. You can set this to 'From Pane'.

---
Tags: 7, panels
---


# Question
Title: How do I override /theme/custom twig in my module to render input fields?
I have a module that is building a form. I want to theme the form using twig within my module so it does not interfere with my theme/custom twigs.

My buildForm function is:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

```

I have set the theme for the form as `custom_form` and it works fine using this in my .module file:

```
function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_form' => array(
      'render element' => 'form',
    ),
    'input' => array(
      'template' => 'input',
      'render element' => 'element',
    ),
  );
}

```

However the input fields are still being rendered using `input.html.twig` file in my /theme/custom theme folder.

I have created copied the twig template file using the same name and placed it in my custom\_module folder however Drupal is still using my theme input.html.twig file.

How do I override this twig and use the input.html.twig file in my custom\_module templates folder?

Thanks

# Answer
> 0 votes
Found the answer after some intensive searching and looking at Drupal From API: Create a twig file for the theme, I called it `custom-input.html.twig` and place it in your custom\_module templates folder. Then you tell Drupal about it using `hook_theme()` function:

```
function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_input' => array(
      'render element' => 'element',
    ),
  );
}

```

Lastly, in the buildForm function you say what theme will render the element like below:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
    '#theme' => 'custom_input'
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

```

This will tell Drupal to render the form input elements using the custom twig file you created.

---
Tags: 8, theming, forms
---


title: Convert UTC to local time in date field

text:
# Question
Title: Convert UTC to local time in date field
I have a content type with a date field, which I convert to a specific date format in a preprocess function:

```
$variables['date'] =
\Drupal::service('date.formatter')->format($variables['node']->field_datum->date->getTimestamp(), 'long_date_without_time');

```

But as Germany is one hour ahead, a date like 2015-03-31 23:01:08 UTC converts to 1. April 2015. How can I convert this to our local time?

EDIT: I already set the correct timezone in the UI. And I just saw that the wrong dates are only shown when I set my system time between 11pm and 1 am...

# Answer
> 0 votes
The date formatter service automatically converts it to whatever time zone you selected when you installed the Drupal site, `admin/config/regional/settings`.

Also, if you allow users to set their own timezone in `user/1/edit`, it would use that time.

So either you need to change the timezone in `admin/config/regional/settings` and/or in `user/1/edit`

---
Tags: theming, 8, datetime
---


# Question
Title: Copy a user directly in database from another database (from production to dev-site)
related to this post for Drupal 6 (Adding a new user directly in database), I wanted to ask for help for my problem:

I have a *drupal 7* site which is already online ("in use/production"). Users can register there.

To get an up to date dev-enviroment, I download the files (uploaded files, modules and so on) via ftp from my production server to my dev server. The DB is migrated by "backup and create"-module (export on production server, import on dev-server and vice versa).

As I develop the features in my dev instances, new users register on my production site. If I now import my new backup of the dev-server to production site, the new users registered are lost because the db has been overwritten by the backup.

How can I copy these new user accounts directly to the dev database? what database tables are involved in Drupal 7?

THX in advance phil

# Answer
Databases shouldn't be copied upstream, they should only be copied downstream, for the exact reason you are seeing.

This is a bit of a problem in Drupal 7.

If you need to move content up from dev -\> production, like new nodes or you want to move configuration, then the best way to do it is either manually, or to set up something like the migrate module to migrate your content.
> 1 votes

# Answer
I'd suggest you take a look at the Deploy module. It allows you to copy and stage content across Drupal sites in a clean way and is designed for use cases like yours. It has support for moving user accounts as well.

**NOTE:** Always remember to take a backup of either sites before doing any DB surgery :)
> 0 votes

---
Tags: 7, users
---


# Question
Title: Webform does not submit, instead redirects to self
My soon-to-be production Drupal site's Webforms have stopped saving submissions; instead it comes back to the same page, complete with the inputted values. I do not have a timeline when it stopped working. In a sandbox environment, Webform 7.x-3.17 works fine.

**I'm looking for some suggestions to further debug.**

I've tried the following, but to no success:

* Disabling any modules that refer to Webform (notably Webform Template and Webform Validation, and my own custom module that had been using `hook_form_alter`).
* Upgrading to the latest Webform (yes I remembered to use update.php).
* Based on documentation, combining `hook_form_alter($form, &$form_state)` with `array_unshift($form['#submit'],'my_custom_submit')` to insert a custom callback, where I called `drupal_build_form($form['form_id']['#value'],$form_state)` to emulate a submission.
* Obviously flushing caches consistently.
* Ensuring that the Webform is published.
* Writing a bare-bones module to simply monitor `$form_state['executed']` (it always returns false).
* Checking my server's `error_log` both on SSH and FTP.
* Checking Reports \> Recent log messages.
* **New:** Tried disabling & uninstalling Webform, deleting old Webform files, and installing a fresh new version of Webform; no good.

I'm pretty sure the issue is not isolated to Webform, so it wouldn't make sense to post to their issue queue.

What other debugging methods can I pull out to help crush this bug? If I disable every module without uninstalling, is an entire FTP backup necessary or just SQL?

**EDIT: Some more things I've tried as per suggestions (unsuccessfully)**

* Explicitly defining $cookie\_domain and $base\_url in settings.php
* Looking through Trigger and Action modules for any potential misfiring redirects

# Answer
I have never had any problem with the Webform module, but if it happened to me I would double check sites/default/setting.php to see if there are any settings for an explicit `$base_url` or `$cookie_domain`. The latter is much improbable, since you would probably have problems with logging in.
> 2 votes

# Answer
Just in case you are using the Boost module, that was happening to me and the problem was in the .htaccess file, check my solution here: https://drupal.stackexchange.com/a/207102/11424
> 1 votes

# Answer
I had the same issue. Like Dennis, the problem was caused by putting a URL alias on the webform node. When I removed the alias and did a full URL then it worked just fine. In my case, there was a conflict because my chosen URL alias was equal to a directory name on my site. So I could use a different alias and it worked fine. I just can't use the alias I wanted, unless I rename the conflicting directory on my site.
> 1 votes

# Answer
I was just getting exactly this issue. I found that the problem was that the form was being altered in a way that prevented webforms from understanding it. As far as I could tell, the $form\_state was not being affected by the changes, but altering the $form was still enough to break the whole thing.

I haven't found the workaround yet. I'll update my answer if I do.

Update: For my workaround, I used the #prefix and #suffix to add markup to elements instead of putting them in form containers. This fixed the problem.
> 0 votes

# Answer
I wanted to add my two cents worth here. I had the same issue on a dev site. The site will go live soon, but I was checking the functionality and got this very same issue.

The problem was caused by putting a URL alias on the webform node. When I removed the alias and did a full URL (mysite.com/?q=node/8) then it worked just fine.

Also, I don't have clean URLs enabled so that might fix the issue with the URL alias.

But I wanted to throw this out to anyone else with the issue . . .
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: Rule to loop over products with one specific SKU in Drupal Commerce cart
I'm still a novice at Rules. I'm using Drupal Commerce and have the Flat Rate shipping service enabled. I'm using Rules to calculate a surcharge to the flat rate based on the number of items in the shopping cart. So far this rule works.

However, I now want to modify the rule so that it only calculates the surcharge based on the number of products *with a specific SKU*. All other line items in the cart, which may be other products, should be ignored for the purposes of this calculation.

If I was just coding this, I would put an if statement in the loop and look at whether the current line item has a specific SKU. But I totally don't understand how to do that with Rules.

Thanks for any help.

Here is my current rule:

```
{ "rules_createspace_flat_rate_calculator_expedited_" : {
    "LABEL" : "CreateSpace Flat Rate Calculator (Expedited - US)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "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" : "ship_manuals_to_you_expedited_"
        }
      },
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" :     "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "value" : "US"
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "order_line_items" : "Order line items" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "order-line-items:quantity" ],
                  "op" : "*",
                  "input_2" : "250"
                },
                "PROVIDE" : { "result" : { "shipping_volume_surcharge" : "Shipping Volume Surcharge" } }
              }
            },
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "shipping-volume-surcharge" ],
                "component_name" :    "flat_rate_ship_manuals_to_you_expedited_",
                "round_mode" : "1"
              }
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_add" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "1000",
          "component_name" : "flat_rate_ship_manuals_to_you_expedited_",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

# Answer
> 2 votes
Your real challenge appears to be this part of your question:

> ... put an if statement in the loop and look at whether the current line item has a specific SKU ...

Here is how to get that to work:

***Easy, no?***

PS: I'm assuming this question is about D7 ...

---
Tags: commerce, rules
---


# Question
Title: How does the Drupal session system work?
I would like to implement the familiar "Remember me" functionality on user login forms, i.e. if a registered user leaves the browser without hitting the log out link, (s)he will still be logged in when visiting the website afterwards. A quick search leads to the Remember me module, whose description states:

> (...) the default Drupal behaviour is to remember your session for the extent of 3 weeks and 2 days. (...) Can you imagine the colossal risk this places on users accessing your service from public terminals or shared workstations, with no means to their disposal of securing themselves against this threat.

If the first sentence is true, it seems that I do not need the module to accomplish my need. Indeed, I can safely exit Firefox without loosing my session for "a while" (I do not know the exact time interval). However, other users on my website complain that they are immediately logged out after closing their browser.

So now I want to know the ins and the outs of the matter. Are sessions handeled differently for different browsers and, if yes, why? Does Drupal remember sessions for the extent of 3 weeks and 2 days and, if yes, why was this long time interval chosen? Is not using a module like Remember me indeed a risk?

# Answer
Drupal has a pluggable session handler, however it generally uses a cookie + database session model by default.

The `sessions` table in the database stores the session details for the users. The session id is stored and matched from a browser cookie.

The settings for session duration can be found in settings.php, in particular:

```
/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

```

You can adjust those settings to affect the session lifetime. Indeed, the "remember me" module uses the `session.cookie_lifetime` setting to apply its functionality.
> 2 votes

# Answer
> However, other users on my website complain that they are immediately logged out after closing their browser.

They should not be, unless they have history set to `Never remember history/cookies` or they use an app/extension that clears the history/cookies when the browser is closed.

So the cause of the problem is really on their end.

You could use IP Login so they get logged in automatically.
> 0 votes

---
Tags: 7, sessions
---


# Question
Title: AJAX loading of a view on click of a button?
I want to switch between two methods of sorting and displaying items in Views by toggling a button. My exposed filters are in the URL so I want to include the query in the path in order to keep the exposed filter results. Both displays of the view have "use ajax" set to "yes".

My link is :

```
$link_path = ($display_data->display_options['path'] . '/nojs');
$query = drupal_get_query_parameters();
$toggle_link = l($toggle_icon, $link_path, array('html' => true, 'query' => $query, 'attributes' => array('class' => array('use-ajax'))));

```

Which outputs something like:

```
<a href="href="/my_view_page_1/nojs?terms=test&param1[0]=123">[omitted SVG path for brevity]</a>

```

In a js file in my theme, I have:

```
    /**
     * Toggle button and ajax views
     */
    var viewId = settings.mytheme_toggle_view.view;
    var viewDisplayId = settings.mytheme_toggle_view.current_display;
    var viewOtherDisplayId = settings.mytheme_toggle_view.other_display;
    $.ajax({
        url: settings.basePath + 'views/ajax/' + settings.mytheme_toggle_view.query,
        type: 'post',
        data: {
          view_name: viewId,
          view_display_id: viewOtherDisplayId,
          view_args: {}, // your views arguments
        },
        dataType: 'json',
        success: function (response) {
            var newView = ($(response[1].data));
            $(".view-display-id-" + viewDisplayId).replaceWith($(newView));
        }
    });
    /* End views ajax stuff. */

```

What happens now:

1. I go to my view and select my exposed filters and hit "apply"
2. I arrive at my view's default display page
3. Before I can click anything, AJAX fires and replaces the view content with the alternative view content.
4. If I click the toggle, it is a link (with full page reload, not AJAX) to the default display page again.
5. Step 3 repeats.

What I want is for the view to

1. Not change on pageload, but wait until the toggle button is clicked
2. Be able to be toggled back and forth rather than only toggling once and then becoming a regular, page-reloading link.
3. Preserve the exposed filters
4. Have the pager still work (currently is a link to some JSON output of the settings object).

# Answer
Views Modes

> A Drupal Views display plugin which provides alternate display modes that can be switched to for a single View. This allows exposed filter parameters or contextual filters to be kept active while switching display mode.

Sounds like this module does what you're trying to do. There's only a dev version, but might be worth a look.
> 0 votes

---
Tags: views, javascript, ajax
---


# Question
Title: 8 How do I display "Showing content between date1 and date2" on the current pager item?
I am creating a list of content with a mini pager. I can't seem to find an option to print the date range of all the nodes being displayed in the current pager item. The content type has a date field. I would like to say "Showing content between date1 and date2" on each pager item based on the date field in the content type.

**Clarification:** Except the date1 and date2 are the same field. This approach would not print the date range automatically based on a single date field... Let's say I have 100 node items with a NewsDate field. On each page, filter should show the the most recent to the latest date on top of each page. "Showing pages between "date range".

# Answer
There is an other way for "Showing content between date1 and date2" use the Exposed filters fields for the "Start date" and "End date" with Is between Operator. According to field created in the content type, From this You can easily filter the content according your filled date and set displayed items in pager. Hope its helpful to you!
> 0 votes

---
Tags: views, 8, datetime
---


# Question
Title: Any performance impact or reason to delete unused views?
I have maybe 250 views on a site build and estimate that I use around 150 of them.

Is it ok to leave the extras there unused? It would take days trying to guarantee views aren't being used in custom blocks and in hooks for other views.

# Answer
If they are never loaded/rendered, there should be no performance hit, except for the admin viewing the `/admin/structure/views` page since they get listed there.

Ok, maybe a slight performance hit, since the view table ID's in your DB is bigger, so it would take longer to find an ID, but if you're caching your Views you will be fine.
> 1 votes

---
Tags: 7, views
---


title: Product page with 2 times css

text:
# Question
Title: Product page with 2 times css
Im trying to create a product page, but my boss wants different css for every next photo and text. I need 2 different css styles, that will aply on where the image is. Like the first block will have the image at the left and the second block will have the image on the right.

This is basicly what im trying to do :

I think I could do this with css and some custom classes? So that every added block with text and image will align itself properly without having to edit the css for every block everytime you create a new block. If someone could point me in the right direction on how to achieve this, that would be great !:)

# Answer
If you are achieving this html by using views then set the rows even and odd patterns and do the CSS according to the even and odd class.
> 0 votes

---
Tags: theming, 8, blocks, media
---


# Question
Title: How to resolve my error when uploading files?
In our Drupal site when we try to upload .zip file having 210MB size, we are getting an error saying:

> The file NewEdition105.zip could not be saved. An unknown error has occurred.
>
> The file in the Sai Rel File field was unable to be uploaded.

If I try with a 100mb .zip file I am able to upload. My maximum upload file size is 1800MB, upload\_max\_filesize=1600MB and post\_max\_size=1600 MB.

Did anybody face a situation like this? Any solution for this?

# Answer
You can try the Pack & Upload module for this. This module can be used to upload the zip file.
> 0 votes

---
Tags: 7, files
---


# Question
Title: Using an admin account as the sender for an action rule instead of site:current-user
I am using a reaction rule that triggers, when a new user is registered. This rule sends a private message to a role ( service-role ).

The sender of the message is the actual logged in user - in this case the user that was just created, the new user.

I want the sender to be the admin but I have no change to select the admin the the data-selection field. How can I archive any other user that the actual logged in user?

# Answer
If you don't find what you're looking for, you could try to use the `Switch to the direct input mode` button and then enter the userid of the admin.

That's a kind of "hardcoding" one may say, but at least it is "a" way to use what you're asking for.

Be aware: that userid to be entered can be an identifier of just any userid (so if the userid entered is not a user who is "***the admin***" (as in your question), that should work too.
> 0 votes

# Answer
I was able to select the wanted sender User by typing in the USER ID when the form is in direct input mode. To get to this "direct input mode", use the button "switch to direct input mode", as shown here:

After doing so, the form will look like so:

So in the end, the result of doing so is that if you read your private messages, then the sender is not the new user anymore, but the user you selected by ID manually (as shown in the above form).
> 1 votes

---
Tags: 7, rules
---


title: Store images in file or media entity?

text:
# Question
Title: Store images in file or media entity?
When I start a Drupal project, should I use the Media module for image files?

I hope I can upgrade to Drupal 8.3, where parts of the Media module are in core.

# Answer
> 3 votes
I would go with Media suite simply because I believe files should be treated like full entities as nodes are. It grants you more options and flexibility in media management and reuse instead of the standard upload field.

---
Tags: 8, media
---


# Question
Title: Can AJAX be enabled for a form element inside a tableselect row?
Firstly, a working select element with an AJAX callback:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['select'] = [
    '#type' => 'select',
    '#options' => [
      0 => 'ZERO',
      1 => 'ONE',
      2 => 'TWO',
    ],
    '#ajax' => [
      'callback' => [$this, 'ajaxSelectChanged'],
      'event' => 'change',
    ],
  ];

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

  return $form;
}

public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
  $selection = $form_state->getValue('select');
  // Do something with the selection.
}

```

Now I want to put the select element inside a tableselect element...

This comment shows how form elements may be added inside the rows of a tableselect (which is also a form element).

Here's my attempt:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  // Build the sortable table header.
  $select_options = [
    0 => 'ZERO',
    1 => 'ONE',
    2 => 'TWO',
  ];

  $form['table'] = [
    '#type' => 'tableselect',
    '#header' => [
      'name' => $this->t('Name'),
      'select' => $this->t('Select'),
    ],
    '#options' => [
      'alice' => [
        'name' => $this->t('Alice'),
        'select' => [
          'data' => [
            '#type' => 'select',
            '#options' => $select_options,
            '#ajax' => [
              'callback' => [$this, 'ajaxSelectChanged'],
              'event' => 'change',
            ],
          ],
        ],
      ],
      'bob' => [
        'name' => $this->t('Bob'),
        'select' => [
          'data' => [
            '#type' => 'select',
            '#options' => $select_options,
            '#ajax' => [
              'callback' => [$this, 'ajaxSelectChanged'],
              'event' => 'change',
            ],
          ],
        ],
      ],
    ],
    '#empty' => $this->t('There is nothing to see here.'),
  ];

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

  return $form;
}

public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
  $selection = $form_state->getValues();
  // Do something with the selection.
}

```

It works, except for the AJAX callback, which never runs.

* Am I doing something wrong?
* Is there a way to let form elements inside a table trigger AJAX callbacks when they are changed?

# Answer
The reason that `#ajax` doesn't work for your tableselect options is that the render array is inside a render attribute - render attributes are not processed as render element children.

That means that they don't receive an ID, or a name. And that the `RenderElement::preRenderAjaxForm` does not process them.

There are several ways to circumvent this problem.

Option 1: Create a hidden ajax elements below the table and trigger them via ajax. Option 2: Run the required processing yourself.

Here is a sample implementation of Option 2:

```
class SandboxForm extends FormBase {
  public function getFormId() {
    return 'sandbox';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Build the sortable table header.
    $select_options = [
      0 => 'ZERO',
      1 => 'ONE',
      2 => 'TWO',
    ];

    $form['table'] = [
      '#type' => 'tableselect',
      '#header' => [
        'name' => $this->t('Name'),
        'select' => $this->t('Select'),
      ],
      '#empty' => $this->t('There is nothing to see here.'),
      '#options' => [
        'alice' => [
          'name' => $this->t('Alice'),
          'select' => [
            'data' => [
              '#type' => 'select',
              '#options' => $select_options,
              '#ajax' => [
                'callback' => [$this, 'ajaxSelectChanged'],
                'event' => 'change',
              ],
            ],
          ],
        ],
        'bob' => [
          'name' => $this->t('Bob'),
          'select' => [
            'data' => [
              '#type' => 'select',
              '#options' => $select_options,
              '#ajax' => [
                'callback' => [$this, 'ajaxSelectChanged'],
                'event' => 'change',
              ],
            ],
          ],
        ],
      ],
      '#process' => [
        '::processTable',
        [Tableselect::class, 'processTableselect']
      ]
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#ajax' => [
        'wrapper' => 'test',
        'callback' => [static::class, 'ajaxSelectChanged'],
      ],
    ];

    return $form;
  }

  public function processTable(&$element, FormStateInterface $form_state, &$complete_form) {
    foreach (array_keys($element['#options']) as $option) {
      foreach (array_keys($element['#options'][$option]) as $col) {
        if (is_array($element['#options'][$option][$col]) && isset($element['#options'][$option][$col]['data'])) {
          $element['#options'][$option][$col]['data']['#name'] = implode('-', [$element['#name'], $option, $col]);
          $element['#options'][$option][$col]['data']['#id'] = implode('-', [$element['#id'], $option, $col]);
          $element['#options'][$option][$col]['data'] = RenderElement::preRenderAjaxForm($element['#options'][$option][$col]['data']);
        }
      }
    }
    return $element;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state); // TODO: Change the autogenerated stub
  }

  public static function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
    $selection = $form_state->getValue('select');
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $selection = $form_state->getValue('select');
  }

}

```
P.S.

I know that for regular `table` elements you can pass render array by not using the `#rows` attribute and passing them as children. I tried it here and it failed, though I could be missing something.
> 1 votes

# Answer
Here is my solution:

* Add placeholders (like a simple string, or an empty array) to the table row, where the select lists should go.
* Add select lists below the table, and check that they have fully functional AJAX callbacks.
* Register a `#pre_render` function on the form which moves the select lists into the table.

In the buildForm function:

```
$form['#pre_render'] = [[$this, 'preRender']];

```

And then in the form class:

```
public static function preRender(array $form) {
  foreach ($form['table']['#options'] as $delta => &$row) {
    $row['select_lists']['data'] = $form['select_lists'][$delta];
    unset($form['select_lists'][$delta]);
  }
  return $form;
}

```

I also tried `hook_form_alter`, but it runs too early, and messes up the AJAX. Apparently, a `pre_render` function runs after the AJAX stuff has been set up by Drupal, and then we can move the element anywhere on the page without affecting the AJAX functionality.
> 3 votes

---
Tags: 8, forms, ajax
---


# Question
Title: Where to add "No results behaviour" to a view?
I'm using an exposed filter. When there is no result, where do I add "No results behavior" for the view?

# Answer
> 8 votes
On the view settings page, click on the *Add* button shown to the right of *No results behavior*. (The following screenshots are taken from the *Taxonomy term* view, but what described is valid for every view.)

>

>

In the dialog box that appears next, select *Text area* and click on the *Apply (all displays)* button at the bottom.

>

The button name changes to *Apply (this display)* when *This page (override)* is selected for *For* on the top.

>

In the *Content* text area that appears in the next dialog box, you can enter the text to show when no results are returned from the view.

>

If you need it, you can also use some global tokens, listed under *Available global token replacements*.

>

# Answer
> 1 votes
..............Have you tried here?

# Answer
> 1 votes
In the view settings, it's in the middle column, between *Footer* and *pager*.

The screenshot I am showing is for the front page view that comes with Drupal 8.

>

---
Tags: views, 8
---


# Question
Title: How to check whether the page content is been managed by blocks, views or anything?
I have one webpage (created in Drupal 7) and I am not able to figure out wether the content comes from blocks, views or anything else? I have checked blocks and views but there it is not appearing. How to check?

# Answer
If you are logged in as administrator of the site, usually you should see either a edit button (for full nodes) or a contextual link for editing the a view or a node. You will need to have permission to see contextual links.
> 0 votes

---
Tags: 7
---


# Question
Title: Is it possible to get client ip in setting.php
I'm trying to get the client IP in settings.php for security reasons, using the following code. I have to support `X-Forwarded-For` header because accessing web server over loadbalancer.

```
$clientIp = \Drupal::request()->getClientIp();

```

It causes the following error.

> The website encountered an unexpected error. Please try again later.
> Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/my-site/docroot/core/lib/Drupal.php).
> Drupal::getContainer() (Line: 218)
> Drupal::request() (Line: 759)
> require('/var/www/my-site/docroot/sites/default/settings.php') (Line: 116) Drupal\Core\Site\Settings::initialize('/var/www/my-site/docroot', 'sites/default', Object) (Line: 1015)
> Drupal\Core\DrupalKernel-\>initializeSettings(Object) (Line: 642)
> Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

Any suggestions to fix this?

# Answer
In `settings.php` the drupal kernel is not loaded yet, so the service container is not initialized. Use the php superglobal `$_SERVER`instead:

```
$client_ip = $_SERVER['REMOTE_ADDR'];

```
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: Hiding referenced term name from node display
I've stumbled upon a situation where I want to display a link and a custom icon for the link (I'm using paragraphs module) which will be themed correctly later, BUT. After providing a taxonomy term with a image field and making it display ONLY the image by default I'm still getting a h2 of the linked terms name.

I already tried hook\_entity\_view, but it doesn't have separate values for icon and the randomly displayed term name - only the term id meaning I cannot unset it at this hook.

Any suggestions/experience on how should we work with this?

# Answer
> 1 votes
In the content type or paragraph type go to *Manage Display* and configure the format of the term field as "Rendered entity".

Copy `taxonomy-term.html.twig` to the template folder of your theme and remove the linked title: `<h2><a href="{{ url }}">{{ name }}</a></h2>`

**taxonomy-term.html.twig**

```
<div{{ attributes }}>
  {{ title_prefix }}
  {% if not page %}
    <h2><a href="{{ url }}">{{ name }}</a></h2>
  {% endif %}
  {{ title_suffix }}
  {{ content }}
</div>

```

# Answer
> 0 votes
Have you checked the corresponding template? To be sure just set debug: true in your root project services.yml file. the inspect the HTML code with your web browser dev tool.

You should find comments like (just an example here):

```
<!-- FILE NAME SUGGESTIONS:
   * field--node--title--reception-center.html.twig
   x field--node--title.html.twig
   * field--node--reception-center.html.twig
   * field--title.html.twig
   * field--string.html.twig
   * field.html.twig
-->

```

Then find the corresponding template and edit it in order to hide the label. In your case that template could be a field template or a term view mode template.

---
Tags: nodes, 8, taxonomy-terms, paragraphs
---


title: Add comments via REST

text:
# Question
Title: Add comments via REST
I am using waterwheel-swift to connect my iOS app to Drupal 8. Logging-in and node posting/editing work great, but when I try to post a comment, I get a 400 error.

I am using the following code.

```
    let body = [
        "entity_type": [
            [
                "value": "node"
            ]
        ],
        "entity_id": [
            [
                "target_id": self.nodeID
            ]
        ],
        "field_name": [
            [
                "value": "field_x"
            ]
        ],
        "comment_body": [
            [
                "value": "How are you?"
            ]
        ]
    ]

    waterwheel.entityPost(entityType: .Comment, params: body as paramType) { (success, response, json, error) in
        if (success) {
            print(response)
        } else {
            print(error)
        }
    }

```

I get the following error:

> Error Domain=Alamofire.AFError Code=3 "Response status code was unacceptable: 400."

rest.resource.entity.comment config is the following.

```
  langcode: en
  status: true
  dependencies:
    module:
      - basic_auth
      - comment
      - csv_serialization
      - hal
      - serialization
      - user
  id: entity.comment
  plugin_id: 'entity:comment'
  granularity: method
  configuration:
    GET:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    POST:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    DELETE:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    PATCH:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie

```

Please point out if something is wrong with my code.

# Answer
Got it resolved, the problem was, i was not passing the parameter comment type. Made the following changes to body parameter and it now works.

```
let body = [
        "entity_type": [
            [
                "value": "node"
            ]
        ],
        "entity_id": [
            [
                "target_id": self.nodeID
            ]
        ],
        "field_name": [
            [
                "value": "comment_x",  // Machine name of the field on the node
                "format": "no_html"
            ]
        ],
        "comment_body": [
            [
                "value": "How are you?"
            ]
        ],
        "comment_type": [
            [
                "target_id": "comment_x"  // Machine name of the comment bundle
            ]
        ],
        "uid": [
            [
                "target_id": self.UID
            ]
        ],
    ]

```
> 1 votes

---
Tags: 8
---


# Question
Title: Update values of multiple value field programmatically? (Rules action)
I'm trying to create a rule to populate a multiple value order reference field in Drupal Commerce, on checkout complete.

I haven't been able to achieve this through Rules UI, so instead I'm trying to programmatically create the action but can't figure out how to set the actual value.

I simply want to add a reference of the newly created order to the purchased product, while keeping the references already set (in this particular case an order will never contain more than one product).

I have added an order\_reference\_field (Commerce Order Reference module) to my product, showing checkboxes with multiple values allowed.

Below my code:

```
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;

    $wrapper = entity_metadata_wrapper('commerce_product', $product);

    $wrapper->field_order_reference /***** What to do here? *******/

    $result = $wrapper->save();

  }
}

```

EDIT:

I have gotten a little further with the code below.. It works the first time an order reference is set, but the second time i get the following error "The website encountered an unexpected error. Please try again later."

Found the example a bit down this page: https://drupal.org/node/1021556

```
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased Product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $orderID;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}

```

# Answer
> 1 votes
DOH! - Seconds after adding my previous edit i realised what was wrong. Below the final code :)

```
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom group'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();
    $new_ref = commerce_order_load($orderID);

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $new_ref;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}

```

---
Tags: commerce, rules
---


# Question
Title: Simpletest fails with "invalid database prefix" - no other information given
I am trying to setup a simple test that tests some breadcrumb altering code I have introduced only for a specific content type.

Here is the test, still just barebones:

```
namespace Drupal\mymodule_breadcrumbs\Tests;

use Drupal\simpletest\WebTestBase;

/**
 * Class ArticleBreadcrumbTest
 * @group mymodule_breadcrumbs
 */
class ArticleBreadcrumbTest extends WebTestBase {
  protected $node;
  private $account;

  /**
   * Modules to install.
   * @var array
   */
  public static $modules = ['node', 'mymodule_breadcrumbs', 'menu_breadcrumb'];

  /**
   * Set up our test.
   */
  public function setUp() {
    parent::setUp();

    // create admin user
    $this->account = $this->drupalCreateUser(['administer site configuration', 'administer content']);

    // create article node
    $this->node = $this->drupalCreateNode(array(
      'title' => t('Test Article'),
      'type' => 'article',
      'status' => 1,
    ));
  }

  public function testNodeTitleIsInBreadcrumb() {
    $this->drupalGet('node/' . $this->node->id());
    $this->assertResponse(200);
    #$this->assertText('Home > ' . $this->node->getTitle(), 'Breadcrumb contains the node title.');
    // get page
    // test that breadcrumb is correct per node title
    // change node title
    // save node
    // visit node, check that breadcrumb is updated
  }
}

```

However, I am getting this error and not sure what to make of it:

```
The website encountered an unexpected error. Please try again later.

InvalidArgumentException: Invalid database prefix: in Drupal\Core\Test\TestDatabase->__construct() (line 81 of core/lib/Drupal/Core/Test/TestDatabase.php).
simpletest_log_read(NULL, , ) (Line: 476)
_simpletest_batch_finished(, Array, Array, '1 sec')
call_user_func_array('_simpletest_batch_finished', Array) (Line: 414)
_batch_finished() (Line: 81)
_batch_page(Object) (Line: 55)
Drupal\system\Controller\BatchController->batchPage(Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

It's a very basic test, why would it cause an error like that?

Also I am running this from the UI runner, if that makes a difference.

# Answer
> 0 votes
Well, this appears to be due to one of my dependencies missing a `.schema.yml` file (Menu Breadcrumb).

After patching that module to have a schema file, the console error AND the generic error in the testing UI went away. I can now execute the test from either interface.

See: https://www.drupal.org/node/2848879

# Answer
> 0 votes
For functional (browser) tests you need to provide some environment variables, in this case the `SIMPLETEST_DB` environment variable.

It can either be supplied in the phpunit.xml.dist file, or in phpunit command, or actually added to the environment before executing the phpunit command.

The format of the variable is seen in the phpunit.xml.dist file provided by Drupal core.

```
<!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
<env name="SIMPLETEST_DB" value=""/>

```

From the error it seems that the provided SIMPLETEST\_DB is not valid.

*Note: the author mentioned that he was using the Admin UI and this answer does not address this problem.*

---
Tags: 8, testing
---