# Question
Title: Drush CC all returning "No Drupal site found, only 'drush' cache was cleared"
I've tried other solutions, but none of them are specific to my setup. I just started using the new Linux subsystem featured in the recent Windows 10 update. I'm using WAMP x64 v3.0.6, and have successfully cloned my website and got it up and running. At the root of the Linux subsystem, I installed Drush globally with Composer, using the directions given on the Drupal webapage.

Typing `drush status` returns the following when I run it in my default directory:

```
Drupal version         :  7.50
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  aerosphere
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/bob/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /mnt/c/wamp64/www/drupal-7.50
 Site path              :  sites/default

```

But, as mentioned in the title, `drush cc all` returns `No Drupal site found, only 'drush' cache was cleared.[warning]` I assume it has something to do with adding a path to the .bashrc, but I don't know what to add. Any tips would be greatly appreciated!

My question is different from "Drush - No Drupal Site Found when clearing cache", they're on a Mac and using MAMP, and I'm using WAMP on Windows. I've tried the solutions offered on that post, but the issue has not been resolved.

I'm obviously having issues connecting to MySQL as I get this when I run `mysql` command:

> The program 'mysql' can be found in the following packages: * mysql-client-core-5.5 * mariadb-client-core-5.5 * mysql-client-core-5.6 * percona-xtradb-cluster-client-5.5
>
> Try: sudo apt-get install .

So I've added these lines to my `.bashrc` file:

```
PATH="$HOME/.composer/vendor/bin:$PATH"
export PATH="/mnt/c/wamp64/mysql/mysql5.7.14/bin:$PATH"

```

The top line was added to get drush working. I've checked multiple times, and I have the path correctly set, but it's still not working.

# Answer
> 14 votes
There are a few things you can do to help debug your drush. Here is what you can try:

**Debug output**

Use `drush cc all -vvv`

This will provide you with some valuable information in terms of what Drush is doing in the background and maybe show you the actual error message.

**Check your settings.php**

Depending on your setup you may be passing in environment variables to your settings.php file for a database configuration for instance. Or perhaps to provide memcache. Drush unfortunately does not pick these up as it's bypassing apache. Therefore I would give it a test run without environment variables to see if that eliminates the issue or help narrow it down. For debug purposes it may be worth just using a clean copy from the example.settings.php and just modifying the database array to test this.

**Check the mysql client is available**

This is one that tripped me up a while ago and the drush -vvv will point you in the right direction. If it can read the settings.php, which it appears it seems to be able to as it gets the db settings, then perhaps it can't connect to your mysql database. One of the issues I had was that mysql client command was not available. E.g. try calling 'mysql' and see if that works. After fixing that it worked. In my Mamp setup it was just a matter of ensuring the correct path to the executable was in my shell $PATH.

I hope this helps.

# Answer
> 7 votes
Noting that your `drush status` output *does* give a valid `root`, `site path`, `database user`, and `database name`, that means that drush is finding a valid `settings.php` file with credentials in it and can read it.

However, `drush status` does not have the line

```
Drupal bootstrap                :  Successful

```

which would indicate that it can actually load.

If you run

```
drush sql-cli

```

It will attempt to generate a mysql client connection to the database and that will probably generate a more readable error to what is happening.

Also, `drush sql-connect` will show the connection information (including passwords, so be careful pasting).

# Answer
> 5 votes
This usually happens when the directory where you are calling `drush` is not a Drupal site or not a sub-directory of a Drupal site or maybe drush cannot recognize your site. Here are some tips which might help:

* If you are working on a **single-site** Drupal installation, make sure `sites/default/settings.php` exists.
* If you are working on a **multiple-site** Drupal installation, make sure:
    + You have a settings file for your site in `sites/example.com/settings.php`, where `example.com` would be usually your site's domain.
    + You run the command `drush use example.com` to change to the site you are currently wanting to work with.

Hope it helps. Happy coding!

# Answer
> 3 votes
Drupal site not found error comes up when Drush cannot find your Drupal installation. You can specify the path to the Drupal installation as shown below:

```
drush -r path/to/docroot cc all

```

# Answer
> 2 votes
One specific case where this might happen, with the exact same core status report, is when `~/.my.cnf` is setup with only a `password` entry, without a matching `user`, and the database connection in `settings.php` is setup with a different user (and password). The mysql error log will probably say something like this for each drush run:

```
2018-06-29T08:49:30.926226Z 1046 [Note] Access denied for user 'user'@'localhost' (using password: YES)

```

I.e. database connection fails during drush/drupal bootstrapping. In my case this happens in Drush 8.x. I haven't investigated other versions. It seems like drush uses your `~/.my.cnf` instead of values provided by `settings.php`

## Solution

Either add an additional `user` entry in `~/.my.cnf` or remove the `password` entry:

```
[client]
user = your_mysql_username
password = your_mysql_pass

```

# Answer
> 1 votes
Had the same problem when running drupal on windows and using drush on the Windows Subsystem for Linux. jnpWebDeveloper's answer helped me to fix it. These are the steps i needed to do:

1. mysql is missing on the subsystem. You need to install it via sudo apt-get install. Pointing in the path to your windows mysql executable will probably not work even if the path is correct.
2. You will need to replace localhost with 127.0.0.1 as the hostname in your settings.php. Otherwise mysql will try to connect to a mysql server on your linux subsystem using the local socket. You want it to be able to connect to the mysql server running on windows.

# Answer
> 0 votes
Not able to execute `mysql` command (or other equivalent command depending on your db driver) from the shell is the main problem of Drush not being able to connect to Drupal site. Run `drush -d sql-connect` to find out that is the case.

The following lines added to `~/.bashrc` should be fine:

```
export PATH="$HOME/.composer/vendor/bin:$PATH"
export PATH="/mnt/c/wamp64/mysql/mysql5.7.14/bin:$PATH"

```

where `/mnt/c/wamp64/mysql/mysql5.7.14/bin` is your path to your `mysql` command.

To reload the shell startup script, run:

```
~/.bashrc

```

or re-login. This can be also verified by echoing your PATH by: `echo $PATH` in Bash shell.

For any other similar issues, check: Drush installed and running; No Drupal site found even with uri specified.

# Answer
> 0 votes
This is most likely an edge case but I'll share it in case it helps someone.

In my case, this issue was triggered by changing the password for root in MySQL (server is Linux).

I have a file, `~/.my.cnf`, which contains these lines:

```
[client]
user=root
password=mypassword

```

This allows me to run mysql commands inside bash scripts without requiring user interaction. Seems it affects how Drush works too. I changed the root password without updating this file, and the drush problem began. Updating the password fixed the problem, as did removing this file.

# Answer
> 0 votes
Wow! For me it was the inclusion of the `settings.local.php` file which wasn't working anymore locally.

Previously I did it like so, and still do on the live server where it's still working. But locally on my macOS with MAMP this returned a wrong path and so the `settings.local.php` file wasn't included anymore and Drush didn't found the default site anymore.

```
// OLD WAY.
if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php')) {
  include DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php';
}

```

I fixed it by replacing the code by the one that's used in Drupal 8 and 9 and now is open for backporting, see https://www.drupal.org/project/drupal/issues/1118520.

```
// NEW WAY.
$local_settings = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings)) {
  include $local_settings;
}

```

# Answer
> 0 votes
In My case database read replica was pointed to another endpoint that was causing the same issue. Commenting or changing to correct one fixed the issue.

# Answer
> 0 votes
I usually face this issue on my local. To fix it you need to set the password for user.

I solve it using below query.

```
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpassword';

```

---
Tags: 7, drush, installation, composer
---


# Question
Title: Why are my $messages delayed one page refresh?
I have a page with a very simple template:

```
<!DOCTYPE html>
<html>
<head><title>TEST REGISTRATION PAGE</title></head>
<body>
    <?php
        print drupal_get_form('user_register');
        print $messages;
        print $closure;
        print $main_content;
    ?>
</body></html>

```

Basically, it displays the registration form and nothing else.

1. I enter some bad data on the form — an already used username (admin), and no email address.
2. I click "create new account".
3. The page seems to submit and reload, but nothing has happened — **no error messages are displaying**.
4. I refresh the page (F5).
5. Firefox displays "to display this page, Firefox must send information that will repeat any action that was performed earlier" — so I know that my POST went through previously.
6. I click "resend" in that dialog window.
7. My error messages appear — "e-mail address field is required", "the name admin is already taken".

This occurs for *all* of the forms I've tested so far, not just the registration form.

Why is this happening? What can I do to fix it so that the error messages display the first time?

I'm happy to do whatever I need to do debug this, but I need some direction to start looking in. :)

# Answer
Most likely the problem is that you are calling the form when the messages already have been created, which is why they don't appear. You need to call the form, earlier in the process of the page being built or get the messages, with drupal\_get\_messages.

What you really should do it is to create this functionality in a module and theme the page instead, of doing this in your theme. You could potentially run into many more problems like this.
> 4 votes

# Answer
We solved the form validation problem, (form validation happening after the messages have been rendered, and showing up on the next request), by..

forcing the form validation in hook\_node\_view

```
/**
 * This is a fix for a bug where the validation error messages lag a
 * full request behind form submissions
 */
function your_module_node_view($node, $view_mode){
  // check that form id is the form you want
  if ( !isset( $_POST['form_id'] ) || $_POST['form_id'] != 'your_form_id' ){
    return;
  }
  // this forces validation of the form
  drupal_get_form('your_form_id');
}

```
> 3 votes

# Answer
I also suffered from this problem. @googletorp's answer helped me to solve it.

At the beginning of page tpl. Get the rendered content of forms i.e. for my case:

```
$register_form = drupal_get_form('user_register_form');
$register_form_content = render($register_form);

$form_user_pass = drupal_get_form('user_pass');
$form_user_pass_content = drupal_render($form_user_pass);

$login_form = drupal_get_form('user_login_block');
$login_form_content = render($login_form);

```

Then at the message print section, get the messages calling drupal\_get\_messages() at the page tpl. $messages is still unable to fetch the messages without another page refresh.

```
<?php
    $messages = drupal_get_messages('error');
    if(is_array($messages['error']) && count($messages['error'])) {
?>
    <div id="messages">
        <div class="section clearfix">
            <div class="messages error">
                <ul>
                    <?php
                    foreach($messages['error'] as $item) {
                        echo '<li>'.$item.'</li>';
                    }
                    ?>
                </ul>
            </div>
        </div>
    </div>
<?php
    }
?>

```

Then print the rendered form content at the proper section and it solved :).
> 2 votes

# Answer
Not directly a solution for the question asked, but I came across this when I was having the same problem:

If your form block is called directly from the tpl.php file (perhaps for layout reasons), then you'll get delayed messages.

I.e. I was loading a block with the following code in my template file:

```
$vars['contact_details'] = module_invoke('viewusercontact', 'block_view', 0);

```

And then rendering it in my tpl.php file.

```
<?php print render $contact_details ?>

```
> 1 votes

# Answer
I came across this issue on a Drupal 7.x installation and the problem was that the form was being loaded programmatically in `HOOK_preprocess_node()`. Moving it to `HOOK_preprocess_page()` fixed the issue.
> 0 votes

---
Tags: 6, sessions
---


# Question
Title: How do I show a product attribute in a cart?
I don't know why the item name shows "price" in the shopping cart.

>

My product variation type have 2 fields: *Certificate choice* (attribute) and *Course period*.

>

How can I customize my formatter in the cart?

>

The last image is my views "Cart form"

# Answer
The price must be showing because that is all that is configured to be rendered for the referenced entity in whatever view mode it's defaulting to. If you want something like you've pictured, you're going to need to use the individual fields, which likely means adding another reference to get the attribute / value data, adding all three of the fields you want to render (course name, attribute value, and period), and then configuring the View to ensure all three of those fields are rendered into the single column.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: How to set field value in custom webform submit handler?
In a custom submit handler, I want to set a field value for a text field (`my_field_machinename`) in my webform. The handler is getting called correctly, but the value is not getting stored. What do I have to change in the code below to make it work?

I know I could use the presave hook, but I would prefer to make the alteration within the submit handler.

```
class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($form_state);
  }

  /**
   * Set my field values
   */
  private function submitMyFieldData(FormStateInterface $formState) {
    $formState->setValue('my_field_machinename', [['value' => '123']]); // Does not work

  }

}

```

# Answer
> 3 votes
Only now did I realize there is not only a submitForm method but also a presave method. I therefore changed my code as follows which is woking fine for me:

```
class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($webform_submission);
  }

  /**
   * @param $webform_submission
   *
   * Manipulate data.
   *
   */
  private function submitMyFieldData($webform_submission) {
    $data = $webform_submission->getData();

    // to get a value from a form field
    $form_value = $data['my_field_machinename'];

    // to set the value of a form field
    $data['my_field_machinename'] = $form_value + 1;

    $webform_submission->setData($data);

  }

```

---
Tags: 8, webforms
---


# Question
Title: How to get a referencedEntity field value in current node language
I am trying to get some node's content inside a block.

I managed to get the fields i wanted, but they are always returned in my site default language instead of the current translations (ex. /node/1 and /fr/node/1 returns the same english content instead of the translation)

It works fine for simple fields, but can't get it to work for referencedEntities :

I am inside a Block build() function :

```
$node = \Drupal::routeMatch()->getParameter('node');

// Simple text field : Correct value depending on language
$correctValue = $node->field_test_text->getValue();

// Paragraphs/referencedEntities
$paras = $node->get('field_paragraphes')->referencedEntities();
foreach ($paras as $para) {
   // Not translated, always in default language ?
   $badValue = $para->get('field_test_in_para')->getValue();
}

```

Thanks a lot.

# Answer
> 11 votes
The code for your problem (You need to use getTranslation to get a translation and hasTranslation to check is is it actually has a translation or not):

```
$lang_code = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$node = \Drupal::routeMatch()->getParameter('node');

// Paragraphs/referencedEntities
$paras = $node->get('field_paragraphes')->referencedEntities();
foreach ($paras as $para) {
  // Remember to check if translation exists
  if ($para->hasTranslation($lang_code)) {
    $para = $para->getTranslation($lang_code);
  }
   $goodValue = $para->get('field_test_in_para')->getValue();
}

```

Eventhough this code will work and fix your problem, you might consider if you are doing things right. Most of the time, when doing things the proper way, you wont need to handle translations. A lot of modules/systems does this automatically when rendering stuff or using modules like views. Most of the time, when you need to handle translations yourself, there would be a simpler way to do this.

# Answer
> 7 votes
You can try to force the use of the current language:

```
$langcode = $this->languageManager->getCurrentLanguage()->getId();
$value = $para->getTranslation($langcode)->field_test_in_para->value;

```

Or try to use the node language:

```
$node_language = $node->language()->getId();
$value = $para->getTranslation($node_language)->field_test_in_para->value;

```

# Answer
> 0 votes
This is definitely due to a core bug. See https://www.drupal.org/project/drupal/issues/2915972 Reviews and support over there would be most welcome. Thanks! -Derek

---
Tags: nodes, 8, entities, i18n-l10n
---


title: Link to a referenced entity

text:
# Question
Title: Link to a referenced entity
I have a entity A with an entity reference to entity B, and an image field. I created a view to display an entity A. I want to link the image field to the page displaying the referenced entities B.

Firstly, I've added the entity reference field in my view and checked "Exclude from display", in order to get in the image field the replacement token, but I could not get the link. I just get the the entity B title.

Afterwards, I added a relationship to entity B in my view. No more success.

Could you help me?

# Answer
> 1 votes
ER fields store only the ID of the referenced entity.

Pulling in other information about the referenced entity usually involves adding Relationships, but some details can also be shown through the `Formatter` Field setting.

## Set `Formatter` to `Entity ID` and Rewrite

Without adding the Relationship edit the ER field, set the `Formatter` to `Entity ID`, then under `Rewrite results` turn on `Override the output of this field with custom text` and enter something like this into the Text field:

`<a href="/node/{{ field_myreferencetoB__target_id }}">{{ field_myImagefield }}</a>`

Check the correct tokens under `Replacement patterns` a bit lower under the Text field.

You can also achieve similar result with `Output this field as a custom link` which has more options for the link if you need them. In this case the Text field will only hold the image token and this option will contrast the anchor HTML.

This approach is helpful when you have a multivalue field it will be possible to show all values in the same row, while using a Relationships usually splits them into separate rows and it requires more steps to aggregate them.

## Use the ER Relationship

If you add the ER Relation ship you will be able to add the `Link to content` field and make it use that Relationship to show the link to the Referenced entity instead of link to the original row entity.

You may want to use the `Output the URL as text` option to make the token output more predictable.

Now you have the referenced entity link in your Views you can use it to Rewrite other fields.

---
Tags: 8, views
---


# Question
Title: Webform is not submitting after 1st submit?
I am not able to submit a webform which is configured with honeypot.

I have tried following steps for anonymous user:

1. Place the webform using the webform block in a page.
2. Submit the webform. It got worked for 1st time.
3. When trying to submit from 2nd time onwards it is showing a message "There was a problem with your form submission. Please refresh the page and try again.".
4. After clearing cache only one submission is happening. From second submission onwards iit is not working.

Following are the module details: Drupal: 9.1.x Webform module:6.0.3 Honeypot: 2.0.1

There is no time restriction given in Honeypot module.

# Answer
This piece of code helped to solve the issue. Clearing the cache for every submission of a webform which is protected by honeypot.

```
    function MODULE_NAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $advanced_validation = \Drupal::config('honeypot.settings')->get('advanced_validation');
      if ($advanced_validation) {
        $form['#cache'] = ['max-age' => 0];
      }
    }

```
> 1 votes

---
Tags: webforms
---


title: Breadcrumbs not appearing

text:
# Question
Title: Breadcrumbs not appearing
I have a custom theme extending the bootstrap theme. In my theme there are no extra files except the .info.yml file. Everything else is inherited from bootstrap. I have also kept the regions in my custom theme, identical to the parent bootstrap theme.

For some reason none of the blocks including the breadcrumbs appear when I use my custom theme. I made sure to place those blocks from the block layout section inside those regions. But it's not showing. Weirdly, it's coming fine for the parent bootstrap theme and all of the core themes, but not my theme.

Breadcrumb visibility is also on in the theme settings page.

Any leads I can look into for checking where lies the problem?

Thanks in advance...

# Answer
I had to check the conditions applied to the block when it is placed inside a region.
For me, this was the case. The issue happened because of some default values stored from one of my custom condition plugins.
> 0 votes

---
Tags: 8, theming, breadcrumbs
---


# Question
Title: How do I change pager (# of items) for one page display in a view?
I have a view that will have about 7 different display pages. Some of the pages will have a different amount of items displayed on that page.

When I'm on my Publication Page (display name) and change `Use pager:Display a specified number of items | 3 items` to `15`, it changes it for all displays in this view.

How do I override it for this display only. Here is a screenshot of the page I'm currently on: https://ibb.co/8YJpC1d

I thought this would be something easy (probably is), but I honestly couldn't find anything online to help me.

# Answer
I guess I answered my own question, when I clicked the left side `Use pager:Display a specified number of items` it let me select if I want to override for just that display.
> 0 votes

---
Tags: views, paging
---


# Question
Title: Unable to install ... already exist in active configuration
On Drupal 8.1 I keep running in those kind of messages when I try to activate a custom module or a custom feature that makes some modification to the basic page. (add fields).

It is really annoying...

**Steps:**

* Clear database entirely
* go to /install.php and choose Standard profile
* Now that the site is running go to Extend
* Select Feature - Basic page

**Result:**

`Unable to install Feature - Basic Page, core.base_field_override.node.page.promote, core.entity_form_display.node.page.default, core.entity_view_display.node.page.default, core.entity_view_display.node.page.teaser, field.field.node.page.body, node.type.page already exist in active configuration.`

Well yeah... that is what I want to do: Change those default settings!

**Expected:**

Be able to install my feature that makes some modifications to the basic page.

**My Feature**

Here is my Feature create with the Features module

It basically adds two fields, banner\_image and background\_image to the basic page

Files:

```
config
    install
        core.base_field_override.node.page.changed.yml
        core.base_field_override.node.page.created.yml
        core.base_field_override.node.page.promote.yml
        core.base_field_override.node.page.status.yml
        core.base_field_override.node.page.sticky.yml
        core.base_field_override.node.page.title.yml
        core.base_field_override.node.page.uid.yml
        core.entity_form_display.node.page.default.yml
        core.entity_view_display.node.page.default.yml
        core.entity_view_display.node.page.teaser.yml
        field.field.node.page.body.yml
        field.field.node.page.field_banner_image.yml
        field.field.node.page.field_image.yml
        field.storage.node.field_banner_image.yml
        language.content_settings.node.page.yml
        node.type.page.yml
feature_basic_page.features.yml
feature_basic_page.info.yml

```

Why this simple thing is not supported? Is it a bug? What should I do to be able to use my feature?

# Answer
With `drush en` it works!

```
[profile_test]$ drush en feature_basic_page -y
The following extensions will be enabled: feature_basic_page
Do you really want to continue? (y/n): y
feature_basic_page was enabled successfully.   [ok]

```

EDIT: there is a way better solution now, see: How do I remove a configuration object from the active configuration?
> 2 votes

# Answer
With Drush, you can run `drush config-delete module_name.settings` to delete the configuration causing the error.

When not sure about what to delete, you can `drush config-get | grep your-keywords` to find the correct name to feed config-delete with.
> 38 votes

# Answer
Use the Easy Install module to purge the active configuration without using the Devel module or Drush. It works even if you have missed out the optional folder and the `enforced` option in the module's configuration files.

> A module built to resolve and avoid the error "Unable to install already exists active configuration" when re installing/un installing the drupal 8 modules , it works even if the module's configs not contains enforced in yml and not added configs in optional folder. It purge the active configuration object of uninstalled modules and helps to remove configuration object while uninstalling a module without using Drush / Devel / Drupal Console / Features Modules.
> 6 votes

# Answer
For a Pantheon site, I used the following Drush commands.

* On the Pantheon site, `drush @pantheon.SITENAME.ENVNAME config-delete ERRORNAME`
* On the local site, `drush config-delete ERRORNAME`
> 6 votes

# Answer
This thing is not supported because a module may not replace a config entity that already exists with install config.

To add form and view mode configurations for an already existing node type, you have to implement this in code in hook\_install().

Or you have to delete the node type first on your site, but then you also have to delete the content.

And no, this is not a bug, this is how it is defined to prevent loss of configuration.
> 3 votes

# Answer
Sometimes modules do not cleanly uninstall. Trying to re-enable a newer version would cause then this issue.

Do a DB backup first and run the following:

```
drush @site.env sqlq 'DELETE FROM config WHERE name LIKE "%module_name%";'

```
> 1 votes

# Answer
Let’s say that you don’t want to lose your settings for the module that somehow — on it's own — decided to become disabled. Do this:

***(optional)***

a) Backup your whole database. Put that someplace safe, just in case! ;-)

```
mysqldump -u {db_user} -p{db_pass} {database_name} > maybe-horrible-things-will-happen.sql
# HINT: no space after "-p"

```

b) Backup your whole Drupal config:

```
drush config:export --destination=/some/path/where/this-folder-will-be-created

```

Your sites current configuration will get dumped into `this-folder-will-be-created`.

*SEE*: https://drushcommands.com/drush-9x/config/config:export/ for more info.

*ASIDE*: a and b aren’t really optional ... because Drupal 8 does bad things, for no good reason, all the time; you better have a backup!

***(END optional)***

**STEP 1**) Tell drush to open the config file for `core.extension`:

```
drush config:edit core.extension

```

*ASIDE*: This uses whatever editor your shell has set for the `VISUAL` environment var; mine is: `VISUAL=vim`

**STEP 2**) Add the missing keys under the `module` key. Here's an example:

```
module:
  commerce_square: -2
  action: 0
  address: 0
  # ... [lots of others] ...
  draggableviews: 0
  # ... [lots of others] ...
  media: 0
  # ... [lots of others] ...
  site_settings: 0
  # ... [lots of others] ...
  scss_compiler: 1
  views: 10
  demo_commerce: 1000
theme:
  bootstrap: 0

```

**STEP 3**) Save your edits and drush will proceed to do some horrifying Drupaly voodoo that magically re-enables your modules without losing your work.

*ASIDE*: I'm pretty sure that the `: 0` but is the module weight because of the last entries in my config. I left three examples: `scss_compiler`, `views`, and `demo_commerce`, to illustrate the point.

### Errors I saw.

If drush spits out an error like...

```
[error]  Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.
  Configuration <em class="placeholder">views.view.product_sorter</em> depends on the <em class="placeholder">DraggableViews</em> module that will not be installed after import.

```

... then you'll need to add that key under `module:` also. I was trying to save `site_settings` and had no idea that `draggableviews` and `media` has also decided to go on holiday.

After adding `media` and saving the edit again, then I got the notification for `draggableviews`. Then after adding both `media` and `draggableviews` in the next go around, other bad things happened; read on...

If drush spits out an error like...

```
Table 'draggableviews_structure' already exists.

```

... then you might have to backup that table, delete the modules tables, and try again.

*ASIDE*: You can find out what the tables are for a given module by examining it's hook\_schema() implementation, within it's module\_name.install file. For example, the draggableviews.install file has this entry:

```
/**
 * Implements hook_schema().
 */
function draggableviews_schema() {
  $schema['draggableviews_structure'] = [
  //...
}

```

I didn't end up having to do that for the `draggableviews_structure` table, but here's how you'd go about that unpleasant task:

1. Dump the modules tables, then after you're sure you have the modules data, drop the modules tables.

```
mysqldump -u {db_user} -p{db_pass} {database_name} draggableviews_structure > draggableviews_structure.sql

```

```
mysql -u {db_user} -p{db_pass} {database_name} -e 'drop table draggableviews_structure'

```
2. re-edit the core.extension config; STEPs 1–3 above.
> 1 votes

# Answer
If you want to add configs to your custom module but they already exist in the active configuration, and for some reason you can't use drush to delete those configs (in my case because it's part of an install profile), and you are sure there won't be a problem with you overwriting the config, here's an approach to replacing those configs.

Add a new folder in your custom module, /config/hook\_install and add your config .yml files in that folder, then in your module's hook\_install.

```
use Drupal\Component\Serialization\Yaml;

/**
 * Implements hook_install().
 */
function mymodule_install() {

  // Replace these configs.  We're using code to do this, as they are already
  // installed.
  $config_files = [
    'language.types',
    'language.negotiation',
  ];

  foreach ($config_files as $config_id) {
    $raw_data = file_get_contents(drupal_get_path('module', 'mymodule') . '/config/hook_install/' . $config_id . '.yml');
    \Drupal::configFactory()->getEditable($config_id)
      ->setData(Yaml::decode($raw_data))
      ->save();
  }
}

```
> 0 votes

---
Tags: 8, features
---


# Question
Title: Setting custom key names for exported JSON view fields
I have a result set similar to this (using Views RESTful Export):

My question, how to change `created_1` key and name it something else?

# Answer
> 1 votes
From views you can configure the custom name/alias for fields from **Fields | Settings** option under **Format**. Check the screenshot for reference

---
Tags: views, 9
---


# Question
Title: Why can't I override the base region.html.twig template
I created a custom theme that has the `bootstrap_barrio` contrib theme as `base theme`. Everything is setup and working except that my custom `region--content.html.twig` in the /templates folder of my custom theme isn't being picked up. Drupal continues to use the base `region--nowrap.html.twig` that came with bootstrap\_barrio. My custom template shows up in the list of template suggestions when twig debugging is on.

I thought all I needed to do to override a base template was create a custom template into the custom theme, rebuild cache and Drupal will pick it up, as long as it conforms to the theme hook suggestions naming convention.

**Twig Debugging Output:**

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'region' -->
<!-- FILE NAME SUGGESTIONS:
   x region--nowrap.html.twig
   * region--content.html.twig
   * region.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/contrib/bootstrap_barrio/templates/layout/region--nowrap.html.twig' -->

```

# Answer
> 2 votes
I found a solution to this problem. Apparently if you have active "Clean wrapper for (x region)" on your theme, it will use that damn nowrap template no matter what. Disabling that goes back to use your default theme templates. You can find it over: /admin/appearance/settings/themeName Screenshot to follow:

# Answer
> 1 votes
The `x` in the twig debugging indicates the *active* template. Twig always goes from most specific (top of list) to least specific (bottom of list). So, for this order:

```
<!-- FILE NAME SUGGESTIONS:
   x region--nowrap.html.twig
   * region--content.html.twig
   * region.html.twig
-->

```

If `region--nowrap.html.twig` is present in the current theme or any of the parent themes, it will be given priority over any of the "lower" files.

In your case, You can confirm this by renaming `region--nowrap.html.twig` in the parent theme; this should cause `region--content.html.twig` in your subtheme to be given priority.

Solution: Override `region--nowrap.html.twig`, not `region--content.html.twig`.

---
Tags: 8, theming
---


title: Custom tokens in custom module

text:
# Question
Title: Custom tokens in custom module
The story : I create lets say a simple module to store input data and sent a mail when you click save. Now i done the part of store data, send mail and retrieve data, but i would like to add tokens to the mail part.

So for now i have something like this.

```
 function mymodule_form (){
         $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#size' => 60,
        '#maxlength' => 100,
        '#description' => t('Input your first and last name.'),

        $form['submit'] = array(
        '#value' => 'Save',
        '#type' => 'submit',
        '#submit' => array('mymodule_submit'),
         );

    return $form;

}

```

Now you have **mymodule\_submit** that saves the data and sends mail.

```
function mymodule_submit(){

 here goes the part for saving data into table(not going to write it)....

/*mail send*/
    $text=array();
    $subject=array();
    $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");
    foreach ($mail as $data){
        $text = $data -> text;
        $subject = $data -> subject;
    }

    $params = array(
    'subject' => $subject,
    'body' => $text,
            );
     $to =$emailto; //db_query that selects from table
     $from =$emailfrom; //db_query that selects from table
    drupal_mail('person', 'my_module', $to, language_default(), $params, $from, $send = TRUE);

    /*end mail send */

}

function mymodule_mail($key,&$message,$params)
{

  switch ($key) {
    case "my_module":
        $message['subject'] = $params['subject'];
        $message['body'][] = $params['body'];
      break;

  }
 }

```

Now I made a form for inserting subject and body of mail hence `$mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");`

My question is how can i allow user to use tokens or something else to add tokens like in drupal account mail settings(like: account activation, account blocked etc...), where you can add tokens to text so that you get :

\[user:name\],

A site administrator at \[site:name\] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

\[user:one-time-login-url\]

So to clarify ... I have a form that user uses to input mail data but for now he can only input text , i want to make it possible for him to use tokens(or something else like `drupal_set_message(t('Saved input @var!', array('@var'=>$temp)));`) when he inputs data...

Its a form like mymodule\_form.

# Answer
You would have to add them to a global token piece like \[site\] for them to be able to be used anywhere tokens are used.

But to use in a custom module you can use the following hooks:

Generate token info:

```
/**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_token'] = array(
    'name' => t('My token'),
    'description' => t('A token I use in my module.'),
  );
  return $info;
}

```

Give values to token:

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

  if ($type == 'my_custom_tokens') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'my_token':
          // Work out the value of our token.
          $value = 'Value of token';
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

```

That should get you started with custom tokens. I've used this a few different times with different situations and it works very well.
> 1 votes

# Answer
The answer given by @burnsjeremy shows you how to define the custom tokens. To actually use the custom tokens, you need to use token\_replace(). Token replacement should be done in your custom hook\_mail(). Because your module is called 'mymodule', your hook\_mail() should be called mymodule\_mail(). If you want your hook to be actually used, you MUST call drupal\_mail() with 'mymodule' as the FIRST argument. You currently are passing the wrong parameters to drupal\_mail() \- what you are doing now is causing Drupal to use the hook person\_mail() to send your email, so Drupal is ignoring your mymodule\_mail().
> 0 votes

# Answer
Thanks for the help i did it this way:

```
  function mymodule_submit(){

 here goes the part for saving data into table(not going to write it)....

/*mail send*/
    $text=array();
    $subject=array();
    $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");
    foreach ($mail as $data){
        $text = $data -> text;
        $subject = $data -> subject;
    }

   $params = array(
'subject' => $subject,
'body' => $message,
'!buyer_name'=> $name,
'!buyer_lastname'=> $lastname,
etc...

        );

     $to =$emailto; //db_query that selects from table
     $from =$emailfrom; //db_query that selects from table
    drupal_mail('person', 'my_module', $to, language_default(), $params, $from, $send = TRUE);

    /*end mail send */

}

function mymodule_mail($key,&$message,$params)
{

  switch ($key) {
    case "my_module":
        $message['subject'] = $params['subject'];
        $message['body'][] = $params['body'];
      break;

  }
 }

```

Then i just call !buyer\_name !buyer\_lastname when writing a text in text box.
> -1 votes

---
Tags: 7, emails, tokens
---


title: Add event listener to modal close

text:
# Question
Title: Add event listener to modal close
In Drupal we can open a modal is two ways, either with HTML:

```
<a class="use-ajax profile-page-link" data-dialog-type="modal" href="/node/1" data-dialog-options="{"width":800}">Open Modal</a>

```

Or with JS:

```
let ajaxSettings = {
  url: 'node/1',
  dialogType: 'modal',
  dialog: { width: 800 },
};
let ajaxObject = Drupal.ajax(ajaxSettings);
ajaxObject.execute();

```

Once the modal is open I would like to attach an event to the close button so I can drop a cookie on the close event to show the visitor has seen the modal and not show it to them again.

The close button has the class `ui-dialog-titlebar-close` but this is added after the initial page load so to attach an event we would need a dynamic click handler such as:

```
$('body').on('click', '.ui-dialog-titlebar-close', function() {
    alert('close button was clicked 2');
});

```

However this event never fires. This ctools issue mentions the same thing and has a solution involving binding to the `CToolsCloseModalBehaviors` event, however that was 6 years ago and I'm using D9 with no ctools so need to find a new solution.

When I inspect the attached events on the close button I can see `jquery.ui/ui/widget-min.js` `r()` and an anonymous function in `jquery.min.js`. Using non minified vs would help but not sure how to do that?

# Answer
> 5 votes
In core dialog.js code I've found a following lines of code.

```
$(window).trigger('dialog:afterclose', [dialog, $element]);

```

and

```
$(window).trigger('dialog:beforeclose', [dialog, $element]);

```

Means that it is possible to assign event listener to these events using the following code sample:

```
$(window).on('dialog:afterclose', (e) => {
  console.log(e);
});

```

P.S. Just don't forget to put it into Drupal behaviors and use .once to ensure that event listeners won't attach multiple times.

# Answer
> 2 votes
The clue was seeing the Drupal's modal just uses jquery widgets. So a simple Google for "jquery widget close event" lead me to this SO answer.

So the solution is:

```
$('#drupal-modal').on('dialogclose', function(event) {
    alert('closed');
});

```

---
Tags: modal-dialogs
---


# Question
Title: How do I let users cancel their account with JWT / JSON:API?
I am making an Ionic app with Drupal as the backend. Users log in via JWT. I'm using JSON:API to send data to Ionic. Now I want to allow users to cancel their accounts in the app (by JSON:API) instead of forcing them to log into the Drupal website and cancel there.

How can I do that?

# Answer
This method uses the JSON:API Resources module.

It assumes:

* Upon cancellation, blocking the user is OK. (Admins will manually delete the accounts completely later.)
* Logged-in users will simply make a GET request to `www.example.com/jsonapi/MYMODULE/cancelaccount` to cancel their accounts (the app will provide an "Are you sure?" dialog and so forth).

There is probably a better way to do this but I am sharing my solution here because a Google search didn't reveal anything on this topic.

**What to do**

First, create a custom module.

Then, in `MYMODULE.routing.yml`:

```
MYMODULE.user_cancel:
  path: '/%jsonapi%/MYMODULE/cancelaccount'
  defaults:
    _jsonapi_resource: Drupal\MYMODULE\Resource\MYMODULEUserCancel
  requirements:
    # Give all authenticated users permission.
    _permission: 'view own commerce_order'
  options:
    no_cache: 'TRUE

```

Next, in `MYMODULE/src/Resource/MYMODULEUserCancel.php`:

```
<?php

namespace Drupal\MYMODULE\Resource;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\ResourceResponse;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeAttribute;
use Drupal\jsonapi_resources\Resource\EntityQueryResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Processes a request for a collection containing a user's article nodes.
 *
 * @internal
 */
class MYMODULEUserCancel extends EntityQueryResourceBase implements ContainerInjectionInterface {

  /**
   * The current user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected AccountInterface $currentUser;

  /**
   * Logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  protected $loggerFactory;

  /**
   * Constructs a new EntityResourceBase object.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
   *   The Watchdog logger.
   */
  public function __construct(AccountInterface $account, LoggerChannelFactory $logger_factory) {
    $this->currentUser = $account;
    $this->loggerFactory = $logger_factory->get('MYMODULE');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user'),
      $container->get('logger.factory'),
    );
  }

  /**
   * Process the resource request.
   *
   * Code example:
   * https://git.drupalcode.org/project/jsonapi_resources/tree/9.x-1.x/tests/modules/jsonapi_resources_test/src/Resource.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   * @param \Drupal\jsonapi\ResourceType\ResourceType[] $resource_types
   *   The route resource types.
   *
   * @return \Drupal\jsonapi\ResourceResponse
   *   The response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function process(Request $request, array $resource_types): ResourceResponse {
    $uid = $this->currentUser->id();
    // Make sure that we do not try to cancel user 1 or anonymous.
    if ($uid !== 1 && $uid !== 0) {
      $user_storage = $this->entityTypeManager->getStorage('user');
      $current_user = $user_storage->load($uid);
      // See: https://drupal.stackexchange.com/a/204422.
      // Send the user the "account blocked" confirmation email.
      _user_mail_notify('status_blocked', $current_user);
      $current_user->set('status', FALSE);
      $current_user->save();
      $this->loggerFactory->notice("User account for UID @uid cancelled by JSON:API.", [
        '@uid' => $current_user->id(),
      ]);
    }

    // Some data to return with JSON:API.
    $custom_field_data = [
      'cancelled' => TRUE,
    ];

    $links = new LinkCollection([]);
    $resource_type = reset($resource_types);
    // To disable caching, set metadata.
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheMaxAge(1);
    $primary_data = new ResourceObject(
      $cacheability,
      $resource_type,
      $current_user->uuid(),
      NULL,
      $custom_field_data,
      $links
    );
    $top_level_data = new ResourceObjectData([$primary_data], 2);
    $response = $this->createJsonapiResponse($top_level_data, $request, 201, []);
    $response->addCacheableDependency($cacheability);

    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteResourceTypes(Route $route, string $route_name): array {
    $fields = [
      'drupalUid' => new ResourceTypeAttribute('drupalUid'),
      'status' => new ResourceTypeAttribute('status'),
    ];
    $resource_type = new ResourceType('current_user', 'current_user', NULL, FALSE, TRUE, TRUE, FALSE, $fields);
    // @todo Add role entities as a relatable resource type.
    $resource_type->setRelatableResourceTypes([]);
    return [$resource_type];
  }

}

```
> 0 votes

---
Tags: users, authentication-authorization
---


# Question
Title: Module listing page leading to php timeout
I am noticing that when I open the Modules listing page - admin/modules/ it leads to php timeout. There was no problem in listing out all the modules with drush. On opening the Modules listing Form in the core.

```
\Drupal\system\Form\ModulesListForm

```

I traced the problem to the following loop in the form.

```
$form['modules']['#tree'] = TRUE;
foreach ($modules as $filename => $module) {
  if (empty($module->info['hidden'])) {
    $package = $module->info['package'];
    $form['modules'][$package][$filename] = $this->buildRow($modules, $module, $distribution);
    $form['modules'][$package][$filename]['#parents'] = ['modules', $filename];

  }
}

```

If I do a break; the page loads up correctly with just one module and no errors. I believe its due to the sheer number of modules and the data that needs to be processed before generating the page.

So there is no bug but simply due to the data size in the loop. Has anyone faced this issue before and know how to speed up things?

P.S I am using the lightning installation profile.

# Answer
The solution to this was to increase the RAM in the server. We were using a container and the container was very restrictive in the amount of available RAM.
> 0 votes

---
Tags: 8
---


# Question
Title: Show latest changes in node "View" tab while using Content Moderation
I had been trying a lot to display latest revision into view tab irrespective of its state, so if a node is in "Draft" state I still want it to be displayed under "View" Tab rather than "Latest version". I had tried using hook\_ENTITY\_TYPE\_view, hook\_ENTITY\_TYPE\_view\_alter and even tried in template\_preprocess\_node hook but no luck. I was able to load latest revision but not able to set it using below code in preprocess,

```
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->getType() == 'news' && $variables['elements']['#view_mode'] = 'full') {
    $node = $variables['elements']['#node'];
    $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($node->id());
    $node = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
    $variables['elements']['#node']  = $node;
  }
}

```

Also tried with below code from a custom module,

```
function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node = Node::load($build['#node']->id());

  if ($entity->bundle() == 'article' && $view_mode = 'full') {
    $revision_ids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);
    $latest_rev_id  =  end($revision_ids);
    $node_new = node_revision_load($latest_rev_id);

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
    $storage = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId());
    //$node = $storage->load($build['#node']->id());
    $build_new = $view_builder->view($node_new, $view_mode);
    //$output = render($build);

    $build['#node'] =  $build_new['#node'];
  }

}

```

Please if anyone can point me in a right direction it will be very helpful. Thanks in advance.

# Answer
> 1 votes
Finally after spending huge amount of time on this, I am able to figure it out. Thanks to shawn-conn's answer here - Take over display of a content type node route I have created a custom module and have added below files and code to achieve this,

First created mymodule.services.yml and added below code,

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

Then created Routing folder under src. Added file named RouteSubscriber.php with below code,

```
<?php

namespace Drupal\mymodule\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

```

Then added NodeRedirectController.php under src/Controller directory with below code,

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Display latest revision content in view mode
    if ($node->bundle() === 'my_content_type' && $view_mode == 'full') {
      $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($node->id());
      $node_new = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
      return parent::view($node_new, $view_mode, $langcode);
    }
    // Otherwise, display as per Drupal's default behaviour
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

```

This might help someone.

---
Tags: 8, nodes
---


title: Import users from a CSV file

text:
# Question
Title: Import users from a CSV file
How can I import users fom a CSV file in Drupal 8?

I’ve found this module but it is not updated for Drupal 8:

https://www.drupal.org/project/user\_import

I think that I can make an import directly with a MySQL script but is it possible with Drupal (I know I can insert datas directly into database but I don't know if Drupal system will allow that method)?

I’ve found this question but it is not exactly what i need : Importing a bunch of users from csv spreadsheet file into Drupal 8

I import data from a csv file and it is not a migration from a drupal site.

# Answer
> 1 votes
To make it with Migrate you need to setup Migrate Plus, Migrate Tools and Migrate Source CSV together, there is lot of examples in the web already:

http://valuebound.com/resources/blog/how-to-migrate-users-from-a-csv-file-drupal-8

https://agencychief.com/blog/drupal-8-csv-migration

https://www.mtech-llc.com/blog/lucas-hedding/migrating-using-csv

# Answer
> 2 votes
> I think that I can make an import directly with a MySQL script but is it possible with Drupal (I know I can insert datas directly into database but U don't know if Drupal system will allow that method)?

Instead of MySQL this would be a Drupal method to insert users by using the Entity API:

```
$user = User::create([
  'name' => 'foobar',
  'mail' => 'foobar@example.com',
  'status' => TRUE,
]);
$user->save();

```

So if you don't want to use Migrate there are other ways for such a simple import task. You can use a php library of your choice to fetch the data and then add the user entities one by one. I answered a similar question for importing nodes at a time when Migrate was still in alpha: Is there a way to migrate only nodes?

# Answer
> 0 votes
Here I found the solution for it. Please follow this link https://github.com/steveoliver/user\_import and install the extended module. You can import the user data file through this path (path: '/admin/people/import').

# Answer
> 0 votes
User CSV Import is the module you want.

Migrate is a powerful and robust platform for integrating any arbitrary data source, but User CSV Import is tailor made for uploading CSVs of user data.

https://www.drupal.org/project/user\_csv\_import

There are other modules, like Bulk User Registration, which are less featureful. For example Bulk User Registration doesn't support any fields - you must manually write code to handle fields.

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


# Question
Title: Escaping CSS digits, 0 is removed from CSS aggregated files
The following HTML markup won't work on a production site.

```
<div class="iconleft 109">TEXT</div>

```

This is the code in the custom.css file.

```
.iconleft.\31 09,
.iconleft.\31 12,
.iconleft.\31 10,
.iconleft.\31 11,
.iconleft.\31 20 {
  background: #B0CD00;
}

```

`.iconleft.\31 09` works on localhost with xampp and no aggregation. On the production site, where Advanced CSS/JS Aggregation is activated, it wont work for 109.

In the aggregated CSS file, I see `.iconleft.\31 9` as CSS class. It seems that 0 has been removed.

Do you have any hint?

# Answer
I think the code is valid.

Anyway due to lack of time i decided to ad an "id" to the class. So the html is now

```
<div class="iconleft id-{{ child_id }}">Text</div>

```

And the css

```
.iconleft.id-109,
.iconleft.id-112,
.iconleft.id-110,
.iconleft.id-111,
.iconleft.id-120 {
  background: #B0CD00;
}

```

This is working for me.

But if somebody knows why aggregation removes the "0" please let me know.
> 0 votes

---
Tags: theming, css-js-aggregation
---


# Question
Title: How can I capture Watchdog output during a functional test?
I have a functional test that is failing, and I think that there could be some useful information in the database log, but unfortunately the test suite only runs in containers on GitLab CI so I don't have any way to get to the database log while the environment is running.

Is there any easy way to get a dump of the contents of the watchdog log in a test artifact?

# Answer
The Watchdog to File module is handy for this use case. You can initialize it in a test setup, like so:

```
<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * My browser tests.
 */
class MyBrowserTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->enableFileLogging();
  }

  /**
   * Enables logging of ALL watchdog events to a file.
   */
  protected function enableFileLogging() {
    $installer = \Drupal::service('module_installer');

    $installer->install([
      'watchdog_file',
    ]);

    $config_factory = \Drupal::configFactory();
    $config         = $config_factory->getEditable('watchdog_file.settings');

    $log_path =
      sprintf(
        '%s/artifacts/watchdog-%s.log',
        dirname(DRUPAL_ROOT),
        $this->databasePrefix
      );

    $config->set('log_filename', $log_path);
    $config->save(TRUE);
  }

}

```

Then, just configure GitLab CI to capture the test artifacts folder:

```
  artifacts:
    when: always
    reports:
      junit: artifacts/junit/*.xml
    paths:
      - artifacts/*
      - web/sites/simpletest/*

```

As a bonus, the above snippet *also* captures browser output produced by browser tests, in case you need to review them as well.

Each watchdog log will be named according to the Simple Test database ID that is used for the corresponding test run. For example, if you have five cases in your test, you should end up with five watchdog file logs.
> 3 votes

---
Tags: 8, testing, log-messages
---


# Question
Title: Get total of all orders cost of a specific user programmatically
I want to get total cost of all the order placed by an user programmatically in Drupal 8. I used below code to get total orders count, same way need to get total cost.

```
$query = \Drupal::entityQueryAggregate('commerce_order')
  ->condition('uid', $user_id)
  ->condition('state', 'completed')
  ->groupBy('uid')
  ->aggregate('order_id', 'COUNT')
  ->execute();

```

# Answer
I don't know if it will be work or something like this...

```
$user_id = \Drupal::currentUser()->id();
$orders = \Drupal::entityTypeManager()
->getStorage('commerce_order')
->loadByProperties(['uid' => $user_id]);

$orderPrice = [];
foreach($orders as $key => $value) {
   $orderPrice[] = $value->get('total_price')->getValue()['0']['number'];
}
$total = array_sum($orderPrice);
kint($total);

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Views AJAX pager not working, though AJAX is enabled
I have a view of 6 news items on my front page. These get rendered in teaser mode. I enabled a pager of 6 items, and also enabled AJAX as you can see in the settings below. AJAX is enabled in the Drupal modules, I am not blocking Javascript and the `ajax.js` file is loaded fine when I inspect my site. I have checked the console for errors, but no errors were shown. I tried to disable semantic views, but to no avail.

The view export can be found here, and the site can be found here. This is just a test environment: some other pages may not work.

A bigger image can be found here

# Answer
> 18 votes
I can't (yet) answer your question, but I can see where I think it's going wrong.

The Views JS is loading for your site, but the Views classes aren't being applied the same on your site and the test I'm using. I expect if you swap to another theme, you'll see the View start working. (That doesn't mean you need to abandon your theme, but it may help you track the problem down.)

In your JS console, you can inspect variables - and the relevant variable for you looks like `Drupal.views.instances.GENERATEDNAMEHERE.element_settings.selector`.

On a working test site, I see this (zoom in to see the JS). Note that the value in `selector` can then be used to obtain the wrapper div for the view HTML.

(To test: Copy the value from `selector`, and use it as a jQuery() selector. You can do this in your JS console.)

On your site, I see a value set in the same (similar, due to the generated ID) location, but that same value doesn't match an element in your HTML - jQuery returns an empty array, instead of an array populated with (one) matching HTML element.

So ... you need to work out what about your theme is preventing that DIV being applied. If your theme is from Drupal Contrib, you might check the issue queue. If you're using a module which strips extraneous DIV elements, that might be a place to look. And so forth.

Hope this helps ... it's not really an answer, but I hope it moves you closer to one!

# Answer
> 1 votes
Remove JS aggregation from admin/config/development/performance - This will resolve the issue for the meantime...

# Answer
> 0 votes
It's because of your templates files. Due to the default classes. Please check with views related files (views-view tpl files) or pager related twig files (pager.html.twig)

For Example: inline js-pager\__items

```
 <ul class="pagination inline js-pager__items">
           {# Print previous item if we are not on the first page. #}
           {% if items.previous %}
             <li class="previous">

```

---
Tags: views, ajax, paging
---


# Question
Title: How can I disable all the JavaScript scripts?
I am trying to disable all the JavaScript on all the pages of a Drupal 8 site for anonymous users if there is a particular header in the request object.

I tried out this code.

```
/**
 * Implements hook_js_alter().
 */
function MODULE_js_alter(&$javascript, AttachedAssetsInterface $assets) {
  if (MODULE_get_headers()) {
    unset($javascript);
  }
}

```

```
/**
 * Implements hook_page_attachments_alter().
 */
function MODULE_page_attachments_alter(&$attachments) {
  // This is for disabling all 3rd party libraries.
  if (MODULE_get_headers()) {
    $attachments['#attached']['library'] = [];
  }
}

```

It does seem to work to a certain extent. It disables most of JavaScript, but I am seeing the styles are also off (which might be expected) as the CSS libraries might also be removed.

Is there a better way to do this? Maybe Drupal has an option to turn off all the JavaScript.

# Answer
You don't necessarily need to turn off aggregation if you want to remove all javascript. You could for example remove the placeholder in the html template, then the (already aggregated) javascript won't be replaced in the html page:

```
function mymodule_preprocess_html(&$variables) {
  if (MODULE_get_headers()) {
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts']);
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts_bottom']);
  }
  $variables['#cache']['contexts'][] = 'headers:my-header';
}

```

You need a cache context for the request header. This doesn't work for the *Internal Page Cache*, though. So you need to uninstall this module or extend it to add the request header to the cache key.
> 3 votes

---
Tags: 8
---


# Question
Title: How do I add a <div> over a paragraph's field, depending on another field of this paragraph?
I have a paragraph (from the paragraphs module) which has two fields :

* `field_title` (text)
* `field_title_level` (list text)

The `field_title_level` can have either `h2`, `h3`, or `h4` as a value. What I would like to do is to surround the title text with a `h2`/`h3`/`h4` div.

I tried using templates (paragraph, or field). With the field one, I managed to add a div over the title, but I didn't manage to access the `field_title_level` in order to add the correct div. And using the paragraph template, I didn't manage to add any div over the title.

Any clue?

# Answer
> 1 votes
Don't use the field template -- you'll find it difficult to change the formatting of one field based on the value of another field at that level. You'll want to use the paragraph template (or sometimes even the node template containing the paragraphs entity reference revisions field) so that the values of both fields are in scope at the same time.

Something like this might work in the paragraph template:

```
{% if content.field_title_level.value == "h2" %}
  <h2>{{ content.field_title }}</h2>
{% endif %}
{% if content.field_title_level.value == "h3" %}
  <h3>{{ content.field_title }}</h3>
{% endif %}
{% if content.field_title_level.value == "h4" %}
  <h4>{{ content.field_title }}</h4>
{% endif %}

```

You could use `{% if %}{% elseif %}{% else %}{% endif %}` instead of consecutive `if`s to provide a default ... I don't know what your data structure looks like.

You did mention that you want to use `<div>` elements, so maybe you want something more like this instead:

```
{% if content.field_title_level.value == "h2" %}
  <div class="h2">{{ content.field_title }}</div>
{% endif %}
{% if content.field_title_level.value == "h3" %}
  <div class="h3">{{ content.field_title }}</div>
{% endif %}
{% if content.field_title_level.value == "h4" %}
  <div class="h4">{{ content.field_title }}</div>
{% endif %}

```

Be aware, though, that `<div>` elements are not semantic HTML like the header tags. (Even though they may be visually styled to appear like HTML headers, they will not be treated the same way by assistive technologies, like screen readers for the blind.)

Finally, note that you can do some very cool tricks by rendering Paragraphs content in the node template, by iterating through the items in the Paragraphs entity reference revisions field like so:

```
{% if node.field_paragraphs_items %}
  {% for item in node.field_paragraphs_items %}
    {% if item.entity.field_title %}
      {% if item.entity.field_title_level_value == "h2" %}
        <h2>{{ item.entity.field_title }}</h2>
      {% endif %}
      {% if item.entity.field_title_level_value == "h3" %}
        <h3>{{ item.entity.field_title }}</h3>
      {% endif %}
      {% if item.entity.field_title_level_value == "h4" %}
        <h4>{{ item.entity.field_title }}</h4>
      {% endif %}
    {% endif %}
  {% endfor %}
{% endif %}

```

(Markdown syntax highlighting does not like my Twig, so there may be some errors in this example but hopefully you get the idea.)

Note the use of `item.entity` (in the node template) instead of `content` (in the paragraph template.) Just as pulling back from the field template to the paragraph template brought more field values into scope, rendering paragraphs entity references in the node template in this way will give you access to field values from the node as well as those in the paragraph.

There are pros and cons to both approaches. Keeping paragraph markup in the paragraph templates will keep your Twig tidier, so I generally recommend it unless your business logic requires you to render Paragraphs conditionally based on values in the parent node.

# Answer
> 0 votes
I remember seeing a video several years back about paragraphs being used with a "switch" field where the switch value controls the orientation of the content, or color, or something similar. I can't find it ATM, maybe you can do a search and be more lucky.

In the meantime there's this article with similar vibes: Drupal Paragraphs: let content managers easily choose coloring

---
Tags: theming, paragraphs, 9
---


# Question
Title: How do I display the file size and format of attachments on a node templates?
In the node template I output the attached files (multiupload file field). Need to output the size and format of each file. I do it like this:

```
{% for file in node.field_news_files %}Size {{ file.entity.filesize.value }} in {{ file.entity.filemime.value }} format{% endfor %}

```

I get this result: Size 2227507 in APPLICATION/PDF format

The goal is to get this result: Size 2MB in PDF format

Can I output the data as I need in the node template or do I need to redefine it file-link.html.twig?

# Answer
The Format Bytes module provides a Twig filter for that.

> In twig when you get the value of a file, the size is in simple bytes and if you're intending to show it to your end-user, it's not user-friendly, this simple Twig filter helps with that and renders the file size in it's respected: 'B', 'KB', 'MB', 'GB', 'TB'
>
> Example usage:
>
> ```
> {{ node.field_attachment.entity.field_file.entity.filesize.value | format_bytes }}
>
> ```

The alternative would be to do the same formatting that module does in your own preprocess function for the template.
> 4 votes

# Answer
My task is solved in two steps:

1. Install the "Format Bytes" module to output a clear file size
2. Output a field with files in the node.html.twig template, where we use the necessary markup and redefine the file format that we use in the field settings. In the example below, my final code is on twig without markup.

My field with files, which can have multiple values: "**field\_page\_files**"

```
{% if node.field_page_files is not empty %}
    {% for file in node.field_page_files %}

        {# Output the file label, if it is empty-output the machine name of the file #}
        {% if file.description is not empty %}
            {{ file.description }}
        {% else %}
            {{ file.entity.label }}
        {% endif %}

        {# Redefining the output of the file format, output of the file size by Format Bytes module #}
        ({% if file.entity.filemime.value == "text/plain" %}txt{% elseif file.entity.filemime.value == "application/pdf" %}pdf{% elseif file.entity.filemime.value == "application/rtf" %}rtf{% elseif file.entity.filemime.value == "application/rar" %}rar{% elseif file.entity.filemime.value == "application/zip" %}zip{% elseif file.entity.filemime.value == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" %}docx{% elseif file.entity.filemime.value == "application/msword" %}doc{% elseif file.entity.filemime.value == "image/jpeg" %}jpeg{% elseif file.entity.filemime.value == "image/png" %}jpeg{% elseif file.entity.filemime.value == "image/gif" %}gif{% elseif file.entity.filemime.value == "application/vnd.ms-excel" %}xls{% else %}file{% endif %}, {{ file.entity.filesize.value | format_bytes }})</span>
    {% endfor %}
{% endif %}

```

In my example, I use the following file formats for the field: txt, pdf, rar, zip, doc, docx, jpg, jpeg, gif, png, xls, rtf
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Behavior to use .insertAfter() on load + after each ajax call?
So I have a views page that outputs some elements in the grid. And I have a custom block on the page that needs to be inserted between those elements. On load it using .insertAfter() to randomly insert that block between view content element in the grid.

The problem is it works on load, but after each Ajax call on the pager i want to insert same block again in the grid, but that elements does not exist anymore. Not sure how to resolve this. Here is my code:

```
Drupal.behaviors.modalYoutubeVideo = {
  attach: function (context, settings) {
    function moveTileBetweenElements() {
      // Get random number between 1 and 23 and insert after that :nth-child.
      var rndInt = Math.floor(Math.random() * 23) + 1
      var wrapper = $('.view-products .view-content a:nth-child(' + rndInt + ')');
      var tile = $('.block-custom-order-tile');
      $(tile).insertAfter($(wrapper));
    }

    moveTileBetweenElements();

    $(document).once('weberAjaxViews').ajaxComplete(function (event, xhr, settings) {
      moveTileBetweenElements();
    });
  }
};

```

# Answer
In Drupal `ajaxComplete()` is not required, as Drupal executes each iteration of `Drupal.behaviors.*.attach()` whenever an ajax call is complete. This function receives an argument, `context`, which on page load contains the entire contents of the document, and on AJAX calls contains the new part of the DOM being inserted into the page. This piece of the document can be parsed for the elements you are searching for. These two APIs are combined with `jQuery.once()` to ensure that code is not executed on any piece of the DOM more than once.

Example:

```
(function ($, Drupal) {

  /**
   * Does something.
   *
   * @param DOMelement context
   *   Contains a the full document on page load, or new parts of the
   *   DOM being inserted into the page after ajax calls.
   */
  function doSomething(context) {
    $(context).find(".some_dom_element").once("arbitrary-key").each(function () {
      // Do some stuff a single time on each instance of .some_dom_element that
      // appears on the page, both on page load and after any ajax loads.
    });
  }

  Drupal.behaviors.someArbitraryKey = {
    attach: function (context) {
      doSomething(context);
    }
  };
}(jQuery, Drupal));

```

Note that if you create your own ajax calls, you will need to pass any new parts of the DOM to Drupal.attachBehaviors():

```
$.ajax({
  url: '/path/to/ajax/callback',
  complete: function (data) {
    var newContent = $(data);
    // Pass the DOM element the jQuery object contains,
    // not the jQuery object:
    Drupal.attachBehaviors(newContent.eq(0));
    newContent.insertAfter($("#some_element"));
  }
});

```
> 3 votes

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


title: Getting values on twig node template

text:
# Question
Title: Getting values on twig node template
I have installed ECK module in my website. Using it I have created a "report eck" entity in which I have different bundles like section, notes, etc., each containing different fields. I have my content type "Report" in which I have referred "report eck" entity using entity reference field. Now, in my nice template, I need to get various values including the bundle type, in which I am facing lots of trouble. My bundle type is coming up as following when I am doing kint() on my reference field, but I am not able to get this bundle type and many other values, please guide.

Also, it seems to be a protected values, so I navigated to "Available Methods" tabs and found method 'getEntityKey()' which seems to be useful, but how can I use it in twig template??

# Answer
These are protected. You need to use any available getters to access them. Example, for nodes, the method is `getType()`. `$node->getType()`. Most generic entities should have a `bundle()` method that returns type.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Abundle/8.4.x

Examples:

`$bundle = $myEntity->bundle();`

`$variables['bundle'] = $bundle;`

Twig: `{{ bundle }}`
> 0 votes

# Answer
I will go for `render` option and use the template instead of manually accessing values. Alternatively, you can go for custom twig functions or filters to access referenced field values.
> 0 votes

---
Tags: theming, 8, nodes
---


# Question
Title: How can I add classes to rows depending on the loop index?
I have received a design where they want to have the latest three articles links put on the top of the front page (over their respective images) so that the first is taking left half of the page and second and third to split (vertically) the right half top.

I thought that view-view--latest-articles.html.twig would solve the problem elegantly like this:

```
<div class="row">
{% for row in rows %}
    {% if loop.index == 1 %}
      <div class="col-6">
          {{ row }}
      </div>
    {% elseif loop.index==2 %}
    ...   // dull and inelegant code dismissed
    {% endif %}
{% endfor %}

```

But if I put debugging code for loop.index into the code it only shows the index once and splurts out all the rows after it, never minding my if. It still shows the index once, so I know it IS using the template.

Am I missing something or trying just to it in a wrong way?

# Answer
And as it so often happens: Just after fighting a pair of hours with this and then finally asking the question here, I found out the solution myself. I had to make the code in views-view-unformatted--latest-articles.html.twig (i.e. had to add the -unformatted to my question part).
> 0 votes

---
Tags: views, theming, 9
---


# Question
Title: Get all orders count of a specific user programmatically
I want to get count of all the order placed by an user programmatically in Drupal 8.

# Answer
Below code will give count of completed orders placed by an user.

```
$query = \Drupal::entityQueryAggregate('commerce_order')
  ->condition('uid', $user_id)
  ->condition('state', 'completed')
  ->groupBy('uid')
  ->aggregate('order_id', 'COUNT')
  ->execute();

```
> 0 votes

# Answer
You can remove the `->condition('state', 'completed')` to get all order placed by user.

```
$query = \Drupal::entityQueryAggregate('commerce_order')
  ->condition('uid', $user_id)
  ->groupBy('uid')
  ->aggregate('order_id', 'COUNT')
  ->execute();

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to make exposed filters to hide filed with no value
I am using exposed filters in Views to give user opportunity to select attribute. I used field with taxonomy term as exposed filters.

As a result, exposed filter shows all possible variants for this field (all terms), instead which really were used in this material. I mean, that user can select any term from vocabulary even if I did not use this term in this content type material. How to hide unused terms in exposed filters?

# Answer
> 2 votes
The below code comes from a current project of mine. I've made it more generic for your purposes, so it's untested. You'd need to modify the query depending on your usage - it's going to throw errors if you use as-is.

```
<?php
// Add this to a custom module, replace "mymodule" with your module name
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  //dsm($form); // Display available form vars
  $field_id = 'id_assigned_in_views'; // Change for the field ID in question.
  // Only alter forms with the necessary field.
  if (isset($form[$field_id])) {
    // Do your entity_field_query or db_query here
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', array('tags'))
      ->propertyOrderBy('weight');
    $result = $query->execute();
    $terms = $result['taxonomy_term'];
    // Add a default so the filter is optional.
    $options = array('' => t('- All -'));
    foreach($terms as $tid=>$term) {
      //dpm($term);
      $options[$tid] = $term->name;
    }
    // Alter the field.
    $form[$field_id]['#type'] = 'select';
    $form[$field_id]['#options'] = $options;
    $form[$field_id]['#size'] = 1;
  }
}
?>

```

# Answer
> 0 votes
Check this module https://www.drupal.org/project/better\_exposed\_filters. This module works with views and allow the option to "Show only used terms: Restrict exposed filter values to those presented in the result set."

It has many other features, very powerful for usability.

---
Tags: views
---


# Question
Title: Integrating websockets server to the database
I'm running a headless Drupal+Angular application where I want to run a server with some clients using WebSockets (and Ratchet). I managed to make a server script detached from Drupal sending messages to multiple Angular apps. Now I want to implement the server to Drupal in order to update an entity and pass the updated entity to all clients.

I'm struggling with the best architecture and what is possible.

### Scenario I

Implement the server in a Drupal module in order to access the database directly to get and update the entity and then pass the entity to clients.

### Scenario II

The server connects to the database directly, do custom queries and pass the entity to clients.

### Scenario III

Create API's where the server can get and update the entity and pass the entity to clients.

For security reasons, I want to avoid Scenario II. Scenario I seem to be the nicest approach, but I'm unsure whether it's possible.

# Answer
> 0 votes
First, Drupal (PHP) makes a lousy websocket server (it’s completely engineered the other way around for it) with php 8 we are getting closer but that’s out of scope for drupal.

But Drupal services (with possibly a JWT or openID Connect endpoint) seems like the best path forwards.

(That would be a variant of option 3)

---
Tags: 9, nodejs
---


# Question
Title: How can I copy block placements and settings between themes?
How to copy blocks placement and settings between themes? suggests that, in Drupal 7, I could run the following two SQL queries to copy block placements and settings between themes.

```
DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')

```

What is the equivalent query/method I could use to achieve the same task in Drupal 8?

# Answer
There is a module available for Block backup and restore. https://www.drupal.org/project/block\_backup\_restore
> 2 votes

# Answer
Drupal 8 block settings are in configuration files. It is possible to transfer them but takes a bit of editing / file renaming.

You first have to do a complete export of the configuration files. In this, the ones you are looking for have names like block.block....yml, e.g.: block.block.old\_theme\_main\_menu.yml

First step is to rename these to block.block.new\_theme...yml, e.g : block.block.new\_theme\_main\_menu.yml. Generally a quick bit of editing to create a script to do the renaming is the easiest.

Next, you need to change the internal theme references to the old theme to the new theme. E.g. the old theme yml file will look like:

```
langcode: en
status: true
dependencies:
  config:
    - system.menu.main
  module:
    - block_class
    - system
  theme:
    - old_theme
third_party_settings:
  block_class:
    classes: ''
id: old_theme_main_menu
theme: old_theme
region: navigation_collapsible
weight: -34
provider: null
plugin: 'system_menu_block:main'
settings:
  id: 'system_menu_block:main'
  label: 'Main navigation'
  provider: system
  label_display: '0'
  level: 1
  depth: 2
visibility: {  }

```

A good editor should be able to do a replace in files to change old\_theme to new\_theme. Double check that your theme names are unique in these files.

If the new theme does not have the same regions, then you will need to figure out how to change the region: setting to match your new theme.

In your new theme, create a config directory in the root and then an install directory under it.

Put all the yml files in the install directory.

Uninstall / re-install the new theme to import the settings here.

This assumes the same site with the same code / custom blocks.

If you are going to use this theme in a new site, you will have to make sure the site will provide the blocks defined in the yml config. Generally, the install directory is used to place system level blocks (e.g main menu) that core provides. But if you set up a system with a distro or manually to provide other blocks, this works as well.

There may be some minor gotcha's like visibility settings using the wrong node id and the like.
> 1 votes

# Answer
I was mostly successful in migrating about 500 blocks from one theme to the next by doing the following:

```
1. copy all block configs for old theme (eg block.block.theme1.*) to tmp directory
2. Removed configs that were disabled 'status: false'
3. bulk rename 500+ config files from theme1 to theme2 (need a tool for regex or partial string renaming, I used Windows PowerRename)
4. Renamed same theme name strings within each file
5. Removed uuid from each file
6. Copied back into my sync directory and imported.

```
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Can I use a contextual filter to remove content?
So I have this view that searches for content (articles, blogs, etc.) associated with a particular author name. Is there a way with this that I can pass a contextual filter of taxonomy terms that would filter out content?

So let's say we have a couple articles tagged with "love", and "questions" but I have one article also tagged with "talk". Is there a way I can pass that term "talk" as a contextual filter (or filter criteria) to block it from showing up in the list? Essentially I'm hoping there is something like "Content: Does not have taxonomy term ID" or something like that.

# Answer
## Regular Filter

You can add the regular Filter for the Taxonomy term Entity Reference field, select the `Is none of` under `Operator`, and then click to select "talk" from the terms list.

## Contextual filter

You can also use the `Exclude` option in the Contextual filter for the ER field. I would use this option only if I needed the filter to be Contextual for some reason, if I needed options that come with it, otherwise just use the regular filter.

1. Add the Contextual filter for your Taxonomy term Entity Reference field, and configure it with these options:
`When the filter value is NOT available`
**Provide default value**
**Fixed**
**\[Taxonomy term ID for "talk"\]**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
**\[Your Vocabulary\]**
`More`
**Exclude**
2. Check your results to see if the content tagged with "talk" is removed.

Enter `all` into Views Preview field to bypass the Contextual and check if the "talk" nodes come back (be careful if you have more than one Contextual filter, you may need to provide more than one argument for Views to show results).
> 1 votes

---
Tags: 7, views
---


# Question
Title: Defaulting a value for a new boolean field added to an existing content type with content?
We have a Drupal 8 site. For one of our features, I added a boolean field called 'Pinned' to a our Blog Post content type.

As I added the filed as a filter criteria to views, I noticed that, no matter what configuration I selected, `Is equal to` \+ `True`, `Is equal to` \+ `False`, `Is not equal to` \+ `True`, `Is not equal to` \+ `False`, my view preview, which had had results, suddenly gave no results. I thought surely one of these combinations must apply to at least one node.

I added the 'Pinned' field to the fields of the view to examine the values, and removed it from the filter criteria. It turns out that the field was technically `NULL`, from the join-- there was no record in `node__field_pinned.field_pinned_value`.

To further test, I edited one of our blog posts nodes. When I checked the 'Pinned' checkbox, the value in the view became 1. When I then unchecked the checkbox and saved the node, then value became 0.

Trying to think of ways to auto-populate the field, I made the 'Pinned' field required.

But, all that did was make it necessary to check the checkbox when editing or adding a Blog Post.

This didn't solve my problem, and seemed to make the field redundant anyway. You can't save the node without checking the checkbox; you have to check it.

**Edit** going off Grapple's answer, I found that if I changed the widget to "Check boxes/radio buttons" on the "Manage form display" page of the content type. This does allow you to set a default value, but it does not auto-populate existing node field values, nor does it auto-populate the form widget for existing nodes.

It only auto-populates the form for new nodes.

It seems like a boolean field with a checkbox widget is meant for situations where the user cannot advance without checking the box, such as accepting terms of service, etc.

As it is, it is difficult to use, because we have hundreds of Blog Posts, and it's pretty labor intensive to edit each one and check, then uncheck the box. We only want a few pinned posts, but we can't have views of unpinned posts being empty.

Is there a way I can add a Boolean field to a content type with existing nodes and have it auto-populate with values?

# Answer
If the field has a default value configured, you may be able to cause the "Pinned" field to be populated by bulk editing the nodes from the content overview page, and toggling a different value like 'Published', 'Sticky', or 'Promoted to front page'.

---

For a programmatic solution, implement `hook_post_update_NAME` to load the necessary entities and update the new field with the required default value.
> 1 votes

# Answer
Because of the problems with no default value, we decided to re-utilize the 'sticky' field on our content type. A default value of '0' already exists for that field.

If you are in a situation where you can't use that, look at `hook_post_update_NAME` as gapple answers.

**Edit** We just learned, the hard way (bug report), that the use of the sticky fields requires the "Administer Content" permission, which is an administrative permission (Drupal lists a warning message next to it.)

In our case, I don't want all of our blog editors to have this permission, so this is not a permanent solution for us.
> 0 votes

# Answer
I faced the same issue: created a new boolean field in an existing content and needed to use it as a filter criteria in a View.

My solution involved implementing `hook_views_query_alter()` to manually add the `JOIN` and a `WHERE` clause to address nodes that had not yet received values for my new boolean field.

Important to note that, in order for this solution to work, I didn't add the filter criteria in the View, otherwise Drupal would have added the `JOIN` and a `WHERE` clause that would cause no results to be returned.

I used a custom module for this. This is the contents of `my_module.module`:

```
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // Only applies to 'my_view', for two REST Export displays
    if ($view->id() == 'my_view' && in_array($view->getDisplay()->display['id'], ['rest_export_1', 'rest_export_2'])) {
        // Add JOIN to main view query
        // LEFT JOIN node__field_hide_feed ON node_field_data.nid = node__field_hide_feed.entity_id AND node__field_hide_feed.deleted = 0
        $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', [
            'type' => 'LEFT',
            'table' => 'node__field_hide_feed',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
            'extra' => [
                [
                    'field' => 'deleted',
                    'value' => 0,
                ],
            ],
        ]);
        $query->addRelationship('node__field_hide_feed', $join, 'node_field_data');

        // Add WHERE clause
        // AND (node__field_hide_feed.field_hide_feed_value IS NULL OR node__field_hide_feed.field_hide_feed_value = 0)
        $query->where[] = [
            'conditions' => [
                [
                    'field' => 'node__field_hide_feed.field_hide_feed_value',
                    'value' => NULL,
                    'operator' => 'IS NULL',
                ],
                [
                    'field' => 'node__field_hide_feed.field_hide_feed_value',
                    'value' => 0,
                    'operator' => '=',
                ],
            ],
            'args' => [],
            'type' => 'OR',
        ];
    }
}

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Show latest content date from group content type
I've a group type vendor with following groups:

* V1
* V2
* V3

Each group is associated with content type notes as shown below:

Notes (Content Type) with nodes associated with groups:

```
N1 (Group: V1)
N2 (Group: V1)
N3 (Group: V2)
N4 (Group: V2)
N5 (Group: V3)

```

So the relationship between them goes like this.

| Vendor (Group Type) |
| --- |

| Group V1 | Group V2 | Group V3 |
| --- | --- | --- |
| N1 | N3 | N5 |
| N2 | N4 | None |

Where N\* are nodes of content type **Notes**

I want to create a view where following data should be displayed:

```
V1
    Latest content update date
V2
    Latest content update date

```

But I do not want all the contents update date listed. When I use grid layout I can group the content as per associated group but the output contains all the last updated date for all contents. I want to limit the output only to last 2-3 contents.

Example:

Views -\> Grid Layout -\> Group by group title -\> Number of columns per row -\> 2

Output:

```
V1

N1 last update date     N2 last update date

V2

N3 last update date     N4 last update date

```

Expected output:

```
V1

N1 last update date

V2

N3 last update date

```

# Answer
After a some research and hit and trial I'm able to configure views output as per requirements with Views merge row module. Below are the steps I've followed:

1. Install Views Merge Row module.
2. Create a Views with group content type.
3. Select Format -\> Card
4. Add fields:
    * Group Title
    * Content Changed on (relationship content)

3. In card settings Select "Group Field 1" as a Group Title.
4. Now under views Advance-settings Select "Merge rows"
5. Under Merge row settings select following configuration:

| Field | Merge Option |
| --- | --- |
| Group Title | Use Values of this field as a filter |
| Content Changed | Use First Value of this Field |

6. Sort -\> Ascending
> 0 votes

---
Tags: views, 9, group
---


# Question
Title: When "drush updatedb" is executed, are scripts cached by OPCache invalidated?
For sites that have PHP OPCache enabled:

1. Does updating site using Drush require restarting the webserver to invalidate the scripts cached by OPCache?
2. Does Drupal core or Drush invalidate OPCache before running updates?
3. Is setting `opcache.enable_cli` to 0 a better strategy in this scenario?

# Answer
Updated response to address the questions as asked.

1. Yes, either the web server need to be restarted or the web-server's OPCache needs to be cleared. Drush cannot clear the web-server's opcache as it is a CLI application. Instead of restarting the web server a php script with following content can be added to next to Drupal's update.php

```
 <?php
 opcache_reset( );
 /*
 Following measures should be taken to safeguard this file from malicious use
 a) Set filename with a long random string as a name (like 100+ characters).
 b) Check the IP address of the requester so the script can only be called from trusted networks.

 To clear cache visit this file at
 siteurl/random_long_string_eiquooR3.php
 or use curl siteurl/random_long_string_eiquooR3.php
 Check the IP address of the requester so it can only be called from trusted networks.
 */

```
2. Neither Drupal core nor Drush invalidate OPCache.
3. Yes, setting opcache.enable\_cli to 0 is a fine, it is anyways off by default. Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

---

Original Answer by @greggles

1. Restarting the webserver works, but takes quite some time. A more efficient solution is to have a way to call opcache\_reset.
2. Opcache must be reset by calling `opcache_reset` from within the web process. If you call it inside drush then it will not clear the opcache for the webserver so it won't help the problem.
3. Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

If you want to clear opcache as part of a deploy process, I suggest adding a file that contains `opcache_reset` and then you have to protect access to that file so malicious users can't easily call it:

1. Give it a long random string as a name (like 100+ characters).
2. Check the IP address of the requester it can only be called from trusted networks.
> 3 votes

# Answer
We just ended up writing a more general solution to purge PHP and Database cache's used by Drupal Core. This module provides three ways to purge Opcache.

* Web browser user interface
* Curl commands
* Drush commands

The Cache Utility module is available on Drupal.org
> 0 votes

---
Tags: 8, drush, caching, updating
---