# Question
Title: Add onsubmit attribute to specific webforms
I am having difficulties regarding the way to add onsubmit to some forms.

I have embedded forms in landings, called via

```
<?php
    $nid = 12;
    $wnode = node_load($nid);
    $form = drupal_get_form('webform_client_form_' . $nid, $wnode, array());
    print render($form);
?>

```

I would like these forms to have an extra "onsubmit" attribute to call a function.

I've seen some examples of codes like this

```
$form['#attributes']['onsubmit'] = 'return myFunction();';

```

I do not want to put this code in the core of the module, to avoid conflicts with the landings in which the script called is not present.

What would be the right way to get this?

I hope to express myself clearly, thank you

# Answer
> 0 votes
You need to use `hook_form_alter`, check the $form\_id like `if($form_id == MY_FORM_ID)` and add your submit handler `$form['actions']['submit']['#submit'][] = 'MY_SUBMIT_HANDLER';`

---
Tags: forms, webforms
---


# Question
Title: Why is the 'values' array not set on an unsaved entity? Is there a way to make it get populated?
When I load an entity, its protected 'values' property contains all of its field values.

But when I create a new entity with MyEntityClass::create($array\_of\_values), its 'values' property is not set until I have saved it.

Is there a way to get that set, for the purposes of debug output?

# Answer
The code comments in ContentEntityBase say that $values always hold the original, unchanged values of the entity:

```
/**
 * The plain data values of the contained fields.
 *
 * This always holds the original, unchanged values of the entity. The values
 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
 * is used for values in default language.
 *
 * @todo: Add methods for getting original fields and for determining
 * changes.
 * @todo: Provide a better way for defining default values.
 *
 * @var array
 */
protected $values = [];

```

Quick glance through the code suggests that the public method `updateOriginalValues()` would do the trick:

```
/**
 * Updates the original values with the interim changes.
 */
public function updateOriginalValues() {
  if (!$this->fields) {
    return;
  }
  foreach ($this->getFieldDefinitions() as $name => $definition) {
    if (!$definition->isComputed() && !empty($this->fields[$name])) {
      foreach ($this->fields[$name] as $langcode => $item) {
        $item->filterEmptyItems();
        $this->values[$name][$langcode] = $item->getValue();
      }
    }
  }
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Help with LDAP module for user authentication in Drupal 8.3.7
I just installed Drupal 8.3.7 via composer and am trying to get user logins to work against our LDAP server. I added and enabled the following modules:

We are using ldaps on port 636 rather than START-TLS on port 389 so I configured the LDAP settings as follows:

```
[SERVER section]
  Name: <whatever>
  Machine-readable name: ldap (not the hostname of our LDAP Server)
  LDAP Server Type: Default LDAP
  Server address: ldaps://<ip address of ldap server>
  Server port: 636

[BINDING section]
  Binding method for searches:L Service Account Bind: Use credentials in the Service Account field below to bind to LDAP
  DN for non-anonymous search: <dn for ldap auth user>
  Password for non-anonymous search: <password for ldap auth user>

[USERS section]
  <base dn for users>
  AuthName attribute: cn

```

When I try to test this config, I enter my cn in the "Testing Drupal Username" field and then click the Test button. I receive the following errors:

```
  Failed to bind with service account. LDAP error: Can't contact LDAP server (-1)
  Failed to find test user <my cn> by searching on cn = <my cn>.'

```

I can perform an ldapsearch using the auth ldap bind DN ok on the Drupal server. I enabled logging but the messages sent to /var/log/localmessages are not useful. I just see things like:

```
  ldap_search() function error. LDAP Error: Can't contact LDAP server (-1), ldap_search() parameters:
  LDAP search error: Can't contact LDAP server (-1). Context is base DN: <base dn> | filter: (cn=<my cn>)| attributes: []

```

Anyone have any ideas? I looked at the tcpcdump output comparing ldapsearch and the Drupal LDAP test and I don't see any TLS handshakes in the Drupal test case so I'm not convinced I have the ldaps part of the configuration working correctly.

# Answer
Found the problem. I had a temporary cert in /tmp and specified in /etc/openldap/ldap.conf but systemd starts httpd with a private /tmp so the cert was not being found.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: How to change taxonomy term in field with Rules?
I have a field `status` that when user uploads a file, is populated by a taxonomy term "uploaded". Now when an administrator downloads the file I need the `status` field up change to taxonomy term `processing`. I have tried using **Rules** but can't get it right.

The Rule is like so:

* Event-\>content type viewed
* Condition-\>User has Role of Administrator
* and I can't set the action.

The action data is `[node:field-status]`, Value `[node:field-status:parent:1]` But when I test it, it changes the status to "none". The taxonomy terms in order are: uploaded, processing, admin hold, error, closed. So shouldn't the `parent:1` be processing?

Am I asking to much of Drupal 7.50, or can someone point me in the right direction?

# Answer
> 1 votes
### Question clarification

There is something in this question that I find bizarre: the requirement relates to "*when an administrator downloads the file*", but then the Rules Event mentioned is "*content type viewed*" (and combined with a Rules Condition "*User has Role of Administrator*").

Therefor I'm going to assume that "Content is viewed by a user who has the admin role" is an acceptable translation of "*when an administrator downloads the file*". With that in mind, read on about (a) what the reasons (multiple ...) are why it doesn't seem to work and (b) how to make this to work anyway ...

### Mistake 1 - Use the correct token

The `node:field-status` is clearly a term reference field, which can, obviously, only have 1 possible value, which is one of these: uploaded, processing, admin hold, error, closed.

When you're using the Rules UI, in this case you should just use the token `[node:field-status]`, and NOT (repeat: NOT) `[node:field-status:parent:1]`. That explains '*... when I test it, it changes the status to "none" ...*' (as in the question).

### Mistake 2 - Rules Condition 'Entity has field' is missing

From the Rules Conditions mentioned (only "user has role admin"), I'm about sure that there is a crucial additional Rules Condition that you would need ALSO to make this work. I.e. you need to tell the Rules module that you want to do something with the `node:field-status` field. I.e. you need to add a Rules Condition of "Entity has field" (related to that `node:field-status` field). Even though there are variations (other Rules Conditions), this "Entity has field" is what for me always seems to work when I want to do something with a field in Rules.

Using this Rules Condition is like ringing a bell for the Rules module to prepare for that, and have Rules already go retrieve the existing data about that field, so that you can (eg) test the existing value it contains (in a subsequent Rules Condition).

### Mistake 3 - Rules Event 'Content is viewed' may be too late

Whatever you want to happen (via Rules), if you're using Rules Event 'Content is viewed', that you may simply be too late: the content is already being shown, so if the Rules Conditions or satisfied, what else do you want to happen. That is what 'Content is viewed' is all about.

If you didn't want to content to be visible at all (which does not seem to be the case here though), sorry, you're too late. If you did want something to happen BEFORE showing the content, then you should have used Rules Event "Drupal is initializing". Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this. And if you want the user to see the result of your Rules Action(s), a page refresh is needed for that.

### Possible alternative

Here is a rule (in Rules Export format) that might possible be an acceptable alternative (solution) to answer this question, using `field_demo_tags` as the machine name of the term reference field and which I labeled "Demo tags" (adapt to fit your own machine name of your field before trying to import this rule):

```
{ "rules_update_taxonomy_term_of_a_node" : {
    "LABEL" : "Update taxonomy term of a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } },
      { "data_is" : { "data" : [ "node:field-demo-tags" ], "value" : "1" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "This is a node with value \u0022[node:field_demo_tags]\u0022 for field \u0022Demo tags\u0022 ..." } },
      { "data_set" : { "data" : [ "node:field-demo-tags" ], "value" : "2" } },
      { "drupal_message" : { "message" : "Be aware: the value of the \u0022Demo tags\u0022 field just got updated to [node:field_demo_tags] (refresh the page to see the updated version ...)" } }
    ]
  }
}

```

Some more details about it:

* Rules Event: Content is viewed
* Rules Conditions:
    + Entity has field, for field `field_demo_tags`.
    + The term id of the current value of the term must be the one for `uploaded` (adapt this term id to fit your case).
    + Current user has role Administrator.
* Rules Actions:
    + Show a message (to confirm we have a hit, mostly for demo/debugging purposes).
    + Do your thing, i.e. update the term id to the value of the term corresponding to `processing` (adapt this term id to fit your case).
    + Show a message (to confirm we did our job, and suggest a page refresh).

For short: if a node is viewed by a user who has role admin, and the node has been tagged with the term with Term Id = "`1`" (which could be the equivalent of `uploaded` in the question), then the term will be changed to the term with Term Id = "`2`" (which could be the equivalent of `processing` in the question). Additionally, an informational message will be shown similar to this:

> This is a node with value "uploaded" for field "Demo tags" ... Be aware: the value of the "Demo tags" field just got updated to processing (refresh the page to see the updated version ...)

**Voilà**, 2 mistakes corrected, and a workaround for the 3rd mistake, which is hopefully acceptable ...

---
Tags: taxonomy-terms, rules
---


# Question
Title: New Drupal 8 install, homepage works, all other pages throwing a 404
I have a server that houses my personal website (in the root folder.) Let's call it me.com. In the root I have: me.com files, a /dir/ called "me2." In /me2/ I have my drupal 8 install for a new site. Installed fine. Logged in, can access homepage. Every other link I click goes to a 404. I am not sure why this is happening.

\*Edit: "me.com" site is Wordpress.

# Answer
> 2 votes
The problem may be that you don't have the .htaccess file on the root of your Drupal 8 website.

---
Tags: installation
---


# Question
Title: Get users by display name on reference autocomplete field
I need a list of users for a reference autocomplete field. I know about the realname module, but I haven't installed it, neither will I as long as it remains an RC (and I don't need all it provides). Anyway, I copied the code I needed from it and adapted it accordingly.

My users have a first\_name and last\_name fields. Here is the query I came up with in order to return the JSON for my autocomplete field:

```
$sql = "SELECT u.uid
        FROM users u
        INNER JOIN users_field_data ud ON u.uid=ud.uid
        LEFT JOIN user__field_first_name fn ON fn.entity_id=u.uid
        LEFT JOIN user__field_last_name ln ON ln.entity_id=u.uid
        WHERE CONCAT_WS(:separator, fn.field_first_name_value, ln.field_last_name_value) LIKE :text OR ud.name LIKE :text";

$uids = \Drupal::database()->queryRange($sql, 0, 10, [
    ':text'      => '%' . db_like($input) . '%',
    ':separator' => ' ',
])->fetchCol();

```

Do I have an alternative to this? I would rather not reference individual tables.

# Answer
A potentially cleaner/easier way to do that would be to leverage the JSON API. After you install that module, you should able to make a call to the /jsonapi/user/user endpoint (see the "GET user accounts section on https://www.drupal.org/docs/8/modules/json-api/fetching-resources-get), and parse out the UIDs into the array.
> 0 votes

---
Tags: 8, users
---


# Question
Title: How to show the content of a group on the group page when using the Group module?
Using the Group module, you can create a group, say 'group ABC', and create or update some nodes so that they belong to that group. But when you visit the "Group ABC" page, you don't see those nodes. Moreover, by browsing the nodes you don't see anything indicating those nodes belong to "Group ABC".

How to list the nodes that belong to a group on the Group page?

Note: This module is available for both Drupal 7 and Drupal 8, and this question applies to both releases.

# Answer
> 0 votes
To show the content of a group, you need to create a view. The Group module provides Views 'relationships' to any node's parent group.

With that, these are the steps required:

* Create a view about content.
* Add a relationship to the parent group.
* Add a contextual filter on the group's id (`gid`).
* Create a page, a block, a content pane, etc (whatever fits your needs).

Below is an export of a (simplified) view created (in Drupal 7) using the steps described above:

```
$view = new view();
$view->name = 'group_content';
$view->description = 'Show all nodes that belong to a specific group';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Group content';
$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'] = 'Group content';
$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,
  ),
);
/* Relationship: Content: Parent group */
$handler->display->display_options['relationships']['parent_group']['id'] = 'parent_group';
$handler->display->display_options['relationships']['parent_group']['table'] = 'node';
$handler->display->display_options['relationships']['parent_group']['field'] = 'parent_group';
/* 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;
/* 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: Group: Group ID */
$handler->display->display_options['filters']['gid']['id'] = 'gid';
$handler->display->display_options['filters']['gid']['table'] = 'groups';
$handler->display->display_options['filters']['gid']['field'] = 'gid';
$handler->display->display_options['filters']['gid']['relationship'] = 'parent_group';
$handler->display->display_options['filters']['gid']['exposed'] = TRUE;
$handler->display->display_options['filters']['gid']['expose']['operator_id'] = 'gid_op';
$handler->display->display_options['filters']['gid']['expose']['label'] = 'Group ID';
$handler->display->display_options['filters']['gid']['expose']['operator'] = 'gid_op';
$handler->display->display_options['filters']['gid']['expose']['identifier'] = 'gid';
$handler->display->display_options['filters']['gid']['expose']['required'] = TRUE;
$handler->display->display_options['filters']['gid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

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

```

# Answer
> 0 votes
Maybe Kristiaan Van den Eynde's reply to the question posted in this node here https://www.drupal.org/node/2689663 will be "enlightening" enough...

or this step-by-step guide here, edited by Pierre Vriens, too: https://www.drupal.org/node/2693847

Or/and this blog post: https://www.optasy.com/blog/drupal-8-group-module-how-list-related-group-content.

Good luck!

---
Tags: nodes, group
---


# Question
Title: Is it properly to include a third-party php library via composer without creating drupal module for it?
I want to ask a theoretical question.

For example, there is a project on Drupal 8. Working on the project, developers find a php library on the GitHub, include it via Composer and use it in their modules.

They don't create drupal 8 module which would present the library and contain files of the library, copied from GitHub before. And to use the library it would be necessary to install the module.

Is it the correct way to attach an external php library via composer and afterwards use it without creating a module for Drupal 8 for this library ?

# Answer
> 0 votes
Sure, you can do that on a project.

But you're probably going to write code somewhere to actually integrate that into Drupal and expose it somehow, and that will be in a module (or theme). But especially if that's a custom module that is just used for that site, you kind of have to add it to the project composer.json as composer doesn't include composer.json of moules that aren't actually added themself with composer (excluding solutions like merge plugin)

---
Tags: 8, theming, composer
---


# Question
Title: How to check if user has passed the quiz already before granting user points?
I'm awarding users points for passing a quiz successfully. However, there's nothing stopping the user taking the quiz again and again to score more points.

I have thought of these options, but I don't know how to implement them:

1. check if the user has achieved a certain score before awarding points
2. lock down the quiz for users who have already passed it, redirecting them to their results page
3. tagging the quiz with users ID when they complete it the first time and and denying points when they complete it again.

Any help?

# Answer
> 1 votes
### Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) ***Passed Quizes***. Here is an export of the flag I used for this (you should be able to import it in your own site also):

```
$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

```

This flag will be used in the custom rule, detailed in the next step.

### Step 2 - Create a single rule to cover all situations

Here is a rule which illustrates how to resolve the challenge in your question:

```
{ "rules_process_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Process a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "rules_conditional", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT flag_flagged_node" : {
                "flag" : "passed_quizes",
                "node" : [ "quiz-result:nid" ],
                "flagging_user" : [ "site:current-user" ]
              }
            },
            "DO" : [
              { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
              { "flag_flagnode" : {
                  "flag" : "passed_quizes",
                  "node" : [ "quiz-result:nid" ],
                  "flagging_user" : [ "site:current-user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "Congratulations, you passed this quiz yet ANOTHER time (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } }
            ]
          }
        ]
      }
    ]
  }
}

```

This rule requires the Conditional Rules module to be enabled (head over to the next step for some (multiple!) alternatives which does not need this extra module).

Here are the critical pieces of this rule to make Rules-magic happen:

* The very first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
* If the quiz node (to which this quiz result relates) is not yet flagged (by the flag from Step 1), and the quiz result is that it is at leastd equal to the *pass rate of that quiz*, then you have your very first hit you're looking for. At which time the quiz node gets flagged.

Use the Rules UI to import the above rule in your own site, after you enabled the Conditional Rules module and completed Step 1. After you are convinced it works as designed, simply add your additional Rules Action(s) to grant the *User points* ... only the very first time.

### Step 3 - Possible Rules variations

Some variations of the rule included in Step 2, which should also achieve a similar result:

* Replace the logic implemented via the Condtional Rules module by 2 equivalent Rules Components (so that you don't need the extra module). Refer to "What's the alternative to using the Conditional Rules module?" for way more details on this.
* If you DO NOT want anything to happen if the quiz was already passed before, then the "else"-part of the Conditional Rules logic is empty. In that case you could rework the remaining Conditional Rules logic to a regular Rules Condition (to be executed as the very last one). As a variation, clone such rule variation in a 2nd variation, in which you just reverse that very same Rules Condition (with Rules Action as in the "else" part of the Conditional Rules logic).

### Showtime

Here is a sample of a message I received after passing a quiz:

* The ***very first time***:

> Congratulations, this is the FIRST time you passed this quiz (with a score of 80 %, whereas the pass rate is 75 %).
* The ***next time***:

> Congratulations, you passed this quiz yet ANOTHER time (with a score of 100 %, whereas the pass rate is 75 %).

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

# Answer
> 0 votes
What version of the quiz module are you taking? The quiz settings do allow you to restrict how many times a user is able to take a quiz.

This answer doesn't address points, it simply limits the number of times that they can take the quiz.

Go to the quiz or the global quiz settings. Under "availability options" there is an option near the bottom to select how many times a user can take the quiz:

So this might be a way to address the second point of locking down a quiz and redirecting the users to their results page.

---
Tags: rules, quiz
---


# Question
Title: Get a node using the same category (taxonomy term) the current node is using
I have two types of nodes: *News* and *Page*. Every *News* node can be assigned to a category (taxonomy term), which is used also from the *Page* nodes.

I would like to get in a view all the *News* nodes that have the same category the current node has.

How can I achieve this?

# Answer
> 5 votes
Add CONTEXTUAL FILTER (Earlier arguments) on CONTEXTUAL FILTERS section on views click add, select "Content: Has taxonomy term ID" and in "WHEN THE FILTER VALUE IS NOT IN THE URL" choose Provide default value. Choose "Taxonomy ID from URL" check "Load default filter from node page, that's good for related taxonomy blocks". It will create a related taxonomy.

# Answer
> 2 votes
If your goal is to show a list of **News** nodes on a **Page** node that share a given taxonomy term, then you can do this:

* Create a **Taxonomy Reference** field on the **Page** content type. If you prefer, you could create an **Entity Reference** field instead.
* Assign the same taxonomy reference field to the **News** content type.
* Create your view. Add fields and filters to your view from the **News** Content type.
* Add **Has Taxonomy Term** ID as a contextual filter.
* Under **When the filter value is not available**, choose **Taxonomy term ID from URL**. Enable **Load default filter from node page, that's good for related taxonomy blocks**, and **Limit terms by vocabulary**, then choose the shared vocabulary.
* Under **When the filter value *is* available or a default is provided** choose **Specify validation criteria**. Set the **Validator Term** to Taxonomy Term and choose the shared vocabulary.
* Under **Filter value type** choose **Term name converted to term ID**.
* Under **Action to take if filter value does not validate** choose **Display all results for specified field**.
* Test by previewing with the NID from a Page node that shares a vocabulary term with at least 1 News node.

Note that this approach does not require any Relationships in the view. There are a lot of posts that deal with similar problems that add one or two relationships to the view, but they aren't needed here and, even if they work, are a lot more complicated and slower for Views to execute.

# Answer
> 0 votes
Please check the below link: Related content in drupal 7

You need to create a view and add a contextual filter to display the nodes based on the particular taxonomy term from the currently active node.

Make sure you are not having the views filter for one particular node type.

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


# Question
Title: Drupal UserLoginForm vs UserAuthenticationController login function - which to override?
I have a drupal site where I am customizing the login by validating credentials against an OAuth2 provider, implementing the OAuth2 password flow, basically what this module does, except I am using D8 and this is for D7

https://www.drupal.org/project/oauth2\_authentication

I upgraded that module to D8. It works by adding a replacing the validateAuthentication function in the #validate array of the form with an implementation that validates against the external OAuth provider. I upgraded all that to D8, but then I noticed in D8 that the login method of the UserAuthenticationController is also called to validate credentials.

So I have a couple questions

1. These two things both do basically the same thing. Both pieces of code (UserLoginForm and UserAuthenticationController) validate against the user table in the DB. Why are both doing essentially the same thing? Are they both actually being called?
2. I realize it would be a cleaner implementation (and more Drupal 8-like) to override the UserAuthenticationController. If my module registers the /user/login route to a different controller (provided by my module) will this override the default mapping to the UserAuthenticationController?

Thanks in advance. I am new to drupal so any help would be appreciated.

# Answer
UserAuthenticationController is a service that can be used by e.g. apps and decoupled websites.

Either one or the other is used, not both.

But both use the user.auth service, which receives username and password and returns a user ID in case of a match.

So if you want to override a single place to do that, that's what you want to do. Implement a service provider in your module and switch out the class of that service definition.
> 1 votes

---
Tags: 8
---


title: How sensitive is a site's UUID?

text:
# Question
Title: How sensitive is a site's UUID?
I have set up continuous integration for a Drupal site. After every `git push` the site is built remotely from scratch in a Docker container. It runs a site install, sets the site's UUID to import the configs, creates some sample content and then runs Behat tests.

For simplicity I'd simply commit the UUID in a text file and then import it like so:

```
drush cset system.site uuid "$(< sites/default/uuid.txt)"

```

The underlying question I have is if it's OK – from a security point of perspective - to commit a site's UUID into a public Git repo? Does that create any vulnerabilities to my site?

# Answer
> 1 votes
Sorry, only after I created the question it came to my mind that the UUID itself already may be present inside a config YAML. And indeed it is. Inside `system.site.yml`. So, I guess when it's OK to have it printed inside a config YAML – with the purpose to get version tracked – it's no problem to have it inside a text file as well.

---
Tags: 8, security, entities
---


title: display a vimeo frame in a view

text:
# Question
Title: display a vimeo frame in a view
I have a field that holds a vimeo video ID, I'm trying to display this content using a view where I'm rewriting this field, but the markup is getting stripped out.

```
<iframe src="//player.vimeo.com/video/[view_field_id]" width="WIDTH" height="HEIGHT" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

```

How can I display a vimeo iframe in drupal using views?

# Answer
> 2 votes
As per this support request in Views issue queue: Views: Rewrite field, strips some HTML tags (SOLUTION/WORKAROUND FOUND FOR STYLE TAG) Views strips out certain tags. It does this using filter\_xss\_admin, which if you look at that API entry calls filter\_xss, passing in an array of allowed tags. `iframe` is not one of those unfortunately.

So I think that you might need to do a workaround. I would look at two ways of doing this:

1. Rewrite the outut in a Views template. You click on `Theme:Information` at the bottom of the advanced pane in Views UI and you would select the theme file for the Vimeo field. More at An Intro to Drupal Views Templates and Theming
2. Create your own theme function to output the iframe. Enable Views PHP and call the theme function from a rewritten Views field.

# Answer
> 0 votes
you can create view custom template file and than add iframe and in ifram you can print view fields and i know you are entering just vimeo link in back-end and in views thats field link will display so you can print that field in iframe in view template file.

---
Tags: views
---


# Question
Title: How can I configure the Mail System module to use Swift Mailer for registration emails?
This seems like it should be straightforward, but I haven't had success theming the default registration emails on my site. I am able to see the themed email (just using swiftmailer.html.twig in my theme) when I send a test email via the Swift Mailer UI, but using Swift Mailer for my formatter and sender in the default mail system config in the Mail System UI and using my theme to render the emails, I'm still not getting the themed registration emails as I would expect. I must be missing something simple, but I've tried all sorts of combinations without luck.

# Answer
> 0 votes
The trick was to make sure the 'Respect provided e-mail format' option is *unchecked* in the message settings. Then I added a plugin to force HTML output for these email, as per this suggestion and used that for my Formatter and Sender in the mail system settings.

---
Tags: 8, emails
---


# Question
Title: How to create a rule to conditionally send a notification email, based on field value?
In the Article content type, I have a field called "Assign to" which is a reference to a User entity. So that the users (editors) can know witch articles are assigned to them by the administrators.

How should I configure the Rules module to send an email to editor when article is assigned to an editor, telling editors witch article is assigned to them, and who assigned this article?

# Answer
> 0 votes
Here is a sample of a rule (in Rules export format), which will send an eMail to the userid selected via the field `field_article_reviewer` (= a field I added to my "Article" content type that is defined as an entity reference to a 'user'), and this whenever content of content type "Article" is saved:

```
{ "rules_notify_editor_about_outstanding_review" : {
    "LABEL" : "Notify editor about outstanding review",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-article-reviewer]",
          "subject" : "Article waiting your review",
          "message" : "[node:author] has submitted a new Article post waiting your review.\r\n\r\nYou can review it at: [node:edit-url].",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

If (before importing this rule in your environment) in the above exported rule you'd change the field `field_article_reviewer` to match with your field name of the editor, you should be pretty close to getting it to work.

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

---
Tags: rules, entities, emails
---


# Question
Title: Need help with superfish module on Bartik theme
Need your help on this subject. Pretty like Bartik theme but as you know can’t have sub menu on Main menu on Bartik theme, so I would like to use Superfish module on it.

I have searched internet to find solution but failed, and I don’t think there is same post here, so please allow me to post it here.

What I have done:

1. Have installed superfish module successfully, I am sure.
2. Have created subtheme of Bartik successfully, I am sure too. (name is subtheme3)
3. Added a region calls superfishmenu to subtheme3.info below header region.
4. Copied page.tpl.php to sbuntheme3 folder and change some code to it.
5. Disabled Main menu in Menu Setting, so there is only Superfish menu shows.

My problem: No.1, Superfishmenu block shows but the width is not like others short and at the center of screen. I would like to make it as same wide as other regions like featured region.

No.2, the sub menu of superfish menu doesn’t show sub menu but if I flush all the cache and the message shows, which give a lot padding space, then the sub menu shows. When the message is gone, the sub menu can’t show again.  I am not good at CSS and PHP, and I believe the problem is CSS and the PHP code in page.tpl.php.

Is there anyone can give me the correct codes for them?

# Answer
You need to add this block in Featured region.Check out this https://d25zd.ply.st/

You don't need any code just place block by admin interface.
> 1 votes

---
Tags: navigation
---


# Question
Title: What are the ways to handle a fresh new project?
There is a lot buzz around regarding installing Drupal via Composer, but many tutorials manage Drupal via Drupal Console. Last but not least, the other Drupal command line tool, Drush. It causes lots confusion and I would love to hear a good round up what each tool brings.

# Answer
> 2 votes
This is maybe not a *stackexchange* question but a good question to rather discuss somewhere else. The reasons for your confusion are caused by a problem, the Drupal community is already aware of for a long time but it is not easy to find a better solution for that than as it is at the moment.

### An overview

**Drush** was ***THE*** terminal command line tool for Drupal and was precursor in type of such tools long time before Composer or other command line tools like this even existed. It was a very helpful tool for Drupal developers on a daily basis, was VERY innovative in this time and still is.

**Drupal Console** raised over the last years in the time of when Drupal 8 was on development state and the Symfony PHP framework started to become the underlying construction kit for this new Drupal version. A decision which was long discussed and worried about ot map a good future for Drupal and its principles. A lot of stress and discussion raised in this time regarding the community choices afterwards again and even forks have started. Drupal Console has tried to fill gaps of Drush and treis to find its gap now between Drush and Composer.

**Composer** is like Symfony a widespread tool on many development projects and therefor not to ignore. Drupal has learned from its isolated position with its own tools in history and tries to adapt tools which are common for developers.

*It's all in all a very basic and flat explanation here. But I wanted to keep it simple yet. There are many details missing and finally all 3 tools have a good reason to coexist IMHO.*

## TL;TR

**Drush =** Command line Devel, **Drupal Console =** Good module and theme creation helper, **Composer =** Maybe *THE* Drupal project installer in the near future (even admin UI implementation discussion occurs atm).

---

**A good source to read about the work on this:** An interesting discussion is going on here regarding Drush pointing same points you have asked about: https://www.drupal.org/node/2906637

---
Tags: 8
---


# Question
Title: How do I import images using the module migrate source CSV?
I'm using the module migrate source csv to import a csv file. I took a look at the page https://www.drupal.org/docs/8/modules/migrate-source-csv/using-the-migra... to understand how to use the module. This is my CSV file.

```
id,title,body, field_image
1,title 1,some body text 1, image_from_the_web.jpg
2,title 2,some body text 2, image_from_the_web.jpg
3,title 3,some body text 3, image_from_the_web.jpg

```

This is my configuration.

```
id: basuuid
label: Import articles
migration_groups:
  - ACME import

source:
  plugin: csv
  # Full path to the file.
  path: '/mypath/to/file/acme_articles.csv'
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  # Field enclosure. Double quotation marks (") by default.
  enclosure: '"'
  # The number of rows at the beginning which are not data.
  header_row_count: 1
  keys:
    - id
  # Here we identify the columns of interest in the source file.
  # Each numeric key is the 0-based index of the column.
  # For each column, the key below is the field name assigned to
  # the data on import, to be used in field mappings below.
  # The value is a user-friendly string for display by the
  # migration UI.
  column_names:
    0:
      id: 'Unique Id'
    1:
      title: 'Title'
    2:
      body: 'Post body'
    3:
     field_image: 'Image'
process:
  title: title
  body: body
  field_image:  field_image
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

```

When I want to execute `drush migrate-import basuuid`, I get this error:

> Call to a member function getFileUri() on a non-object in /drupal/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php

I took a look on other topics to solve my problem, without success.

How do I migrate images?

Thank you

# Answer
You have to create a separate yml for the image config. There's a tutorial here: https://www.mtech-llc.com/blog/ada-hernandez/how-migrate-images-drupal-8-using-csv-source
> 0 votes

---
Tags: media, importing-exporting
---


# Question
Title: How to access fields from a goal when creating a node with Rules?
I'm trying to create a rule with the Rules module that posts a node when users achieve a goal (using the Goals module 7.x-1.3). I want to get fields from the goal like the goal image and other fields, but there's no data selector for the goal completed.

I can't find a way to fetch the completed goal entity. I've tried using a data comparison condition, but it'll only give "goal" data selector without any fields.

Any hints?

# Answer
Have a look at this rule (in Rules export format), which is an example of how to get this to work:

```
{ "rules_show_a_message_after_goal_completion" : {
    "LABEL" : "Show a message after goal completion",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "goals", "rules" ],
    "ON" : { "goal_awarded" : [] },
    "IF" : [ { "goals_goal_condition" : { "goal_id" : "2" } } ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "goal", "id" : "2" },
          "PROVIDE" : { "entity_fetched" : { "goal_fetched" : "Fetched goal" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about the \u0022[goal-fetched:ftitle\u0022 goal which you just completed:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Description\u003C\/strong\u003E = [goal-fetched:field-goal-description]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Category\u003C\/strong\u003E = [goal-fetched:field-goal-category]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Level\u003C\/strong\u003E = [goal-fetched:field-goal-level]\u003Cbr \/\u003E" } }
    ]
  }
}

```

Some details about this rule:

* Rules Event: "***`A goal is completed by a user`***", as in your question.
* Rules Condition: "***`The goal completed by a user`***", a Rules Condition provided by the Goals module (disclosure: I'm its maintainer). In my case, I used the goal with goal id = "`2`" (replace with the goal id that matches your case).
* Rules Actions:
    + "***`Fetch entity by id`***", whereas the entity is a goal, and the id of it is (also) "`2`" (replace with the goal id that matches your case).
    + "***Show a message on the site***", which is just to demo / test some of the field values related to that goal (adapt the machine names of those fields to match your field names).

So by adding the Rules Condition "***`The goal completed by a user`***", and by also adding the Rules Action to "***`Fetch entity by id`***", in any subsequent Rules Action you should have access to all fields of the goal (with the goal id that matches your case).
> 1 votes

---
Tags: rules, 7
---


# Question
Title: How to calculate points for each question of a Quiz and show their total?
I want to build a quiz with points to each question and then sum those points and have a final result.

Example:

### Question 1?

* A. xxxxxxxx (add 0 points)
* B. xxxxxxx (add 1 points)
* C. xxxxxxxx (add 2 points)

and it continues to other questions.

Then, in the end I want something like this:

```
Total points: 20

```

(if the points are between)\[15-20\]: display message !you're awesome

Is this possible to do with Drupal? And how?

# Answer
The Quiz module will allow you to set up a quiz in drupal.

> The Quiz module lets you create graded assessments in Drupal. A Quiz is given as a series of questions. Answers are then stored in the database. Scores and results are displayed during or after the quiz. Administrators can provide automatic or manual feedback.

The module has a node type of quiz, which has "Results Feedback" that you could use to score your results. The multiple choice questions also allow you to set the "score if chosen."
> 0 votes

# Answer
If you're using the 7.x-5.x version of the Quiz module, you can take advantage of all sorts of Rules facilities that are available now. More details on how to get this to work are explained in what follows ...

### Step 1: Use Max Score related to each question

Navigate to relatie path `node/nid/quiz/questions` in your site (with "`nid`" the node id of the quiz), to list all questions for the selected quiz. Then use the column titled "Max score" to enter the amount of *points* you want to be rewarded for each question.

### Step 2: Use Rules to calculate the total points

Have a look at this custom rule (in Rules export format):

```
{ "rules_process_all_answers_at_the_end_of_a_quiz" : {
    "LABEL" : "Process all answers at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_points" : "Total points" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "quiz_result_answer",
            "property" : "result_id",
            "value" : [ "quiz-result" ],
            "limit" : "100"
          },
          "PROVIDE" : { "entity_fetched" : { "answer_fetched" : "Fetched answer" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "answer-fetched" ] },
          "ITEM" : { "current_answer" : "Current answer" },
          "DO" : [
            { "drupal_message" : { "message" : "For the answer with number [current-answer:number] the points awarded are [current-answer:points-awarded]" } },
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-points" ],
                  "op" : "+",
                  "input_2" : [ "current-answer:points-awarded" ]
                },
                "PROVIDE" : { "result" : { "caluclation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-points" ], "value" : [ "caluclation-result" ] } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The total number of points you earned is [total-points:value]." } }
    ]
  }
}

```

This rule will calculate the sum of all *points* earned for each question, and show a set of messages at the end of the quiz which looks similar to this example (in which I used 4 questions):

> For the answer with number 1 the points awarded are 2
>
> For the answer with number 2 the points awarded are 0
>
> For the answer with number 3 the points awarded are 4
>
> For the answer with number 4 the points awarded are 8
>
> The total number of points you earned is 14.

If you have the Rules UI enabled, you should be able to simply import this rule in your own site.

Homework: use the Conditional Rules module to add an additional Rules Action to display your "*awesome*" message also (based on the value of the `total_points` variable.

***Awesome, no?***

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

---
Tags: quiz
---


# Question
Title: Which entity to check in Rules to disallow taking a Quiz after passing it?
I need a way to restrict Quiz access for users who have achieved a passing grade to stop them retaking the quiz to gain more user points.

It displays "*You have already passed this Quiz.*", but I can't find an entity to check for it with the Rules module. Previous quiz result fields always return 0 which makes them worthless. Assigning roles won't work because I want to have quizzes daily.

Any hints?

PS: I'm using Quiz 7.x-5.1

# Answer
Even though the Quiz 7.x-5.x release comes with lots of new Rules capabilities, I've not found any entity to check if a user already passed some quiz. However, using the Flag module you can implement an appropriate flag, and then just check if the quiz node (an entity ...) was flagged by the current user. Read on for how to do so ...

### Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) ***Passed Quizes***. Here is an export of the flag I used for this (you should be able to import it in your own site also):

```
$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

```

This flag will be used in the custom rule, detailed in the next step.

### Step 2 - Flag a Quiz node after passing the quiz

Create a custom rule to flag the quiz node (using the flag from Step 1) after a user passed the quiz and which looks like so (in Rules export format):

```
{ "rules_flag_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Flag a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [], "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      },
      { "NOT flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
      { "flag_flagnode" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

```

### Step 3 - Create a rule to disallow taking a passed quiz again

Here is a rule which illustrates how to resolve the challenge in your question:

```
{ "rules_disallow_taking_a_passed_quiz_again" : {
    "LABEL" : "Disallow taking a passed quiz again",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "quiz-result" ] } },
      { "drupal_message" : {
          "message" : "You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "[quiz-result:nid:url]\/quiz-results" } }
    ]
  }
}

```

Here are the critical pieces of this rule to make Rules-magic happen:

* The Rules Event "After saving a new Quiz result" is what gets triggered right after a user attempts to start taking a quiz (a first time, or another time), so even before the first question of a quiz is shown.
* The first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
* The last Rules Condition, which verifies if the quiz node (to which this quiz result relates) is already flagged (by the flag from Step 1), which indicates this user already passed this quiz.

If all Rules Conditions are satisfied, then these Rules Actions will be executed:

* Delete the newly created "*quiz result*" entity (this is needed, otherwise if the user would try another time to take the quiz, it would be considered as an attempt to *resume* taking the quiz, starting from the very first question, and the used Rules Event would NOT (repeat: NOT) be triggered ...).
* Show an appropriate message.
* Perform a redirect (to show the result summary of the quiz for the current user), to relative path `node/nid/quiz-results` (using `nid` as the node id of the quiz).

Use the Rules UI to import the above 2 rules in your own site, after you completed Step 1.

### Showtime

Here is a sample of a warning message I received after passing a quiz, and trying to take the quiz again:

> You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...
> 1 votes

---
Tags: rules, quiz
---


# Question
Title: Drupal 8: how can I "eager load" Entities referenced via EntityReferenceFieldItemList field
*Note: this is my first Drupal project as I am usually working with Laravel.*

I have some entities `my-nodes` that have a field EntityReferenceFieldItemList (a multi-select linking to other entities of another content type `related-nodes`).

I want to query the `my-nodes` entities together with the related entities in 1 query (in Laravel I would describe this as eager loading the relationship).

The `my-nodes` entities all reference different `related-nodes` entities and I need to access `related-nodes` related values.

I'd like to optimize the amount of calls to the database to possibly only 1.

Method `referencedEntities` does not look like what I need because it's lazy loading, not eager loading:

```
$node->get($field)->referencedEntities();

```

Any idea? Thanks in advance!

# Answer
This doesn't exist in Drupal, you can't load entities of different types at once, the best you can do is load all referenced entities of the same type at once, which is what referencedEntities() does.

Each entity type has its own storage handler which doesn't know anything about other entity types, as far as those handlers are concerned, those other entities might not even be in the database but stored in MongoDB or text files.
> 3 votes

---
Tags: 8, entities, database
---


# Question
Title: if empty statements in views fields or field templates
Normally, my situation is easily solved using views rewrite feature. However, in this case I am unable to use views rewrite because I have data attribute tags in the field wrappers that are stripped out by views. So I need to handle this at the template level. I have no problem with the field data itself, but with the field wrappers. I need to use php if statements in either views-view-field.tpl.php or views-view-field.tpl.php to enclose the wrapper html too along with the field. But i can't figure out the php syntax to use to accomplish this. I need to be able to show the field data plus wrappers if the field has content, but show some empty field without the wrappers if there is no data.

so far i have tried things like views-view-field.tpl.php

```
<?php if ($output): ?>
    <p class="tms-caption font-alt-1 text-medium weight-light color-white hide-on-mobile mb-30" data-animate-in="preset:slideInDownShort;duration:900ms;delay:500ms;" data-no-scale><?php print $output; ?></p>
<div class="clear"></div>
  <?php elseif ($empty($output)): ?>
    <div class="view-empty">
      <?php print $empty; ?>
    </div>
  <?php endif; ?>

```

How can i revise my if statements to it works in either fields or field.tpl.php?

# Answer
First of all, there is no such thing as `$empty` in views-view-field.tpl.php

Second, if you're not printing anything when the output is empty, then there is no need to add an else statement. Thus, this should do the trick:

```
<?php if (!empty($output)) : ?>
    <p class="tms-caption font-alt-1 text-medium weight-light color-white hide-on-mobile mb-30" data-animate-in="preset:slideInDownShort;duration:900ms;delay:500ms;" data-no-scale><?php print $output; ?></p>
<?php endif; ?>

```

The first line means if NOT empty, in PHP `!` = not.
> 0 votes

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


title: Consuming RESTful web services

text:
# Question
Title: Consuming RESTful web services
Is there any existing Drupal 8 module (on drupal.org, GitHub or anywhere else) that would leverage Guzzle to consume JSON and/or HAL+JSON Web Services over REST?

Alternatively, is the recommended way to necessarily write a custom module leveraging the Guzzle HTTP Client that ships with Drupal core?

My end goal is to be able to create a 1:1 relationship to map fields (node, user...) with key/value pairs from RESTful web services. Then I need to be able to read, update or delete those values.

# Answer
> 10 votes
OH, just realized now, maybe I misunderstood the question 100%

This is the code which basically generates the output:

```
$serializer = \Drupal::service('serializer'):
$output = $serializer->serialize($entity, $format);

```

with $format for example being 'json'.

Luckily the serializer is symetric, so you can do the same the other way round.

```
$client = \Drupal::service('http_client');
$result = $client->get('http://example.com/entity/node/1', ['Accept' => 'application/json']);
$output = $result->getBody();

$serializer = \Drupal::service('serializer'):
$entity = $serializer->deserialize($output, 'Drupal\node\Entity\Node', $format);

```

# Answer
> 2 votes
From the HTTP Client Manager module page:

> Http Client Manager introduces a new Guzzle based plugin which allows you to manage HTTP clients using Guzzle Service Descriptions via JSON files, in a simple and efficient way

# Answer
> 0 votes
There is a module "RESTful Web Services" - Exposes entities and other resources as RESTful web API. The guzzle is the standard http **client** used in the Drupal core. "RESTful Web Services" It is modified module "Services" from Drupal 7. It is the **service**. But the idea is the same. To communicate any service with Drupal as a service.

https://www.youtube.com/watch?v=0mTTfCZ8Iac

---
Tags: 8, services
---


# Question
Title: Problem with custom dropdown default value
I've written a module that allows users to alter the display of a Date/Time object by allowing them to change their timezone via a front-end block.

It does it's primary function properly, changes the time display as expected, however, what is supposed to happen is that once you pick a timezone, the page reloads, and the dropdown form will default to the timezone you selected. Except it doesn't, it stays on a single default value

The array is the #options list for the dropdown item, and the single item underneath is the #default\_value key for that dropdown.

As you can see, the default value should be set to Australia/Melbourne, but in the dropdown it's not, it's set to America/Creston Mountain time.

I cannot figure out what's going wrong, have I done the default value code incorrectly or something?

**EDIT**

This is the code for the select element

```
$timezone = mymodule_timezone_get_user_timezone();
$options = variable_get('mymodule_timezone_select', system_time_zones());
$options = array_filter($options);

// doing a dpm($timezone) comes back with Australia/Melbourne
// doing a dpm($options) comes back with the arrow shown above

$form['timezone_select'] = array(
  '#type' => 'select',
  '#title' => '',
  '#options' =>  $options,
  '#default_value' => $timezone,
  '#prefix' => t('<div class="description">Please select your timezone from the drop down box below and click update to convert your viewing times accordingly.</div>'),
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Update') ,
);

```

And the code referenced in this snippet

```
function mymodule_timezone_get_user_timezone() {
  $retrieved_timezone = session_cache_get('mymodule_timezone_user_timezone');
  if (empty($retrieved_timezone)) {
    $retrieved_timezone = drupal_get_user_timezone();
  }
  return $retrieved_timezone;
}

```

The variable for 'mymodule\_timezone\_select' is just from the default system\_time\_zones() but the admin has been given the option to delete ones they don't want the user to see (since they are several hundred options by default)

# Answer
Managed to figure out what was wrong, and my own apologies to those who tried to help me, it turns out that the culprit was with the caching settings for my custom block, which wasn't something I'd included in the description of the question.

Originally my block\_info code looked like this

```
function mymodule_timezone_block_info() {
    $blocks['mymodule_timezone'] = array(
        'info' => t('Timezone'),
        'cache' => DRUPAL_CACHE_PER_USER,
    );
    return $blocks;
}

```

Which should in my mind have been the correct setting, since I wanted it to cache the users response. The weird part is that it *did* work locally like this, and the same code even worked on another site, on the same server, with the same drupal caching/session caching settings etc.

The correct solution was to do this instead

```
function mymodule_timezone_block_info() {
    $blocks['mymodule_timezone'] = array(
        'info' => t('Timezone'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $blocks;
}

```

Again, apologies to those who tried to help and couldn't, it's my fault for not including all parts of the block setup in the original request.
> 0 votes

# Answer
Are you providing `#default_value` when loading form? If yes, you need to make sure that you're providing what is selected by user first. Check example below:

```
global $user;
// Check if user has set the timezone,
// if yes use that else set to default 'America/Creston'

$timezone = isset($user->timezone) ? $user->timezone : 'America/Creston';
$form['timezone'] = array(
  '#type' => 'select',
  '#title' => 'Select Timezone',
  '#options' => $options,
  '#default_value' => $timezone,
);

```

As per Form API Reference Documentation, it says `#default` value is:

> The value of the form element that will be displayed or selected initially if the form has not been submitted yet.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to access the order amount without tax in Rules?
I have a rule which adds a percentage of the order amount to the shipping costs.

I use "commerce-line-item:order:commerce-order-total:amount" as the base price.

But unfortunately this amount has the tax (21%) in it.

How do I get the total amount in my rule without the tax in it?

# Answer
> 0 votes
I solved it using the `commerce_price_components` module. Some details about it (from its project page):

> Extension to Drupal commerce that provides a price formatter to enable/disable price components such as discounts or taxes when displaying prices. This gives the admin absolute control over which components should be displayed and which shouldn't.
>
> It also provides two Views handlers to display/hide price components in cart totals and order totals.
>
> Additionally it has basic rules support that gives to the commerce administrators the ability to do conditions using price components such as discounts or taxes and react accordingly.

It gave me a new data selector, i.e `site:current-cart-order:commerce-order-total:base-price:amount`, which was exactly what I needed.

---
Tags: commerce
---


# Question
Title: How do I get the output of a single field?
How do I get the output of a field of a node? I have some weird subpage construct using entity references (one 'main' node and a few 'sub'-nodes).

Each of these nodes have a header image to be displayed above the content. What I am trying to do is for the sub-nodes to 'inherit' the header image of the main node.

I implemented `hook_node_view` and I have got the node, I just don't know how to build the renderable array for it.

```
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($view_mode == 'full'){
    if((!isset($build['field_headerimage']) || !isset($build['field_headerimage'][0])) && $entity->hasField('field_location')){
      $location = $entity->get('field_location')->referencedEntities();
      if(is_array($location) && isset($location[0])) {
        $node = $location[0];
        dsm('yay, now what?');
        dsm($node->label());
      }
    }
  }
}

```

# Answer
> 0 votes
The answer to my own question seems to be like so:

```
$build['field_headerimage'] = $node->get('field_headerimage')->view();

```

---
Tags: nodes
---


# Question
Title: How to write page.tpl.php where the HTML files is more than one?
I'm using Drupal 7 and trying to set my custom theme up.

I usually replace the `index.html` to `page.tpl.php`, then I change what I want it to be dynamic on my site. But now I have more than one HTML file which is about.html, blog.html and contact.html

Can anybody explain to me how to write that?

# Answer
> 0 votes
Actually you may have to create a page--front.tpl.php for index page of your website and a page.tpl.php to have all other pages.

you could also use theme debug mode too. it can be enabled by including the following in settings.php,

**$conf\['theme\_debug'\] = TRUE;**

The ablove will include theme suggestions as html comments, that helps you theming your pages.

# Answer
> 0 votes
Simply create a file with the name "page.tpl.php". Below is the structure of how a theme folder should look like:

For further details read here.

---
Tags: theming
---


title: Drush bootstrap level error

text:
# Question
Title: Drush bootstrap level error
Im running onto some issues with Drush. I worked with php 5.3 and after upgrading to 5.5, i ran into some issues and decided to downgrade my PHP version back to 5.3. Now im running into the issue that Drush isnt working anymore.

```
Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment [error]
to run this command.
The drush command 'cc all' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                     [error]
Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.28
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : 127.0.0.1
  Database username : root
  Database name     : drupal_practice2
  Default theme     : garland
  Administration theme: garland
  PHP configuration :
  Drush version     : 4.5
  Drush configuration:
  Drush alias files :
  Drupal root       : /var/www/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.

```

Ive been searching on google for almost 3 days now and re-installing my computer would be a lot faster. I have lots of data so i dont want to re-install.

Someone that can help me with the solution?

# Answer
> 0 votes
Your problem is that Drush is running the PHP version that you have installed for your hosting environment (and Drush's own php.ini). You need to get Drush to run its own PHP that it installs with.

What host are you running on? If it is Windows then open a console and type set. That will show you the environment variables that you are using for your account. If there is a PHP variable in there, note it's contents and delete it by issuing the following command in the command windows: set PHP=

If that doesn't work set it back to what is was before. Any other platform I cannot help you with.

Also check this post: Modifying the PHP or PHP configuration that drush runs under

# Answer
> -1 votes
Before doing anything time-consuming just go to the root of the directory and then run the command again.

Run from here at Drush console: /var/www/drupal

---
Tags: drush
---


# Question
Title: Is alternative available in back end for drush migrate-import "ID"?
I have been migrating the contents using the migrating source csv, tools and plus modules

As followed the instruction, I have to use the drush command **drush migrate-import 'ID'** to complete the migration process.

Is there any option available in backend instead of using the drush command.

# Answer
> 1 votes
We can achieve this, without using the Drush Commands

> drush migrate-import 'ID'

After the import process,

```
$migration = "Migration ID"
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();

```

If you dont want to use Drush Commands, then Create the custom module and use this above command.

---
Tags: 8, importing-exporting
---


# Question
Title: How to implement a Rules Condition like [account:last-login] = never?
**Here is my contextual explanation**:

I would like to redirect on a special page for first time after login. But registering system is using an email validation, so the path to the first login is "user/reset/uid/\*", which brings the user to its profile page to save a password when the user clicks the one-time login button. This is fine and using a redirect after register of any kind is overriding it, which I don't want to. So I'm looking for a data comparison with the Rules module.

**My question**: How can I compare as a condition with rules `[account:last-access]` or `[account:last-login]` with something that would say `never`?

**The rule would be this:**

* Rules Event : After updating account (because of the one-time login password change)
* Rules Condition : `[account:last-login]` = `never`
* Rules Action : redirect toward my special welcome page

These are the modules used:

* rules
* reference with user reference sub-module
* ajax register (which usefully rewrite login to home)

# Answer
It looks that what you're trying to do implement (= do a data comparison with "never") is not an obvious thing to do. Therefor, you may want to go for a plan-b that, for sure, will implement what you're trying to achieve, i.e. "*... redirect on a special page for first time after login ...*" (as in your question). Read on for more details.

Create a custom rule that looks like so (in Rules export format, use the Rules UI to import it in your own site):

```
{ "rules_redirect_new_users_to_special_page" : {
    "LABEL" : "Redirect new users to special page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
      { "redirect" : { "url" : "welcome\/newuser" } }
    ]
  }
}

```

Some details about this rule:

* Rules Event: User has logged in.
* Rules Condition: User does NOT (!!!) have a role with role id = "`4`".
* Rules Action:
    + Grant User the role with role id = "`4`".
    + Perform a page redirect to relative path `welcome/newuser`.

So this rule checks if a user does not yet have some (designated) role with role id = "`4`" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case then the user is granted that role, followed by a page redirect to relative path `welcome/newuser` (adapt to whatever path that fits your case). Obviously, next time a user performs a login again, the Rules Condition will no longer be TRUE, and no more redirect will be performed.

Pretty similar to "*... redirect on a special page for first time after login ...*" (as in your question), no?

### Variation

What is explained before in this answer, does require some extra (dedicate) role. If you rather want to keep the number of roles in your site to a minimum, you could also use the Flag module (as an alternative for such extra role). Some more details about this variation:

* Define a "*global*" flag to flag users
* Replace the Rules Condition (to check for the dedicated role), by another one like "Check if the user is NOT flagged" (by the global flag).
* Replace the Rules Action (to grant the dedicated role), by another one like "Flag this user flagged" (by the global flag).

***Voilà*** ... use the solution you prefer, either one will do ...
> 2 votes

# Answer
Unless your site has been running since before 1970, I think you're fairly safe to compare them with zero.

The `login` and `access` columns of the `users` table both have a default of zero, so values will be zero for new users that haven't logged in/accessed the site yet.
> 0 votes

---
Tags: 7, users, rules, redirection
---


# Question
Title: How to call a view in a twig.template not page
I don't find good info on how to call for an existing view in a particular twig.template (NOT the PAGE.HTML.TWIG!!!!).

The systemname of my view is this: testfeest

So I find sollutions online and tried them:

1. {{ testfeest }} not working
2. {{ content.testfeest }} not working
3. {{ view.testfeest }} also not working

Keep in mind that:

* I don't want to create a extra block of region for this
* The view will be placed not in the page template but a node template

Hope somebody can help me... Thanks for reading. Kristof

# Answer
> 1 votes
One very simple method is to install the Twig Tweak module and use:

```
{{ drupal_view('testfeest', 'display_id') }}

```

# Answer
> 1 votes
You can also create a new variable for the template in question and use views\_embed\_view:

```
function mytheme_preprocess_node(&$variables) {
  // check for node type...
    $variables['myview'] = views_embed_view('view_id', 'display_id', $args);
  // endcheck
}

```

Clear the cache, then in the node twig you can output it:

`{{ myview }}`

---
Tags: views, theming, 8
---


# Question
Title: Accessing values of unknown field types when using entity_metadata_wrapper
I've been looking into using the Entity Metadata Wrapper classes (defined by the entity module in Drupal 7) to access field values, as this seems to be a clean way of doing so.

There a couple of things that make this a bit awkward however. Assume I have a wrapper for a content type that defines a field named `field_something` as such:

```
$wrapper = entity_metadata_wrapper('node', node_load($nid));
$value = $wrapper->field_something->value();

```

The first problem I have is that I have no way of knowing before hand whether what I get is an actual value (a string, an entity, etc.), another metadata structure wrapper (when fields have multiple values) or an array (when fields have multiple properties).

I have found a way to answer those questions using the `info()` method:

```
$info = $wrapper->field_something->info();
$is_multi_value = (strpos($info['type'], 'list<') === 0);
$has_multiple_properties = isset($info['property info']]);

```

However that is hardly practical. Whenever I want to use a field without knowing it's definition before hand, I must take into account several cases. This makes my code quite heavy.

In order to deal with this I have written some code which:

1. Ensures we always get returned an array, even if it's a single value field ;
2. When there are multiple properties, return the value of the first column.

Point 1. here will always work, unless the caller want to know whether this was a single value field or not. Point 2 works in some cases, not all, but is convenient when it applies.

Here is the code:

```
function entity_metadata_simple_values($field) {
  $fields = array();
  $values = array();
  $info = $field->info();
  if (strpos($info['type'], 'list<') === 0) {
    foreach ($field->getIterator() as $field_iteration) {
      $fields[] = $field_iteration;
    }
  } else {
    $fields[] = $field;
  }
  foreach ($fields as $final_field) {
    $ff_info = $final_field->info();
    if (isset($ff_info['property info'])) {
      $column = reset(array_keys($ff_info['property info']));
      $values[] = $final_field->{$column}->value();
    } else {
      $values[] = $final_field->value();
    }
  }

  return $values;
}

```

So my question is: are there simpler/better ways to address this problem of getting values from the metadata wrapper when the field type is not known ?

# Answer
So as no one has come up with another solution, I will answer my own question:

There **isn't** a simpler way to access values of unknown field types when using entity metadata wrappers.

There are alternative methods to the one I initially described (for instance those pointed out by @thepearson). In particular this method is useful:

```
 entity_property_list_extract_type($type)

```

It will return the listed type if your type is a list (eg. 'integer' if your type is 'list\<integer\>'), or false if your type is not a list. Internally it does a strpos just like the code I initially posted, but I guess it's more future proof.

The conclusion is that:

* Entity metadata wrappers work well if you have no idea of your field types, and want to carefully address each possible case ;
* Entity metadata wrappers work well if you know exactly what types your fields are, and you want to use them ;
* If you have only some ideas of what your field types are like (for instance all text, but you don't know if they are formatted or not, and you don't know if they are single or multi valued) then Entity metadata wrappers do not provide any short-cuts and you need to write your own as I did in the initial question.
> 3 votes

# Answer
Here are a few suggestions to make this process a little easier.

```
$wrapper->field_something->type();

```

will return the type of the field, ie `node`, `taxonomy_term`, `integer`, `text` etc. You could then handle the value returned from `$wrapper->field_something->value()` correctly.

Also

```
$wrapper->field_something->raw()

```

will return the raw value of the field. Which will either be an `array` in the case of multi valued fields of just the value. For instance an `entity_reference` will be the `nid` (or entity id) of the referenced entity, or an `array` of referenced entity id's.
> 4 votes

# Answer
For the single/multiple field check I've found it useful to test the wrapper object's type, which will be `EntityListWrapper` for a multi-value field and `EntityValueWrapper` for a single-value field:

```
<?php
...
$wrapper = entity_metadata_wrapper('user', $account);
// Get address, or first address if a multi-value field instance.
if (get_class($wrapper->field_address) == 'EntityListWrapper') {
  $value = $wrapper->field_address[0]->value();
}
else {
  $value = $wrapper->field_address->value();
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Is there a way to Embed Facebook Videos?
D7.37:

I am Trying to embed Facebook Videos and cannot find a way to do it.

Points:

1. Have already installed: Media-Module, Oembed, Media-YouTube, but cannot get Oembed to actually embed anything.
2. The Media-YouTube works; I can embed YouTube Videos.
3. I can embed SoundCloud Audio.
4. I can embed Flickr Images.
5. I cannot get anything Facebook related to embed.
6. Is this even possible in D7?
7. I tried downloading the Video-Lightbox software, but it would not take URL's from Facebook.

When I try to “cut & paste” the Facebook URL into the Video-Light-Box software, the URL seems to be loading then just terminates producing nothing. If I do the same thing with a YouTube-Video an actual file is embedded.

When I try to embed the Facebook URL via the Media-Module-Browser, I get an error “SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'oembed://https%3A//www.facebook.com/AnimalsAustralia/videos/1015' for key 'uri'”; however the file brokenly loads and then is only available as a Link to Facebook NOT an Embed.

When I try to embed the Facebook URL via the WYSIWYG-Editor-AddMedia Button, either as a new Facebook URL or an entry from the Media-Library, a small Icon appears which is also only a Link and not an Embed.

When I try to embed the Facebook URL via the WYSIWYG-Editor-AddMedia Button, but wrapped in \[embed\] {Facebook URL} \[/embed\] tags, I receive an “Unable to handle the provided embed string or URL” error message.

BTW I have scoured the settings to be sure that "Rendered-File" is selected in the Media-Display settings of this Content-Type. I have a Content-Type set up specifically for handing Media and configured to allow Remote Media Types of Video.

What might I be missing?

# Answer
> 1 votes
I was able to embed facebook, youtube and vimeo videos in a view using just the following:

1. Drupal version: 7.54
2. Media Module version: 7.x-2.0-rc5
3. Media: oEmbed Module version: 7.x-2.7
4. Entity view modes module: 7.x-1.0-rc1 // optional

Facebook URL: https://www.facebook.com/video.php?v=10153231379946729

Try the above URL format. If the video still won't embed, then it's probably the configuration.

---

My media field in the content type is setup as follows:

1. Field Type: File
2. Widget: Media Browser
3. Enabled browser plugins: Upload and Web
4. Allowed file types: Image and Video
5. Allowed URI schemes: oEmbed resources and Public files
6. Allowed file extensions for uploaded files: png, gif, jpg, jpeg

Note this field supports both images and videos.

---

Then you need to setup your file display for videos here:

/admin/structure/file-types/manage/video/file-display

I used the Entity view modes module to create a a new view mode for this field. Then I selected the oEmbed formatter for my view mode.

---

Then in the view, select the Rendered file formatter and the view mode you created.

---

Then when creating the node, try the above url.

---
Tags: files, nodes
---


# Question
Title: How to assign "Access Results" permission per Webform?
On Drupal 7, my client would like to give a user to see a particular Webform's "Access Results". How can I assign the "Access Results" permission per Webform, beside using "Permissions per Webform"?

# Answer
> 2 votes
Sounds like you need Permissions per Webform module

You can set permissions per Webform as it suggests. Under the form settings.

# Answer
> 1 votes
Try Webform access granular module. This allow you to specify a specific user(s) per webform.

---
Tags: webforms
---


# Question
Title: Bulk import select element options of a Webform from CSV
I am using the Webform 8.x-5.0-beta16 module in Drupal 8.

I added a select field in which I would like to set around 250 options.

Is there a way to easily import these options from a CSV?

# Answer
It's easier to enter the values editing the webform via Source(YAML).

The CSV values can be easily processed into a format such as " 'label': 'value' ". Then when editing YAML source it's just a list you can Copy & Paste.

For the record, it would end up looking like this (and so on):

```
select_field:
 '#type': select
 '#title': 'Title'
 '#options':
   'label1': 'value1'
   'label2': 'value2'

```
> 2 votes

# Answer
You can also use `hook_webform_options_alter()` or `hook_webform_options_WEBFORM_OPTIONS_ID_alter()` to dynamically populate options.

See https://git.drupalcode.org/project/webform/blob/HEAD/webform.api.php#L108 for more info.
> 0 votes

---
Tags: 8, webforms, importing-exporting
---


# Question
Title: Drupal 8: Form fields are not updating when checking triggering element
I have added a button to the node add form which allows the user to import data from the last node created into this one. Within hook\_form\_alter, I have:

```
// Import previous month's data if requested
$trigger = $form_state->getTriggeringElement(); //Check to see if button pressed

if ($trigger['#name'] == 'import_previous') {
  $id = \Drupal::request()->query->get('field_patient'); //grab node id from url
  $previous = st_access_patient_get_previous($id); //grab actual node
  $previous_array = $previous->toArray(); //cast node to array

  // Match up data from previous node to fields in this form, set default value
  foreach ($previous_array as $label => $field) {
    if (substr($label, 0, 5) == 'field' && $form[$label]['#access'] == TRUE) {

      if (array_key_exists('#default_value', $form[$label]['widget'])) {
        if (array_key_exists('target_id', $field[0])) {
          $form[$label]['widget']['#default_value'] =  $field[0]['target_id'];
        } else {
          $form[$label]['widget']['#default_value'] =  $field[0]['value'];
        }
      } else {
        if (array_key_exists('target_id', $field[0])) {
          $form[$label]['widget'][0]['value']['#default_value'] = $field[0]['target_id'];
        } else {
          $form[$label]['widget'][0]['value']['#default_value'] = $field[0]['value'];
        }
      }

    }
  }

}

$form['previous_import'] = [
  '#type' => 'button',
  '#name' => 'import_previous',
  '#value' => t("Import the previous month's values"),
  '#weight' => -9999,
  '#submit' => ['import_previous_submit'],
];

```

My understanding is that the button will just submit the form, I don't actually need

```
'#submit' => ['import_previous_submit']

```

When pressing 'import\_previous' button the field values are not updated. If I remove the conditional (which just runs the replacement logic on every form load) then everything works fine. So, I know my logic for the replacement itself is correct. But once I wrap my replacement logic in:

```
if ($trigger['#name'] == 'import_previous') {}

```

Then the fields no longer update when the button is pressed. The conditional passes, so I know that is correct. Something else is keeping the form default values from being set. I have tried to add:

```
  $form_state->setRebuild(TRUE);
  $form_state->setCached(FALSE);

```

after:

```
$trigger = $form_state->getTriggeringElement();

```

and directly before the final closing tag of the conditional. I have also tried to add it to a submit function 'import\_previous\_submit'. No love with any of that. Any help is greatly appreciated.

# Answer
You don't need to check the triggering element if you use it's own submit handler because the submit handler is only triggered by this element.

```
function your_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['previous_import'] = [
    '#type' => 'submit',  // changed to submit
    '#name' => 'import_previous',
    '#value' => t("Import the previous month's values"),
    '#weight' => -9999,
    '#submit' => ['import_previous_submit'],
  ];
}

function import_previous_submit(&$form, FormStateInterface $form_state) {
  // Example of altering / setting the field values. You have to adapt your foreach stuff.
  $user_input = $form_state->getUserInput();
  $user_input['title'] = [['value' => 'test']];
  $form_state->setUserInput($user_input);

  $form_state->setRebuild();
}

```
> 2 votes

# Answer
Sorry, I forgot that when submitting a form that 'default\_value' is no longer in play, I need to be using 'value'. Have been looking at this for too long.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Migrate API - Multiple multi language images in nodes
I am using "**migrate api**" for migrate content from another database (not drupal database).

I need migrate multilingual content with multiple images associated where alt and title are also multilingual.

How must I build this migrate yml for the images?

I have the next config for a unique image file:

```
'field_image/target_id':
    plugin: migration
    migration: news_image
    source: file
'field_image/alt': 'alt text'

```

but I don't know how build this config for save multiple values instead one. I searched for examples and in documentation but I didn't find anything similar.

I don't need a manual, only a orientation of how must be the configuration.

Thanks!

# Answer
In the end, it was easy. Just follow the steps below:

1. Import files (only files, without alt and title)
2. Import content. For the field of image must have all the identifiers of the images and the alt and title. It is necessary to use the iterator plugin.

---

```
  field_images:
    plugin: iterator
    source: IMAGESVAL
    process:
      target_id:
        plugin: migration
        migration: news_images
        source: fid
      alt: alt
      title: alt

```
> 0 votes

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


# Question
Title: How can I configure the search engine to search by dates? Drupal 7
I am new using drupal and I am creating a website for renting various items. I need the searcher to give me as a result the available articles between 2 dates, that is, the user searches for items that are available between 2 dates, for example, I am looking for an amplifier that is available between September 11th and Augus 2th.

Please help me. Thanks.

# Answer
You have not mentioned is it drupal 7 or 8 If it is drupal 7 i think it will help you. First you install date module. You can add a date field with a start and an end date. Other than that the rest is simple. Go to your view and add two filters.

First filter will be your start date where the field is "less than or equal to" -\> "now" you can write that only if you select "enter a relative date"

Second filter as you may have guessed will be your expire date field where the field is "is greater than or equal to" -\> "now"

If "less than or equal to" and "greater than or equal to" don't appear as options, make sure you've enabled the Date Views module. (It is installed as part of the Date project.)
> 0 votes

---
Tags: 7, search, datetime
---


# Question
Title: How to change drupal views filter from string to in opreator
```
/**
 * Implements hook_views_data().
*/
function ***_views_data_alter(array &$data) {
  $data['content_moderation_state_field_data']['moderation_state']['filter']['id'] = 'content_moderation_state_select';
}

/**
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("content_moderation_state_select")
 */
class ModerationStateFilter extends InOperator {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  /**
   * Helper function that generates the options.
   * @return array
   */
  public function generateOptions() {
    $workflow = \Drupal::entityTypeManager()->getStorage('workflow')->load('editorial');
    $destinations = $workflow->getStates();
    $options = [];
    foreach ($destinations as $item){
      $options[$item->id()] = $this->t($item->label());
    }
    return $options;
  }
}

```

This works fine on config views,but can't save views conrrect.

# Answer
Add filter value schema file in your module config/schema dir works fine. \***.views.schema.yml

```
# Schema for the views filter value.
views.filter.content_moderation_state_select:
  type: views.filter.in_operator
  label: 'Moderation state'

views.filter_value.content_moderation_state_select:
  type: views.filter_value.in_operator

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Twig invalid render array keys from a valid array
In hook\_preprocess\_menu I am creating an array to send to the menu twig tpl (eventually it will be entity paragraph data but for now they are hard values as examples). However, I just receive array key invalid errors. How should this be formatted correctly for the template?

```
function hook_preprocess_menu__main_menu(&$vars) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if($node->field_menu_highlights){
    $highlight_values = $node->get('field_menu_highlights')->getValue();

    foreach ($highlight_values as $key => $item){
      $ent = \Drupal\paragraphs\Entity\Paragraph::load($item['target_id']);
      $vars['highlight'][$key]['title'] = 'Title here';
      $vars['highlight'][$key]['desc'] = 'Description here';

    }
  }
}

```

The template:

```
{% for value in highlight %}
    {{ value }}
{% endfor %}

```

Error eg:

```
User error: "title" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

```

# Answer
Build the array with renderable children:

```
  $vars['highlight'][$key] = [
    'title' => [
      '#markup' => 'Title here',
    ],
    'desc' => [
      '#markup' => 'Description here',
    ],
  ];

```

Now the loop to render each value separately should work or have the same result by rendering the complete render array:

```
{{ highlight }}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Preprocess image: how to get parent entity?
I'm using responsive images (single `img` tag with `srcset` and `sizes` attributes). My content editors can manipulate the displayed size of the image with a custom field on a shared parent entity. Therefore I can't meaningfully use the sizes field from the responsive image module, because my editors can set the image size from 10% of a fixed container up to 100vw on per paragraph level.

I know how to preprocess the sizes attributes, but I don't know how to get to my shared parent entity, which holds the field determining the size of the image's parent container:

```
function template_preprocess_responsive_image(&$variables) {
  // pseudocode: don't know how to this
  $imageField = $variables['whatever'];
  $parentParagraph = $imageField->getParentMediaEntity()->getParentParagraphEntity();
}

```

My question is how do I get the parent paragraph entity as written above in pseudocode?

# Answer
> 8 votes
Here is the the "real" code counterpart to the pseudecode from the question:

```
function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  // get the imagefield's parent entity
  $fieldParent = $variables['item']->getEntity();

  // this line is only needed if using media entities (= entity references)
  // must disable entity view caching to work correctly
  $fieldParent = $fieldParent->_referringItem->getEntity();

  // get the image width from the custom field
  $myImgSizes = $fieldParent->get('field_image_size')->getString();
  // can't change attribute here => store it temporarily
  $variables['responsive_image']['#attributes']['data-overridesizes'] = $myImgSizes;
}

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //override sizes attribute with my calculated value
  if (key_exists('data-overridesizes', $variables['img_element']['#attributes'])) {
    $variables['img_element']['#attributes']['sizes'] = $variables['img_element']['#attributes']['data-overridesizes'];
    unset($variables['img_element']['#attributes']['data-overridesizes']);
  }
}

```

If using media (=entity references) you also have to disable view cache for entites (see this question)

```
function MODULENAME_entity_view(&$build, $entity, $display, $view_mode) {
  if ($entity->getEntityTypeId() == 'media' && $entity->bundle() == 'image' && $view_mode == 'my_uncached_viewmode'){
    unset($build['#cache']['keys']);
  }
}

```

---
Tags: 8, entities, media, theming
---