# Question
Title: Remove "Password reset instructions" hint on reset you password page?
Could not find any hooks or templates for it.

# Answer
You want to use `hook form alter` like this:

```
function mymodule_form_alter($form_id, &$form) {

  if ($form_id == 'user_edit') {
    $form['fieldname'] = '';
  }
}

```

If you install devel and kint, then you kan `kint($form)`, to see what the fieldname is.
> 1 votes

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


# Question
Title: Notice: Undefined offset: 14 in user_node_load() (line 3682 of modules/user/user.module)
I'm getting the following error:

Notice: Undefined offset: 14 in user\_node\_load() (line 3682 of modules/user/user.module).

What fields in the db do I need to alter to fix this? I've tried "users" table, creating new admin and altering the UUID to 1 as I thought this would fix it, but no.

Can anyone offer any advice of how to fix this?

Many thanks

# Answer
> 1 votes
You're either trying to load node 14 or user 14 and that doesn't exist.

# Answer
> -1 votes
This happened when you exported the content to another installation and viewed the content - the new install was looking for the same user id that created the content on the original site.

Solution - Create a new user and update author in corresponding node.

---
Tags: users
---


# Question
Title: Is it possible to use drush migrate-import to import custom fields?
I am trying to migrate a Drupal 7 site to Drupal 8 on a new server I have copied the db so it can be used locally. I have run the drush migrate command and migrate-status shows a bunch of things that are ready for import. I can import users with drush migrate-import d7\_upgrade\_users. However the users have custom fields associated with them and I can't find how to import those fields through drush. Trying to export a csv from the old host is virtually impossible as it crashes out trying to do the export.

Is it possible to import all user data including passwords and custom fields from the command line using drush (or other command line tools) without the need to import everything?

# Answer
I am currently working on a similar migration and had a similar problem. In my case the custom fields were part of the Profile2 module in D7. I installed the D8 Profile module and added a patch that fixes the Profile2 import

https://www.drupal.org/files/issues/2018-05-16/profile-migrate-from-profile2-D8-2957256-4.patch

After that, the custom fields were automatically created, populated and linked to the correct user.

Not sure if that is what you need.
> 0 votes

---
Tags: users, drush, migrations
---


title: How to create a sponsors logo block?

text:
# Question
Title: How to create a sponsors logo block?
I have some experience with Drupal 7, but not that much. Now I'm working on my first Drupal 8 website and stumbled over the following situation:

In a first iteration, the website should use the default theme and should be as drupal-ish as possible in its solutions. One requirement is, that I have a list of 5 "sponsor logos" that should appear on the frontpage and the imprint. They should all appear in the same height and in one row (on a desktop browser and probably break on mobile).

Due to the fact that they should appear on different pages, I guess, I want to create a block for this. But what would be the most Drupal way, to add this row of logos to this block?

Just adding pictures in the editor feels a bit "undrupalish" and it seems to be meant for only one image. Adding code by hand and adding the addresses of the images feels a bit like "Why am I actually using a CMS?"

I hope my question is precise enough to get some input.

# Answer
> 1 votes
A proper way IMO is a “Sponsor” Entity content type with the Fields you need, then create as many Sponsors as you need. Then use Views to create a Block display and select all published Sponsor content and output it as needed. Then place the block in the desired region. Later you may want to expand on sponsors and add more structured data around them, which is why you'd have a content type (or custom entity type) over just a single-use block type.

# Answer
> 0 votes
You could create a custom block type with an image field and its cardinality would be 5, in this way you can:

* Require the 5 images to be mandatory
* Use image styles to optimize the images
* Use responsive images to optimize for mobile
* Use a twig template to avoid errors in the markup and streamline the deployment of adjustments in the future (via code push).

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


# Question
Title: When the admin changes(Add/Remove) roles of the user, how to get assigned and removed roles of that user?
There are more than 20 user roles(Editor,approver,new admin..) in the project. Whenever the admin assign/delete the role to user then the user should be notified with email. Email should say Hey Prabhakar You have been assinged to following roles or you have been removed from following roles.

# Answer
> -1 votes
Implement `hook_user_presave`:

```

/**
 * Implements hook_user_presave()
 */
function yourModuleName_user_presave(&$edit, $account, $category){
  foreach ($account->roles as $role_id => $val) {
    $user_roles_existing[] = $role_id;
  }
  foreach ($edit['roles'] as $role_id => $val) {
    // $edit['roles'] contains all roles ids as key and selected role id as val. If not selected then value is 0
    // ex. $edit['roles'] = array(5=>5, 6=>0) here role id 5 selected
    if ((int) $val > 0) {
      $user_roles_form[] = $role_id;
    }
  }
  $user_roles_new = array_diff($user_roles_form, $user_roles_existing);
  $user_roles_removed = array_diff($user_roles_existing, $user_roles_form);
  //roles added
  if (count($user_roles_new) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing new roles count' . count($user_roles_new));
  }
  //roles removed
  if (count($user_roles_removed) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing Removed roles count' . count($user_roles_removed));
  }
}

```

---
Tags: users
---


# Question
Title: How can I install Drush without Composer?
I've been trying to install Drush for a while but have failed. I have no experience in command line applications.

I've seen quite a few tutorials:

but each one says that Composer is required. The catch, I can't seem to get Composer to work either.

Would I ever be able to install Drush, but still work around installing Composer?

Specifications:

1. Windows 10
2. Drupal 8.1.8
3. Cpanel 56.0.33
4. Php 5.59 (or higher according to this)
5. Composer Manager 8x-10-rc

# Answer
This is the simplest solution I have found.

If you don't want to use composer, follow the instructions here...

https://sharpi.sh/blog/web-development/install-drush-on-ubuntu-quickly-without-composer/

1. Download a Drush release from Github to user folder

`wget https://github.com/drush-ops/drush/releases/download/8.1.17/drush.phar`

2. Rename drush.phar to drush

`mv drush.phar drush`

3. Find the bin directory

`echo $PATH`

which shows something like.... /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

I’ll go with /usr/local/bin

4. Move drush to the bin

`mv drush /usr/local/bin/drush`

5. Change permissions to

`chmod +x /usr/local/bin/drush`

6. Test with

`drush version`
> 6 votes

# Answer
Just follow the installation instructions on http://docs.drush.org/en/8.x/install/ No need for Composer to use Drush 8.

PS! Drush 9 is meant to be installed site local - as part of your Drupal installation - using Composer.
> 1 votes

---
Tags: drush, composer
---


# Question
Title: field_type with existing data cannot have its keys changed
our site is throwing up the following error:

```
A list field (field_type) with existing data cannot have its keys changed. in list_field_update_forbid() (line 363 of /modules/field/modules/list/list.module).

```

I've already researched and found on the drupal developer site a documentation about this error: https://drupal.org/node/1294264

But honestly I don't know what to do.

Has anybody an idea?

Thank you and best wishes

Chris

# Answer
> 9 votes
Try to delete the specified config file:

`drush config-delete <name of the config to delete>`

and than import the config again:

`drush cim`

# Answer
> 2 votes
If anyone else comes across this, Double check the "Allowed Values" of the features field in question against what is listed in the site you are overriding. In my case, fixing the discrepancy there sorted everything out. Essentially, the values in the features export didn't include an option that was added, and referenced in the DB by a node.

# Answer
> 0 votes
Expanding Michiel's answer... This worked for me in Drupal 8, assuming you've got your config exported before making changes. I was able to edit the config file with new Allowed Values then delete and re-import. Old nodes retained the previous values, new and edited nodes get the new choices.

Edit the config file.

Then delete the config with drush

`drush config-delete <name of the config to delete>`

Then import the config again:

`drush cim`

---
Tags: entities
---


# Question
Title: Can I get the absolute path to the frontpage in theme_preprocess_html?
Is it possible to get the absolute path to the homepage or `<front>` eg: `https://www.domain.com/homepage` in the `theme_preprocess_html` hook? I tried `global $base_url` but it throws an error.

# Answer
> 4 votes
I used `\Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]);` from one of the comments in:

How to get the base URL of a site

Here is the entire working snippet:

```
/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {

  // Modify if we're on nodes
  if ($node = \Drupal::request()->attributes->get('node')) {
    // Get the node-type
    $nodetype = $node->getType();
    // Switch class for node-type
    switch ($nodetype) {
      case "landing":
        // prefetch frontpage from landing pages
        $frontpage_path = \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]);
        $prefetchfront = [
          '#tag' => 'link',
          '#attributes' => [
            'rel' => 'prefetch prerender',
            'href' => $frontpage_path,
          ],
        ];
        $variables['page']['#attached']['html_head'][] = [$prefetchfront, 'prefetch'];
      break;
    }
  }
}

```

---
Tags: 8, hooks
---


# Question
Title: Views contextually filtered by terms in paragraphs
TL;DR, Below are the structure of content types, paragraph types and taxonomy in my site.

**Taxonomy vocabulary - Category**

* Terms - Sports, Politics, Business

**Paragraph type - Multi Article**

* Fields -

+ Category (term reference to Category vocabulary)

**Content types - Landing page , Article**

* Landing page (fields) -
    + Multi category (Paragraph field referring to Multi Article paragraph type)\[unlimited\]
* Article (fields) -
    + Category term (term reference field to Category vocabulary) \[unlimited\]

**Sample content example -**

Landingpage A paragraph field has Sports,Politics

Landingpage B paragraph field has Politics

Landingpage C paragraph field has Business,Sports

Article A is tagged with Business

Article B is tagged with Sports,Business

Article C is tagged with Politics,Sports

**Desired output -**

*Landingpage A detail page should be showing something like -*

**Sports** \[based on paragraph field\]

* Article B \[based on term reference\]
* Article C \[based on term reference\]

**Politics**

* Article C \[based on term reference\]

*Landingpage B detail page should be showing something like -*

**Politics** \[based on paragraph field\]

* Article C \[based on term reference\]

*Landingpage C detail page should be showing something like -*

**Business** . \[based on paragraph field\]

* Article B \[based on term reference\]

**Sports** \[based on paragraph field\]

* Article B \[based on term reference\]
* Article C \[based on term reference\]

Can this be achieved with views and contextual filters ?

Question in detail - Forgive me for a lengthy question.

I have a field in the content type - Landing Page, which refers to a Paragraph type.

The paragraph type intern has a term reference field.

When I edit/ create a Landing page content, the desired term names are selected and saved (it can be any number of terms and it doesn't mean that this landing page is tagged to these terms. This is done just to categorise the result while rendering).

I also have another content type - Article which are actually tagged to some terms (both the above paragraph term reference and Article term reference are of same vocabulary)

Now, when any of the landing page content is rendered, I would like to show the latest 5 (or any number) Article contents tagged with each term that was added to the paragraph field which was selected from the paragraph field earlier.

The idea is to make the view result dynamic based on the terms added in the paragraph field of the content. In other words, the view result should vary on every node detail page.

Is there a way to achieve this with the help of views ? My final hope if I don't find a solution is to programatically fetch the latest contents under each term and display them. Would like to know if a better more elegant way is there with views.

Note - The reason why Paragraph is chosen is due to the flexibility it provides with rearranging the terms etc.

Would be great if any reference or examples are provided if my approach is right. Thanks.

# Answer
> 1 votes
Although there are multiple ways of doing this, here is probably one of the better ways if editor/front-end control is what you are after. These days, paragraphs are pretty commonly used to give easier control to editors.

It will be setup a little differently however.

1. First, install and enable the block\_field module. This will create a new type of reference field. We will use this later on.
2. Create a new View, choose Block display. Choose the Article bundle for your content. Add some fields from Article that you want to see. Add a new basic filter criteria for the category term reference field. Set its default value to Sports.
3. You should now have a view showing all articles where the category contains sports. Now duplicate this sports block, make another block for politics, and so on. Changing the filter criteria to match each term.
4. Your view should have a few blocks in it now. One for each term. Now go edit your Multi Article Paragraph type.
5. Delete your term reference field from the paragraph, and add a new field. Under references you will see a Block (plugin) now. Choose that. Name it whatever, set to unlimited.
6. On your new field, at the very bottom, drop down the Blocks fieldset. By default every block will be checked, uncheck them. Scroll down until you see your 3 view blocks you made. Check each of them. Then save the field.
7. Now go create a new landing page as if you are an editor. Your Multi Article paragraph will have a block reference. Choose add block, and pick one of the view blocks. Add a paragraph item for each view block you want to display.

You can then make many landing pages, allowing the editor to choose which types of articles to display. Here is my landing page A.

---
Tags: views, 8, entities, paragraphs
---


title: Get taxonomy terms added to nodes

text:
# Question
Title: Get taxonomy terms added to nodes
I am trying to get all the taxonomy terms added to a node. How would I get only the taxonomy term values that are added to a code in a `mymodule_preprocess_node` hook?

Current term list:

* value1 (tid=1)
* value2 (tid=2)
* value3 (tid=3)

Node list:

* node1 has `field_category = 1`
* node2 has `field_category = 3`
* node3 has `field_category = 1,2,3`

Here is what I tried, but cannot find a way to filter and only return the taxonomy term values that are added to a node.

```
// Returns entire list of values, but we want only ones added to Basic page
$term_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('field_category');

$nodes = \Drupal::entityTypeManager()->getStorage('node');

```

I am trying to get all the taxonomy term values, but just the entity field values.

# Answer
> 3 votes
**Another example:** As with all referenced entities you can load them quickly using the referencedEntities() method.

Also, if you are not using the Devel module and Devel Kint submodule, you should check it out. You can then use ksm() to explore variables and see available methods.

```
function hook_preprocess_node(&$variables) {

  //make sure you have Devel module installed, then you can use ksm() to explore variables
  //ksm($variables['node']);

  if ($variables['node']->hasField('field_permit_city')) {
    //this will give you the referenced terms on the node as objects
    $term_objects = $variables['node']->get('field_permit_city')->referencedEntities();
    $term_labels = [];
    foreach ($term_objects as $term_object) {
      print $term_object->id(); //the id of the term
      print $term_object->label(); //the term title
      $term_labels[] = $term_object->label(); //build an array of term labels
    }
    //send an array of term titles over to the node twig template
    $variables['my_custom_template_variable'] = $term_labels;
  }
}

```

Then in your node.html.twig template you can iterate through the labels and do the stuff.

```
{% for term in my_custom_template_variable %}
    <p>{{ term }}</p>
{% endfor %}

```

# Answer
> 2 votes
> To get all the taxonomy terms added to a node.

In `hook_preprocess_node` you can use something like:
add `use Drupal\taxonomy\Entity\Term;` to the top of your file.

```
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->bundle() == 'your_content_type_name') {
    //- Array of terms
    $terms = [];
    $categories = $node->field_category->getValue();
    foreach ($categories as $category) {
      $term = Term::load($category['target_id']);
      //- You can get the name of term by.
      /**
       * $term->getName()
       */
      //- You can get the description of term by.
      /**
       * $term->getDescription()
       */
      $terms[] = $term;
    }
  }
}

```

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


# Question
Title: Database Insert Slower On Production Server
I recently upgraded the PHP version to 7.1 on my production server. I also updated my local to 7.1 and staging to 7.1. Only on production, I am seeing a slow down when I import a csv file and insert records into the database:

```
$fp = fopen($file_path, 'r');
if ($fp === FALSE) {
  // Failed to open file.
  watchdog('ea_test', 'Failed to open %file_path', array('%file_path' => $file_path));
  $context['finished'] = TRUE;
  return;
}
fseek($fp, $context['sandbox']['offset']);

for ($i = 0; $i < $limit; $i++) {
  $line = fgetcsv($fp);

  if ($line == FALSE) {
    $done = TRUE;
  }
  // If first line just skipping ahead.
  elseif ($context['sandbox']['records'] < 1) {
    $context['sandbox']['records']++;
  }
  else {
    try {
      db_insert('ea_csv_test')
        ->fields(array(
          'agent_number' => $line[0],
          'total_signatures' => $line[1],
          'template_number' => $line[2],
          'photo' => $line[3] ? 1 : 0,
          'total_views' => $csv_line[4],
          'total_clicks' => $csv_line[5],
          'annual_cost' => $csv_line[7],
          'monthly_cost' => $csv_line[8],
          'popular_button' => $csv_line[9],
          'month' => $csv_line[10],
          'asof' => date('Y-m-d 00:00:00'),
        ))->execute();
    }
    catch (Exception $e) {
      // By setting the databse error it will fail and display the last bad
      // record. Normally I would log/email this but I think it
      // will send too many. More than likely if one is bad they all
      // will be bad.
      $database_insert_error = $e->getMessage();
      $error = TRUE;
    }

    // Set the current position of the file so it starts from there.
    $context['sandbox']['offset'] = ftell($fp);

    $context['sandbox']['records']++;
  }
}

$eof = feof($fp);

```

On local / staging it takes 9.51 seconds to process a csv file. On production, that same exact file takes 166 seconds.

When I comment out the `db_insert`, it runs the code in 1.34 seconds so I would say the problem is with the database insert.

Also, I import the CSV file directly with a SQL query and it runs extremely fast so I don't think it is the database itself.

**Environment Differences**

*Mariadb*

Locally: 5.5.5-10.2.20-MariaDB-log

Production: 5.5.5-10.2.20-MariaDB-log

**Edit**

Just to make sure tried using `mysqli_query()` (Set up connection once above the for loop) but it is still slower:

```
$sql = "INSERT INTO ea_csv_test (
agent_number,
total_signatures,
template_number,
photo,
total_views,
total_clicks,
annual_cost,
monthly_cost,
popular_button,
month,
asof)
VALUES (
'{$line[0]}',
'{$line[1]}',
'{$line[2]}',
1,
100,
2000,
'{$line[7]}',
'{$line[8]}',
'{$line[9]}',
'{$line[10]}',
'2019-12-12 02:02:01'
)";

if (mysqli_query($conn, $sql)) {
  echo "New record created successfully\n";
}
else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn) . "\n";
}

```

# Answer
I was able to figure out the problem. I started to compare my innodb settings and I noticed that `innodb_flush_log_at_trx_commit` was set to 2 on local and staging and 1 on production. I changed it to 2 and it fixed the issue.

I read a couple of posts (for example this one) and it seems like it is pretty safe to do it unless you are doing something super mission critical like bank transactions.
> 0 votes

# Answer
> You know you can run a LOAD DATA (LOCAL) INFILE query through Drupal too, right?

As Clive stated in his comment, it is possible, I have done it in the past. You can avert the performance issue here for a while, or use this to come up with perhaps a better more performant solution.

https://gist.github.com/kevinquillen/45fb33206559449e9cb2

The key is this function:

```
/**
 * This takes the provided uploaded file and imports it directly into a temporary table in the database.
 * Drupal has some issues executing the statement, so the PDO class is leveraged with some different options to allow it without error.
 * @param $table_name
 * @param $uri
 * @param $message
 * @param $context
 */
function populate_mysql_table_with_infile($table_name, $uri) {
  $database = Database::getConnectionInfo()['default'];
  $data_source = 'mysql:host=' . $database['host'] . ';dbname=' . $database['database'];
  $db_user = $database['username'];
  $db_password = $database['password'];
  $connection = new PDO($data_source, $db_user, $db_password,
    array(
      PDO::ATTR_EMULATE_PREPARES => TRUE,
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_PERSISTENT
    )
  );
  $statement = $connection->prepare("LOAD DATA LOCAL INFILE '" . drupal_realpath($uri) . "' INTO TABLE " . $table_name . "
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\r\n'
    IGNORE 1 LINES");
  $statement->execute();
  $statement->closeCursor();
}

```
> 1 votes

---
Tags: database, performance
---


title: Turn form builder response into HTML

text:
# Question
Title: Turn form builder response into HTML
I have a node type called "competition". I can get a form for it like so:

```
$values = array('type' => 'competition');
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('node', 'default')
  ->setEntity($node);
$form = \Drupal::formBuilder()->getForm($form);

```

In a controller it's easy enough to return $form and it will be rendered. But I want to do other things with this form so I need it back as HTML. How can I turn $form into fully rendered html?

# Answer
> 1 votes
I managed to use:

```
$html = drupal_render($form);

```

Just like you would do in Drupal 7. Not great, but solves my problem.

---
Tags: 8, forms
---


title: How to connect to MySQL using Docksal?

text:
# Question
Title: How to connect to MySQL using Docksal?
I'm using Docksal as a local environment. How do I connect to the MySQL database in the Docksal container? Can I just use my local instance of MySQL instead? Also if anyone knows how to import a database for use with the Docksal MySQL instance that would be great.

Thanks!

# Answer
Connecting to a local MySQL DB did not work, however, this did:

`cd docroot`

`fin db import /path/to/.sql/file`

More can be found here https://docs.docksal.io/service/db/access/.
> 3 votes

---
Tags: 8
---


title: Change site name programmatically

text:
# Question
Title: Change site name programmatically
We have a requirement that when we save a node that nodes title should be the site name. We used to do it in Drupal 7. But I was not able to find the proper method for it in Drupal 8.

This is what we tried:

```
$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('system.site.name', "Demo Site");
$config->save();

```

Got it from here: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api

Any suggestions?

# Answer
Nearly :

```
$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('name', "XXXXXXX");
$config->save();

```

Just have to implement hook\_node\_update to fit your needs.
> 2 votes

---
Tags: 8, configuration
---


# Question
Title: How to preprocess group title render in views?
I tried to preprocess a title of the group in the result of the rendering of the view.

Example:

Actual: `Group 1 title
Item 1
Item 2
Item 3
Group 2 title
Item 4
Item 5
Item 6`

Expected: `Group 1 title
Item 1
Item 2
Item 3
Group 2 title
Item 4
Item 5
Item 6`

Here the similar question on the drupal.org https://www.drupal.org/project/drupal/issues/2950737.

# Answer
> 1 votes
If you want to change the template for the title of the group, why don't you override the template file **views-view-grouping.tpl.php** for Drupal 7, or **views-view-grouping.html.twig** for Drupal 8.

By standard Drupal templates names, overrides are also working with this one.

views-view-grouping--**MACHINEVIEWNAME**.tpl.php for a specific view

views-view-grouping--**MACHINEVIEWNAME**--**MACHINEDISPLAYNAME**.tpl.php for a specific display of a specific view.

Hope this can help you.

---
Tags: views, 8
---


# Question
Title: How can I limit the exposed filters to only display values for which content exists?
We have a view for the *Basic page* content type, which has a *Category* field that allows to enter multiple values.
All values for *Category* are displayed (*IoT*, *Cloud*, *Security*), but there are only nodes that use *IoT* and *Cloud*. I want to display only *IoT* and *Cloud* for the *Category* exposed filter.

How can I limit the exposed filters to only display values for which content exists?

The view settings are the following.

Format * Show: Content | Teaser
* Format: Unformatted List | Settings

Filter Criteria * Authored on (exposed)
* Category (field\_category) (exposed) | Settings (settings is set to Category tag, selection type = Dropdown)
* Author (exposed)
* Published (= Yes)
* Content Type (= Basic Page)

Sort Criteria * Content: Authored on (desc)

Contextual Filters, Relationship * None

Exposed form * Exposed form style: Better Exposed Filters | Settings
* Settings are set to default in Better Exposed Filters

Other * Use Ajax: Yes
* Use aggregation: no
* query settings: default settings

Here is what we tried. This only gets me the nodes that have a value for `field_category` and all term values for `categories` term individually.

```
function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $node_storage = Drupal::getContainer()->get('entity_type.manager')->getStorage('node');
  $node_ids = $node_storage->getQuery();

  // This returns all nodes with a value for *field_category*.
  $nodes = $node_ids->condition('type','page')
    ->exists('field_category')
    ->condition('status', 1)
    ->sort('title')
    ->execute();

  // returns all taxonomy terms.
  $category_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('categories');

}

```

# Answer
This works for me:

```
function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['tid']['#options'])) {
    foreach ($form['tid']['#options'] as $key => $value) {
      // Limit to numeric keys to exclude the 'All' option.
      if (is_numeric($key)) {
        // Start database query.
        $query = \Drupal::database()->select('taxonomy_index', 'ti');
        $query->fields('ti', ['nid']);
        $query->condition('ti.tid', $key);
        $nodes = $query->execute()->fetchAssoc();
        // Remove option if term has no instance.
        if (!$nodes) {
          unset($form['tid']['#options'][$key]);
        }
      }
    }
  }
}

```

You will probably need to adjust the 'tid' in $form\['tid'\]\['#options'\] to the Filter identifier as defined in your views' filter settings. Credits for the quick and efficient database query go to https://drupal.stackexchange.com/a/219368/25154.
> 2 votes

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


# Question
Title: create views for a field submitted more than once in one row
I have a content type that only has one field. (for example weight) The user submits this field multiple times. now I want to create a view that shows all the weights submitted by the user in one row, not in separate rows.

How can I create this kind of view?

# Answer
1)Change your views format into grid set its maximum column

3)Allow Group By Authored into Grids

4)Add css

```
   float: left;
   width: 80%;

```
> 0 votes

---
Tags: views
---


# Question
Title: 'drush' is appended to each path breaking its commands
I don't normally use Drush on Windows, but tried it and noticed that it appends *drush* as a kind of root directory for any action, thus breaking said action.

For example, `drush dd` gives:

> The command could not be executed successfully (returned: 'Path/To/Composer/vendor/drush/drush/drush' is not recognized as an internal or external command, operable program or batch file. , code: 1)

The correct path is *Path/To/Composer/vendor/drush/drush*.

When running `drush en mymodule`, the debug information contains the following.

> \[preflight\] Alias paths: drupal\site\root/drush/sites,drupal/site/root/drush/sites

*drupal/site/root/sites* I think makes more sense.

The error is *Command pm:enable was not found*.

Maybe this is a coincidence and the two are unrelated, but how does one configure Drush directories?

The Drush version is 9.5.2.

# Answer
I haven't used Drush under Windows, but something tells me that the problem could be solved by by editing the path to the Drush executable, perhaps in a Windows environment variable.
> 0 votes

# Answer
I don't think you have installed Drush 9 correctly as Drush is trying to execute

```
Path/To/Composer/vendor/drush/drush/drush

```

Drush 9 should be installed site-locally, not globally, and be launched using Drush Launcher - see http://docs.drush.org/en/master/install/

We can't help you anymore without knowing how you installed Drupal and Drush. The recommended approach to install Drupal is using https://github.com/drupal-composer/drupal-project (which includes a site-local Drush).

PS! `vendor/drush/drush/drush` exists, but it is a script for Linux.
> 0 votes

---
Tags: drush
---


# Question
Title: How to use an user profile custom field using Rules?
Working with Drupal 8.4.5 and Rules 8.x-3.0-alpha3 and Typed Data 8.x-1.0-alpha1

With Drupal 7 Rules, we may use an user custom field for data comparison (address or vocabulary for example). And it was easy to create the condition `Entity has field` with a select list to choose the right field (cf screenshot) :

Now, in Drupal 8 Rules, the procedure has changed and I did not manage to reproduce this simple condition `Entity has field` since the Field select list has disappeared and custom fields are hidden in the Data selector suggestions (cf screenshot)

So my question is : **how to use my custom field in a Rule** (simple data comparison, for example)? What is the new way to write `user:field_custom`?

Surprisingly, the help text within `Entity has field` condition says : ...To make entity fields appear in the data selector, you may have to use the condition 'entity has field'...

It seems like an infinite loop to me?

Furthermore, "More useful tips about data selection is available in the online documentation" and there we have documentation about Drupal 7 Rules.

Ultimately, I need to create a Rule in Drupal 8 to automatically give an user role when a new account is saved, depending on a custom field value.

The question below is quite similar.

How to custom field has a value with the Rules module?

**EDIT** : I found an alternative for my specific need with the module Auto User Role (still in dev version). It seems to work nicely (only when saving a new user, not after editing an user, so the custom field is required at creation)

# Answer
> ... since the Field select list has disappeared and custom fields are hidden in the Data selector suggestions.

The above is a partial quote of your question. IMO that's not correct. Instead it should say "... since the Field select list **does not appear yet** and custom fields **are not shown yet** in the Data selector suggestions".

And similar to the (my) answer to the question you linked to: those or some of the things that are still missing in the most recent D8 version of Rules. Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8.

One never realizes what ***has been*** done, only what ***remains to be*** done ... So start here if you wonder how to contribute.
> 1 votes

# Answer
To get access to user's custom fields from a condition you need first to add the 'Entity is of Bundle' condition. See the following tutorial: https://www.drupal.org/project/rules/issues/2912457#comment-12904391

But if you create a User in a Rule and want to get access to its custom fields from this Rule then you can use 'Rules User Fields' module.
> 1 votes

---
Tags: 8, rules
---


# Question
Title: How to get rendered content properties from an entity reference in Twig
I'm using the Stock Photo Search module, for particular image fields, and it has its own field type with interesting properties.

As far as I can tell, the only way to access the URI of the image is `content.field_stock_photo[0]['#uri']`. There is no `node.field_stock_photo.0.entity.uri.value` or similar. The only way to access the URI is through the rendered entity.

The problem I'm running into is when using a reference to another node that has the `stock_photo_search` field, I have no way to access this rendered entity from a reference. `node.reference.0.entity.field_stock_photo.value` doesn't do it, and as far as I can tell `node.reference.0.content.field_stock_photo` doesn't work.

How do I go about getting properties from a rendered entity of a reference in Twig?

# Answer
> 1 votes
In PHP you could force to build the render array of the field of a referenced entity early:

```
$build = $node->reference->entity->field_stock_photo->view();

```

And then look for '#uri' in the build array.

---
Tags: 8, theming
---


# Question
Title: How display node author roles at node.html.twig
My user case is:

Extlink module can add exception classes to avoid processing some links.

I want some external url links on nodes whom author belongs to a special role (premium) can be mark with a class (for example with premium role name) to set an exception at external links module.

Well, at node twig template I can render node owner name, using this: {{ node.Owner.name.value }} but I don't know how render author roles.

# Answer
You can get roles in twig using:

```
{%  for role in node.Owner.roles %}
    {{ role.entity.label }}
{% endfor %}

```

**Update :**
If you want to use roles in classes i recommended you to use `clean_class` filter to get the clean css class from roles instead of the code you post in comment use this:

```
   {% set custom_classes = [] %}
    {% for role in node.Owner.roles %}
      {% set class_role = role.entity.label | clean_class %}
      {% set custom_classes = custom_classes | merge([class_role]) %}
    {% endfor %}
    <div {{ attributes.addClass(custom_classes) }}>
      {{ content }}
    </div>

```
> 2 votes

---
Tags: theming, nodes
---


# Question
Title: Reindex Search API indexes for Behat testing
I tried to use index the newly created contents to be able to test a page, but the problem is most of the times the tests fails, because the indexing process not finished yet until the contents starts checking. (i.e. if I stop before pageload with a breakpoint the testing, then the next steps always pass)

Method 1:

```
$search_api_index = search_api_index_load('SEARCH_API_INDEX_ID');
search_api_index_items($search_api_index);

```

Method 2:

```
search_api_cron();

```

The question, how can I call the indexing to wait until it's fully indexed before it goes forward?

# Answer
> 1 votes
The ultimate solution is `$search_api_index->server()->commit()` which needed because, there's a commit delay which you can set inside the `solrconfig.xml` and this delay cause the problem. (Or you can just `sleep(1)` your code, but that's not flexible at all and ugly...)

---
Tags: 7, testing
---


# Question
Title: Call to a member function label() on null after saving a node with a taxonomy term
I create nodes, which have a taxonomy field, like this:

```
$node = Node::create([
  'type' => 'article',
  'status' => 1,
  'title' => 'Some title',
  ...
  'field_taxonomy' => [1, 2, 3],
]);
$node->save();

```

The nodes are saved and can be displayed. But the views, which should display articles with selected taxonomy terms, return the following error message:

```
Error: Call to a member function label() on null in Drupal\taxonomy\Plugin\views\field\TaxonomyIndexTid->preRender() (Line 149 in /var/www/html/core/modules/taxonomy/src/Plugin/views/field/TaxonomyIndexTid.php)
#0 /var/www/html/core/modules/views/src/ViewExecutable.php(1503): Drupal\taxonomy\Plugin\views\field\TaxonomyIndexTid->preRender(Array)
#1 /var/www/html/core/modules/views/src/Plugin/views/display/Page.php(183): Drupal\views\ViewExecutable->render()
#2 /var/www/html/core/modules/views/src/ViewExecutable.php(1630): Drupal\views\Plugin\views\display\Page->execute()
#3 /var/www/html/core/modules/views/src/Element/View.php(77): Drupal\views\ViewExecutable->executeDisplay('alle', Array)
#4 [internal function]: Drupal\views\Element\View::preRenderViewElement(Array)
#5 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#6 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#7 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(226): Drupal\Core\Render\Renderer->render(Array, false)
#8 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}()
#9 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(227): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#10 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#11 /var/www/html/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#12 [internal function]: Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#13 /var/www/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(111): call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#14 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(156): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))
#15 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#16 /var/www/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /var/www/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#20 /var/www/html/modules/jsonapi/src/StackMiddleware/FormatSetter.php(51): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#21 /var/www/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\jsonapi\StackMiddleware\FormatSetter->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#22 /var/www/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#23 /var/www/html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#24 /var/www/html/core/lib/Drupal/Core/DrupalKernel.php(669): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#25 /var/www/html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#26 {main}.

```

If I manually open the editing form for every of the new nodes and save the node (without changing anything), then the error message disappear and the views display correct content. Resaving all new articles in a bulk operation or clearing all caches do not solve the issue.

The line 149 in /core/modules/taxonomy/src/Plugin/views/field/TaxonomyIndexTid.php looks like:

```
127 public function preRender(&$values) {
128     $vocabularies = $this->vocabularyStorage->loadMultiple();
...
144     foreach ($result as $node_nid => $data) {
145         foreach ($data as $tid => $term) {
...
149             $this->items[$node_nid][$tid]['vocabulary'] = $vocabularies[$term->bundle()]->label();
...
            }
        }
    }

```

# Answer
I believe it has to do with how you are trying to assign values to the field.

I think you want:

```
$node = Node::create([
  'type' => 'article',
  'status' => 1,
  'title' => 'Some title',
]);

$node->set('field_taxonomy', [1, 2, 3]);
$node->save();

```
> 1 votes

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


# Question
Title: How do you set a node reference field's default value when creating a node programatically?
I use this:

```
$values = array(
  'type' => 'competition',
  'title' => 'my title goes here',
);
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

```

This works perfectly. But the problem is, I also have a node reference field called "field\_competition\_node\_reference". But this doesnt work:

```
$values = array(
  'type' => 'competition',
  'title' => 'my title goes here',
  'field_competition_node_reference' => 1,
);

```

How would one go about doing this? The value on the object is "target\_id". Maybe that's why "create()" doesnt work?

# Answer
This should work :

```
$values = [
  'type' => 'competition',
  'title' => 'my title goes here',
  'field_competition_node_reference' => [['target_id' => 1]],
];
Node::create($values);

```
> 0 votes

# Answer
```
  $node = Node::create([
      'type' => 'competition',
      'title' => 'my title goes here',
       'field_competition_node_reference' => [
         'target_id' => 1,
       ],
    ]);
    $node->save();

```

Another way to create node with reference field is:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->create(array(
  'type'        => 'competition',
  'title'       => 'my title goes here',
  'field_competition_node_reference' => [
    'target_id' => 1
  ],
));
$node->save();

```

Don't forget Add namespace.

```
  use \Drupal\node\Entity\Node;

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Why are there 2 ways to handle configuration?
In Drupal when we are working with read-only config we use

```
$page_cache = \Drupal::config('system.performance')->get('cache.page');

```

Why this static call for read-only object?

and when we use working with a config where both read and write is possible. we use this service 'config.factory'

```
$config = \Drupal::service('config.factory')->getEditable('system.performance');
$config->set('cache.page', ['enabled' => 1, 'max_age' => 5]);

```

what leads to this design?

# Answer
> 6 votes
This change record explains it all: Configuration objects by default are immutable.

> `ConfigFactoryInterface::get()` no longer returns configuration objects that can be saved. This is to ensure that configuration overrides do not get into active configuration. Configuration overrides are, for example, global overrides set in `settings.php` or translations provided by the locale module. If you need to get a configuration object that can be saved, use `ConfigFactoryInterface::getEditable()`. Objects returned by that method will not have overrides applied.
>
> ### Previously
>
> ```
> // Just get the site name (with overrides).
> $site_name = \Drupal::config('system.site')->get('name');
>
> // Set the site name.
> \Drupal::config('system.site')->set('name', 'My fantastic site')->save();
>
> ```
>
> ### Now
>
> ```
> // Just get the site name (with overrides, same as before).
> $site_name = \Drupal::config('system.site')->get('name');
>
> // Set the site name.
> \Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();
>
> ```

Are you also/alternatively asking why there's a `Drupal::config` method, but not a `Drupal::configFactory` method, i.e. why do you have to use the generic `Drupal::service` method for the second one?

If so, that's simply because the shortcut methods exposed on the `Drupal` class are for the most regularly used services. The `config` service is used in procedural code a lot more than `config.factory`, so there's no shortcut method for it. There are hundreds (thousands?) of services throughout the system so providing a method for each would be overkill

---
Tags: 8
---


# Question
Title: Send mail to product owner only when the email adress is available
As a follow up to previous questions asked by me: Send mail to product owner with Rules and Fetch Customer Profile from Line Items. I have the following question.

I created a rule to send an e-mail to the product owner of a product in my commerce webshop. The email address is added to the product by hand in a custom field. The rule is working when the email address is available but when not available it sends out an error. How can I check to see if the e-mail address is there and only then send the e-mail.

This is my rule:

```
{ "rules_svds_send_mail_to_product_owner" : {
"LABEL" : "SVDS: Send mail to product owner",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "SVDS" ],
"REQUIRES" : [ "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "commerce_order", "value" : [ "commerce-order" ] },
      "PROVIDE" : { "variable_added" : { "commerce_order_value" : "Commerce Order" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "line_items" : "Commerce Line Items" },
      "DO" : [
        { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-items" ] } }
      ]
    }
  }
]
}
}

```

The component I use in the loop is like this:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
"LABEL" : "Perform an action on a selected line item",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
  "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : {
        "type" : "commerce_product",
        "id" : [ "selected-line-item:commerce-product:product-id" ]
      },
      "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
    }
  },
  { "entity_fetch" : {
      "USING" : { "type" : "commerce_order", "id" : [ "commerce-order:order-id" ] },
      "PROVIDE" : { "entity_fetched" : { "fetched_customer" : "Fetched user" } }
    }
  },
  { "mimemail" : {
      "USING" : {
        "key" : "[commerce-order:order-id]",
        "to" : "[product-fetched:field-e-mailadres-product]",
        "subject" : "Product ordered",
        "body" : "E-mail body text",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
]
}}

```

Thanks in advance

# Answer
> The email address is added to the product by hand in a custom field

I supouse that the field for entering email, is an email field (must enter a 'valid email' in format: somename@someurl.something, avioding a 'blah blah email'), if so: then in your rule add a condition: \[your\_email\_field\] is not empy, if that condition is far away to be implemented in rules area: condition, then use rules conditional module, when your a ready to implement 'send email' in your rule, before that accion, add condition: \[your\_email\_field\] is not empty, if user entered a 'fake email', drupal will send email, but it will not go anywhare, this way you can avoid your error, and only valid emails will be delivered.
> 0 votes

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


title: Get params cookie_domain

text:
# Question
Title: Get params cookie_domain
I would like to retrieve the parameter cookie\_domain set in the services.yml like this:

```
parameters:
  session.storage.options:
    cookie_domain: '.domain.ext'

```

I try this:

```
(new SessionConfiguration())->getOptions(\Drupal::request());

```

This recovers the default value not my value

# Answer
> 1 votes
You can get the cookie domain this way using the session\_configuration service.

```
$sessionConfig =\Drupal::service('session_configuration');
// Get the current request.
$request = \Drupal::request();
// Get options from the request.
$options = $sessionConfig->getOptions($request);
$cookie_domain = $options['cookie_domain'];

```

# Answer
> 0 votes
You can also use this approach:

```
$session_parameters = Drupal::getContainer()->getParameter('session.storage.options');
$cookie_domain = $session_parameters['cookie_domain'];

```

example:

```
// Get the cookie domain from container parameter config
$cookie_domain = '';
try {
  $session_parameters = Drupal::getContainer()->getParameter('session.storage.options');
  $cookie_domain = $session_parameters['cookie_domain'];
} catch (Exception $e) {
  watchdog_exception('cookie_domain', $e);
}

```

---
Tags: 8
---


# Question
Title: How can I limit displayed nodes by term reference from current user?
I am trying to create a view that to show content classified by taxonomy term and the hierarchy level of the logged in user within that taxonomy vocabulary.

For instance, the content is organized in 10 different levels of a taxonomy ranking, and each user is progressing through each level of that taxonomy (in an educational pathway), and we want to show all content of those levels that the user has reached and could have possibly have gone through up to that point.

For example if the user has reached level 5 (or has been given that rank by admin), the view will show all content for levels 1 through 5, but not anything higher. If user is level 7, then the view will show all content with taxonomy 1 through 7 but nothing higher.

How can I do that? How can I reference the user in a view and take their taxonomy term to limit the view's content based on that?

# Answer
> 0 votes
To control access to your content based on taxonomy terms you need to use modules like Taxonomy Access Control or Permissions by Term. With proper configuration these will prevent users from viewing content they don't share terms with, even if they can guess the content links for example.

You can create Views that lists content based on shared taxonomy terms, but Views don't control access to original nodes pages. If a user can guess the node paths, or you have content listed on Taxonomy pages and the Taxonomy pages aren't access-controled then they will be able to see the content links there and click through.

Using one of those modules you will be able to control access through terms alone, or you may need to create a new user Role for each term, it depends on your details.

Once you solve the Permissions problem you can create Views that would show content that the current user shares terms with.

The easiest way to approach this is not to rely on weight/order at all. You can treat terms like badges: if a user reaches 3rd level, they would be tagged with the first 3 terms, and not only the third term. Drupal doesn't care if you name them "level-1" and "level-2" or "beginner" and "medium". You just have to make sure to add terms to the user once they pass a level, and keep all the terms they "collected" before.

If you go for only the one highest term they have reached you have to take care of the removing the current term when a new one is reached, it introduces complexity that isn't necessary if you're relying on taxonomy terms.

There are still ways to show only the highest term if you want to use it to rank a user.

To create a page showing content that the current user shares terms with you use Relationships to the taxonomy reference field. The details are almost the same as in this QandA: Based on user's country filter content of same country?

---
Tags: views
---


# Question
Title: RESTful view contextual filter to use path alias
I have created a RESTful view in Drupal 8, there I need to display a few of node contents by node alias in contextual filter.

View URL: `www.example.com/api/book-details/{node-alias}`

Instead of node alias if I use node ID, it's working fine. For example: `api/book-details/100` (node ID 100) is working fine.

URL alias for node 100 is "first-content". So how do I fetch details using node alias in contextual filter? For example: `api/book-details/first-content` (this is not giving any result).

# Answer
As No Sssweat already mentioned in his comment there is no Contextual filter available for path aliases, you can try to create your own (and share on drupal.org while you're at it :) ).

But if you have set your aliases based on node Titles then you may get away with using `Content: Title` as your contextual filter.

Just be careful about the `Case in Path` setting and you'll probably need `Transform spaces to dashes in URL` under `More`.
> 0 votes

---
Tags: views
---


# Question
Title: How to programmatically alter feed item values before saving
Feeds Tamper does this job, which allows me to "tamper" with feed items' values before saving it to an entity.

My question is how can I do that programmatically in Drupal 8 with a custom module.

# Answer
> 5 votes
Thanks to No Sssweat, I managed to use an EventSubscriber using `afterParse` event to do this job.

File 1: mycustommodule/mycustommodule.services.yml

```
services:
 mycustommodule.feeds_subscriber:
   class: Drupal\mycustommodule\EventSubscriber\FeedsSubscriber
   tags:
     - {name: event_subscriber}

```

File 2: mycustommodule/src/EventSubscriber/FeedsSubscriber.php

```
<?php

namespace Drupal\mycustommodule\EventSubscriber;

use Drupal\feeds\Event\FeedsEvents;
use Drupal\feeds\Event\ParseEvent;
use Drupal\feeds\Feeds\Item\ItemInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Subscriber to Feeds events.
 *
 * This happens after parsing and before going
 * into processing.
 */
class FeedsSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Acts on parser result.
   */
  public function afterParse(ParseEvent $event) {

    /** @var \Drupal\feeds\FeedInterface $feed */
    $feed = $event->getFeed();
    $feed_bundle_name = $feed->bundle();

    // Only alter a particular feed
    if ($feed_bundle_name == "MY_FEED_IMPORTER_MACHINE_NAME") {

      /** @var \Drupal\feeds\Result\ParserResultInterface $result */
      $result = $event->getParserResult();

      for ($i = 0; $i < $result->count(); $i++) {
        if (!$result->offsetExists($i)) {
          break;
        }

        /** @var \Drupal\feeds\Feeds\Item\ItemInterface $item */
        $item = $result->offsetGet($i);

        /**
         *
         * My custom code here using $item->get() and $item->set()
         * to alter whatever values I want.
         *
         */
      }
    }
  }
}

```

---
Tags: feeds
---


# Question
Title: How to reference URL relative to current page in a block
I have a custom block where I need to reference a URL relative to the current page (such as node/7/images or node/293/images) that will link to the "Images" view mode I made for the node. I am using a module so that a view mode is accessible via URL (which I have as node/#/images), but I am having trouble getting a working link to /images that would work on any given node.

I have tried to link it to /images and /#/images but have gotten a 404 each time, likely because it is going to example.com/images or example.com/#/images. I have also tried using the Token for current page URL which 404'd as well.

Is there a way, hopefully through the UI, in which I can reference the current node in a way that on any given node the link to the "Images" view mode will link to /node/\[current node #\]/images?

I have seen ways to implement it using custom modules or code, but I am not very experienced with putting custom code into Drupal and prefer to use the UI is possible.

***update***

I briefly had a fix, but then I broke it. I had got it working adding a link that referenced "images/" (without the quotations). While viewing the node, the custom block originally linked to example.com/node/#/images as intended.

However, I then configured the block to be hidden on \*/images (wasn't necessary to link to the view while viewing it). After I did this, the link broke on the node page, instead now referencing to example.com/node/images, missing the node # in the URL. I have no idea how this got broken as I only worked through the UI

I tried deleting the block then adding it again with no effect

Using "#/images" will direct to /node/123#/images (adding the actual # into the URL) - while this gets the current node id into the URL it doesnt work with the presence of the # symbol

# Answer
> 0 votes
Adding a relative path (without the starting "/") is WRT the current "directory", so when you're on a node page the "directory" is "node" and the NID is the "page". Your "images" is supposed to be another page within the same "directory". That's the simplified explanations about how relative paths work in general.

To solve your problem the easiest way is probably through a Token. Do you have Token Filter or a similar module installed and configured? If your Text format doesn't evaluate tokens you won't get the correct output.

Try some available tokens in your text and see what they output. Maybe there's a \[current:path\] or similar token, or \[current:nid\]. When you find one with the output you like you can contruct the link:

`<a href="/node/[current:nid]/images">Images</a>`

or

`<a href="/[current:path]/images">Images</a>`

If you need more control over the Block Visibility you can try Block Exclude Pages.

Another way to create contextually aware links is through Views (Block display). You would have a Node ID as the contextual filter, and override the Link to content field to add "/images" at the end of it.

---
Tags: path-aliases
---


title: Show only rows with highest values

text:
# Question
Title: Show only rows with highest values
Drupal 8.x

I have a view returning:

* UID: 1, NID: 1, **VALUE: 9**
* UID: 1, NID: 3, VALUE: 8
* UID: 1, NID: 2, VALUE: 7
* UID: 2, NID: 9, **VALUE: 5**
* UID: 2, NID: 5, VALUE: 4
* UID: 2, NID: 7, VALUE: 3

I would like to only return:

* UID: 1, NID: 1, **VALUE: 9**
* UID: 2, NID: 9, **VALUE: 5**

My goal is to show only one row per **UID** which contains the highest **VALUE**. For this view, **NID** does not matter, but it is a part of the Database table and query being sent to views with `hook_views_data()` and is used elsewhere.

Can the Views module accomplish this?

# Answer
> 1 votes
In Drupal 7 there was the Views Reference Filter.

Basically, what you're after is filtering one view with another (if you have to go through the interface and not code a custom solution). Those database queries can be quite slow so you're advised to use caching.

Views Field View has the D8 version. The strategy is to create two Views displays, one listing Users, the other Views listing only one node sorted by Value descending and with a contextual filter for UID. Then you insert the second view into the first one (as an additional field).

This way you get the one node that has the highest value for the particular user.

---
Tags: views, 8
---


# Question
Title: What is the right way to use a different base theme for some pages when applying custom theme?
I know that custom theme usually inherited from the "stable" theme, and the default backend theme is "seven. I like the UI of "/user/login","/user/register" and "/forum" pages. If I use a custom theme inherited from "stable", how can I make the UI apperance of these special pages stay in "seven" theme? I tried to set the "base theme" to "classy" or "false", but the theme suggestions still choose the "stable" as a default.

# Answer
> 1 votes
> How can I make the UI appearance of these special pages stay in "seven" theme?

Seven is the default theme for admin paths in Drupal. To mark special pages like the user login as admin path use the module Admin Login Path.

You can add your own paths in a custom route subscriber like the one from the module:

```
<?php

namespace Drupal\admin_login_path\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Define the routes we want to use the admin theme.
    $login_routes = ['user.login', 'user.register', 'user.pass'];
    foreach ($collection->all() as $name => $route) {
      if (in_array($name, $login_routes)) {
        $route->setOption('_admin_route', TRUE);
      }
    }
  }

}

```

# Answer
> 0 votes
Just for completeness: there are modules for D8 that allow you more control over which theme to use on which pages:

In D7 the most popular is ThemeKey.

---
Tags: 8, theming
---


# Question
Title: Create a Display Suite Custom Block Field Programatically
Can anyone provide sample code for a custom module and/or provide a reference for hook\_ds\_fields\_info that utilizes 'field\_type' =\> DS\_FIELD\_TYPE\_BLOCK, that will actually render in admin/structure/ds/fields. I'm working in 7.2-2.14 of display suite.

The API documentation appears to be incomplete as listed here: http://www.drupalcontrib.org/api/drupal/contributions%21ds%21ds.api.php/function/hook\_ds\_fields\_info/7.

I'm thinking I may be missing some sort of related render function for the block to appear (https://ohthehugemanatee.org/blog/2014/04/02/how-to-create-a-custom-display-suite-field/) however even using this example barebones in a standalone module I don't necessarily get my custom block to show. I am referencing a custom block initially built out in a custom module.

```
function module_ds_fields_info($entity_type) {
  $fields = array();

  $fields['title'] = array(
    'title' => t('My Custom Module'),
    'field_type' => DS_FIELD_TYPE_BLOCK,
    'ui_limit' => array('article|*', 'audience_page|*', 'overview_page|*', 'page|*', 'product|*', 'product_overview|*'),
    'properties' => array(
      'block' => 'my_custom_module',
      'block_render' => DS_BLOCK_CONTENT,
    ),
  );

  return array('node' => $fields);

}

```

# Answer
> 0 votes
As already reported in this DS issue, you need to alter DS\_BLOCK\_CONTENT to DS\_BLOCK\_TEMPLATE.

We had a similar issue where from a certain point in time, the block was no longer rendered. That point in time was a security update on the DS module, we applied somewhere a month ago : https://www.drupal.org/sa-contrib-2018-019

---
Tags: display-suite
---


# Question
Title: Form multiselect item and url encoding with GET method
I have a form on a Drupal 7 site, which is submitted using the GET method to refresh the page's display using the query parameters.
One of the parameters uses the select box, with the multiple option. This results in the query parameter using the format option%5B%5D=39&option%5B%5D=54

Is there a way to have the form submit and merge the query parameters into something like option=39+54

# Answer
This is the solution that I have working at the moment, although I am not sure if this is the correct way to do this.

First is that instead of loading the form into my render array with `drupal_get_form()` I have now used `drupal_build_form()` which seems to allow GET method forms to use the validate and submit form hooks.

Then in the submit hook have `$form_state['redirect']` to a custom formatted URL which is cleaner for end users.
> 1 votes

---
Tags: 7, forms
---


title: Create a node using services with PHP

text:
# Question
Title: Create a node using services with PHP
I want to add a new page node using drupal services and REST server.

```
$postdata = http_build_query(array(
      'type' => 'page',
      'title' => 'aaa',
      'field_test[en][0][value]' => '<p>test</p>\n',
      'field_test[en][0][format]' => 'filtered_html'
      )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/json'."\r\n".
                     'Cookie: ' . $sessid."\r\n",
        'content' => $postdata
    )
);

    $context = stream_context_create($opts);
    $contents = file_get_contents($main_url."node", false, $context);

    echo json_encode($contents);

```

When I run above code I get an error:

```
Warning: file_get_contents(http://192.168.1.129:80/test/node)
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0
401 Unauthorized:
Missing required argument node in D:\xampp\htdocs\serv\server.php on line 61

```

# Answer
I think that you need make an authenticated request, unless you want any user to create nodes.
I have created nodes before using curl. You need enable the "Session authentication", activate the user login action in the resources section of you service, and enable request "application/x-www-form-urlencoded" in the server section.

This is the code

```
    $base_url = 'http://localhost/endpoint';
    $params = http_build_query(array(
       'username' => 'admin',
       'password' => 'qwerty',
    ));
    // set up the request
    $curl = curl_init($base_url . '/user/login.json');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    // make the request
    $response = curl_exec($curl);
    curl_close($curl);
    $user_data = json_decode($response);
    // login successful
    if (isset($user_data->sessid)) {
      $node_params = http_build_query(array(
        'type' => 'page',
        'title' => 'Test page',
      ));
      // set up the authenticated request
      $curl_node = curl_init($base_url . '/node.json');
      curl_setopt($curl_node, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl_node, CURLOPT_POST, true);
      curl_setopt($curl_node, CURLOPT_POSTFIELDS, $node_params);
      curl_setopt($curl_node, CURLOPT_COOKIE, $user_data->session_name . '=' . $user_data->sessid);
      // make the authenticated request
      $node_response = curl_exec($curl_node);
      curl_close($curl_node);
      var_dump(json_decode($node_response));
    }

```
> 3 votes

# Answer
SOLVED:

This line:

```
'content' => $postdata

```

I changed by:

```
'content' => $postdata
    'content' =>

    '&node[type]=page'.
    '&node[title]='.$_POST['title'].
    '&node[body][und][0][value]='.$_POST['body'].
    '&node[body][und][0][format]=filtered_html'

```

And now it works :)
> 1 votes

# Answer
This code is worked for me to create new node.

You need to enable "login" action under user section of resources.

```
<?php
  $username = "admin"; //site user
  $password = "admin123"; //site password
  $session;
  $endpoint = "http://localhost/sitename/endpoint/";
  $debug;

 $ch = curl_init($endpoint . 'user/login.json');
 $post_data = array(
  'username' => $username,
  'password' => $password,
 );
$post = http_build_query($post_data, '', '&');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
  "Accept: application/json",
  "Content-type: application/x-www-form-urlencoded"
));

$response = json_decode(curl_exec($ch));
//Save Session information to be sent as cookie with future calls
$session = $response->session_name . '=' . $response->sessid;
//GET CSRF Token
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => 'http://localhost/sitename/services/session/token',
));
curl_setopt($ch, CURLOPT_COOKIE, "$session");

$response = curl_exec($ch);
$error    = curl_error($ch);
$info     = curl_getinfo($ch);

$csrf_token = $response;
$node = array('type'=>'documents','title'=>'tall123');
$post = http_build_query($node, '', '&');
$ch = curl_init($endpoint . 'node/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array (
  "Accept: application/json",
  "Content-type: application/x-www-form-urlencoded",
  "Cookie: $session",
  'X-CSRF-Token: ' .$csrf_token
));

$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_r($response);

?>

```
> 0 votes

---
Tags: nodes, services
---


# Question
Title: How can I put custom javascript file at bottom
When I want to override sites/all/libraries Example/example.js file from my custom js file but example.js file at bottom than custom.js file the problem is not give my result of custom.js file because it is above than example.js file.

# Answer
If you want your JS file to load after another js file, you could add a dependency

```
cuddly-slider:
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - some_module/example

```

---

If you want to swap the JS files, load your file instead of the original one, you can accomplish that in hook\_page\_attachments\_alter.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to programmatically update a user role name
I would like to update role name programmatically in Drupal 7. Does Drupal provide its own functions to do that, or do we need to query the database and update the name manually?

Please note that this is not about changing the role a user has, but changing the name of a role.

# Answer
> 3 votes
Information about user roles should never be loaded/saved directly from the database, but using the functions the User module provides, such as:

As for changing the role name, that is not as simple as editing the role object and saving it, since the role name is required to be unique. (The *name* field, in the database, is the unique key for the *role* table.)

Before saving the role object, the code should verify the name is not already used, as the following code does.

```
// Load the role object from the database into the $role variable, using user_role_load()
// or user_role_load_by_name().
// The $role_name variable is assumed to contain the new name you want to give to the role.

if (!(bool) user_role_load_by_name($role_name)) {
  // There isn't a role with that name, so it's possible
  // to change the role object and save it.
  $role->name = $role_name;
  user_role_save($role);
}
else {
  // There is already a role using that name.
  // Make the name unique, or abort the operation.
}

```

Using the functions made available from the User module is preferable, since it allows other modules to react to changes to roles. Those functions invoke at least one of the following hooks.

---
Tags: 7, users
---


title: Restrict block visibility by page url

text:
# Question
Title: Restrict block visibility by page url
Can I restrict the block visibility only show for `/worker/*/` but not `/worker/*/...`?

# Answer
I think block\_exclude\_pages was created for these types of scenarios
> 3 votes

---
Tags: 8, blocks
---


# Question
Title: Countries Additional Data Tokens not working
I'm using Pathauto and Countries to build path aliases that reflect the country and corresponding continent of a node. For example if a node's country field is set to Spain the url should be: `europe/spain/node-title`.

My pattern is: `[node:field-prgm-country:continent-name]/[node:field-prgm-country]/[node:title]` The country renders correctly but the continent shows nothing. I've tried any other additional data (see attached image) and none of it shows.

How do access this additional country data for use in my path aliases?

# Answer
It apperas to be a known issue with some of the country metadata so the current solution is to use the following slightly different continent token:\[node:field-prgm-country:continent\]/\[node:field-prgm-country\]/\[node:title\]
> 0 votes

---
Tags: 7, path-aliases, tokens
---


# Question
Title: How to print text (formatted, long) in twig without raw filter?
We have a text (formatted, long) field that is used to insert embed code such as the Youtube embed code for videos.

When printing the field in twig we are finding that rather than rendering the embed code, it is displaying the embed code as string. To get around this, we currently apply Twig's Raw filter, but wanted to see if there was a way to not use the raw filter and render the field as is.

Content type (basic page):

1. body (text, formatted long) field
2. title

Current results (inserted into Body field using Full HTML text format, displayed as string):

```
<script type="text/javascript" id="vidyard_embed_code_SkWfXrpFKFpS9JrytJwqMt" src="//play.vidyard.com/SkWfXrpFKFpS9JrytJwqMt.js?v=3.1.1&type=lightbox"></script><div class="outer_vidyard_wrapper"><div class="vidyard_wrapper" onclick="fn_vidyard_SkWfXrpFKFpS9JrytJwqMt();"><img width="360" src="//play.vidyard.com/SkWfXrpFKFpS9JrytJwqMt.jpg?" alt="Generating Leads with Video Content"><div class="vidyard_play_button"><a href="javascript:void(0);"></a></div></div></div>

```

Desired results (output of body field shows the video)

# Answer
> 5 votes
You have to prepare rendered array, this is example for paragraph field.

```
<div class="accordion-body">
            {% set accordion_body = paragraph.field_text_of_accordion_entry.value %}
            {%  if accordion_body|length == 0 %}
              {% set accordion_body = ' ' %}
            {%  endif %}
              {% set body = {
                  '#type':   'processed_text',
                  '#text':    accordion_body,
                  '#format':  paragraph.field_text_of_accordion_entry.format,
                } %}
              <div class="accordion-body-container">
              {{body}}
              </div>
          </div>

```

# Answer
> 10 votes
With the excellent Twig Tweak module you can do this:

```
{{ node.FIELD_NAME.value | check_markup(node.FIELD_NAME.format) }}

```

This feature (and more) is well documented on the module's cheat sheet.

---
Tags: 8, entities, wysiwyg
---


# Question
Title: Using different field template suggestion in different view mode
I have a field `field_a` that has a template suggestion of `field--node--field_a.html.twig`. Using that field template suggestion, I've modified the field to render a certain way within the template `field--node--field_a.html.twig`.

If I then create a `teaser` view mode and want to have the field render slightly different within the teaser, how do I write the field template suggestion to ***target only the teaser view mode***?

# Answer
You can do it like so in your themes `MYTHEME.theme` file:

```
/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];
}

```

You can remove `$element['#bundle']` but I left that in there, it will create new template suggestions so you can target view modes *by node type* instead of apply it to every teaser view mode of every node type.

You could just create two suggestions as well if you want:

```
/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#view_mode'];
}

```

This will create new suggestions, as:

`field--ENTITY--FIELD-NAME--ENTITY-BUNDLE--VIEW-MODE.html` and `field--ENTITY--FIELD-NAME--VIEW-MODE.html.twig`, so you would have:

`field--node--field-a--article--teaser.html.twig` and `field--node--field-a--teaser.html.twig` to use.

Then, of course, the normal code in the field template works just the same:

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

Now you can markup fields for view modes of all node types, or also override it for each node type.
> 5 votes

---
Tags: 8, theming
---


# Question
Title: Redirect to a specific page in ajax callback
How can I redirect to a specific page in an ajax callback using Drupal 7, I've already tested this method:

```
function my_ajax_callback($form, &$form_state) {
  if (!user_is_anonymous()) {
    return $form['my_fieldset'];
  }
  else {
    drupal_goto('login');
  }
}

```

but that code doesn't redirect to `/login` when current user is anonymous.

# Answer
I had the same problem. You should try this:

```
ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('login');
return array('#type' => 'ajax', '#commands' => $commands);

```
> 2 votes

---
Tags: 7, ajax, redirection
---


# Question
Title: LoadTest fail due to "chmod(): Operation not permitted"
I downloaded and installed a new Drupal 8 site via Composer.
I generated a new module using Drupal Console.
I tried running a phpUnit functional test of the newly generated module, and it keeps failing due to some folder permission:

> Exception: Warning: chmod(): Operation not permitted Drupal\Component\PhpStorage\FileStorage-\>createDirectory()() (Line: 168)

What grind my gears is that it was working OK a few days ago. Something is clearly wrong with my system, I just don't know what that is, or what changed since then.

I'm running a WSL with Apache 2.4.37 (PHP Version 7.2.12-1+ubuntu18.04.1+deb.sury.org+1).

I have all the detailed steps to reproduce the case, my full *phpinfo*, and some more relevant information in this gist I created.

I spent the last few days browsing for a known solution, and some cases appear to be similar, but none of them seems to hit the spot.

I am using Windows 10.0.17134.407; the tests from the browser are passing. All the files and folders on the project are owned by 'zoio' (user and group); the file permissions for folders and files in modules, sites/default/files, and sites/simpletest are set to 0777.

I tried to follow the tips on this WSL issue, but I just ended up with a different failure, still related to permission and ownership.

> Drupal\Tests\sandbox\Functional\LoadTest::testLoad()
> Exception: User warning: mkdir(): Permission Denied
> Drupal\Component\PhpStorage\FileStorage-\>createDirectory()() (Line: 174)
> /mnt/c/www/temp/d8\_temp/web/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php:51 (...) /mnt/c/www/temp/d8\_temp/web/modules/custom/sandbox/tests/src/Functional/LoadTest.php:33
> ERRORS!
> Tests: 1, Assertions: 1, Errors: 1.

# Answer
> 2 votes
The thing is, the `chmod` wasn't really working.

It was an issue with the mounted drivers in the WSL Ubuntu installation. Based on Stefanos Petrakis' comment, simply trying to unmount and mount the driver with the proper options enabled wouldn't solve the issue by itself. What solved was a bit more drastic:

1. Factory reset the ubuntu (how-to);
2. re-mount the driver, with the metadata option included (source):

sudo umount /mnt/c
sudo mount -t drvfs C: /mnt/c -o metadata,uid=1000,gid=1000
3. Install php, Apache, and everything.

Only then, the phpunit tests did work properly.

# Answer
> 0 votes
It seems like the user **zoio** (the user you're running `vendor/bin/phpunit` as) doesn't have write permissions on your module folder.

Can you tell your module folder's owner and group?

If **zoio** isn't the owner and neither of its groups are assigned to this folder, then your script really won't be able to `chmod` it or modify its contents.

You need to grant write permissions to either the owner or the group.

As a quick and dirty test, you can try running `chmod -R 777 path_to_your_module_folder`.

Just remember to adjust folder permissions back once you've figured out the problem.

Let me know if this helps.

# Answer
> 0 votes
One way to make this run would be by using `sudo` and the same user as the one running apache (that would be www-data according to your gist):

```
sudo -u www-data vendor/bin/phpunit -c ./web/core/ \
  ./web/modules/custom/sandbox/tests/src/Functional/LoadTest.php

```

Good luck!

P.S.: (inspired from https://serverfault.com/a/453823)

---
Tags: testing
---


# Question
Title: Display different icons depending on field value
I am trying to produce a result that requires PHP code to evaluate whether a Drupal 8 node field is a "x", an "f", a "m", a "h", or an "l".

Thanks to some help on an earlier question, I've accomplished my task (to replace the value with a useful icon) when the value is binary: if it exists, show this. If it's empty, show nothing. I've done this via CSS.

Now I'd like to extract the actual value of the node field, and display different icons based on its value.

I am not planning to do this via a function, but rather by code on the node itself. Is there some syntax I can use within the php that will extract this? So that I can have the equivalent of:

```
$price = $node[field][value];

```

then I'd do:

```
if ($price == "m") { // use icon X }
else if ($price == "h") { // use icon Y };

```

Thank you for any and all help/suggestions!

# Answer
> 2 votes
This only requires one field. It sounds like it is a list (text) field to me.

This should be done as a new variable to the node template by way of using `hook_preprocess_node` in your `MYTHEME.theme` (replace any instance of MYTHEME with your actual themes name, i.e. `bartik`) file. Here is an example:

```
function mytheme_preprocess_node(&$variables) {
  $type = $variables['node']->getType();

  if ($type == 'NODE_TYPE') {
    $price = $variables['node']->get('field_name')->value;

    switch ($price) {
      case "m":
        $variables['custom_icon'] = 'icon1';
        break;

      case "h":
        $variables['custom_icon'] = 'icon2';
        break;

      case "x":
        $variables['custom_icon'] = 'icon3';
        break;

      case "f":
        $variables['custom_icon'] = 'icon4';
        break;

      case "l":
        $variables['custom_icon'] = 'icon5';
        break;

      default:
        $variables['custom_icon'] = FALSE;
        break;
    }
  }
}

```

Then, create a `node--NODE-TYPE.html.twig` file, where `NODE-TYPE` is the machine name (bundle) of the node in question (ex. `article`, `page`, `product`).

In this file, you now have a new variable available to use, which would be output with:

```
{% if custom_icon %}
  {{ custom_icon }}
{% endif %}

```

If no value, or value does not match whats expected, the switch statement will set the variable to FALSE so you can check in Twig if you should output it or not.

# Answer
> 0 votes
To display different icons depending on some field values you can simply make use of `template_preprocess_field`. Get the field value and add a CSS class accordingly. And the rest is just CSS.

```
/**
 * Implements template_preprocess_field__FIELD_NAME().
 *
 * @param array $variables
 */
function MYTHEME_preprocess_field__field_price(&$variables) {

  // Get the field value.
  $value = $variables['element'][0]['#markup'];

  // Do whatever else you need to do with $value.
  // ksm($value); ...
  // ...

  // And then append $value as a new CSS class to the field wrapper.
  $variables['attributes']['class'][] = $value;
}

```

Install the Devel sub-module Kint to let `ksm()` pretty-print the value for debugging.

---

Note, depending on the field type you used, the value may be hidden in `$variables['element'][0]['#text'];` or `$variables['element'][0]['#value'];` or something else. Simply check what's inside `$variables['element']` via `ksm($variables['element'])`, first.

---
Tags: 8
---


# Question
Title: Pass parameters for node access on RESTful call
I'm trying to figure out how to pass a filter parameter on a Services rest call. I've got a node of a specific type that I'd like to access through the Services module and rest. I'm testing with FireFox RestClient and I can get all nodes of the particular type by typing

```
http://localhost/drupal/gpa/node/?parameters[type]=node_type

```

But, I'd like to be able to get **one** specific instance of 'node\_type' that contains a specific field value. I've taken a look at node\_resource.inc, but, I can't seem to make heads or tails of what I need to use as parameters. I've tried several variations that typically return no result, or, all instances of, 'node\_type'.

Is it possible to filter the returned results, or, is my approach incorrect?

**EDIT**: If any C# programmer stumbles across this, I was able to use the Basic HTTP Authentication module to prevent unauthorized access to the view. First, as Tyler indicated, I needed to change the permissions settings. In My case, I chose a Role (Administrator).

# Answer
The entity index resources unfortunately cannot be used to filter by field values, they can only filter by entity property values (e.g. node nid, title, type, etc). I think you have two options:

1. create a custom service resource that uses parameters and a database query (or entity field query) to filter and return what you want
2. use views\_json (a sub module of views\_datasource) to create a View with a contextual filter for your field
> 1 votes

---
Tags: 7, services
---


# Question
Title: Post/redirect form to url of node selected
This is a continuation of this:

https://www.drupal.org/project/webform/issues/3023984

I was able to redirect to a node/term url using the token based on the answer provided, great! However this is where it gets complicated. The first select list has three items, selecting one item will open a corresponding conditional second list - that is, there are 3 hidden list that will get displayed based on the selection of the first.

\[webform\_submission:values:ELEMENT\_KEY:entity:url\]

will work only for one list. How can I make ELEMENT\_KEY be based on the selected list.

Thanks

# Answer
> 2 votes
You need to set the selected node's URL as the confirmation URLs token.

Here is an example webform that redirects to the select node when submitted.

---
Tags: webforms
---


# Question
Title: Programmatically get the continent from ISO2
I am using the Countries module to assign countries and associated data to nodes. I am currently writing a custom token and only can access the ISO2 data for the value, not the associated data (full name, language, ISO3).

How can programmatically get the other data with only the ISO2?

# Answer
Continuing the answer from the initial question, I think you have to load the Country entity to replace the token with what values you are after.

Based on looking at the Countries module, it stores countries as a custom entity:

```
/**
 * Implements hook_entity_info().
 */
function countries_entity_info() {
  $return = array(
    'country' => array(
      'label' => t('Country'),
      'plural label' => t('Countries'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'base table' => 'countries_country',
      'token type' => 'country',
      'fieldable' => TRUE,
      'module' => 'countries',
      'entity keys' => array(
        'id' => 'cid',
        'name' => 'iso2',
        'label' => 'name',
      ),
      'bundles' => array(
        'country' => array(
          'label' => t('Country'),
          'admin' => array(
            'path' => 'admin/config/regional/countries',
            'access arguments' => array('administer site configuration'),
          ),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Country'),
          'custom settings' => FALSE,
        ),
      ),
    ),
  );
  return $return;
}

/**
 * Loads a country entity by ISO alpha-2 code.
 *
 * This is also a menu wildcard loader.
 *
 * @param string $iso2
 *   An ISO alpha-2 string. This is case-insensitive.
 *
 * @return object
 *   A country object loaded by the entity controller.
 */
function country_load($iso2) {
  // The URL's should be case insensitive.
  $iso2 = $iso2 ? drupal_strtoupper($iso2) : $iso2;
  return entity_load_single('country', $iso2);
}

```

It *looks* like the `iso2` value is the entity id, based on this code and the helper load function here, so, you can access the full entity when a token is replaced by:

```
/**
 * Implements hook_tokens().
 */
function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node']) && array_key_exists('MYTOKEN', $tokens)) {
    $country = country_load($data['node']->field_prgm_country[LANGUAGE_NONE][0]['iso2']);
    // $country should be a fully loaded Country entity with all its fields and properties
    // check out $country here with ksm($country);exit;
    $replacements['[node:MYTOKEN]'] = // data you want to show;
  }

  return $replacements;
}

```

It looks like the Country module provides its own `country:` scope of tokens, but I do not know how (or if) they work in the context of fields on a node. This should get you closer at least.
> 1 votes

---
Tags: 7, tokens
---


# Question
Title: How can I embed a view in an email sent by Rules without resorting to the PHP filter?
I want to embed a view in an email sent by the Rules module using the standard "Send mail" action. I have the Mime Mail and Mail System modules installed, and I can send HTML email when it is included in the body of a rule.

Based on this question, I tried the Insert View module, but that only allows views to be inserted into node content, not rules (which are entities, but Insert View does not support generic entities). I tried adding `[view:view_name=display_name]` to the message body of my rule, but the view did not appear. To make sure it wasn't working, I added another rule with the "show a message" action and tried to embed the view there, which also didn't work. However, I can place the exact same code inside a node body and the view DOES appear, so it appears that Insert View does not work with Rules.

Entity Views Attachment does support generic entities, but this "attaches" the view, whereas what I am trying to do is embed the view in a rule's email message body like this:

> MY TEXT - HEADER
>
> EMBEDDED VIEW
>
> MY TEXT - FOOTER

I also only need to do this for one email, so if possible, I would like to add something like a custom token for Rules to embed the view, but I'm not sure how to go about that.

# Answer
> 4 votes
Using Insert View, Mime Mail and Mail System module, you can send views in emails.
After installing and enabling the above modules, you will need to configure Mail System settings and Text Format settings.

* In the Mail System settings,
*Change all settings to use **MimeMailSystem** class to send mails.*
**Note:** Site-wide default MailSystemInterface class should be **MimeMailSystem**.
* In the text formats settings,
*Enable **Insert View Filter** in each text format you require.*

The problem for you isn't with the rules. It should be the Mail System settings. I hope this would work.

# Answer
> 1 votes
Ultimately, I solved this by using `views_embed_view()` in the Mime Mail template in my theme directory.

Specifically, I created files like `mimemail-message--key.tpl.php` for the relevant mail **keys** and then I added `views_embed_view()` and other PHP code in the relevant template files.

# Answer
> 0 votes
My site has access-by-term module ABT, (good module to control access to data) this means that if i insert a view in my email, content will be not accesible by anyone not loggedin with certain permissions/roles/abt etc, so my email will be usesless, a blank email. This is what i did:

I installed views rules module, now built a rule to 'build views email data & send it', inside my rule, i had to run 3 rules-views, one main-view to pull UID's to be emailed, other 2 views are nested inside main-view, to acomplish this look here, inside main-view loop i added 2 TEXT empty variables, one for each children-views-rules, having all data accesible stored in tokens sent by views-rules, i built my view row by row with a cutom module using hook\_rules\_action\_info() returning each row already formatted, now in my rule, after each row returned i add an action: set-a-data-value: \[my-text-var\]=\[my-text-var\]\[my-row\] (i did this 2 times, var1 & var2), now inside main-view-loop but outside inner views-loops in body content of my email i just added my variables containing all rows \[my-text-var1\] \[my-text-var2\], done! works beautifull.

NOTE: i'm using a SMTP mail server, so i can not use MIME mail or similar modules, my email looks like an HTML email, but is just text, be aware of what you can do retunrning $var\[\] arrays from rules\_custom\_action\_info()

# Answer
> -1 votes
I have the same situation trying to embed a view in a email and using the action **Send mail** instead of **Send HTML email** in rules solved the problem for me aswell.

# Answer
> -2 votes
Use views\_embed\_view function. Its pretty simple to embed views

---
Tags: views, rules, emails
---


# Question
Title: What is the best way to forward visitors to my homepage to an external site but leave the backlinks accessible?
Maybe not distinctly a Drupal question, I have an older Drupal 7 site that I want to leave up for backlinks, but any new visitors I want to redirect to a new external website. So `domain.com` would redirect to `newdomain.com` but `domain.com/node/6` is still accessible.

Update: Server is nginx and I don't have access to server settings and routes.

# Answer
It sounds like one thing you could do is edit the themes `template.php` file and do something like:

```
/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    $url = 'http://newdomain.com';
    drupal_goto($url, ['external' => TRUE], 301);
    // perhaps alternatively you could use header();
  }
}

```

Outside of doing this at the web server level, it might be the smallest change to do it.
> 1 votes

---
Tags: 7, redirection
---