# Question
Title: How to implement user enrollment or subscription?
I want to create a website with few courses in it. Each course will have a node of content type `Course`. I want users to be able to enter the course.

So this is sort of a "many-to-many" relationship question for Drupal, as for each subscription I will need to keep details on the progress, e.g. "last completed lesson", "total score", etc.

Is there a module that will have Enrollment/Subscription as a separate Entity/Content or Relation module will do it?

What is the best approach?

**UPDATE 1**:

* This should allow to show all students subscribed to a course on a course page;
* Show all current subscriptions with their details (fields) to student on my\_courses page.

**UPDATE 2**: Can I use Open Group module for that?

# Answer
It seems that this can be done with Entity Registration module.
> 1 votes

# Answer
You could build it yourself, or why not go for a free ride? The OpenAcademy distribution looks like it is preconfigured with the kind of things that you would need.
> 0 votes

# Answer
You might want to give it a try to use the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

It is available as of D7, and has a D8 version also. It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

# Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

```
Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

```

### Group Types

The above example consists of 3 ***group types***:

* Class.
* Customers.
* Project.

### Group Roles

For each of the 3 group types, there are specific ***Roles*** defined, some more details about some of them:

* for the *Class* group, these are the 2 roles that are configured:
    + Instructor.
    + Student.
* for the *Project* group, these are the 3 roles that are configured:
    + Project Manager.
    + Developer.
    + Customer.

These are the *Group Specific Roles*: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "*Class*", the defined roles are **Instructor** and **Student** (which are not available for the other group types.

On top of the group specific roles, there are also *Special Global Roles*: These are the special (hardcoded) roles named **Outsider** (= a signed in user that did not join a group) and **Member** (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role **Anonymous** is related to a user that is not signed.

### Groups

Each of the configured group types can have any number of ***Groups***.

Examples of groups:

* for the *Class* group type, there could be these **Groups**:
    + Getting started with Drupal.
    + Drupal for site builders.
    + Become an expert in using the Rules module.
* for the *Customers* group type, there could be these **Groups**:
    + Service Requests.
    + Order Processing.
    + Sales Orders.
    + Relationship Management.

### Permissions

For each of the configured group types, you can then also configure for each ***Content Type*** which ***Role*** has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

# Comparison with the Organic groups module

Have a look at my answer to "What are the features of the Group module versus Organic Group module?" for details about:

* How both modules (Group versus Organic groups) compare to each other.
* Integration with various modules that you might want to take advantage of also.

# Resources

**PS**: this answer applies to either D7 or D8.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Show a field in table if current user is node author
I want to create a view block that shows all published nodes of a certain content type. I've included an image below.

However the trick here is to only show the link `Print Report` if the logged in user is the author of that node. So if you look at my image above, the user Dennis Bonilla should be able to see his `Print Report` link but not see one for the row below for Test McTest.

Is there a module that can help me do this or some administrative trickery in the views ui? Or maybe even programmatically?

# Answer
This is possible via views UI itself.

* Create a view with content types you need as a filter criteria
* Then add a "relationship" for "Content: Author". Now add a "contextual filter" for the field "user: uid" with a default argument for "user-id of logged in user" to filter the view.

+ Now you will get the list of nodes authored by current logged in user.
    + To get the Print Report Link you could make use of Views PHP module and by adding `content:nid` field

### To List all nodes and Add print report link to only contents of the current user

* Add a *Content: Author UID* and a *Global: PHP* field
* In `global:PHP` field, add conditions like below:

```
global $user;
if ($user->uid ==  $row->uid) {
  echo 'print reports';
}

```
> 0 votes

# Answer
Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

1. Views PHP
2. Computed Field
> 0 votes

# Answer
The answer of @Pravin Ajaaz is correct but I'd have to disagree of using PHP Views don't use this module .. its bad!

alternatively write you PHP code in the server side ,, and that's possible by writing the result of that field which is well documented here:

Theming a single field in a Views 3 template
> 0 votes

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


title: access by term not working

text:
# Question
Title: access by term not working
I installed drupal 7, and ABT module.

Created taxonomy vocabulary 'Proj' with terms 'proj1' 'proj2'
added term ref 'Proj' field under Article cck
added term ref 'Proj' field under Users (Account settings-\>manage fields)

Enabled abt's Control "view" access with this field. =\> Yes, but allow... on both the term ref fields (Account, article)

Created User1 (proj1 term ref)
Created User2 (proj2 term ref)

Created article PROJ1 article (proj1 term ref)
Created article PROJ1 article (proj2 term ref)

I can see both the articles as admin, but have no access to any of the articles when logged in as User1 or User2

Am I missing any step? please help
Thanks in advance.

# Answer
https://www.drupal.org/node/1967042

Create term ref field in User account
And under article cck, add term ref under "add existing field", only then this works!!

Documentation for this module has to be updated, wasted so much of time without proper documentation. Otherwise, great module.
> 2 votes

---
Tags: 7, users, taxonomy-terms
---


title: Using debounce.js

text:
# Question
Title: Using debounce.js
I see that debounce.js is included in the Drupal 8 core (core/misc/debounce) and I'd like to leverage it for a slider (Slick Slider) that will only be called on mobile only. While I think the function I've created is correct, I'm not sure how to access the debounce function in my js file. So, for example, in `global.js` I have the following:

```
(function ($, Drupal, debounce) {
  'use strict';
  Drupal.behaviors.mobileSlider = {
    attach: function (context, settings) {
      var viewportChange = debounce(function() {
        var bodyWidth = $(window).width();
        if (bodyWidth <= 768) {
          // enable slider
        }
        else{
          // destroy slider
        }
      }, 250);
      window.addEventListener('resize', viewportChange);
    }
  };
})(jQuery, Drupal, Drupal.debounce);

```

I also see that when I'm logged in I see debounce.js is called but when I view the site when not logged in I don't see debounce called despite listing it as a dependency in libraries.yml

```
global-scripts:
  js:
    js/global.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/misc/debounce.js

```

# Answer
You are declaring the dependency of your JavaScript in the wrong way. It's core/drupal.debounce, as the System module uses in system.libraries.yml.

```
drupal.system.modules:
  version: VERSION
  js:
    js/system.modules.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.debounce
    - core/jquery.once
    - core/drupal.announce

```

What you use as dependency is the machine name of the library that, as visible in core.libraries.yml, is drupal.debounce.

```
drupal.debounce:
  version: VERSION
  js:
    misc/debounce.js: {}
  dependencies:
    # @todo Remove Drupal dependency.
    - core/drupal

```

The *core/* appended first means it's the *drupal.debounce* library defined in the core.libraries.yml file.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: How do I create a link to a node to put in new entity?
So what I'm trying to do seems pretty simple. And I've found lots of posts similar to it but none have really helped me.

I have a an application content type, when somebody submits it, I'd like to use the rules module to create a post in the forums that has either a.) a link to the application b.) the data from the application in the body of the forum post.

I've figured out how to create a forum post each time the application is saved. Seems to be working ok. I've also figured out how to set the body to be either a static message, or the contents of ONE of the fields from the application.

What I cant figure out is how to either combine fields from the application to set the forum body to (which i'm guessing is a more complex thing), or to simply have a link to the application be what is put in the body of the forum message, which seems like it should be simple. I've looked at the rules faq at https://groups.drupal.org/node/15542 but it seems to think that i should have a NID option in the selector which i do not. (yes its set to trigger after save)

My data selector for setting the body field of the forum entity only includes site, node, and entity. And the Node options are only the individual fields of the application. It doesnt include any NID or options to link the the node itself. I choose other options like convert data type i can find UID and URL options, but then I don't know how to use the variable in the set data action.

I'm guessing that it has to do with the type of the body field and its only showing me things of the same type and i have to convert the UID/URL or something, but apparently I'm slow, anyone want to point me in the right direction?

My current rule (in export format):

```
{ "rules_test_application" : {
"LABEL" : "test application",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--guild_application" : { "bundle" : "guild_application" } },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "guild_application" : "guild_application" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "forum",
        "param_title" : "New App: [node:title]",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : { "data" : [ "entity-created:language" ], "value" : "en" } },
  { "data_set" : { "data" : [ "entity-created:taxonomy-forums" ], "value" : "9" } },
  { "data_set" : {
      "data" : [ "entity-created:body" ],
      "value" : { "value" : {
          "value" : "link to application that generated this post",
          "format" : "Plain_text"
        }
      }
    }
  }
]
}
}

```

# Answer
> 0 votes
Entity-created:body was a formatted text type. Because of that the rules selector was only showing values from the Node that were also Formatted text.

Once I changed the data value i was modifying to entity-created:body:value, the text part of the formatted text, it allowed me to select more things in the selector including the node:url.

---
Tags: 7, rules, nodes
---


# Question
Title: How to store value of variable if it is changed inside of ajax callback function?
I have a form with several ajax callback functions. And I have a variable which should change its value inside these callback functions. Unfortunately, I have faced with a problem. Namely, I don't know how to store the value of the variable after change. Because after the callback function executed the value is lost.

There is a little example of code.

```
class MyForm extends FormBase {
    public $i = 0;

public function buildForm(array $form, FormStateInterface $form_state){
    ...
    $form['add_more'] = [
        '#type' => 'submit',
        '#value' => 'Add More ...',
        '#ajax' => [
            'callback' => '::addMore',
        ]
    ];
    ...
}

public function addMore(array &$form, FormStateInterface $form_state){
    ...
    $this->i++;
    ...
}
}

```

Here the variable $i doesn't increase its value whenever the button is being pressed. Could you clarify, what should I do if I want the variable to increase its value whenever the button has been pressed ?

# Answer
> 1 votes
The ajax callback is not for form logic. It's only supposed to send back a new version of `$form` or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.

Use instead `buildForm()`. You can check which button was clicked with `$form_state->getTriggeringElement()`.

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

    $form['#prefix'] = '<div id="ajax_wrapper">';
    $form['#suffix'] = '</div>';

    $i = $form_state->get('elem') ? $form_state->get('elem') : 1;
    $trigger = $form_state->getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) && $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state->set('elem', $i);

    $form['counter'] = [
      '#markup' => $form_state->get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' => 'button',
      '#value' => 'Btn',
      '#ajax' => [
        'callback' => '::addMore',
        'wrapper' => 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &$form, FormStateInterface $form_state){
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state){

  }

```

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


title: Problem to acces admin of my site

text:
# Question
Title: Problem to acces admin of my site
I cannot acces admin of my website via Drupal.site.

I always have a screen saying "Drupal is under maintenance" but no login and password field.

Could anybody tell me how to access my site ?

# Answer
> 0 votes
Type user/login in the URL (Drupal.site/user/login OR Drupal.site?q=user/login) to access Login page. Only site admin can login when the site is under maintainance mode.

---
Tags: users
---


# Question
Title: How to get Drupal 8 View to Accept Parameter as argument?
I created a view that shows a bunch of cars. I allow you to filter by brand using an exposed block. If you filter, it results in a path like this:

```
/?brand=Volkswagen

```

I want brand to have the path:

```
/Volkswagen

```

instead.

How would one do this with Views? Or is this something that should rather be attempted with rewrite rules in htaccess?

# Answer
You can do it with a contextual filter. In the "Configure contextual filter" menu select "Provide default value". For type choose Raw value from url.

There is more info on contextual filters in this article.

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

If you are using taxonomies and want to use the name instead of id in the url you need to setup the relationships first and use name as the contextual filter.
> 2 votes

# Answer
It sounds like you maybe want a taxonomy rather than create your own view?

You can create re-write rules for the alias using something like pathauto and then you could get the url to look like you want.
> 1 votes

---
Tags: views, 8
---


# Question
Title: Remove items in taxonomy entity relation on node edit form
If a field on the node edit form is a entity relation to a taxonomy term vocabulary, I want the taxonomy terms be restricted on certain conditions. I don't know how to do it safely. I have tried it in `hook_form alter()`. Deep in the "array stack" of the form variable is the definition of the entity reference form field.

>

Is the only way to "hack" the "#process" array, or is there any object-oriented way to filter the items in the drop down element?
Is there any form "plugin" to filter the items in Drupal 8?

# Answer
You're deep in the field definitions there, that's the wrong place, you can't change anything there and you don't need to.

In case of a select, the available options are already part of the form; they should be in `$form[$field_name]['widget']` somewhere.
You could also try to use `hook_options_list_alter()`.
> 2 votes

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


title: Drupal Simpletest for Image Upload

text:
# Question
Title: Drupal Simpletest for Image Upload
The following code is working fine for uploading images. The node is being created but the uploaded images (under /sites/default/files/simpletest) are getting deleted after each complete test suite run.

Here the sample code

```
public function testArticleCreate() {
  $edit = array();
  $edit['title'] = $this->randomName(8);
  $edit["field_description[und][0][value]"] = $this->randomName(16);
  $field_name = 'field_image';
  $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = 'sites/default/files/test-image.png'; // existed
  $this->drupalPost('node/add/article', $edit, t('Save'));
  $this->drupalGet("node/1/edit");
  }

```

Screenshot

Getting 404 not found for the image path (sites/default/files/simpletest/505284/test-image.png)

Any suggestions?

# Answer
I came to know that it's by design but not a bug. We can do nothing with the uploaded images. The SimpleTest files will be deleted automatically after successful test suite run.
> 0 votes

---
Tags: 7, media, testing
---


title: Complex sorting Views

text:
# Question
Title: Complex sorting Views
Our Drupal 7 site has a feed of events which are parsed into nodes. Not every event is equally relevant, and they would like a way to selecrt the top five events, sorted chronologically, to appear on a block on the frontpage. They would also like the events to no longer display in the block once the event has passed. They are comfortable using Nodequeues and have requested one be created for this functionality. So far, this is pretty basic stuff and I have created a View which accomplishes this. The tricky part happens when there are less than five upcoming events in the queue. In this case, they would like unselected events to fill out any vacancies in the block of five.

Typically when I create a Nodequeue:

1. I create a relationship to the queue
2. I sort by position in the queue
3. I filter that the event is in the queue.

By removing the sort and filter, and instead sort first by if event is in queue and then by event date, I get the content I desire; when more than five events are selected, it works fine. When no events are selected, it works fine, however when there is a mix; naturally the in queue events are listed first. I would like all five events to be sorted chronologically.

An aside, I'm not certain Nodequeue is even the best way to do this; as the position in the queue implies a hierarchy. A flag could mark selected nodes, or a boolean field on the content type, or a taxonomy term might each be better solutions. I'm open to suggestions.

But first, how can I best properly sort this list?

# Answer
> 0 votes
I suggest you to make use of the following hook:

```
function YOURCUSTOMMODULENAME_views_post_execute(&$view){

    switch ($view->name){

 case "YOURVIEWMACHINENAME";

    // Get the result of the view in a array
    $data = $view->result;

    // your custom code to add / remove instances after the view was executed

    // Set the result of the custom code back into the view
    $view->result = $data;
    break;

  }
}

```

Your custom code would be something like If there are less then 5 elements and more then 1 elements in the data array add new elements to the data array coming from another view.

To execute a view in code u can use something like this:

```
  $reflang = views_get_view("NAMOFYOURMACHINENAMEVIEW");
  $reflang->set_display("NAMEOFYOURDISPLAY");
  $reflang->set_arguments(ARGUMENTSFORTHEVIEW);
  $reflang->pre_execute();
  $reflang->execute();

  foreach ($reflang->result as $row => $rowinfo) {
    // add this to the data array
  }

```

Hopefully this helps you to solve the problem.

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


# Question
Title: How do I print an individual field in block.html.twig?
I have tried as many options as I can imagine but none of them prints anything except:

```
{{ content }}

```

However, I require individual fields for more control over theming.

I am using a custom block type and the following function.

```
function THEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestions for custom block bundles.
    if (isset($variables['elements']['content']['#block_content'])) {
    array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());
  }
}

```

The template is working fine. I can hard code some random text and it is displayed. I just can't display the field values.

How do I print an individual field in block.html.twig?

# Answer
> 3 votes
If you have a field called field\_test you schould be able to do like this

```
{{ content.field_test }}

```

and if you want to only print the value you can do like:

```
{{ content.field_test[0] }}

```

If you want to see what is inside the field you can do like this:

```
{{ kint(content.field_test) }}

```

But only if you have `Devel` module installed and have `Devel Kint` enabled you should be able to do that.

Hope this helps :)

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


# Question
Title: Print password confirm field in user register template file
I'm trying to theme the user registration form in Drupal 8.
I have defined a custom template for user registration form and printing the fields with the following code.

```
{{ form.field_profile_title }}
{{ form.field_profile_first_name }}
{{ form.account.mail }}

```

When I try to print confirm password field it's not printing the field.

```
{{ form.account.pass}}

```

What could be the issue?

# Answer
You can always debug your twig template by printing the present variables, with help of of the Kint module (part of Devel) for example:

```
{{ kint(form.account.pass) }}

```

Or you can also print all of them:

```
{{ dump() }}

```

Further information on this page.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How to stop same-state state changes in Workflow state change block?
I am using Workflow with a custom `content type`. I have the Workflow state transition form as a sidebar on my node view page. I made the workflow states into buttons so that you can choose which state to transition to.

How can I remove buttons that are the same state as the node? For example: If the node is already in Draft state, the Draft button should not be shown. If it's in Declined mode, the Declined button should not be shown.

# Answer
> 0 votes
Implement hook\_form\_workflow\_transition\_form\_alter().

```
/**
 * Implements hook_form_form_id_alter().
 * Alter transition form to remove current state button.
 */
function MYMODULE_form_workflow_transition_form_alter(&$form, &$form_state, $form_id) {

  // Get current state to remove current state button.
  $current_sid = $form['workflow']['workflow_sid']['#default_value'];
  unset($form['workflow']['workflow_sid']['#options'][$current_sid]);

  // By default workflow button label became (Update workflow) if the options
  // count equal one. So, We will use the state label name instead of
  // (Update workflow).
  // Check if option count equal one.
  if (is_array($form['workflow']['workflow_sid']['#options']) && (count($form['workflow']['workflow_sid']['#options']) == 1)) {
    $submit_label = current($form['workflow']['workflow_sid']['#options']);
    $form['workflow']['actions']['submit']['#value'] = $submit_label;
  }
}

```

---
Tags: 7, workflows
---


# Question
Title: Bulk deletion of node which are unpublished and which are in between the given dates
I unpublished all the nodes which are created between January 1, 2012 and January 1, 2015. Then, I published 800 nodes.

Now I want to delete all the nodes I first unpublished. I have almost 28,000 nodes. How do I bulk delete them?

I also want to delete the images uploaded along with the nodes.

# Answer
> 1 votes
I suggest to use the Rules module for that. Bulk deletion is explained in one of the first tutorial video's in this series: https://drupalize.me/videos/introduction-rules?p=1157

What you should do:

1. enable Rules and Rules UI
2. create a new Component of type "action set"
3. actions to add: a loop thru the nodes and if the date matches, the node should be deleted

The Views Rules module might be usefull to use views to send the nid's of the nodes to delete to the rules component. I learned a lot about this via the accepted answer to "How to pass arguments to a view from Rules?".

An **alternative** could be the Views bulk operations (VBO) module, which has a "bulk deletion" out of the box. You add a VBO-field in your view and select the "delete" as the action. Maybe this is even better than the Rules (in the way that it will take less time to understand and implement).

# Answer
> 0 votes
Using the VBO module (together with the "*bulk deletion*" out of the box) as suggested in the prior answer is indeed the way to go, BUT ... if you add the Rules module to that also, then the possibilities for what you can do are virtually only limited by your own imagination. Read on for more details ...

# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_delete_nodes_containing_a_specific_value_in_a_text_field" : {
    "LABEL" : "Delete nodes containing a specific value in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "text_field_value" : { "label" : "Text Field Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[text-field-value:value]"
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "node" ] } },
      { "drupal_message" : { "message" : "Deleted node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022 (which contained the string \u0022[text-field-value:value]\u0022 in field \u0022field_free_format_text\u0022)." } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in the subsequent step.
* In my case I have a text field with machine name `field_free_format_text`. Even though the question here does not mention anything about some extra requirements for the nodes to be deleted, you may want to consider adding some relevant additional requirements, as further explained in what follows.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also.

If you want, just copy the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.

After you imported this Rules Component, you can navigate to `admin/config/workflow/rules/components` in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node identifier*** and hit the ***`Execute`*** mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be deleted.

After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.

Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I used the string "GetRidOfThisNode":

> * Deleted node with id "48" and title "Demo field\_free\_format\_text replacement" (which contained the string "GetRidOfThisNode" in field "field\_free\_format\_text").
> * Component rule: Delete nodes containing a specific value in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...

**Attention**: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the delete gets performed also.

# Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your **nodes** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

**Attention**: to process many nodes (such as "***almost 28,000 nodes***" ...) at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!

**Remark**: Your additional question like "*I also want to delete the images uploaded along with the nodes.*" is really a different question. A possible answer to that is what is suggested in the accepted answer to "Find orphaned unused files and images".

---
Tags: 7
---


# Question
Title: How to pass the Body field from a View to Rules?
**Context**: using the Views Rules module to pass a number of items to an action-loop in a Rules component (Action Set).

In views (display: rules) I selected among others the Body-field to be used. This field appears to be an array of different things (value, summary, format), when I use the `[body-from-view:value]` in an action, it seems to be empty.

**Question** I must have some settings wrong. What Data Type do I have to select in the Row Variables (Rules Settings) in the View for the Body-field? Or maybe I use a wrong Replacement Pattern in the Action?

**Note:** handling nid, email, title, date works very well, these have Data type like text, integer, date.

# Answer
I assume you performed the steps similar to what is documented in my answer to "How to send out email based on matching taxonomy terms in user profiles?". And while doing so, you probably used a field name like `body-from-view` in the "*Rules*" display of your view. I'm not sure if it is the only way to get it to work, but below is a possible solution to answer your question ...

# Part 1 - Getting it to work

### Define the body field 3 times in your view

When adding the "body" as a field in your view, add that field 3 times. And when configuring these Views fields, make sure to use these ***field formatters***:

* Default (for the 1st "body" field).
* Trimmed (for the 2nd "body" field).
* Summary or trimmed (for the 3rd "body" field).

### Select the 3 body fields 3 times in your view

When you edit the Rules settings of your view (by using the link that says "edit field info"), use 3 separate variables for each of the 3 body fields, e.g using machine names that look something like so:

* body-default
* body-trimmed
* body-summary-or-trimmed

I'm not sure (yet) about the most appropriate "data type" to use for these 3 variables, but in my case I just used "text".

### Create your Rules Component using appropriate tokens

* Within the Rules Actions of your Rules Component, use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
* Within that Views loop add whatever Rules Action that fits your needs. E.g. to get started, just perform "Show a message on the site". At that point, you should have access to these token values that you're looking for (if you use the same machine names as suggested above):
* `[body-default:value]`
* `[body-trimmed:value]`
* `[body-summary-or-trimmed:value]`

# Part 2 - Showtime

Here is an example of the execution of a rules component, in which I implemented what's mentioned in "Part 1", using a Rules Action to show a message on the site, and which looks like so:

```
<hr />
Details about node with id = [node-nid:value] and title = [node-title:value]:<br /><br />
- <strong>body-summary-or-trimmed</strong> = [body-summary-or-trimmed:value]<br />
- <strong>body-trimmed</strong> = [body-trimmed:value]<br />
- <strong>body-default</strong> = [body-default:value]<br />
<br /><hr />

```

After executing it, and with 3 nodes that were included in my Views result, the result looks like so:

```
Details about node with id = 163 and title = Node with summary and separator line:

- body-summary-or-trimmed = <p>This is the summary of this node ... and there is really nothing else after this (in this summary) ...</p>
- body-trimmed = <p>This is the body of this node, which <strong>does have a summary also</strong> ...</p> <p>It has multiple lines, and the separator line is inserted right here ...</p>
- body-default = <p>This is the body of this node, which <strong>does have a summary also</strong> ...</p> <p>It has multiple lines, and the separator line is inserted right here ...</p> <p>And from here on there is even more content (after the separator line ...)</p> <p>Some more lines (1).</p> <p>Some more lines (2).</p> <p>Some more lines (3).</p> <p>Some more lines (4).</p>

Details about node with id = 162 and title = Node without a summary but with a separator line:

- body-summary-or-trimmed = <p>This is the body of a node which <strong>does not have a summary</strong> ...</p> <p>It has multiple lines, and the separator line is inserted right here ...</p>
- body-trimmed = <p>This is the body of a node which <strong>does not have a summary</strong> ...</p> <p>It has multiple lines, and the separator line is inserted right here ...</p>
- body-default = <p>This is the body of a node which <strong>does not have a summary</strong> ...</p> <p>It has multiple lines, and the separator line is inserted right here ...</p> <p>And from here on there is even more content (after the separator line ...)</p> <p>Some more lines (1).</p> <p>Some more lines (2).</p> <p>Some more lines (3).</p> <p>Some more lines (4).</p>

Details about node with id = 161 and title = Node without a summary and without a separator line :

- body-summary-or-trimmed = <p>This is the body of this node, which <strong>does NOT have a summary</strong> ...</p> <p>It has multiple lines, <strong>but no separator line</strong>  ...</p>
- body-trimmed = <p>This is the body of this node, which <strong>does NOT have a summary</strong> ...</p> <p>It has multiple lines, <strong>but no separator line</strong>  ...</p>
- body-default = <p>This is the body of this node, which <strong>does NOT have a summary</strong> ...</p> <p>It has multiple lines, <strong>but no separator line</strong>  ...</p> <p>And there is even more content ...</p> <p>Some more lines (1).</p> <p>Some more lines (2).</p> <p>Some more lines (3).</p> <p>Some more lines (4).</p>

Component rule: Views Rules demonstration has been executed.

```

# Part 3 - Pieces of the puzzle

### Exported View

Here is an export of the view I created (use the Views UI to import it in your own site, adapt the filter criteria to fit your needs):

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Details about nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Body */
$handler->display->display_options['fields']['body_1']['id'] = 'body_1';
$handler->display->display_options['fields']['body_1']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_1']['field'] = 'body';
$handler->display->display_options['fields']['body_1']['label'] = 'Body - Summary or trimmed';
$handler->display->display_options['fields']['body_1']['type'] = 'text_summary_or_trimmed';
$handler->display->display_options['fields']['body_1']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body_2']['id'] = 'body_2';
$handler->display->display_options['fields']['body_2']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_2']['field'] = 'body';
$handler->display->display_options['fields']['body_2']['label'] = 'Body - Trimmed';
$handler->display->display_options['fields']['body_2']['type'] = 'text_trimmed';
$handler->display->display_options['fields']['body_2']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Body - Default';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['operator'] = '>';
$handler->display->display_options['filters']['nid']['value']['value'] = '10';

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

/* Display: ListToCreateRulesLoop */
$handler = $view->new_display('views_rules', 'ListToCreateRulesLoop', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_variables'] = array(
  'title' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Content: Title',
    'name' => 'node_title',
  ),
  'nid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Nid',
    'name' => 'node_nid',
  ),
  'body_1' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Summary or trimmed',
    'name' => 'body_summary_or_trimmed',
  ),
  'body_2' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Trimmed',
    'name' => 'body_trimmed',
  ),
  'body' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Default',
    'name' => 'body_default',
  ),
);

```

### Exported Rules Component

Here is an export of the Rules Component I created (use the Rules UI to import it in your own site, adapt the Rules Conditions to fit your needs):

```
{ "rules_views_rules_demonstration" : {
    "LABEL" : "Views Rules demonstration",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "details_about_nodes",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "node_title" : { "node_title" : "Content: Title" },
            "node_nid" : { "node_nid" : "Nid" },
            "body_summary_or_trimmed" : { "body_summary_or_trimmed" : "Body - Summary or trimmed" },
            "body_trimmed" : { "body_trimmed" : "Body - Trimmed" },
            "body_default" : { "body_default" : "Body - Default" }
          },
          "DO" : [
            { "drupal_message" : { "message" : "\u003Chr \/\u003E\r\nDetails about node with id = [node-nid:value] and title = [node-title:value]:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-summary-or-trimmed\u003C\/strong\u003E = [body-summary-or-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-trimmed\u003C\/strong\u003E = [body-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-default\u003C\/strong\u003E = [body-default:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

```
> 1 votes

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


# Question
Title: Is there any specific difference between multi site and multi domain?
I didn't see any specific difference between multi site and multi domain. If there any specific reason to differentiate them?

# Answer
Multi site is the ability to have multiple sites running on the same code base. This can be either different domains or different base URLs. E.g. could be http:/example.com, http:/example.org, http:/example.com/new\_site.

This is done in Drupal via different subdirectories in the sites directory. E.g.

sites/default (example.com) sites/example.org (example.org) sites/new\_site (example.com/new\_site)

Multi domain is partially a subset of multi site as shown above. But it can also indicate the same site being accessed via multiple domain names. This is common in multilingual sites. E.g.:

http:/example.com/ =\> site in english http:/example.fr/ =\> same site in french

This is generally done by modifying the settings.php file to allow these alternate domains to be used. And in the case of i18n sites, the language detection settings.

So basically these two terms intersect each other but are still different.
> 1 votes

---
Tags: multi-sites
---


# Question
Title: What can I do to remove this entity definition from the database?
Long story short, in developing a website in Drupal 8 we decided that the custom entity we were building could just as easily be made with standard nodes. We deleted the entity code (or something to that effect) and now, somewhere hidden in the database, is the definition for the team entity that we've removed. Fortunately, this isn't causing too many issues. However, when deleting fields from a content type (and probably in some other circumstances of which I'm not yet aware), we get the following error:

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "team" entity type does not
exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of
[...]/core/lib/Drupal/Core/Entity/EntityTypeManager.php).`

```

I've attempted doing what was suggested here, but it resulted in the above error.

What can I do to clean up the database/website so this error stops happening?

# Answer
**First solution (the best one if you can) (thanks @Clive) :**

* Put the deleted code back
* Uninstall the module
* Reinstall the module with the new code

**Second solution (ugly, but worked for me)**

* Open your favorite SQL client (adminer in my case)
* Search for your entity id in all tables
* Remove all matching entries
* Clear the cache
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Drupal 7 hook_fom_alter not working for custom fields
I have added custom field for email address in my content type. I want to assigned default email address to this field. Following is my code.

```
function request_order_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'request_order_node_form') {
    dsm($form);
    $form['field_your_email']['#default_value'] = 'sam@gmail.com';
  }
}

```

But I am not getting default value in my field.

# Answer
Set default value in field setting and try this after that :

```
print $form['field_your_email']; //check where default value is

$form['field_your_email']['und'][0]['value']['#default_value'] = 'sam@gmail.com';

```
> 2 votes

# Answer
Set

```
package :Core

```

in info file, and then write in your module file

```
//first method
use Drupal\Core\Form\FormStateInterface;

function hook_form_FORMID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['phone_number']['#title'] = t('Start with + and your country code.');
}

//Second Method--------------------------------------------

function hook_form_alter(&$form,\Drupal\Core\Form\FormStateInterface$form_state, $form_id)
{
  if($form_id == 'user_login_form')
{

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('name'),
  );
}

if($form_id == 'second_form')
{
  $form['phone_number'] = array(
    '#type' => 'tel',
    '#title' => t('name'),
  );
}
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: What difference between declaration of an ajax callback function with $this and without it?
There is a form working with AJAX Framework. And there is a form element having the callback function named "myFunction", which is a public method of the form class. The callback can be declared as

```
'callback' => [$this, 'myFunction']

```

And it also can be declared as

```
'callback' =>  '::myFunction'

```

Could you clarify me, what functional difference between these declarations ?

# Answer
The ::method as a string is a special feature of the form API.

It's basically a shorthand for \[$this, 'method'\] and does almost exactly the same. See FormState::prepareCallback

There is one interesting difference, \[$this, 'method'\] has to serialize the whole form object within the form structure, to then unserialize it to call a method on it. But at that point, on a cached request, it is actually a different object because the form system also created a new form object, as part of initializing it and starting to process the request. ::method will actually call the method on the new form object.

Whenever possible, use the short version, sometimes that's not possible, for example when you are inside a plugin (e.g. a field widget) or other class called by the form, in this case, it is recommend to use a static method.
> 9 votes

# Answer
Its the difference between a static method call and an object method call. As per the PHP docs:

> ```
> // Type 3: Object method call
> $obj = new MyClass();
> call_user_func(array($obj, 'myCallbackMethod'));
>
> // Type 4: Static class method call (As of PHP 5.2.3)
> call_user_func('MyClass::myCallbackMethod');
>
> ```

Your first callback is an object call to your method. The second one is a static call to a static method. Since PHP is a forgiving language both approaches will work (PHP will try to resolve them for you) but will emit warnings if your static callback will call an object method and vice versa.

In static context you are not able to call the object methods in your class. In object context however you are able to call static methods. I would recommend to use objects calls as much as possible.
> 2 votes

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


title: Using TableField with Node:Create?

text:
# Question
Title: Using TableField with Node:Create?
I've been struggling with this for a few days. I currently have a form which I am creating and rendering through Drupal 8's Form API. I am saving the inputted field values using `Node::create()` which has been working great. I am now using the Tablefield module for some of the fields. I am struggling to save this data as part of the `Node::create()` function however. I am reasonably new to Form API so I'm sure I'm missing something obvious.

My current `Node::create()` is a little like this

```
$node = Node::create([
      'type'                      => 'business',
      'status'                    => 1,
      'field_membership_type'     => $form_state->getValue('type_of_membership'),
      'field_type_of_business'    => $form_state->getValue('membersInTheQuarter_type'),
      'field_business_size'       => $form_state->getValue('businessSize_antique'),
      'field_business_size_shop_' => $form_state->getValue('businessSize_independentShops'),
      'field_category'            => $form_state->getValue('businessCategory'),
      'field_additional_category' => $form_state->getValue('additionalBusinessCategory'),
      'field_category_custom_'    => $form_state->getValue('businessCategoryCustom'),
      'title'                     => $form_state->getValue('business_name'),
      'field_tag_line'            => $form_state->getValue('tag_line'),
      'field_about'               => $form_state->getValue('about'),
      'field_opening_hours'       => /**This is where I need to access the individual cells of tablefield to set values from my form**/
    ]);

  $node->save();

```

# Answer
> 0 votes
This has not much to do with form API, only with the structure of the field.

You need to pass in the values that the field type expects, based on its propertyDefinitions() method for example. Looking at http://cgit.drupalcode.org/tablefield/tree/src/Plugin/Field/FieldType/TablefieldItem.php?h=8.x-2.x#n141, it does some special processing on it, so might have to account for that.

The easiest option for that kind of stuff is usually to just create a node in the UI, then load it and call $node-\>toArray(). The structure that you get back ther for your field is usually also what it expects to be set.

---
Tags: 8, forms
---


title: JS acting differently when logged in

text:
# Question
Title: JS acting differently when logged in
I am trying to remove a class from inside my navigation menu.

When not logged in, the class is removed. However, when logged in as an authenticated user or administrator, the behavior changes and the class is not removed.

All my other jQuery code works, but not when trying to remove this class. I have been working all day at this trying all kinds of different approaches to target the class I want to remove with no luck.

The class I'm trying to remove is `.visually-hidden`.

HTML:

```
<li class="level-1">
<a>Link 1-A</a>
<ul class="menu visually-hidden">
    <li class="level-2">
        <a>Link 2-A</a>
        <ul class="menu visually-hidden">
            <li class="level-3">
                <a class="is-active">Link 3-A</a>
            </li>
            <li class="level-3">
                <a>Link 3-B</a>
            </li>
        </ul>
    </li>
    <li class="level-2">
        <a>Link 2-B</a>
    </li>
</ul>

```

JS:

```
(function ($) {
  'use strict';

  Drupal.behaviors.themeJS = {
    attach: function (context, settings) {
      var isActive = $('.is-active');
      isActive.parentsUntil('level-1').removeClass('hide-menu');
      isActive.closest('li').children('ul').removeClass('hide-menu');
    }
  };
  $.noConflict();
})(jQuery);

```

The scripts when not logged in:

```
<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"node\/14","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","user":{"uid":0,"permissionsHash":"2dab5eb25c9e6a6f51b06a09a3e186667ade2001f679e71ff82ee2db9657d9f2"}}</script>
<script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
<script src="/core/assets/vendor/jquery/jquery.min.js?v=2.2.4"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.3.7"></script>
<script src="/core/misc/drupal.js?v=8.3.7"></script>
<script src="/core/misc/drupal.init.js?v=8.3.7"></script>
<script src="/themes/custom/sc_theme/js/theme.js?v=8.3.7"></script>
<script src="/themes/custom/sc_theme/js/jQueryRotate.js?v=8.3.7"></script>

```

The scripts when logged in:

```
<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"node\/6","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","user":{"uid":"6","permissionsHash":"856ca48d12c0a856148b853636901b560e0fc56271ca1e4caa6a7ee9f34938bb"}}</script>
<script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>

<!--[if lte IE 9]>
<script src="/core/assets/vendor/classList/classList.min.js?v=2014-12-13"></script>
<![endif]-->
<script src="/core/assets/vendor/jquery/jquery.min.js?v=2.2.4"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.3.7"></script>
<script src="/core/misc/drupal.js?v=8.3.7"></script>
<script src="/core/misc/drupal.init.js?v=8.3.7"></script>
<script src="/themes/custom/sc_theme/js/theme.js?v=8.3.7"></script>
<script src="/themes/custom/sc_theme/js/jQueryRotate.js?v=8.3.7"></script>
<script src="/core/misc/active-link.js?v=8.3.7"></script>

```

# Answer
The problem is that the `active-link.js` is loaded after your `theme.js` file when you are logged in as @4k4 mentioned. This means that the `.is-active` class does not exist until after your code is run.

Two ways come to mind:

1. Add a higher weight to `theme.js` so that it'll be run after `active-link.js`. See the "Weighted JavaScript" Section.
2. Run your code after everything is loaded. E.g. `window.onload`
> 1 votes

---
Tags: javascript
---


# Question
Title: Author can't see drafts when "sent back" from publisher in workbench
I have a problem after installing workbench access, workbench moderation.

When an author creates a blog entry and sets it to needs review, the publisher will receive it in his work bench. When the publisher sets the blog entry back to draft, the author DOES NOT see it in his work bench. If the author were given the link directly to the the blog entry, he can still end it.

How can the author access the draft content that's been sent back to him by using the workbench interface?

# Answer
The creators of workbench didn't accommodate the behaviour that I mentioned in my question. Hence, we have to build a simple module to do this . Here's the code I used from the

```
/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_workbench_moderation_transition().
 */
function mymodule_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (isset($node->nid) && isset($node->vid) && isset($node->uid)) {
    mymodule_node_update($node);
  }
}

```

I got the solution from an answer in this question here:

Assigning revision owner when moderating backwards with Workbench
> 0 votes

---
Tags: workbench
---


# Question
Title: How to create a line graph of the total user points on a profile page?
I'd like to have a line graph of my users' total user points in time on their profile page. Users shouldn't be able to modify the graph: it should simply graph the user points from the day the user registered until today. I'd like to use the Charts module, but I don't know how I can provide the necessary data (date and daily total points).

Perhaps it's also handy to mention that the profile pages on my website have been overridden with "user\_view" (see: How to create a profile page?) into a panels page.

How can I achieve this?

---

**Edit:** I tried to find a solution, using Field Collections as @Felix Eve suggested in his answer. I've successfully added a Field Collection to my users, but I'm still stuck at these points:

1. Save the userpoints at the end of the day as a field collection item for all users.
2. Graph the userpoints in a Chart.

Solving these problems, solves this problem aswell.

# Answer
> 2 votes
I realize this is an old post, but I wanted to add a workable solution for those that find this question when searching the topic.

I've been able to use a combination of the Charts module to create a view that display the ***history*** of the user's total userpoints.

It is fairly straight-forward to create a view that displays all of the userpoints transactions of a given user, however, I found the trickiest part to be display a 'running total' of a user's points.

The following recipe should help you create a view that charts the progression of a user's points over time.

**Step 1:** Download, enable the Charts module

**Step 2:** Create a view that Shows "Userpoints", and create a block view with the Chart display format. Screenshot below:

**Step 3:** Add the relationship Userpoints:User

**Step 4:** Add the following fields:

* Userpoints Transactions: Timestamp
* Userpoints Transactions: Points
* Global: Math Expression

**Step 5:** Set the expression for the math expression field to: \[expression\] + \[points\_1\]. You should also adjust the label for this field.

**Step 6:** In the chart settings, set the label to be the timestamp field and the data to be the math expression. Also, set the chart type to line.

**Step 7:** Add a sort criteria to sort by the timestamp field. Set the timestamp format to be Y-m-d.

**Step 8:** Add a contextual filter: User:uid to filter by logged-in user's uid.

You may want to create a page view to see the chart in action:

# Answer
> 1 votes
I've used either Google Charts, or Flot for this purpose before.

They are both javascript libraries that create graphs based on your input (supplied as js - use drupal\_add\_js).

You can use hook\_user\_view to prepare your data and add the necessary js.

Recently I've been tending to use Flot more as the Google solution requires sending data off to Google servers to get your chart back again (Whilst I'm not paranoid about Google logging my data is just that it slows down page load times).

**Saving the 'User Points'**

I assume users accrue points somehow over the course of the day. So you need to store a date and number of points per user. To do this you could add a field collection field to the user profile with 2 fields, one for date and one for the number of points. Then when ever a point is earned you can update you users profile with the new points. (See this post on Programmatically creating/deleting/modifying field-collection)

**Getting / displaying the data**

In hook\_user\_view the $account object is passed in. This will have your field collection field in it with all of our points data. Load the data (field\_collection\_item\_load) and then loop over it to build up the array of data we want to plot.

A really simple example of a flot graph would be:

```
var data = [[0, 3], [1, 8], [2, 5], [3, 13]];
$.plot("#my_graph", [ data ]);

```

Here 0, 1, 2, 3 are points on the axis and the other number are the values that are used to plot the line. For full documentation see here.

Add this js to the page along with the necessary flot library and job done.

# Answer
> 0 votes
Try using Visualization module. It is easier to use with "Views".

# Answer
> -1 votes
You should be able to use Views Charts to create a view from the userpoints. Note that only a dev release is currently available for D7.

---
Tags: 7, panels, userpoints, charts
---


# Question
Title: How can you refer to content ID from underlying URL while adding a new node?
In Drupal 7, I have a content type with an entity reference field. When adding new content of this type, an entity reference view filters the available options.

A contextual filter on this entity reference view should check whether the data matches against the node ID from URL being viewed while adding the new content.

I'm not sure whether I understand correctly how Drupal is supposed to work here, as everything I've tried gives no results, unless I manually enter test data in which case it works fine.

Let's say a user is on page site.com/?q=node/75, then adds content. The new URL is site.com/?q=node/75#overlay=%3Fq%3Dnode%252Fadd%252Fcontenttype.

The contextual filter is set for "When the filter is not available" to "Provide default value" of type "Content ID from URL". This returns zero results, even though I could manually provide the filter value and it would show the actual results.

Is this because the "Content ID from URL" is coming from the underlying (originating) URL instead of the overlay new content part of the path? Or is there some other issue?

How is it possible to filter contextually against the content ID of the original page from which a user adds new content? If it could be done by passing arguments to the contextual filter with a token from the entity reference field, that would be fine too, however so far I have tried with current page node and more and run into the same problem, it does not filter any of the appropriate results.

Thank you for your help!

# Answer
It seems that the node in the original link is only for the source page, not for the page in question when Drupal determines which data to pass into the contextual filter. Instead, I wound up creating a new URL path pattern and filtering on the basis of that structure. Then I could add token-using links to various pages, with the contextual filter picking up the pattern of those paths.

You can find a full write-up at the Drupal forums:

https://www.drupal.org/node/2905210#comment-12238299

Thank you again for your help! :)
> 0 votes

---
Tags: entities, views
---


# Question
Title: How to generate iframe from Drupal 7 view (custom blog) with security token?
I have a Drupal 7 site with a custom blog created with custom content types and a combination of views. I need to be able to export this blog as an iframe with a "long security token" to be used on a Salesforce site. I have read about several modules that can generate iframes, but I'm not sure how to go about the security side of things. Any suggestions? I've looked into the Entity Iframe project, and this seems to do what I want for individual nodes, but I'm not sure how to do this for the whole view/page.

A more involved alternative can be found here Drupal Iframe Widgets but this doesn't deal with the security side of things.

So, my questions remains: what's the best/easiest way to export a view to another site with a security token?

# Answer
> 1 votes
If you add `?entity_iframe` to the url it will trigger the iframe theme. Entity iframe resize has examples of how to do cross domain communications (assuming sub-domains) securely and with less complexity then the provider / consumer handshake via the PostMessage capability built into browsers (http://caniuse.com/#search=postmessage)

# Answer
> 1 votes
Pretty sure there are many ways to accomplish this, however seems to me the easiest method would be creating a custom module.

This simple module would be responsible for creating a dedicated path for your view, and checking the security token for determining the access to it.

`secret_blog.module`

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

  $items['secret_blog/%'] = array(
    'title' => 'My Secret Blog',
    'type' => MENU_CALLBACK,
    'page callback' => 'secret_blog_page',
    'access callback' => 'secret_blog_access',
    'access arguments' => array(1),
  );

  return $items;
}

/**
 * Page callback.
 */
function secret_blog_page() {
  $view = views_get_view('MACHINE_NAME_OF_YOUR_VIEW');
  $display_id = 'default';
  $args = array();
  $content = $view->execute_display($display_id, $args);

  $build['content'] = array(
    'secret_blog_view' => array('#markup' => $content),
  );

  return $build;
}

/**
 * Access callback.
 */
function secret_blog_access($access_token = '') {
  if ($access_token == 'LONG_SECURITY_TOKEN') {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

```

For this example let's assume your website is served at http://example.com and the blog view would be accessible at http://example.com/secret\_blog/LONG\_SECURITY\_TOKEN

Now, you can provide that URL to Salesforce (or any 3rd party service) for embedding into it.

I suppose you would also need to use a different layout than the site default; you should create the necessary HTML and/or PAGE templates suiting to your needs. To find out proper template names enable theme debugging in `settings.php` file (this feature is available as of Drupal 7.33).

```
$conf['theme_debug'] = TRUE;

```

The suggested template names would be something like these:

* html--secret-blog--LONG\_SECURITY\_TOKEN.tpl.php
* page--secret-blog--LONG\_SECURITY\_TOKEN.tpl.php

---
Tags: 7, entities, importing-exporting
---


# Question
Title: Should the "install" button on admin/modules page say "enable"?
*(I'm still pretty green when it comes to drupal so I thought I'd ask here before putting in a bug report)*

At the bottom of the "Extend" page (admin/modules) the button to apply the changes made to the check-boxes is labelled "install", but (to my understanding) it doesn't install anything, it merely enables (or possibly disables) the already installed modules.

I often find myself at this page after clicking the "Enable newly installed modules" link. I see the "install" button and think "but I just installed, *now* I want to enable".

So, would "Enable / Disable" or "Apply" be a less misleading label?

Or, am I misunderstanding the terminology, or the use of this page?

# Answer
> 1 votes
Technially/In the code, Drupal calls enabling a module "install" and the opposite is uninstall.

I think it's not that part that is confusing, its that downloading the code of a module is also called installing, it's not, that's just downloading a bunch of files. They don't do anything yet, they're just sitting there on the file system.

It's similar to normal programs that you install, first you download them, then you run an installer that installs it. Although that does more than in Drupal as it also copies the files into the right place and so on, Drupal usually just creates some tables and imports the configuration.

Also, small correction to the answer from @Christia: Drupal 8 does not have the concept of disabled modules anymnore, that half-installed state only exists in Drupal 7 and before.

# Answer
> 1 votes
My understanding is that not all modules that are available in Drupal are installed. I am speaking for Drupal 7 as I am not sure about Drupal 8.

There are three phases:

* Enabled: The code is downloaded to your server and the hooks in .module are being called.
* Disabled: The code is downloaded to your server, but the hooks are being ignored.
* Not-Installed: The code is downloaded to your server, but Drupal hasn't run the .install file for the module and/or hasn't been made aware to look for the hooks.

Also, it's worth noting that if you disable a module, all your data and configurations remain, while uninstalling a module invokes the uninstall hook and wipes both.

So as you can see, the label is relevant to whether or not the module needs to be installed or enabled. You can go from not-installed directly to enabled, but you must go from enabled to disabled to not installed especially before removing the module by deleting it's files.

https://www.drupal.org/node/1176662

---
Tags: 8
---


# Question
Title: Use ajax to render a view - pagination not working
I'm trying to render a view using Ajax, but I can't get the ajax pagination to work. I've found the following code which works, apart from the pagination:

```
            $.ajax({
                url: '/views/ajax',
                type: 'post',
                data: {
                    view_name: 'stores',
                    view_display_id: 'default',
                    view_args: {},
                },
                dataType: 'json',
                success: function (response) {
                    if (response[1] !== undefined) {
                        $('.store-locator-view-wrap').html(response[1].data);
                        Drupal.attachBehaviors(); // Thought this would do it, but nope
                    }
                }
            });

```

The links go to /views/ajax?page=1 with the following json:

```
[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"rhm_starter","theme_token":"dRce3KwWhWs1ZpnNe6KVUu31mLX8pdVoZ5XixJo8SVI"}},"merge":true}]
::1

```

# Answer
> 3 votes
The problem here is that the `Drupal.settings` does not have the proper `views` key it needs to attach the behaviors if you are loading a view via `views/ajax`.

There is no good documentation on this, spend alot of time trying to figure it out, but this ended up working. I had to set the `views` key in the settings manually:

```
success: function (response) {
    if (response[1] !== undefined) {
        $('.store-locator-view-wrap').html(response[1].data);

        // Set views key based on response data.
        Drupal.settings.views = response[0].settings.views;
        Drupal.attachBehaviors();
    }
}

```

I also had to make sure the Views js files had been added to my page:

```
$views_path = drupal_get_path('module', 'views');
drupal_add_js(
    $views_path . '/js/base.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);
drupal_add_js(
    $views_path . '/js/ajax_view.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);

```

---
Tags: views, ajax
---


# Question
Title: How to get the current version of a node?
I programmaly want to set the current version of a node to a status in workbench "needs\_review" however the current version of the node is not the published version of the node.

```
$vid
5000 = Published
4999 = Current revision

```

How to get the versionid of a node which contains the current version?

I tried several and I guess:

```
$vid = revisioning_get_latest_revision_id ($nodeid)
$node = node_load ($nodeid, $vid)

```

but this is of course giving an error as a answer as I'm using D7, the function revisioning\_get\_latest\_revision\_id cannot be found.

I also saw https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_revision\_list/7.x But do not understand how the get the current revision of the node.

Any suggestions?

# Answer
For those who need it. It is included in the node structure under value:

```
$node->workbench_moderation['current']->vid

```
> 0 votes

---
Tags: 7
---


# Question
Title: Load form via ajax and submit by ajax not working
I have loaded a form via ajax and submit by ajax not working. But if I load form directly by url ajax submission is working. Form is loaded by ajax is using jQuery.

```
$('#button').on('click', function () {
        $.ajax({
            url: "user_group/edit_ajax/",
            success: function (result) {
                $(".RblockMain").html(result);
            }
        });
});

```

mymodule.routing.yml

```
mymodule.user_group_edit_ajax:
  path: 'user_group/edit_ajax/'
  defaults:
    _controller: '\Drupal\mymodule\Controller\UserController::user_group_edit_ajax'
  requirements:
    _permission: 'access content'

```

UserController

```
public function user_group_edit_ajax() {
        $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\UsergroupForm');

        $body_data = array(
            '#theme' => 'usergroup_edit_ajax',
            '#usergroup_form' => $form,
        );

        $message = \Drupal::service('renderer')->render($body_data);
        $response = new AjaxResponse($message);
        return $response;
    }

```

UsergroupForm.php

```
class UsergroupForm extends FormBase {

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

    $form['user_group_name'] = array(
          '#type' => 'textfield',
          '#title' => '',
          '#required' => TRUE,
          '#attributes' => array('placeholder' => t('Group Name'),),
          '#theme_wrappers' => array(),
        );

    $form['go'] = [
      '#type' => 'button',
      '#value' => $this->t('Submit'),
      '#attributes' => array('class' => array('btn btn-primary'),),
      '#ajax' => [
        'callback' => array($this, 'submitForm'),
        'event' => 'click',
        'progress' => ['type' => 'throbber', 'message' => NULL],
      ],
    ];
    }

public function submitForm(array &$form, FormStateInterface $form_state) {
 $title = $form_state->getValue('user_group_name');
$data = array(
        'type' => 'admin_user_group',
        'title' => $title,
        'uid' => 1,
        'status' => TRUE,
      );
      $usergroup = \Drupal::entityManager()->getStorage('node')->create($data);
$usergroup->save();
$response = new AjaxResponse();
    $response->addCommand(new AlertCommand('Submitted successfully'));

    return $response;
}
    }

```

# Answer
> 6 votes
I had the exact same issue:

When the form was on its own page, ajax submit works.

When the form was loaded through ajax, ajax submit didn't work, submit was redirecting the form to its own page.

After unsuccessfully restarting from scratch twice, I tried to implement this ajax modal example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8/

Success one.

Then removing the openModalCommand to simply display the form on the page.

Success two.

I compared both my unsuccessful attempts and the successful one. There was one difference, in the success one, in the controller the form was built but not rendered.

```
// Controller to load the form through ajax
public function ajaxSupportTicket() {
    $form = \Drupal::formBuilder()->getForm('Drupal\itportal_support\Form\SupportTicketForm');
    $ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

    // Append the form in the page.
    // The form is sent as is, not rendered
    $ajax_response->addCommand(new \Drupal\Core\Ajax\AppendCommand('#selector', $form));

    return $ajax_response;
}

```

Now that this works, the whole ajax api of D8 seems very powerful.

Also, try to get rid of your custom javascript to load the form. It can be done using render array. Place a link with use-ajax class.

```
$output['open_form'] = [
  '#type' => 'link',
  '#title' => $this->t('Open Form'),
  '#url' => Url::fromRoute('mymodule.ajax_form_controller'),
  '#attributes' => [
    'class' => [
      'button',
      'use-ajax',
    ],
  ],
];

// Attach the library for pop-up dialogs/modals.
// drupal.dialog.ajax might be overkill, but I didn't took time to improve
// comments about it are welcome
$output['#attached']['library'][] = 'core/drupal.dialog.ajax';

```

Hopefully, it can help.

---
Tags: 8, forms
---


# Question
Title: Is there a standard environmental indicator for Drupal 8 projects?
I am developing a Drupal 8 site, and I ran into the need to display all errors. I added this line to my settings file, according to this answer:

```
$config['system.logging']['error_level'] = 'verbose';

```

But, when I'm ready to make my site live on production, I don't want error details being shown to end-users.

I want to conditionally display errors based on which environment the codebase is sitting on-- local, dev, staging, and production. In Drupal 8, is there a way to indicate which environment the site is running on? A variable or something? Or is this something that I manage myself?

# Answer
> 2 votes
A standard way to use different settings files per environment is through the use of sites folders. Check out /sites/example.sites.php in your Drupal 8 codebase. It gives instructions.

Basically, you'll copy this file from example.sites.php to sites.php. You don't need to edit it, (but you can if you want to do something unusual).

Then for each site (or environment), you'll have a separate settings.php file in a folder named after the site.

So you might have

* /sites/example.com/settings.php
* /sites/qa.example.com/settings.php
* /sites/dev.example.com/settings.php
* /sites/example.local/settings.php

If you are using git, you might want to uncomment this /sites/example.local/settings.php

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include_once __DIR__ . '/settings.local.php';
}

```

and git exclude

/sites/example.local/settings.local.php

so that each developer can customize his settings.

If you run drush, you can run from the site specific folder on that environment or specify the --uri parameter.

Of course, you could just add conditional code in your /sites/default/settings.php

```
if ($_SERVER['SERVER_NAME'] == 'example.com') {
  $config['system.logging']['error_level'] = 'hide';
}

```

If you jut want to change one variable, and you know that on your production environment $\_SERVER\['SERVER\_NAME'\] is available and correct, then this is an option.

# Answer
> 1 votes
I want to make this plain and simple for people visiting this question: Based on oknate's answer, **there is no standard environmental indicator in Drupal 8**:

> That's something that should be explicitly set up by the developer, the framework shouldn't try to impose that logic. Take Laravel for example, you specify the server's current environment in an .env file that is excluded from version control. Drupal just doesn't have the convention of including that var somewhere; it could if it wanted to, but IMO it's better left up to the dev decide whether they want to solve it in code, through web server environment vars, or whatever else

If you're a developer coming into an existing Drupal 8 project, you have to be told or figure out how the builders managed environmental awareness, if they did at all.

---
Tags: 8
---


# Question
Title: Why I don't get the encryption methods? Encrypt module
I'm working on a Drupal 8 project. I want to send a link to the user via email and passing as parameters some user details that I want to encrypt. When the user clicks the link, I will get those encrypted data from URL and I will decrypt them.

After some research, I decided to use the Encrypt module.

I installed it, I added my key in settings.php, I also created a key in admin/config/system/keys, and now I'm trying to create an encryption profile, but the encryption method list is empty.

Is this the correct way to implement data encryption/decryption? If so, how can I get the encryption method list?

# Answer
> 3 votes
The Encrypt module provides an API, but no encryption methods. You'll need to install a module that provides one. I recommend the Real AES module

---
Tags: 8
---


# Question
Title: Commerce: Don't calculate extra shipping for 1st item
* I have a flat rate of $2.50 for every order.
* I have extra +$1 for every extra item added to cart.

So, if I order 1 item, total shipping is $2.50, but if I order 2 items total shipping is $3.50.

My problem is that in 2nd case, I get total shipping of $4.50 for 2 items instead of $3.50. It calculates the +$1 for both items.

I added the rule condition `Total product quantity comparison` to apply +$1 if quantity is `> 1`. So if I add only item, it doesn't calculate the extra shipping, but as soon as I add more items, it calculates the extra shipping for initial item.

Here's my calculation rule:

I followed this guide: https://vimeo.com/32813567

# Answer
> 1 votes
From the screenprint of your calculation rule it's hard to tell what exactly the logic is that you implemented (an exported rule, created with the Rules UI, provides ALL the details).

Anyway, it seems that your Rules Loop is adding $1 for EACH line item, so also for the very first line item. While your requirement (in your question) states "*+$1 for every extra item*" ... If "extra" is to be translated to "but do not add $1 for the very first item", then clearly in your Rules Loop you should not have added $1 for the very first item.

The easiest way to correct this, is to subtract $1 after your Rules Loop is finished (consider it like a discount for the very first item). If you rather want to go for a slightly more complicated solution, then you could use the Conditional Rules module to add an extra test (Rules Condition!) within your Rules Loop to NOT perform that +$1 for the very first line item (I presume you know what such *test* should look like). My 2 cents: go for the easiest way via the extra correction after the Rules Loop is finished.

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


# Question
Title: Don't calculate shipping for specific item
I have to types of a same product (used a select list field):

```
1|Physical
2|Digital
(key|label)

```

Physical items needs shipping calculated. Digital doesn't.

Problem appears when you add physical and digital item to cart, rules calculate the flat rate shipping to both items. Which is wrong, it should calculate rate to physical and ignore digital product.

I'm thinking it has something to do with data comparison? Am I on the right path? I tried various options/sorting.

**Update**

My exported rule looks like this now (as per the recommendation in the 1st answer to also use the Conditional Rules module):

```
{ "rules__1_extra" : {
    "LABEL" : "+1$ extra",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules",
      "commerce_line_item",
      "rules_conditional",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "data_calc" : {
                "USING" : { "input_1" : [ "list-item:quantity" ], "op" : "*", "input_2" : "100" },
                "PROVIDE" : { "result" : { "result" : "Calculation result" } }
              }
            },
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "result" ],
                "component_name" : "flat_rate_flat_rate",
                "round_mode" : "0"
              }
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_subtract" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "100",
          "component_name" : "flat_rate_flat_rate",
          "round_mode" : "0"
        }
      },
      { "CONDITIONAL" : [] }
    ]
  }
}

```

# Answer
> 0 votes
From the screenprint of your calculation rule it's hard to tell what exactly the logic is that you implemented (an exported rule, created with the Rules UI, provides ALL the details).

Anyway, it seems that your Rules Loop is adding "*an amount to the unit price*" for EACH line item, so it doesn't check (within that Rules Loop) if it is "Physical" or "Digital", which explains why for Digital items shipping gets calculated also (which is not what you want).

The easiest way to correct this, is to use the Conditional Rules module to add an extra test (Rules Condition!) within your Rules Loop to NOT calculate shipping for Digital items (AND remove all Rules Conditions starting from the "AND" you added). As a variation (to not have to use this extra module), transform the 2 Rules Actions within your loop to an equivalent Rules Component (by passing the line-item as a parameter), and within that Rules Component add an extra Rules Condition to check ... indeed ... if it is a Physical item.

**Update 1**

As per the update that was applied to your question (by adding your improved rule using the Conditional Rules module I suggested before), it seems that you've for sure not correctly used that module. Because the **CONDITIONAL** near the end of your exported rule is NOT supposed to be empty. Therefor have a look at this variation of your exported rule (if needed, just import it in your own setup to look at it with the Rules UI):

```
{ "rules__1_extra_not_for_digital" : {
    "LABEL" : "+1$ extra not for digital",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules_conditional",
      "rules",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "product" } },
                  "DO" : [
                    { "data_calc" : {
                        "USING" : { "input_1" : [ "list-item:quantity" ], "op" : "*", "input_2" : "100" },
                        "PROVIDE" : { "result" : { "result" : "Calculation result" } }
                      }
                    },
                    { "commerce_line_item_unit_price_add" : {
                        "commerce_line_item" : [ "commerce_line_item" ],
                        "amount" : [ "result" ],
                        "component_name" : "flat_rate_flat_rate",
                        "round_mode" : "0"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_subtract" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "100",
          "component_name" : "flat_rate_flat_rate",
          "round_mode" : "0"
        }
      }
    ]
  }
}

```

Note these changes I applied as compared to your exported rule:

* The **CONDITIONAL** is to be contained within your Rules Loop (not after it).
* Within that **CONDITIONAL**, I added ***some*** other condition. And only if that condition is satisfied, the 2 Rules Actions (as in your own exported rule) are to be executed.
* Attention about that "some other condition": the actual condition I added is for sure not correct yet to make it match your question, so make sure to rework that to fit your case (I just added this condition here to show how to use that **CONDITION** statement).

Additionally, I'm not sure (actually I doubt) if the very last Rules Action in my updated Rule is still correct. Because you'd only want to do that subtract again if the very first line item actually did pass the test about **CONDITION**. But after you understand how to use the Conditional Rules module, I'm sure you'll get that part fixed also.

**Update 2**

Yet another update, as per this additional comment you added after I added my "update 1":

> I can't find my term field in Data Comparison to select if product is Digital or Physical

That is not a surprise (at least not to me), because think about what kind of data about a product are available when processing a "line item" (inside a Rules Loop in this case here) ... No panic, because if it ***is*** not available, you can ***make*** it available, similar to what is explained in my answer to "How to access commerce\_product field of line-items using Rules to flag the Commerce Product?" ...

Here is a blueprint of what you need to do (to further improve your rule):

1. Create a Rules Component, similar to the Rules Component of Step 1 in my related answer, just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
2. Execute that Rules Component inside your Rules Loop of the rule you already have. But make sure to do so BEFORE the "CONDITIONAL" Rules Action.
3. Move the "CONDITIONAL" Rules Action (and everything inside of it) to the Rules Actions of the new Rules Component you need to create. Make sure to place them AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID". At that point you should have access to your field to indicate "*if product is Digital or Physical*" (because of the "Fetch entity by ID").
4. Make sure that in that new Rules Component you also add a "Provided" variable (= value returned by the Rules Component to the calling Rule), which actually will, in the end, contain the "***Calculation result***" (BTW, `result` is a terrible variable name, hard to know what it is about). And it is that *Calculation result* that is what your main (further improved) rule should calculate, right?

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


# Question
Title: How to merge multiple fields into one, across multiple content types?
I'm updating some old Drupal 7 sites, and I need to merge a number of fields across multiple content types.

For example, I have the *field\_article\_body*, *field\_page\_body*, and *field\_event\_body* fields that needs to be merged into the core *body* field, or the *field\_article\_image*, *field\_page\_image*, and *field\_event\_image* fields that need to be merged into the *field\_image* field.

I am hoping there is some solution which can assist me in combining these fields, or alternatively some SQL magic which an expert can help me with.

Do you have any idea?

# Answer
> 5 votes
By using Views (to build a list of nodes to be updated) and a combination of Rules and VBO (to mass update such lists) you should be able to perform the merge of those fields.

Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that, which is about a variation of your scenario (ie change the value of an existing field, while you want to "copy" the value of an existing field to the value of a new field).

For your case, this example of a **Rules Component** (in Rules export format) should be close to one of the Rules Components you'd need for your "field\_image":

```
{ "rules_set_an_initial_value_for_image_field" : {
    "LABEL" : "Set an initial value for image field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_image" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-image" ], "value" : [ "field_article_image" ] } }
    ]
  }
}

```

**Note**: by using an approach with modules such as above (instead of SQL magic), you do have the advantage that all possible relatic magic will happen automagically and behind the scenes (eg: create a new revision of such nodes). And it avoids your Drupal database gets corrupted because "you forgot some table".

---
Tags: 7, database
---


# Question
Title: Access multivalued field collection tokens in webform email
I tried this token `[webform_submission:source-entity:field_campaign_email_collaterals]` but this results in following html

```
field_campaign_email_collaterals 0 (Edit|Delete),
field_campaign_email_collaterals 1 (Edit|Delete),
field_campaign_email_collaterals 2 (Edit|Delete)

```

How can I get actuall value of this field collection, or else if there is any way to get individual field inside this field collection?

# Answer
> 0 votes
Try using the \[webform\_submission:node\] to access field related tokens. I think you might need to try \[webform\_submission:node:field\_campaign\_email\_collaterals:0\] or \[webform\_submission:node:field\_campaign\_email\_collaterals:0:html\]

---
Tags: 8, webforms, tokens
---


# Question
Title: Drupal 8 Webform URL alias with parameters
On the URL PATH SETTINGS, I want to define the Webform URL alias to include a variable parameter e.g. /my-web-form-url/{id} Is this possible? I want to pass this 'id' as a hidden value in the form.

# Answer
> 2 votes
You would need to write some custom code to support custom URL parameters. (see How to (truly) alter a URL in Drupal 8)

You could easily pass the 'id' as a query string parameter, which is supported as long as you enable 'Allow elements to be populated using query string parameters.' under a Webform's \> Settings \> Form Behaviors.

---
Tags: webforms
---


# Question
Title: Fancy Attributes does not show selected option
I'm trying to use Fancy Attributes to display colour variations in my Drupal Commerce store. The colours, and associated descriptions display, and I can click on a colour to select that variation. My problem is that it does not change the display of the colour variation in any way to show which one is selected. This is especially important because I also have a size attribute that seems to reset the colour attribute if clicked after the colour is chosen.

Is there any way to, for example, make the description bold, or put a different border around the selected colour?

# Answer
> 0 votes
OK... I think I answered my own question. I added the following to *commerce\_fancy\_attributes.css*:

```
.form-type-commerce-fancy-attributes-ajax .description .description-selected {
  font-weight: bold;
  font-size: 12px;
  color: black;
}

```

---
Tags: commerce
---


title: Rest Export JSON format

text:
# Question
Title: Rest Export JSON format
I'm new to Drupal and I've very excited about the possibly of headless as it will align with my current skillset and let me be productive more quicly while I continue to learn Drupal. (I come from a full stack .NET background using consuming REST services on the frontend).

I'm having some trouble with the JSON format.

I've set up a REST Export view in Drupal 8.3 that returns a custom content type. It includes a three fields: title, body(plain text), and an image.

The result that I get has a lot of escape characters and I'm not sure how to get it to just return the plain text data.

Here is the result that I get:

```
[{"title":"A test for the json api","field_body":"This is a test. It\u0026#039;s pretty awesome and I love you.","field_test_image":"\/drupal\/sites\/default\/files\/2017-04\/Adam_Dickison_1.png"}]

```

What I'd like to get back is this:

```
[{"title":"A test for the json api","field_body":"This is a test. It's pretty awesome and I love you.","field_test_image":"/drupal/sites/default/files/2017-04/Adam_Dickinson_1.png"}]

```

I've checked my php.ini and magic\_quotes\_gpc is set to 'Off'.

Can anybody help me figure this out. I didn't see any general settings. I've changed all of the field settings to remove html and to give me just the plain text.

Thanks in advance.

# Answer
> 2 votes
On your view page, click on the 'Field settings'. i.e.

> **Format**:
>
> Show: Fields | Settings

Click on the '*Settings*'. You will see a popup window. And select the '**RAW OUTPUT**' for the respective field. Also, you can provide *ALIAS* for the field.

I guess you were looking for this option.

# Answer
> 0 votes
Looks like I need to decode the unicode string on the client side.

---
Tags: views
---