# Question
Title: Invalid CSRF token using flag.link_builder service (Flag module)
I have a REST route that returns a list of user accounts. I have a flag setup called 'following' as you can follow and unfollow other members. In my REST route, I use:

`$flag_link = \Drupal::service('flag.link_builder')->build('user', $member->id(), 'following');`

which generates the link correctly as far as I can tell. In my javascript object I can see the link that was created. This is an example of the JS object of a user that I use on the front end:

```
0:
  flag_link:
    #access: true
    #action: "flag"
    #attached: {placeholders: {…}, library: Array(1)}
    #attributes: {title: "", href: "/flag/unflag/following/3?destination&token=LEfyLe9PPaQfgNNRSXUA82k4SVHQGRmBEI0adgBva9g", class: Array(1)}
    #cache: {contexts: Array(1), tags: Array(0), max-age: -1}
    #flag: {id: "following", label: "Following"}
    #flaggable: {}
    #theme: "flag"
    #title: {#markup: "Follow this person"}
  id: "3"
  name: "ronnie"
  url: "/user/3"

```

When I go to click the link it 403 forbiddens with the message `message: "'csrf_token' URL query argument is invalid."`

The HTML I am outputting is:

```
<div class="flag">
  <a href="/flag/unflag/following/3?destination&token=LEfyLe9PPaQfgNNRSXUA82k4SVHQGRmBEI0adgBva9g" class="use-ajax" rel="nofollow">Unfollow this person</a>
</div>

```

Any idea what I am doing wrong?

Here is a screen shot of my request when I click the anchor

# Answer
I created an example. You can check it and find the solution there.

https://github.com/Mykola-Veryha/ajax-flag-link
> 0 votes

---
Tags: 8, flags, csrf
---


# Question
Title: How to use modified (calculated) value of a field in Drupal entity query condition?
I have a link field for a content type. I am implementing a validation where users cannot enter a domain name in the field if it has been used already. For that purpose, I need a direct way to derive domain from the field value (full url) for comparison with the domain name of the url entered.

```
$result = \Drupal::entityQuery('node')
->condition('type', 'ABC')
->condition('field_1', parse_url($url_entered)['host']->execute();

```

The problem is **field\_1** is a full url where as I only want validation over the domain name.

Is it possible to do using Entity Query? If not, any suggestions?

# Answer
> 0 votes
To do so you can use **LIKE** operator in your query like the following:

```
$host = parse_url($url_entered)['host'];
$result = \Drupal::entityQuery('node')
  ->condition('type', 'ABC')
  ->condition('field_link', "%" . $host . "%", 'LIKE')->execute();

```

**UPDATE**
if you want to check that the exact host exist, you should select all values of your field and then compare with the entered host.

```
$host = parse_url($url_entered)['host'];
// Select all uris of field link.
$database = \Drupal::database();
$query = $database->select('node__field_link', 'nfl')
  ->condition('nfl.bundle', 'page')
  ->fields('nfl', ['field_link_uri']);
$result = $query->execute()->fetchAll(PDO::FETCH_COLUMN, 0);
$hosts = [];
// extract all hosts.
foreach ($result as $item){
  $hosts[] = parse_url($item)['host'];
}
// Check if the host already exist.
if (in_array($host, $hosts)){
  // Do what you want ici !
}

```

---
Tags: 8
---


# Question
Title: Add class to pagination previous/next button in view Drupal 8
how to add class to pagination previous/next/first/last button in view Drupal 8. Also how to show

First last next previous button default as default is show next/last

# Answer
> 1 votes
One way to add a class to Views pagers is to add the class to the template.

You can copy the template file from `/web/core/modules/views/templates/` into your theme's templates folder and add the classes however you like.

The mini pager template is `views-mini-pager.html.twig`.

---
Tags: views
---


title: Removing a patch from Drupal core

text:
# Question
Title: Removing a patch from Drupal core
I'm using cweagans/composer-patches to apply a patch to drupal/core. When a second developer has pulled down the codebase and run composer install, the installation of drupal/core is failing.

Firstly, I'm not sure why this is happening because composer install works on my local machine?

Secondly, if I remove the patch from my compser.json, and re-run composer install, the patch isn't removed. How can I remove the patch from drupal/core please?

Thanks

# Answer
> 0 votes
When using `cweagens/composer-patches`, the patch only gets applied upon `composer install`. When you remove the patch from `composer.json`, it does not remove the already patched file, because composer isn't tracking that.

So, when you remove a patch from `composer.json`, you need to delete the relevant module/theme/core directory and then run `composer install` again.

As for the second developer's issue, try cloning your code from wherever it is stored and then running `composer install` there; always test from a "fresh" copy of your repository, and then it will be easier to see the issues that people may have when pulling down code for the first time.

---
Tags: 8, composer
---


title: How I change my Site URI in Drupal 8

text:
# Question
Title: How I change my Site URI in Drupal 8
In Drupal 7 I put in settings.php this:

```
$base_url = 'http://mysite.local';

```

And when I run:

```
$ drush uli
http://mysite.local/user/reset/1/1460387746/mTqwCdJ7hi_pmrPRuFOScYwFtoHTmVAW07MV23O3UVk/login

```

The url generated will be fine.

In Drupal 8 I check and still there.

But in my Drupal 8 site, when I try run: $ drush uli

I got:

```
mysite does not appear to be a resolvable hostname or IP, not starting browser. You may need to use the --uri option in your command or site alias to indicate the correct URL of this site.                          [warning]
http://mysite/user/reset/1/1460387905/ntObZiBxAnYdgGoc9jLqCIeQYpN_WjO04UlXcfSNZMo

```

I know I can do this: $ drush uli --uri='mysite.local'

But much work.

Too I can do this with some drush config.

Then, how I do this like Drupal 7 in settings.php?

# Answer
Since Drupal 8 uses Symfony's request stack which generates the base url, some things are not possible to do in the same manner as was possible in Drupal 7.

Instead create `sites/default/drushrc.php` and add

```
<?php

$options['uri'] = 'http://mysite.local';

```

and you should be fine.
> 12 votes

# Answer
@googletorp's answer led me in the right direction (thank you!), but was not the correct answer for me. I am on Drupal 8.6 and drush 9.7. Instead of a drushrc.php file, a drush.yml file was needed.

https://github.com/drush-ops/drush/blob/master/examples/example.drush.yml

specifically, this configuration within it (options is a top-level element):

```
options:
  uri: 'http://mysite.local'

```

There was already a drush.yml file located at /drush/drush.yml so this is the one I used.
> 10 votes

# Answer
for drupal 8.9 and drush 9.7.2

In the outputted list from

```
drush status

```

you will see: "Drush configs". It shows the path or paths to drush configuration files. i.e. /var/www/mysite/drush/drush.yml

in that file you can add:

```
options:
  uri: 'http://mysite.local'

```

drush should pick it up immediately, or after

```
drush cc drush

```
> 6 votes

---
Tags: 8, drush
---


title: Get list of preprocess block variables

text:
# Question
Title: Get list of preprocess block variables
How can I display a list of preprocess block variables so I can conditionally include a library? Using the 'plugin\_id' doesn't seem to work and when I echo all of the variables all I see is a blank page. Is there a Drupal page that will show me what all the variables are for blocks?

My custom block module is called, 'leaflet\_block'.

```
function leaflet_block_preprocess_block(&$variables) {
  echo "<pre>"; print_r($variables); echo "</pre>"; // shows a blank page

  if ($variables['plugin_id'] == 'leaflet_block') {
    $variables['#attached']['library'][] = 'leaflet_block/leaflet_block';
  }
}

```

# Answer
> `echo "<pre>"; print_r($variables); echo "</pre>";`

That's not how it should be done, instead, install the Devel module.

This will allow you to do:

```
dump($variables);

```

If you haven't turned caching off, for developing purposes, then you will have to flush all caches to see the dump.

---

In addition, if you also install the kint package/library with:

```
composer require kint-php/kint

```

now you could also do:

```
kint($variables);

```

Related: Welcome to Kint 101
> 0 votes

---
Tags: 8, blocks, hooks
---


# Question
Title: Using as shipping address the value entered as billing address
In Drupal Commerce 2 how can we allow a customer to select as shipping address the same address entered as billing address?

# Answer
Yes, you can try to custom jquery event.

1.To create a custom js file in your theme folder (/themes/theme-name/js)

Triger Function Like:

$("select\[name='panes\[delivery\]\[select\_address\]'\]").change(function() { //your code //.....

```
});

```

Thanks
> -1 votes

---
Tags: 8, commerce
---


title: How do you add/edit code in Drupal?

text:
# Question
Title: How do you add/edit code in Drupal?
I recently got thrown into a project to fix some problems with a Drupal 7 website for a client despite knowing nothing about it. First of all, is there a way to add my own custom PHP or Javascript code to fix some functionalities without having to create a module? Or are modules the only way of adding code? I find this quite frustrating as I do not understand how you would be able to immediately test things before deploying them. I made a Drupal account & it looks like I would need to make a sandbox, test it there, then install it to the website, but I feel like there must be another way. Is there a way I could just edit the current code on the website or another way to add code to a Drupal website without having to do all that? Thanks! And sorry for the novice question.

# Answer
> 0 votes
Hey Lee since your question is board I am going little verbose here, Yes ideally your custom code should go in as custom module. Since you got into an existing project check for any custom modules made by the previous devs, you can surely edit those. Usually dev encounter 3 types for modules on drupal

1. Core modules: These modules are maintained at it best state since they are the backbone of the CMS. Nowadays they mostly maintain the code base for these modules. Come with the drupal install.
2. Contributed modules: These modules are mostly maintained by the D.O users these module usually bring a feature to the table. For example notify slack used to receive notification to slack once an element is made. These to be added separately. Check how add contrib module.
3. Custom modules: This is were you should concentrate right now. If you think a site require a user/client level changes like extra pages, forms or adding your own JS code etc. you should consider adding a custom module. Follow this link to create a custom module in D7 also please note the directory structure.

Well that been said, why you shouldn't edit the core/contrib module's code base, you can do that but since these modules version controlled. Once a new version is released and added to your site you code will be overwritten. So a big no to this.

You shouldn't worry about the sandbox or most of the things inside the Drupal.org mostly these things are applicable for 1st and 2nd set of modules in my above list.

So my advice will be:

1. Create a local instance of the drupal
2. Add your project repo into it.
3. Check any existing custom module and edit it to your, if not create one for yourself.

I hope this helps.

---
Tags: javascript, hooks
---


# Question
Title: Why is my Rules page redirection based on data comparison not working?
I have to redirect to specific page for article content based on the its entity reference field value

Eg : article content having field\_test2(field\_name) reference to sample / 10164( taxonomy reference field value ) should be redirect to events

I have done this in rules. But the page redirection is not working. I have printed all the variables in article twig all are same but redirection not working.

```
status: true
dependencies: {  }
id: test_workflow_rules
label: 'Test Workflow rules'
events:
  -
    event_name: 'rules_entity_view:node--article'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 48cf31fd-db17-4f6a-ad75-71e9ea7b6b06
  weight: 0
  conditions:
    id: rules_and
    uuid: 3c51e865-1f88-429d-b363-bd7ed62a018f
    weight: 0
    conditions:
      -
        id: rules_condition
        uuid: 45c0f11a-34a3-487d-9e1c-30b3300ee9bf
        weight: 0
        context_values:
          type: article
          bundle: article
        context_mapping:
          entity: node
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: 647b13df-27ec-4c53-88fb-aa010c9e0021
        weight: 0
        context_values:
          operation: '=='
          value: '10164'
        context_mapping:
          data: node.field_test2.entity.tid.value
        context_processors:
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: 2f6d63e8-fb96-4014-b504-900d4763aa08
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 48790fb3-7658-45df-8a8d-ecc6e0f83ff0
        weight: 0
        context_values:
          url: /events
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect

```

The module version - 8.x-3.x-dev

Removing the data comparison and entity is of bundle , the redirection works.

# Answer
Your conclusion is wrong. You say that page redirection does not work, but what is really happening is that your conditions are configured wrong so the redirect action is never used.

For the `rules_entity_is_of_bundle` condition, you have:

```
      type: article
      bundle: article

```

But articles are `node` types, so the `type:` should be `node`. This condition will never be true because of the way you've configured it.

In general, you should debug your Rules one step at a time and use the `rules_system_message` action to display a message on the screen for debugging. First use just the event and the system message action to ensure the message is shown when you expect them. Then add conditions one at a time to see if the conditions evaluate as you expect them to. You can use the system message action to display the values of data like `{{ node.field_test2.entity.tid.value }}`, which will help you see whether the values are what you expect. After you have the conditions working the way you want, *then* add the redirect action.

You can also turn on Rules debug logging to see what Rules are being triggered, by what events they're being triggered, and see the result of each condition evaluation.
> 2 votes

---
Tags: rules, 9
---


# Question
Title: How do I programmatically update the rendering language?
I am trying to programmatically set the Views rendering language of a couple of Views having multiple displays. I found that doing it manually is error prone.

```
use Drupal\views\Views;

$view = Views::getView('ap_country');
print_r($view->display_id);

$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

```

I am trying to achieve something like the above and then export the View. However rendering language does not seem to be a handler.

The reason behind dong this is currently all the views are set to the current Interface language and I want to switch to the content language.

# Answer
> 1 votes
Yes, this is not a handler setting. This is configured directly in a display.

To update a View programmatically use the storage property of the View object (which is by the way a reference to the config object discussed in the comments) and get a reference of a display (the master display is `default`):

```
$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_2');
$display['display_options']['rendering_language'] = '***LANGUAGE_language_content***';
$storage->save();

```

---
Tags: 8, views
---


# Question
Title: How to get a field value and multiply it to get price in a PriceResolver
Getting my feet wet with price resolvers, and I have figured out how to set a new price for all entities that have `field_discount_percentage`. I am then getting the price and multiplying it for the sake of this example by .95 to get a 5% discount.

```
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {
    return $entity->getPrice()->multiply('0.95');
  }
}

```

What I trying to do, is to use `->getValue` or `->getString` for the `field_dicount_percentage` so that I can set the percentage value in the field from the front end.

```
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {

    //here is where i would like to create a variable for the number value of the field, but I get lost...
    $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];

    // I have also tried this
    $discount = $entity->get('field_discount_percentage')->getString();

    return $entity->getPrice()->multiply($discount);
  }
}

```

I am getting empty quotes back from `$discount = $entity->get('field_discount_percentage')->getString();` which is making me wonder if I cannot use a variable to a numerical field value.

> InvalidArgumentException: The provided value "" is not a numeric value. in Drupal\commerce\_price\Calculator::assertNumberFormat() (line 261 of MY-Site\web\modules\contrib\commerce\modules\price\src\Calculator.php).

So what is the best way to do this in a Drupal commerce context?

Any help would be appreciated. :)

# Answer
> 0 votes
I was able to get this to work by checking that `field_discount_percentage` is not empty, rather than just checking if the entity has `field_discount_percentage`. The error must have been from all the other entities that were returning empty fields as a non-numerical value of `""`

```
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && !$entity->get('field_discount_percentage')->isEmpty()) {
     $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];
     return $entity->getPrice()->multiply($discount);
  }
}

```

---
Tags: 8, commerce
---


# Question
Title: How can I prevent a custom block from rewriting HTML?
I have a self-contained widget written by a third party that consists of HTML, JS, and CSS. I've dumped it into a custom block with Full HTML (and verified the Full HTML settings are loose enough that they shouldn't conflict with the markup). Also, I'm using CKEditor. When I save the custom block, it turns `<div class="bookwidget">` into `<div class="bookwidget"> </div>` so that the widget doesn't even get an opportunity to render.

Is there a workaround for this? Is my only alternative to create a custom module?

# Answer
Try going to `Admin menu > Configuration > Content authoring > Text formats and editors` then edit yours (E.g. "basic html")

Down towards the bottom you should see an option: `Correct faulty and chopped off HTML` \- uncheck that option and save.

Not sure why a widget would expect an un-closed `<div />` tag though.
> 0 votes

# Answer
If you want to avoid creating a custom plugin, then I would try creating a new Text Format and remove all processing options and offer no WYSIWYG.

However, this block of code sounds problematic, and the WYSIWYG is not really intended to host full applications. I think you would end up with a more reliable, more secure, higher quality product if you created a custom block and integrated the JS and CSS as libraries. This is more in line with the way that Drupal is intended to operate and allows the markup and JS/CSS assets to properly participate in sanitization, caching, aggregation, etc...
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: How to set up a cron job that runs for a specific rule?
I have a 2 rules that should run each on a specific time interval instead of the regular cron job setting.
I have a list of "Sessions" (entity type) that should be evaluated to see if their booking has expired, if their starting date is in the past, etc. and then certain settings should be updated on each.
I have another list of "Events" (entity type) that does something similar but shouldn't be executed with the same frequency as the Sessions.

Both are rules components.

## My first problem

These components fire when I **force run** my cron job with Elysia Cron module and that works. But it should be automatic. So I have assigned the "rules\_cron" job to a new channel, "channel 2" and it should run every hour but it doesn't do that. rules\_cron apparently runs every 48 hours or so.

## My second problem

What I really need is the **Session component** to run every hour and the **Event component** to run every 15 minutes?

**What am I doing incorrectly and how do I accomplish that?**

# Answer
> 1 votes
> What I really need is the Session component to run every hour and the Event component to run every 15 minutes?

According to your screenshot, it seems you're only running Cron once a day, so even having a shorter schedule than that will not work unless your Cron runs at those needed intervals.

Re-configure your crontab to run at the shortest interval needed. In your case this will be 15 minutes. The configuration of each of those schedules should still ensure that whichever cron hook is only run at the specified times.

# Answer
> 1 votes
For cron jobs more frequent than every 60 minutes, you'll need to add a crontab to the system. I usually set my crontabs to run as frequently as possible, which is once every 60 seconds. This will give you the most granular control over job timing.

Bear in mind that Elysia/Ultimate cron only check as often as you specify. So, they might check every 15 minutes, but if cron, itself, is also running once every 15 minutes, then your timing could be off by up to 14:49. Consider that Elysia Cron might check for a job *just before* the crontab job fires, resulting in Elysia thinking that it is not yet time. It has to wait another 15 minutes until the next check.

Setting the crontab to run once every 60 seconds ensures that your job is not delinquent by more than 59 seconds.

To set up your crontab, please follow these steps:

* Get the link to your site's cron job from `/admin/config/system/cron`
* Open a console on your local machine or remote server, as appropriate, and execute: `crontab -u www-data -e`. Replace **www-data** with the appropriate user if that is not your web server's user.
* In the crontab, add an entry like this: `* * * * * /usr/local/bin/wget --no-check-certificate --quiet -O - <my cron link>`, replacing `<my cron link>` with the link that you copied. Also, BE SURE there is a trailing new line. You also might need to modify the path to `wget`. use `which wget` to determine the path.

Once you set up the crontab, be sure it is also running: https://www.cyberciti.biz/faq/howto-check-cronjob-is-running-not/

# Answer
> 0 votes
If you want to run the cron hook from an individual module (or any other function for that matter), you can use drush's php-eval function. I have a shell script that does this for one client:

```
cd /path/to/site/root
drush php-eval 'mymodule_cron()';

```

Then you just schedule this as you want, for example:

```
*/2 6-19 * * 1-5 ~/scripts/my_custom_cron.sh

```

The only thing to be aware of is that `mymodule_cron()` will also be called by the normal Drupal cron hook if it has the \_cron suffix, so you might want to call it something else if you want to avoid that

---
Tags: 7, cron
---


# Question
Title: How do I get node revisions to use my custom template?
I have a custom node template for my content type of Listing, `node--listing.html.twig`. It is quite heavily customised for the client. However when we go to view a revision (e.g. `/node/144/revisions/273/view`) it doesn't seem to bother loading a template at all, not even `node.html.twig` \- the fields just get dumped onto the page.

Any ideas how to force it to use the custom template?

# Answer
You can try my patch from Make node\_is\_page() work on revisions and previews as well. If that doesn't fix it, you can probably use the relatively simple code update from inside `node_is_page()` to add your own template suggestions using `hook_theme_suggestions_alter`.
> 0 votes

# Answer
Thanks for the suggestion. Actually I have solved this myself in the end, it WAS using the template, it's just that the `page` flag wasn't set in the revision view and that was causing a default view of the node. So my mistake. But worth remembering that when viewing a revision you get `view_mode == 'full'` and `page == false`
> 0 votes

---
Tags: theming, 9
---


# Question
Title: Ultimate Cron installation Table 'db_name.ultimate_cron_log' doesn't exist
After installing the ultimate cron module version 8.x-2.0-alpha4, When I navigate to (/admin/config/system/cron/jobs), I get the following error meassage -

**Base table or view not found: 1146 Table 'db\_name.ultimate\_cron\_log' doesn't exist: SELECT l.* FROM {ultimate\_cron\_log}** l WHERE (l.name = :db\_condition\_placeholder\_0) AND (l.log\_type IN (:db\_condition\_placeholder\_1)) ORDER BY l.start\_time DESC, l.end\_time DESC LIMIT 1 OFFSET 0; Array ( \[:db\_condition\_placeholder\_0\] =\> system\_cron \[:db\_condition\_placeholder\_1\] =\> 0 ) in Drupal\ultimate\_cron\Entity\CronJob-\>loadLatestLogEntry() (line 526 of modules\ultimate\_cron\src\Entity\CronJob.php). Drupal\Core\Database\Statement-\>execute(Array, Array) (Line: 640)

I have tried uninstalling and installing it again, but the error persists. Kindly help.

# Answer
> 0 votes
I ran the following to fix the issue. Manually create tables.

```
CREATE TABLE 'ultimate_cron_log' (
  `lid` varchar(176) NOT NULL COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `log_type` int(11) NOT NULL DEFAULT '0' COMMENT 'Log type',
  `start_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution start',
  `end_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution end',
  `uid` int(11) NOT NULL DEFAULT '0' COMMENT 'User ID',
  `init_message` text COMMENT 'Initial message',
  `message` text COMMENT 'Message',
  `severity` int(11) DEFAULT '-1' COMMENT 'Max severity level of the execution',
  PRIMARY KEY (`lid`),
  KEY `idx_last` (`name`(80),`start_time`,`end_time`,`log_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Logs';
CREATE TABLE 'ultimate_cron_lock' (
  `lid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `current` bigint(20) NOT NULL DEFAULT '0' COMMENT 'Current lock',
  `expire` double NOT NULL DEFAULT '0' COMMENT 'Expiration time of lock',
  PRIMARY KEY (`lid`),
  UNIQUE KEY `idx_name` (`name`,`current`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Locks';
CREATE TABLE 'ultimate_cron_signal' (
  `job_name` varchar(166) NOT NULL COMMENT 'Name of job',
  `signal_name` varchar(166) NOT NULL COMMENT 'Name of signal',
  `claimed` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Is signal claimed',
  PRIMARY KEY (`job_name`,`signal_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Signals';

```

---
Tags: installation, cron
---


# Question
Title: How to add a taxonomy term value as a class?
I am trying to target a specific div with CSS. But for that, I need a unique class in order to target a specific taxonomy term. I look at this question, but that doesn't work as it will target all taxonomy terms.

I have created a `vocabulary` called 'Titles' which has the following terms in it:

>

Which will display the following in my browser:

>

Note that I am not using a view to display these titles. Instead, I used a preprocess function:

```
function MYTHEME_preprocess_node(&$variables) {
  $variables['authortitle'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($variables['node']->getOwner(), 'nodetitle');
}

```

### How can I add "Writer" as a class to the `<a>` tag?

# Answer
To append a term's name as CSS class to the term field itself you could simply implement `template_preprocess_field()` like so:

```
use Drupal\taxonomy\Entity\Term;
use Drupal\Component\Utility\Html;

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  if ($variables['field_name'] == 'field_MYFIELD') {

    if (!$variables['element']['#items']->isEmpty()) {

      // Get the term ID.
      $tid = $variables['element']['#items']->getValue()[0]['target_id'];

      // Load the term.
      $term = Term::load($tid);

      // Get the term name.
      $name = $term->getName();

      // Make the term name safe to be used as CSS class.
      $name_safe = strtolower(Html::cleanCssIdentifier($name));

      // Append class.
      $variables['attributes']['class'][] = $name_safe;
    };
  }
}

```
> 2 votes

# Answer
Using content values for classes can be accomplished in twig. For something as simple as your example above I'd override taxonomy-term.html.twig for my theme. Adding `class="{{ name}}"` to the 'a' tag in there should do it.

You could also use `attributes.addClass()` similar to the way node information is added in those twig files.
> 0 votes

# Answer
I find very useful to have taxonomy based classes in the `<body>` tag.

Typical: you want to hide the "share to social" field form some kind (term) of pages.

Having a term based class in body you can

```
body.tid-123 field-with-social-links  {
  display none;
}

```

Find out how to in https://drupal.stackexchange.com/a/220751/13760
> 0 votes

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


# Question
Title: How do I post JSON data on a remote resource?
I'm working to integrate a Drupal 8 site's content into a 3rd-party search tool. To get our data, the 3rd party requires us to post JSON to their API. Having never done this before, what is conceptually needed to accomplish this in Drupal 8? The site in question is around 5-6k nodes.

My initial thoughts are a custom module with a route that calls a controller function that creates an http client. The client gets its data from a json View. So when I visit the route, it pushes the data to the endpoint? That is my rough guess and any insight is much appreciated.

Thanks!

# Answer
Quite a few ways to do that, but here's one approach using the queue api, for async processing:

1. Add the items to a queue on save.
2. Add a queue worker to process the queue and send the items to the remote service.

If you use a cron queue, you can process them automatically via cron.

More info:
> 0 votes

---
Tags: 8
---


# Question
Title: When should hook_post_update_NAME() be implemented instead of hook_update_N()?
What I found so far is that certain actions are unsafe to be performed inside `hook_update_N()`, but I didn't find any documentation saying which those actions are.

When should I implement `hook_post_update_NAME()` instead of `hook_update_N()`?

# Answer
Normally when you update Drupal core locally you perform the following:

```
composer update
drush updb
drush cex

```

Let's say that there's a core module implementing `hook_update_N()` to update some content or config – an update that triggers entity load and entity save somehow. Now let's say that in some other core module inside some other `hook_update_N()` are updates to the database schema which in the end handles how this content or config is actually stored. How can you reliably ensure that the schema updates run before the content/config updates, especially when some users update their site skipping some few minor releases at once?

So `hook_post_update_NAME()` was introduced to guarantee all schema/structure/format updates have run first and now can be relied on when needing to update content or config on top of them.

---

Now let me also tell you that the most reliable hook for simple content updates from a custom module is `hook_deploy_NAME()`. This hook was introduced in Drush 10.3.0 together with the new `drush deploy` command. Using this new command to replace the old `drush updb && drush cim` deployment routines all `hook_deploy_NAME()` implementations will be picked up **after configuration import**. Which totally makes sense when you want to populate a new field which has only been created and added to config in the same release.
> 7 votes

# Answer
According to the documentation (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook\_post\_update\_NAME/8.4.x) hook\_post\_update\_NAME is for content updates.

Compared to hook\_update\_N: that is for database changes. The two provide a solid way to upgrade your webapplication. I'm only missing a pre-config-update hook and a post-config-update hook. I solve that now using exceptions. When you trow an exception in hook\_update or hook\_post\_update it will mark the update as unprocessed, and will retry to run it the next time you run the `drush updb` command.

Solving those 2 problems:

1. When update logic for content depends on update logic for database: use hook\_post\_update
2. When update logic for content depends on configuration import: retry the hook\_update and hook\_post\_update run.

```
# first try hook_update_N and hook_post_update_NAME
# Add validation to see if the configuration has been updated.
$ drush updb -y

# configuration changes
$ drush config-import sync -y

# update again, it will retry the hook_post_update_NAME
# that failed during the first run.
$ drush updb -y

```
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Ajax error when trying to add another paragraph
Drupal 8.9 and paragraph 8.x-1.11

My issue is that Ajax breaks when altering the #validate form. This is an issue for any form! It may have to do with my ajax, but here is my setup.

I have a paragraph type:

contact\_information

* field\_phone\_number (telephone from core)
* field\_type\_of\_phone (text\_plain)

I have a custom module. In this custom module I am creating a form\_alter on /user/register

I have:

```
function telephone_alter_form_user_register_form_alter(&$form, $form_state, $form_id ){
  //$form['#validate'] = array();  //commenting this in or out doesn't help
  $form['#validate'][] = 'telephone_alter_test_validate';
  //$form['field_phone']['widget']['#element_validate'][] = 'telephone_alter_test_validate';
}

function telephone_alter_test_validate($form, &$form_state) {
   echo "hi"; //prints hi, but ajax breaks
}

```

The validation works, prints out debugging. However, when I try to add another paragraph element, it does nothing. This is for any form. I have tried this on other forms like adding a basic page and trying to call an alter function!

the Ajax error displayed is:

```
[{"command":"insert","method":"prepend","selector":null,"data":"\u003Cdiv data-drupal-messages\u003E\n  \u003Cdiv class=\u0022messages__wrapper\u0022\u003E\n \u003Cdiv class=\u0022alert alert-danger alert-dismissible\u0022 role=\u0022alert\u0022 aria-label=\u0022Error message\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 role=\u0022button\u0022 class=\u0022close\u0022 data-dismiss=\u0022alert\u0022 aria-label=\u0022Close\u0022\u003E\u003Cspan aria-hidden=\u0022true\u0022\u003E\u0026times;\u003C\/span\u003E\u003C\/button\u003E\n \u003Ch2 class=\u0022sr-only\u0022\u003EError message\u003C\/h2\u003E\n \u003Cp\u003EAn unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (40 MB) that this server supports.\u003C\/p\u003E\n \u003C\/div\u003E\n    \u003C\/div\u003E\n\u003C\/div\u003E\n","settings":null}]

```

The Ajax error is key, because if I create an alter form for any other page, I still get the error.

Any help is great! Thank you! I can provide more info if needed

# Answer
I had the same issue. It turned out every time a paragraph is added the validation method runs. In your case, `echo` is illegal and it stops the following process. Try replacing it with php `error_log` or Devel debug functions.
> 1 votes

# Answer
If you "initialize" the **#validate** form array key, you will loose the validations set by other modules (like paragraphs). This is bad practice and can break things.

Add your custom validation method like this:

```
function telephone_alter_form_user_register_form_alter(&$form, $form_state, $form_id ){
  $form['#validate'][] = 'telephone_alter_test_validate';
}

```
> 0 votes

---
Tags: 8, users, forms, ajax, paragraphs
---


# Question
Title: Pass query parameters through local response
I'm trying to pass query parameters received on a controller from an external redirect through TrustedRedirectResponse or LocalRedirectResponse. None of the options seem to be working.

# Answer
Receive the query parameters through the request you've added as parameter to the controller and pass them via the URL of the redirect.

Caching is a bit tricky because generating an absolute local URL bubbles up cacheable metadata which you need to collect by Url::toString(TRUE):

```
public function view(Request $request) {

  $url = Url::fromRoute(
    '<front>',
    [],
    [
      'query' => $request->query->all(),
      'absolute' => TRUE,
    ]
  )->toString(TRUE);

  $redirect = new LocalRedirectResponse($url->getGeneratedUrl());
  $redirect->addCacheableDependency($url);
  $redirect->getCacheableMetadata()->addCacheContexts(['url.query_args']);

  return $redirect;
}

```
> 0 votes

---
Tags: 9
---


# Question
Title: Implement an API to use HTTP extensions like CalDAV
I want to create a calDAV API endpoint. The client would contact my API using methods mentioned in the sabre DAV client documentation https://sabre.io/dav/building-a-caldav-client/ (sabre dav seems to be used by alot of projects so I am using it as a protocol documentation).

Now I am completely lost how to implement that in Drupal. There was a webDAV module but it's abandoned for 4 years and a calDAV module that's abandoned for 9 years...

Can I use REST API and hook it to respond to HTTP request methods like PROPFIND?

# Answer
> 1 votes
I solved this. I added method to the route and @Method({'PROPFIND'}) to the source (I am not sure if this is needed for Symfony).

```
class DavController extends ControllerBase {

/**
 * @Method({"PROPFIND"})
 */
 public function dav() {
     //Get the data, fill into xml twig

        $response = new Response();
        $xml = \Drupal::service('renderer')->renderRoot($build);
        $response->setContent($xml);
        $response->headers->set('Content-Type', 'application/xml');

        return $response
 }

```

module\_name.routing.yml (this seems to be mandatory):

```
    entity.dav_controller.dav:
        path: 'path/to/dav/enpoint'
        methods: [PROPFIND]
        defaults:
            _controller: '\Drupal\path\to\DavController::dav'
            _title: 'my_title'
        requirements:
            _permission: 'access content'

```

This works in 8 and 9.

Note that this does not involve the Drupal REST API. This is supposed to be an own implementation and won't solve the issue for anyone who wants to use REST API to answer to such methods. I am not experienced enough with Drupal to explain if and how one could configure REST API to accept HTTP methods not listed in the REST API documentation. Maybe one could extend own controllers from the REST API, but I didn't inquire into how to do that.

---
Tags: 9
---


# Question
Title: Update customer billing address within custom pane
I am writing a custom CheckoutPaneBase within Commerce 2 that incorporates shipping and billing information. My goal would be to update the customer's billing address, that is stored as billing profile, programmatically. I looked at the billing information Pane and see that they use:

```
  $billing_profile = $this->order->getBillingProfile();
      if (!$billing_profile) {
        $billing_profile = $this->entityTypeManager->getStorage('profile')->create([
          'type' => 'customer',
          'uid' => 0,
        ]);
      }
      $billing_profile->populateFromProfile($payment_method_profile, ['data']);
      $billing_profile->save();
      $this->order->setBillingProfile($billing_profile);

```

But rather that populate from $payment\_method\_profile, I would like to add my own fields' values. I am not sure how I can populate an array to push to populateFromProfile or setBillingProfile or the field values.

Any help or hints?

# Answer
You can update the field value like this:

```
  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default');
  $billing_profile = $cart->getBillingProfile();
  $billing_profile->field_name->value = 'Hello World';
  $billing_profile->save();

```
> 1 votes

---
Tags: commerce
---


# Question
Title: How to filter paragraphs by the field name on parent using entityQuery?
I have a paragraph type `my_paragraph` which is attached to a node type `my_content_type` on multiple fields like `field_a`, `field_b`, `field_c`, `field_d`. I want to load only those attached to some specific fields, let's say `field_a` and `field_c`. I am using `entityQuery`, but open to other suggestions.

The entity/field structure is like:

```
my_content_type: Node
|_ field_a: Paragraph (type: my_paragraph)
|_ field_b: Paragraph (type: my_paragraph)
|_ field_c: Paragraph (type: my_paragraph)
|_ field_d: Paragraph (type: my_paragraph)

```

My code which loads all paragraphs of type:

```
\Drupal::entityQuery('paragraph')
  ->condition('type', 'my_paragraph')
  // Here I want to filter by the field name on the parent entity
  ->condition('PARENT_FIELD', ['field_a', 'field_c'], 'IN')
  // Some more conditions out of context
  ->condition('out_of_context_field', $out_of_context_value)
  ->execute();

```

Is there any entity query condition I can use here?

# Answer
Specifically with Paragraphs there are three extra fields directly on Paragraph level, which are accessible with EntityQuery: `parent_id`, `parent_type` (entity type like "node", not bundle name like "page"), `parent_field_name`

You can use those three with EQ like a normal field, e.g.

```
->condition('parent_field_name', ['field_a', 'field_c'], 'IN')

```

Notice that those three fields are only available for Paragraphs, it will not work with any other entity type.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Apache SOLR index or retrieve the node a file is attached to
I'm building a search engine with `Apache SOLR (8.7.0)` where PDF files are indexed and searched through, that part is working (with search\_api\_attachments in case you're wondering). However, the client wants to show a link to the node where this file was referenced from. This is using plain file fields, no media library. Is there a way to either index the node ID with the file, or get this reference somehow in the view with a relationship or something? Spent a good day on it but couldn't figure it out, maybe I'm just overlooking it. Or is this something that would require me writing a custom hook to add the field to the index? (it seems like quite a general use case to me though)

# Answer
I am not sure if this can be done with a generic file field. It could be possible if it was a media or entity reference field. I think the simplest approach is to use `hook_search_api_solr_documents_alter` to find and add the node ID to the document when it is being indexed.

You can, possibly, then use the new field to create a relationship to Node table in the view to display the link or simply handle it on the theme level.
> 1 votes

---
Tags: 8, views, files, search
---


# Question
Title: Facets hierarchical taxonomy terms not working
I use the Facet module `version 8.x-1.x-dev`. I have a list of taxonomy terms with parents and childs.

The taxonomy term facet is an Entity reference field. I can't get the hierarchical structure working in the frontend.

# Answer
I fixed it by re-added the field from `admin/config/search/search-api/index/default_index/fields` and take the `ID` from the index instead of `name`. Then in the Facet settings use `Transform entity ID to label`. Then the hierarchical structure from the taxonomy terms works!
> 4 votes

# Answer
I was confronted with the same problem, Meez's comment helped me on my version (Drupal 8.9.9, Search API 1.17.0 and Facets 1.5.0), to have the option `Transform entity ID to label` on the facet, you must not go through the selection of an ID or Name attribute on the taxonomy field in `admin/config/search/search-api/index/MYINDEX/fields`, use it directly in the reference field of taxonomy (`field_myfield_taxonomyreference`). Everything else is fine, thank you.
> 0 votes

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


title: How to migrate content from json?

text:
# Question
Title: How to migrate content from json?
I have a json file like this

```
{
  "online": false,
  "key": "123",
  "Product": {
    "name": "product name",
    "Id": 12,
  },
}

```

I have my json migration file

```
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - 'json_path/data.json'
  item_selector: /Product
  fields:
    - name: keyword
      label: 'Keyword'
      selector: name
  ids:
    product_key:
      type: string
  constants:
    vocabulary: tag
process:
  vid: constants/vocabulary
  name: keyword
destination:
  plugin: entity:taxonomy_term

```

but I am getting the following error.

```
Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null

```

It means the xpath is not correct.

I have tried with the `item_selector: $` and for the keyword selector `selector: Product.name` but then I am getting this error.

```
Passed variable is not an array or object

```

I have tried with `item_selector: 0` and `item_selector: /` but nothing worked.

However when I use the following json.

```
{
  "online": false,
  "key": "123",
  "Product": [
    {
      "name": "product name",
      "Id": 12,
    }
  ],
}

```

Notice the \[\] brackets.

What is the issue? How can I make it work without the \[\] brackets because I don't have any control on the json to change it.

# Answer
> 0 votes
The `data_parser_plugin: json` always expects an array with numeric keys as `item_selector`, there is no way you can get around this requirement in YAML. If you want to use a single object as `item_selector`, you have to create your own `data_parser_plugin`.

I've already had that problem in a previous object and creates my custom plugin and used my custom `data_parser_plugin: single_json_object` in YAML instead.

file `MY_MODULE/src/Plugin/migrate_plus/data_parser/SingleJsonObject.php`

```
<?php

namespace Drupal\MY_MODULE\Plugin\migrate_plus\data_parser;

use Drupal\migrate_plus\Plugin\migrate_plus\data_parser\Json;

/**
 * Obtain JSON data for migration.
 *
 * @DataParser(
 *   id = "single_json_object",
 *   title = @Translation("Single JSON object as root")
 * )
 */
class SingleJsonObject extends Json {

  protected function has_string_keys(array $array) {
    return count(array_filter(array_keys($array), 'is_string')) > 0;
  }

  protected function getSourceData($url) {
    $source_data = parent::getSourceData($url);

    if ($this->has_string_keys($source_data)) {
      $sequential_array = [];
      $sequential_array[] = $source_data;
      $source_data = $sequential_array;
    }

    return $source_data;
  }
}

```

---
Tags: 8, migrations
---


# Question
Title: Query condition that needs to return true no longer working
I'm working on updating our sites to D9. One of our custom modules stopped working and I narrowed it down to this bit of code that modifies some query conditions for a view filter. It's trying to set a condition that always returns true (i.e. 1 = 1).

```
function views_taxonomy_filter_process_query_conditions(array &$conditions, $field) {
  foreach (Element::children($conditions) as $key) {
    if ($conditions[$key]['field'] instanceof ConditionInterface) {
      $child = & $conditions[$key]['field']->conditions();
      views_taxonomy_filter_process_query_conditions($child, $field);
    }
    elseif (strpos($conditions[$key]['field'], $field) !== FALSE) {
      // We cannot just unset the condition, because this action might create
      // incorrect query. Let's replace it with 1 = 1 condition.
      $conditions[$key] = [
        'field' => 1,
        'value' => 1,
        'operator' => '=',
      ];
    }
  }
}

```

This worked fine in D8. However I'm now getting this error as it seems to be looking for a column called `1` instead of evaluating that condition:

```
Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause'

```

How can I change this to restore the old functionality? Thank you!

# Answer
I found out here that since Drupal 8.7.0 (at least) the field part of the condition can not be an expression.

Since you can't use "where" you must figure out another way to force the condition to always be true. Maybe you could mess around with the operator like this:

1. Instead of overriding the entire condition, use the "LIKE" operator:

```
$conditions[$key]['value'] = '%';
$conditions[$key]['operator'] = 'like';

```
2. Or if that doesn't work, the "NOT IN" operator:

```
$conditions[$key]['value'] = array('w00t');
$conditions[$key]['operator'] = 'NOT IN';

```

Hope this helps you!
> 2 votes

---
Tags: views, 9
---


# Question
Title: How to implement StackMiddleware for a redirection correctly?
I'm working on a redirection (for unauthenticated users) for my Drupal 8 site. Currently, the redirection works however, the redirection persists even after user is authenticated. I found this article piece helpful to point me in the right direction:

"Drupal 8 has two level cache, page cache and dynamic page cache. The issue you are having is more likely to intercept the page cache. Add new class which implements 'HttpKernelInterface' and register 'http\_middleware' with higher priority than 200 (280 will do)."

My problem is related to intercepting the page cache, so I am currently trying to implement the 'HttpKernelInterface' and register 'http\_middleware' but unsuccessfully. I created a custom module (example\_module for example sake). My example\_module.services.yml file:

```
services:
  example_module.event_subscriber:
    class: Drupal\example_module\EventSubscriber\RedirectAnonymousSubscriber
    tags:
      - { name: event_subscriber }
  example_module.stack_middleware:
    class: Drupal\example_module\EventSubscriber\StackMiddleware
    tags:
      - { name: http_middleware, priority: 210, responder: true }

```

Then in the same module I have a `src/EventSubscriber/RedirectAnonymousSubscriber.php` file like so:

```
<?php

namespace Drupal\example_module\EventSubscriber;
namespace Drupal\example_module\StackMiddleware;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface,HttpKernelInterface {
  private $redirectCode = 301;

    /**
  * The wrapped HTTP kernel.
  *
  * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  */
  protected $httpKernel;

  /**
  * Creates a HTTP middleware handler.
  *
  * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
  *   The HTTP kernel.
  */
  public function __construct(HttpKernelInterface $kernel) {
    $this->httpKernel = $kernel;
  }

  /**
  * {@inheritdoc}
  */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Only allow page caching on master request.
    if ($type === static::MASTER_REQUEST && $this->requestPolicy
      ->check($request) === RequestPolicyInterface::ALLOW) {
      $response = $this
        ->lookup($request, $type, $catch);
    } else {
      $response = $this
        ->pass($request, $type, $catch);
    }

    return $response;
  }

  public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://google.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection',30);
    return $events;
  }
}

```

Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching? Do I have to create a separate custom module to implement my `StackMiddleware` class? How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache and have it run on every page(so it always checks to see if user is authenticated)? Any help appreciated. Thanks!

# Answer
I recently implemented this myself and had to do a fair bit of research and experimenting to get it to work. I too had many of the same questions you have so I've tried to answer them from what I've discovered.

> Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching?

You will only need the "StackMiddleware" to intercept the page caching. It should replace "EventSubcriber" if that already exists.

> Do I have to create a separate custom module to implement my StackMiddleware class?

This can be achieved in the same module.

> How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache?

The redirection function should be called as in the following code.

```
public function handle() {
  // …
  $this->checkForRedirection();
  // …
}

```

> Have it run on every page (so it always checks to see if user is authenticated)?

In my case, the user object wasn't available because the middleware runs prior to any user data being set. What I had was the Drupal session cookie which I could use to check. This cookie is set or unset whether the user is authenticated. This may not be the most robust solution so others are welcome.

I found Replacing hook\_boot() and hook\_init() Functionality in Drupal 8, which was great to get the code working.
> 0 votes

---
Tags: 8, caching, redirection, event-subscribers
---


title: How to delete 'blocked' users in bulk?

text:
# Question
Title: How to delete 'blocked' users in bulk?
There are a spammer(s) out there constantly creating accounts on my site. The accounts are 'blocked' by default so they do not pose a problem, nor does the spammer gain anything from them.

Still, I would like to delete them all but without having to click on the /admin/people page 150 times: canceling accounts 50 at a time.

Is there a way to cancel all 'blocked' accounts in one step?

Drush only appears to let me cancel one at a time...

# Answer
Use the Views Bulk Operations module.

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

You can create a view that shows only the blocked accounts and adds bulk operations to it. In this way, once you select all the accounts with a single click, you can delete them by selecting the operation to do and clicking on the submission button.
> 13 votes

# Answer
Deleting users directly from database is not a good idea. either done through *drush* or by interacting directly with the database through SQL `DELETE`. Some modules, for instance, create *robot users* and these tend to be blocked. Just deleting them may interfere with the module's operation and even make the module fail, leaving you with orphaned data and inexplicable error messages.

When spam registrations appear as "blocked" users, they're blocked because their accounts remain *unverified* (spammers, as a rule, never verify, so their accounts never progress from the blocked status).

A project named LoginToboggan gives you the option to have unvalidated users purged from the system at a pre-defined interval. This will also take care of any spammers that register in the future, without making it necessary to introduce protective measures such as CAPTCHA, that tend to discourage *legitimate* users from signing up.

Using LoginToboggan to bulk-remove spam users is much safer and more robust than hacking the database yourself.

If you don't want to install a module to do this, as an alternative, you can delete the *unverified* users using *drush* and `user_delete()`.
> 3 votes

# Answer
For Drupal 8 with drush under Linux (with bash) you can use following solution:

```
    echo 'select name from users_field_data where status=0 and uid!=0' | mysql --silent drupaldatabase > userlist
    for username in `cat userlist`; do drush user-cancel $username -y; done

```

This is both rather slow (1 user/s) and safe. It doesn't work with special UTF-8 character names and names with spaces.
> 3 votes

# Answer
This is what I did, without adding in any extra modules or coming up with any fancy scripts or bash commands. Obviously, I'm going to get alot of hate for this as it involves hacking core **temporarily**.

But this is the **FASTEST** way. Period.

* edit the file /modules/user/user.admin.inc
* search for limit and change the 50 to a high number
* goto your site and user admin page /admin/people
* filter by blocked
* delete....
* switch the limit number back to 50, because the drupal gods will not like it.

No worries about missing any drupal hooks. Obviously if you set the limit number to high, it might crash your sql server. So set it appropiately. I had 10k worth of blocked users to delete. I set it to 5000 and just had to delete users only on 2 pages.
> 3 votes

# Answer
Or use this module advance user module and token module and open people menu in drupal admin and see the advance tab menu and delete bunch of user records.

https://www.drupal.org/project/advuser

and

https://www.drupal.org/project/token
> 2 votes

# Answer
For Drupal 8, there is the user\_prune module that have few options such us delete never logged in users, or blocked users.

https://www.drupal.org/project/user\_prune It deletes upto 500 users that fit certain criteria per cron run.

If you have huge number and want do it fast, then backup your db and do it via mysql query (not recommended but it works). The below query is assuming you using prefix for your db tables. As of this writing the 3 tables where users are located are:

```
[yourprefix_users , yourprefix_users_data, yourprefix_users_field_data ]

delete u,ud,ufd from yourPrefix_users u inner join
yourPrefix_users_data ud ON u.uid = ud.uid inner join
yourPrefix_users_field_data ufd ON ufd.uid = ud.uid
 where access=0;

```

That deletes those that never logged in (access=0) you can use status=0 for blocked ones.
> 1 votes

# Answer
If you are sure that all of the blocked accounts need removing, then you could run a query in phpmyadmin (or your mysql admin of choice):

```
DELETE FROM users WHERE `status` = 0 AND `uid` != 0;

```

That should get rid of all blocked accounts and leave the anonymous user. Of course you would DEFINITELY want to back your DB up first. Also, realize this also get rid of any accounts that may be legitimate, but that you may have set status as 'blocked' for some reason.

Note: I should say that I know way more about 6 than 7. So if the users table is drastically different in Drupal 7, this may be incorrect.
> 0 votes

# Answer
This is my late to the party solution how to use get this done without having to add vbo. The command itself is probably a bit fragile and may break under certain configurations of mysql but the deletion itself should be safe.

```
drush sqlq "SELECT uid FROM users WHERE uid >= 629" | grep -v uid|tr '\n' ','|awk '{print "drush ev \"user_delete_multiple(array("$1"))\""}'|sh

```

for nodes you can alter appropriately

```
drush sqlq "SELECT nid FROM node WHERE nid >= 435193 AND type='school'" | grep -v nid|tr '\n' ','|awk '{print "drush ev \"node_delete_multiple(array("$1"))\""}'|sh

```

Notice, you need to change nid/uid in the grep portion along with the function call to appropriately grab the uid/nid values.
> 0 votes

# Answer
IN drupal 8 you must delete content for 3 tables.

* first make a copy of your database
    + now go to your phpMyadmin console and pick your database
    + Browse your user\_field\_data table in order to see the UIDS range you want to delete. usually low number UIDs are your real users..
    + now delete the data for blocked users, in my case all users with UID \> 240 are blocked
    + use this SQL commands -change UIDs number for your case. DELETE FROM `users_field_data` WHERE uid \>= 240
    DELETE FROM `users_data` WHERE uid \>= 240 DELETE FROM `users` WHERE uid \>= 240
> 0 votes

---
Tags: users
---


# Question
Title: How can I require customers to fill out a custom field when purchasing certain products?
I'm using the Commerce framework. I use the commerce\_license and commerce\_recurring modules to sell subscription memberships to users.

I'm trying to implement gift memberships, so that User A (the "purchaser") can pay for a subscription for User B (the "recipient").

So, when the purchaser checks out, I need to prompt them for the recipient's email address. How can I do this?

(I can imagine other scenarios where you might want to prompt the customer for a "gift message", or a line of custom text to print on a personalized mug, or something like that.)

I know that the Commerce framework has product attributes, which allow customers to specify things such as color, size, etc. However, as far as I can tell, this doesn't support free-text fields – only radio buttons, select boxes, and the like.

Any ideas?

Bonus question: I'll need to validate the recipient's email address before allowing the purchase, so I can make sure they don't already *have* a subscription. Any thoughts on how to approach that?

Thanks!

# Answer
Add a "Recipient email" field to your order item type and expose it to the Add to Cart form. It's up to you then to override the normal fulfillment process that creates entities for the current user, directing them to another user account instead. You'll also need to accommodate the edge case of a customer buying on behalf of a person who doesn't have a user account yet.

cf. https://docs.drupalcommerce.org/commerce2/developer-guide/orders/order-items
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: Is there a way to add bulk media upload in the modal dialog when using ckeditor and entity embed?
I was a heavy D7 developer and I skipped 8. Now I'm trying to build some sites in 9. Just wrapping my head around what's in core and contrib to get what I need. I was wondering what methods people are using (if any) for the possibility of doing bulk media uploads in the modal dialog in ckeditor using entity embed?

# Answer
Gotta love the downvotes for a basic question. I sure missed you, Drupal community.

I'll answer my own question then.

https://www.drupal.org/project/file\_browser

> This module provides a default Entity Browser that lets you browse and select your files in a nice-looking, mobile-ready Masonry based interface, and upload files using the Dropzonejs module.
> 0 votes

---
Tags: media, 9
---


title: How to sort View on rewritten field?

text:
# Question
Title: How to sort View on rewritten field?
I have a View with a table display format and all columns are set as being sortable. Although the issue isn't specific to Date fields; I am specifically trying to figure out an issue with Date fields.

I have 2 Date fields, one is primary and the other is secondary. I have tried various ways in adding the login for "if (pri) pri, else sec".

1. using no results option for pri date field
2. using twig in a custom text field

The results are:

1. sorts only on the base field; not the rewritten value
2. wsod when selecting to sort on this column

I have tried this both with db search as well as Search API - same results. I seem to be able, with Search API, to create an aggregated "First" field which seems to work; although the date format is not adjustable. I have also seen a patch which allows formatting of the base date fields; but my guess is that this will then give a string sorting of the aggregated field (i.e. Dec comes before June).

My next shot is to use the aggregated date field formatted as SOLR is giving by default and assume that is a valid date sort (I think it is, YYYY-MM-DD) and then do up a field formatter to display the correct date format.

# Answer
> 2 votes
I think the quick answer is "you can't sort on a rewritten value" in Views; regardless if it's a date field or using Search API.

There are however; various workarounds depending on the particular issue. I have used the following now:

* use Computed Field to store the rewritten value in the db and then display/sort on that
* SearchAPI is capable of doing simple rewrites with its Aggregated Field; this may work for simple rewrites.

You can often combine a computed field and a rewrite in Views to take advantage of Views field formatting. Keep in mind that the sorting occurs on the original db value for the field. So, for my example above, you could do a computed field to store the timestamp of the Date Range's end date; and then add that to the View but rewrite that field with the formatted end date. This will then sort on the timestamp; but display the properly formatted value.

---
Tags: 8, views
---


# Question
Title: Replace UID in view tab with name on user profile page
I'm working on a Drupal 8 site. I made a custom page view displaying special content created by the user. The menu tab shows on the user profile correctly by using Pathauto to show the correct address on the primary user profile page using a pattern of: user/\[user:field\_full\_name\].

On the tab page created by my custom view, I can't get it to show the user name, only the user ID from the page view path: /user/%user/other-work

I would like the tab's page view URL to show the user's name instead of just the user ID. I already tried different patterns in Pathauto, but it doesn't seem to have that ability. Pathauto does work for fixing the default user page URL, but none of my custom views pages I added. Does anyone know if it's possible for a custom view page like mine to show the user's name instead of the UID in the tab's URL?

# Answer
> 0 votes
> To replace UID in view tab with name on user profile page:

follow those steps:

1. Create a user relationship :
2. Add contextual filters with **User Name**  3.Configure your contextual filter (**(author) User: Name**) like this
3. Save your configuration.

**Result**

---
Tags: views, navigation
---


title: Migrating link fields to Drupal 8

text:
# Question
Title: Migrating link fields to Drupal 8
I am trying to migrate a link field field\_url from a Drupal 7 site to my Drupal 8 one. The link field is compound, it has a title and a url value. In my process plugin I am selecting the right values (field\_url\_title and field\_url\_url), but I don't know how to map them in my yaml definition file. What I have:

```
          field_url: field_url_url
          field_url_title: field_url_title

```

...maps correctly the url, but does not populate the title one. What's the destination field machine name I would need to use to add in the link title?

# Answer
> 9 votes
Here is an example:

```
field_url:
  plugin: iterator
  source: field_url
  process:
    uri: url
    title: title
    options: attributes

```

Because in D8 the `field_url_url` database field changed to `field_url_uri` and the `attributes` to `options`, you can not use direct mapping on this field.

# Answer
> 5 votes
As of Drupal 8.4, the iterator process plugin is deprecated. Use sub\_process instead

See change record: https://www.drupal.org/node/2880427

```
field_url:
  plugin: sub_process
  source: field_url
  process:
    uri: url
    title: title
    options: attributes

```

# Answer
> 4 votes
As of at least 8.4, the "field\_link" plugin should do the trick. https://api.drupal.org/api/drupal/core%21modules%21link%21src%21Plugin%21migrate%21process%21FieldLink.php/class/FieldLink/8.4.x

```
process:
  field_new_link_field:
    plugin: field_link
    uri_scheme: 'https://'
    source: field_source_link_field

```

# Answer
> 4 votes
If you just want to migrate a link and title from source fields to link fields this should work.

```
  'field_web_link/uri': link
  'field_web_link/title': title

```

---
Tags: entities, migrations, navigation
---


# Question
Title: How to use loadByProperties when one of the properties is an array?
I have this configuration entity and I want to load an entity using the properties label and subregions

Lets say I want to load the entity if it has the label CU and the subregions CU-04. Note that subregions is an array. I tried with this code but is not working.

```
$region = $this->entityTypeManager->getStorage('region')->loadByProperties(['label' => $region, 'subregions' => $subregion]);

```

How can I call loadbyProperties with properties being arrays?

# Answer
> 4 votes
Configuration entities are not queried via SQL, you search within a multilevel array.

See the code docs:

*core/lib/Drupal/Core/Config/Entity/Query/Query.php*

```
  /**
   * Overrides \Drupal\Core\Entity\Query\QueryBase::condition().
   *
   * Additional to the syntax defined in the QueryInterface you can use
   * placeholders (*) to match all keys of an subarray. Let's take the follow
   * yaml file as example:
   * @code
   *  level1:
   *    level2a:
   *      level3: 1
   *    level2b:
   *      level3: 2
   * @endcode
   * Then you can filter out via $query->condition('level1.*.level3', 1).
   */
  public function condition($property, $value = NULL, $operator = NULL, $langcode = NULL) {
    return parent::condition($property, $value, $operator, $langcode);
  }

```

In your case the second level keys are the same as the values. So you have to ignore the second level with an * to query these values.

---
Tags: 8, entities
---


# Question
Title: Promotions not translated on cart and checkout page?
I have commerce site in 2 languages: English (default) and German.

I enabled translation of promotions so when I go to promotions admin page ( /admin/commerce/promotions ) for each promotion there is also "Translate" operation. I can enter German translation for each and it's saved well.

Problem is that when I'm on cart page or later on checkout page (German pages) promotions are displayed in English only. Other content, including subtotal, total, shipping costs are translated well, but promotions are always on English?!?

I searched but couldn't find that anybody reported that issue before, so most likely I overlooked something (hopefully), but just can't find out what it is.

Any idea why promotion titles are not displayed in page language, but always in English (default language)?

# Answer
> 1 votes
I found work-around for this issue. Inside the template that prints that section (`commerce-order-total-summary.html.twig`) there is a loop that prints adjustments:

```
{% for adjustment in totals.adjustments %}
    <div class="order-total-line order-total-line__adjustment order-total-line__adjustment--{{ adjustment.type|clean_class }}">
        <span class="order-total-line-label">{{ adjustment.label|t }} </span><span class="order-total-line-value">{{ adjustment.amount|commerce_price_format }}</span>
    </div>
{% endfor %}

```

and where adjustment label is printed I added **t** twig filter, so now it can be translated on standard user interface translations page:

```
/admin/config/regional/translate

```

I know that it's not optimal solution, but it works, so I hope this can help someone until bug is fixed.

---
Tags: 8, commerce, transliteration
---


# Question
Title: How do I determine the values to use in the payload for the add to cart method in the Commerce API
The documentation for the Commerce API gives the example payload below for adding items to a cart. How do I find the type and ID values for the product variants in my store configuration?

```
{
  "data": [
    {
      "type": "product-variations--default",
      "id": "e8daecd7-6444-4d9a-9bd1-84dc5466dba7",
      "meta": {
        "quantity": 1
      }
    }
  ]
}

```

# Answer
I eventually located these using the path https://mydomain.com/jsonapi/product-variations/default.

A call to https://mydomain.com/jsonapi exposes the end-points you can use, based on your product configuration. Mine looked like this:

```
        "product--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/products\/default"
        },
        "product-attribute": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attributes"
        },
        "product-attribute-value--rate": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attribute-values\/rate"
        },
        "product-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-types"
        },
        "product-variation--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variations\/default"
        },
        "product-variation-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variation-types"
        }

```
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How do I check the image's view mode in the image.html.twig template?
I'd like to detect the custom view mode (Structure \> Display Modes) selected for an media entity (image) and then be able to have html output based on the view mode. Specifically I have a custom view mode named 'top\_banner' and would like to change the formatting of the default element when this view mode is selected. Here is what I have in my image.html.twig template:

```
{% if view_mode == 'top_banner' %}
    <img{{ attributes.addClass(banner) }} data-cover/>
{% else %}
    <img{{ attributes }} />
{% endif %}

```

This however does not seem to detect the view mode. Currently the image is output in the default format \<image {{ attributes }} /\>.

The image is a media entity field and is part of a Paragraph type named x\_banner. The x\_banner Paragraph is then referenced on the x\_page content type.

I've searched and can't seem to find an instance where this is implemented in the field.html.twig or image.html.twig template.

Any assistance with this would be greatly appreciated.

# Answer
If you're using a Media entity, you can check the view mode in the media template: `media.html.twig`:

From the `media.html.twig` file documentation:

> * view\_mode: View mode; for example, "teaser" or "full".

This would let you add the class to the image parent `<div>`.

If you want to target only images, you can do this:

`media--image.html.twig`

And if you want to target only images with the view mode **abc**, you can do this:

`media--image--abc.html.twig`
> 1 votes

---
Tags: theming, entities
---


# Question
Title: How do I print a specific meta tag attribute value in html.tpl.php?
I am trying to create WebSite schema condition output in html.tpl.php in Drupal 7, so installed schema.org module, but it doesn't come with all the fields that my project required, for example, description. How do I get the description value from "admin/config/search/metatags/config/global%3Afrontpage"?

What I have so far.

```
<?php if(drupal_is_front_page()) {
$logoSchema = theme_get_setting('logo');
$urlSchema = $GLOBALS['base_url'];
echo '
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "url": "'. $urlSchema .'",
  "name": "Company Name, Inc.",
  "image": "'. $logoSchema .'",
  "description": "**NEED HELP GETTING THE VALUE**",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "'. $urlSchema .'/search/{search_term_string}",
    "query-input": "required name=search_term_string"
  }
}
</script>';
} ?>
</head>

```

# Answer
1. create a preprocess\_html function in template.php

```
function porto_sub_preprocess_html(&$vars){
  if (drupal_is_front_page()) {
    if (isset($vars['page']) && isset($vars['page']['content']) && isset($vars['page']['content']['metatags'])) {
      $meta_tags = $vars['page']['content']['metatags'];
      if (isset($meta_tags['global:frontpage']) && isset($meta_tags['global:frontpage']['description'])) {
        $meta_desc_list = $meta_tags['global:frontpage']['description'];
        if (isset($meta_desc_list['#attached']) && isset($meta_desc_list['#attached']['drupal_add_html_head'])) {
          if (isset($meta_desc_list['#attached']['drupal_add_html_head'][0]) && isset($meta_desc_list['#attached']['drupal_add_html_head'][0][0])) {
            if ($meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value']) {
              $vars['front_page_meta_desc'] = $meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value'];
            }
          }
        }
      }
    }
  }
  drupal_add_http_header('Cache-Tag','mktg',true);

```

2. This defined meta tag is accessible from html.tpl.php

```
 if (!isset($front_page_meta_desc)) {
       $front_page_meta_desc = '';
     }

```

In the schema JSONLD, you need to call the variable.

```
"description": "' . $front_page_meta_desc . '",

```
> 0 votes

---
Tags: 7, meta-tags
---


title: How can I add a comment form?

text:
# Question
Title: How can I add a comment form?
I'm using views to display the fields of nodes. I prefer to use fields because it allows me to use relationships (bring in author profile picture etc.). Adding the *Content: Comments* field shows the list of comments as well as the comment form for each node. However, when hiding and rewriting the result and/or using the replacement pattern for *Content: Comments*, the comment form disappears.

What methods can I use to display the comment form for each node?

# Answer
> However, when hiding and rewriting the result/and or using the replacement pattern for Content: Comments, the comment form disappears and only the comment list remains.

It's due to a Views UI bug as I was able to replicate the issue on a fresh install.

A workaround you can do is to do the re-writing via template file rather than via UI.

In your theme's /templates folder add:

views-view-fields--**view-name**--**machine-name**.html.twig

and print the view fields there

```
{{ fields.title.content }} {# title field #}

{{ fields.comment.content }} {# comment field #}

{{ fields.field_name.content }} {# some other field #}

```

Flush all caches so template gets pickedup.
> 3 votes

---
Tags: views, nodes, forms, comments, 9
---


# Question
Title: Referencing CSS file from theme library inside Embedded Widget Paragraph type
I have an article page in Drupal 8 that contains a chart (inserted into the page using Text paragraph). The chart uses CSS classes that I have created inside the global stylesheet. It works, but I don't want these CSS classes to be loaded on every single page on my website.

I'm thinking that I would move the CSS classes into a separate file. Then I would move the HTML code for the chart into an Embedded paragraph and reference the theme library.

I'm new to Drupal 8 theming so I'm not sure how I would go about doing that. Can someone give me the general steps?

I think need to do the following.

1. Move CSS classes to a new file
2. create a library refencing the new CSS file that is not loaded by default
3. Add the CSS file URL to the embedded widget "Javascript Source" field

I'm not sure how to add the library refence to my theme or to make it not load by default.

# Answer
Your thought process is correct. To implement below script tag is to be referenced inside the embedded widget

Like: Js

```
<script type="text/javascript" src="/custom.js"></script>

```

Like : Css

```
<link href="/custom.css" rel="stylesheet" />

```

Thanks
> -3 votes

---
Tags: 8, theming
---


# Question
Title: List all node titles to better iterate on a list of names
I have a content type called Country and I have to verify what countries already exists in db and save the missing ones, comparing to a variable with all countries ($country\_list). I am having trouble accessing countries names of my nodes, that are specified as the content type title.

```
  $country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];
  $nodes = node_load_multiple(array(), array('type' => 'country_profile'));
  $nodes_name = node_title_list($nodes);

  foreach ($country_list as $country_name) {
    if (!in_array($nodes_name, $nodes)) {
      // should create new node
    } else {
      // shouldn't do anything
    }
  }

```

The problem is, when i get the `node_title_list()` it doesn't return the 'raw title' (see output below)

Output:

```
    Array
(
    [#theme] => item_list__node
    [#items] => Array
        (
            [0] => <a href="/discover/country_profiles/tanzania">Tanzania</a>
            [1] => <a href="/discover/country_profiles/mexico">Mexico</a>
        )

    [#title] => 1
)

```

How can i do that, so that the output of this list is

```
Array
        (
            [0] => "Tanzania"
            [1] => "Mexico"
        )

```

# Answer
If you just need to create the nodes that don't have a specific title (which I guess it's just a country name), you don't need to use `node_title_list()`, whose purpose is rendering a list of node titles as links. Just load the nodes and check which titles aren't already used.

```
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

```

Even better, load those nodes whose title is equal to one of the country names you already have.

```
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('title', $country_list)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

```
> 0 votes

---
Tags: 7, nodes, database
---


title: Customize menu local task links

text:
# Question
Title: Customize menu local task links
I am looking for a way to customize 'edit', 'view', 'delete' links.

I use bootstrap theme, but i use bootstrap v4 styles for it. I want to add 'nav-link' class to each link.

And find a way to display somewhere, not just below post title.

I couldnt find a tutorial about it. Where should i look for this? template parts (twig) or themename.theme file?

# Answer
> 2 votes
For preprocess function you can use **`HOOK_preprocess_menu_local_tasks(&$variables) {...`** where **`HOOK`** is the name of your active theme.

And for template suggestions you need to enable debugging and see with inspect element, as usual it must be `menu-local-tasks.html.twig`

# Answer
> 0 votes
You can customize the local tasks using menu-local-tasks.html.twig and menu-local-task.html.twig. The Stable core theme has samples of these files. You could also try using hook\_preprocess\_menu(&$vars) in your .theme file. I'm not sure if it processes the local menu items though. I am using it for the main menu.

# Answer
> -1 votes
You could create your own tpl.php! I think there should be a template file within your bootstrap theme. Copy that file to your subtheme templates folder and edit it the way you want it to look like.

---
Tags: theming, 8, hooks
---


# Question
Title: How to create a message with message stack when user becomes a member of a group module group?
Hi currently I try to code a custom module for notification based on message stack module.

Now I'm searching for the event or hook to perform some custom code when the user becomes a member of a group.

I want to create a message based on the message stack like "the user John Doe became a member of group xxx. Visit group xxx."

Unfortunately I didn't found something like that in the module docs, so I ask here.

Thanks in advance for your help

# Answer
It looks like the membership relationship is stored as a `GroupContent` entity, so in theory you would use something like `hook_ENTITY_TYPE_insert()`as your event:

```
function MODULE_group_content_insert(\Drupal\group\Entity\GroupContentInterface $group_content) {
  // This will fire for all types of group content so make sure to filter
  if ($group_content->getContentPlugin()->getPluginId() == 'group_membership') {
    $account = $group_content->getEntity();
    $group = $group_content->getGroup();
    // Create the message
  }
}

```

This is untested so may need tweaking, but it should be close enough to get going.
> 2 votes

---
Tags: 8, group, message-subscribe
---


# Question
Title: Views to show nodes filtered by referenced user
I am really confused about this. Tried with the `Entity reference` view but can not get the result working for me. It should be very easy to do it.

I have a node called `Book`. Book has a field `field_author` that is referenced to `USER`.

**I am trying to show the related books by the same referenced user.**

**Book 1:**

```
Title: Book 1
field_author: user50 //id of this user is 50

```

**Book 2:**

```
Title: Book 2
field_author: user15

```

**Book 3:**

```
Title: Book 3
field_author: user50

```

**Book 4:**

```
Title: Book 4
field_author: user50

```

**My view should display `Book 3` and `Book 4`** when viewing `Book 1` (URL:: example.com/node/1) and display `Book 1` and `Book 4` when viewing `Book 3` (URL:: ecample.com/node/3) and so forth.

# Answer
> 0 votes
What you want to do is often called displaying sibling items. In your case the connection is the ER user connection (not Taxonomy) but you can find examples with details about how to do it, search answers for it.

In short:

1. Create Views of type Book, you'll probably want Block Display, it doesn't have to be Entity reference Display type (that is for influencing choices in nodes in ER fields).
2. Add the Relationship for the User ER field. It should be the forwards Relationship. You can require it if you want to exclude all Books from your list that don't have the User ER filled in.
3. Add the second Relationship for that field, but the reverse one this time (it will be called different). Make it use the first Relationship. You can require it.
4. Add Contextual filter for Node ID, make it use the second Relationship (because this way you get the ID of sibling nodes) and configure it the usual way (default value ID from URL, validate Book node type) etc.
5. The current Book node will also be listed. To exclude it add another Contextual filter for node ID, don't make it use any Relationships, set to default value ID from URL and under "More" choose "Exclude".
6. Under Structure \> Blocks set the Block to display in a theme region, and configure it to use Contextual options. Don't forget the Visibility settings too.

You should now see the block on Book nodes showing their siblings per shared user ER.

You can test Contextual filter when editing Views by entering values into the Preview field. If you have two Contextual filters you have to enter two values separated by "/" In your case enter a book node twice e.g. "12/12". "all/all" usually bypasses the Contextual filter results.
You still have to check that it works by placing the Block in a region at the end, to check your Contextual configuration is correct.

---
Tags: 8, views
---


# Question
Title: Is it possible to change the Alt value inside the image.html.twig template?
Is it possible to change the *alt* value inside the image.html.twig template? I found out that it can be accessed via `attributes.alt`. And then there is a protected value. Is there a way to set it?

Something like:

`{% set attributes.alt.value = 'new alt' %}`

# Answer
> 2 votes
In a Twig template you can use the method attributes.setAttribute():

```
{% set attributes = attributes.setAttribute('alt', 'new alt') %}

```

# Answer
> 1 votes
1. in your theme folder create **{theme\_name}.theme**
2. in your **{theme\_name}.theme** use the fllowing function to alter any image attribute ex (alt):

```
/**
 * Implements hook_preprocess_HOOK
 */
function YourThemeName_preprocess_image(&$variables) {
  $variables['attributes']['alt'] = 'new alt value';
}

```

---
Tags: 8
---


# Question
Title: hide JSON:API endpoint parameters for a client application
# The Existence

I 'am using the JSON:API core module to serve a client (react application)

so that each time I have made a back-office modification I need to reconstruct the URL parameters ex :

* to send the feature image information
`?include=field_featured_image`
* then I have added a paragraph to my article content type so to include the paragraph: `?include =field_featured_image,field_composants`
* to display specific element in the created parapgraph and not all fields I have use the field set `?include =field_featured_image,field_composants&fields[paragraph--composant]=video`
* and so on the modification keep going...

then I need to send the new endpoint to the client (ex: react application)

# The problem

the client is not up to date with the new URL so each time I made a modification I need to communicate it to the front team.

# What do you think about this solution

THE JSON:API parameters will be like BlackBox for the react application :

1. REACT sends a request to DRUPAL without sending any parameters ex: `GET /jsonapi/node/article/55d611ab-5752-469a-bf44-648c8cad2a9f` OR `GET /jsonapi/node/article`
2. on **kernel.request** Drupal takes the request url and alter it by appending the proper JSON:API parmters to it ex: `/jsonapi/node/article?include =field_featured_image,field_composants&fields[paragraph--composant]=video`

> NOTE:
>
> * for easy administration The JSON:API parameters will be configurable from BO.
> * The request handler method can change the parameters according to the requested node bundle or according to collection or single entity request

3. using HTTP client ex(GuzzleHttp\Client) to request the new constructed JSON:API endpoint `$res = $client->request('GET', '/jsonapi/node/article?include =field_featured_image,field_composants&fields[paragraph--composant]=video');`

> problem: for each request instead of a single request I Nedd to execute 2 requests.

4.then send a response to the client : `$event->setResponse($response );`

```
note: for a technical reasons I prefer to keep using JSON:API and not creating custom rest endpoints.

```

# Answer
> 0 votes
Rather than the JSON:API I would go with the REST resource plugins. Here you are basically only writing controller methods and return what you want. That is already part of the Drupal core:

https://www.drupal.org/docs/drupal-apis/restful-web-services-api/restful-web-services-api-overview

Here is a code example (ServicekontoResource.php):

```
<?php

namespace Drupal\fms_api\Plugin\rest\resource;

use Drupal\fms_api\Exception\ServicekontoApi\NoServiceKontoResponseException;
use Drupal\fms_api\ServicekontoApi;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\servicekonto_integrator\Exception\ServicekontoResponseStorageException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * @RestResource(
 *   id = "servicekonto_resource",
 *   label = @Translation("Servicekonto resource"),
 *   uri_paths = {
 *     "canonical" = "/fms-api/servicekonto-data/{session_hash}"
 *   }
 * )
 */
class ServicekontoResource extends ResourceBase {

  /**
   * @var \Drupal\fms_api\ServicekontoApi
   */
  private $servicekontoApi;

  public function __construct(array $configuration, string $plugin_id, array $plugin_definition, array $serializer_formats, LoggerInterface $logger, ServicekontoApi $servicekontoApi) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->serializerFormats = $serializer_formats;
    $this->logger = $logger;
    $this->servicekontoApi = $servicekontoApi;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('fms_api.servicekonto_api')
    );
  }

  public function get(string $sessionHash) {
    try {
      return new ResourceResponse($this->servicekontoApi->provideData($sessionHash));
    } catch (NoServiceKontoResponseException $exception) {
      $response = new Response('Could not retrieve dataset of service konto response.', 500);
      return $response;
    } catch (ServicekontoResponseStorageException $exception) {
      $response = new Response($exception->getMessage(), 400);
      return $response;
    }
  }

}

```

---
Tags: 8
---


# Question
Title: $form_state->set(), $form_state->setValue() doesn't save new value
Below you could find my code. It works fine until below the comment. I also tried countless combination of $form\_state-\>saveValue(), but nothing works. Any ideas?

```
    function myforms_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if ($form_id == 'commerce_product_default_edit_form' || $form_id == 'commerce_product_default_add_form') {
        $form['#submit'][] = 'myforms_extra_submit_handler';
      }
    }

    function myforms_extra_submit_handler($form, FormStateInterface $form_state) {
      $events_dates = $form_state->getFormObject()->getEntity()->get('event_date')->getValue();
      $count = count($events_dates);
      if (empty($events_dates[$count-1])){
        $count = $count - 1;
      }
      if ($count > 0) {
        $start_date = date("j/n/y", strtotime($events_dates[0]['value']));
        $end_date = date("j/n/y", strtotime($events_dates[$count-1]['end_value']));
        if ($count == 1) {
          $count_suffix = "zjazd";
        } else if ($count == 2 || $count == 3) {
          $count_suffix = "zjazdy";
        } else {
          $count_suffix = "zjazdów";
        }
        $date = $start_date.' - '.$end_date.' ('.$count.' '.$count_suffix.')';

        $title = $form_state->getFormObject()->getEntity()->get('title')->getValue()[0]['value'];
        /* code above works, below is the code which doesn't */
        $form_state->set('title', $title.$date);
        $form['elements']['title']['#value'] = $title.$date;
        $form['elements']['title']['#default_value'] = $title.$date;
        $form_state->setRebuild();
      }
    }

```

# Answer
> 2 votes
I assume with *code works* you mean you get the updated title value. Then another submit handler has already transferred the values to the entity and your changes to $form\_state are too late.

So you can try to position your submit handler first:

```
array_unshift($form['#submit'], 'myforms_extra_submit_handler');

```

or update the entity instead of $form\_state:

```
$entity = $form_state->getFormObject()->getEntity();
$title = $entity->get('title')->value;
$entity->set('title', $title . $date);

```

Caveat: Normally submit handlers in entity forms are attached to submit buttons. So you might want to check first all submit handlers which are active in the form before you decide where to place your submit handler.

---

**Different approach**

You are asking why your submit handler is not working and there is definitely a solution for that, but there is probably a much easier solution outside of the form when the form is trying to save the entity. See Programmatically update a field's value

# Answer
> 1 votes
It's not clear what "doesn't work" means to you - what do you expect to happen, and what actually happens? We can only guess at what you mean, so perhaps I'm guessing wrong here ...

Because `$form` is passed to your submit handler by a value, not by reference, the changes you make to `$form` after your comment are confined to the scope of the submit handler and won't affect anything outside your function. If you want to change the elements of the `$form` array you should do that inside your `hook_form_alter()`, or perhaps in an Ajax callback, not in a submit function. A submit function should only be processing the form data, not trying to alter what the form looks like to the end user. But if you really must, then you can change the form values in your submit handler by set the values in `$form_state` instead of changing `$form`.

Also confusing is your `$form['elements']['title']['#value']` \- most form elements have a `#title` to hold the value of the title, or if this were a markup `#type` then you would have a `#markup` to hold the value. I'm not sure why you're trying to set `#value` here. It would help if you would show at least part of the structure of the `$form` you're trying to alter.

---
Tags: 8, forms, hooks
---