# Question
Title: Attaching assets if the page contains a table
I want to attach a CSS file to a page only if it contains a table. I tried

```
function my_assets_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'my_assets/fancy';
  }
}

```

from the guide "Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module" but it does not work. The hook itself and the condition works. The question is where I have to save the `#attached` array in the `$types` variable?

I appreciate your help and feedback.

PS: The following hook attaches the CSS as expected:

```
function my_assets_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_assets/fancy';
}

```

Edit: While using the site I noticed that my CSS loads on sites like "/admin/structure/types". The Twig Debug hint says "THEME HOOK: 'table'". I guess this is important because it does not say this on the other tables I was waiting for to load the CSS.

# Answer
### `'#type' => 'table'`

OK, so I tried it out in a Vanilla D8.6 with a custom module like yours and the Bartik theme enabled. I placed `hook_element_info_alter` in the custom module and checked what Kint `ksm($info)` would return me (matching the code from your question that would be `ksm($types)`). I visited the front page and I saw `'table'` in the array so I thought there must be a table on that page somewhere and the library should get attached. But it didn't. Because there actually was no table.

Only after I added a custom block to the custom module, placed the block somewhere prominent and let it output some sample code from `class Table`:

```
/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['contacts'] = [
    '#type'    => 'table',
    '#caption' => $this
      ->t('Sample Table'),
    '#header'  => [
      $this
        ->t('Name'),
      $this
        ->t('Phone'),
    ],
  ];
  return $build;
}

```

And then the library suddenly got attached as documented. So, yeah, everything's fine. You just need to be sure you really have a `'#type' => 'table'` element on that page. That's all.

---

### `'#theme' => 'table'`

As @4k4 asked in the comments to your question it seems likely you used `'#theme' => 'table'` to build your tables. Then attach the library directly like that (snipped copied from the Node core module):

```
$build['node_revisions_table'] = [
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $header,
  '#attached' => [
    'library' => ['node/drupal.node.admin'],
  ],
  '#attributes' => ['class' => 'node-revision-table'],
];

```

Although in this case you could also make use of `hook_preprocess_table` to have that pattern applied to all tables you've built using `'#theme' => 'table'`.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function my_assets_preprocess_table(&$variables) {
  $variables['#attached']['library'][] =  'my_assets/fancy';
}

```

---

### `<table>`

OK, so after we finally found out you put a table as markup into the body field of your node, using CKEditor, here's what's needed to attach your library accordingly.

You can't check for `'#type' => 'table'` or `'#theme' => 'table'` at this point, as your table is just markup. So simply check for the existence of a `<table>` tag. Or even better, check for just `<table`, because who knows what else attributes can come after that. Pay attention for the **two** underscores in the function name, and replace `body` with the machine name of whatever field you need to preprocess.

```
/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function my_assets_preprocess_field__body(&$variables) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  $items = $variables['element']['#items'];

  $value = $items->first()->getValue()['value'];

  if (\strpos($value, '<table') !== FALSE) {
    $variables['#attached']['library'][] = 'my_assets/fancy';
  }
}

```
> 4 votes

---
Tags: 8, theming
---


# Question
Title: How do I get the token for a date field type to display as a custom format?
When adding content I entered a date which is February 2013 within a Date field type but it is displayed as raw data such as 2013-02-01T00:00:00 for the token that is listed as \[node:field\_fact\_sheet\_date\].

If I instead change the token to \[node:field\_fact\_sheet\_date:custom:F Y\] or \[node:field\_fact\_sheet\_date:custom:F,Y\] then nothing is listed. However it is working when I use \[current-date:custom:F Y\] and displayed correctly as August 2013. How do I get the token for a date field type to display as a custom format?

# Answer
1. A date may be a range, therefore \[node:field\_date\] cannot be considered as a date token. Install Entity API and enable the module "Entity tokens" to get access to the actual date value,
2. Beware that for an obscure reason Entity token replace the underscore (\[node:field\_date...) of the original tokens name by a dash (\[field-date...), you will then have access to a properly formatted date (in my case "\[node:field-date:value:custom:Ym\]", in the original question I guess therefore "\[node:field-fact-sheet-date:value:custom:F,Y\]")
> 2 votes

# Answer
I am also using the Date module in combination with Entity API and Entity tokens but I couldn't get this to work.

My date field has both start and end times so I tried using `event/[node:field-event-date:value:custom:Y]/[node:field-event-date:value:custom:m]/[node:title]` where `value` was the start date of the event but it still didn't work.

I'm not 100% sure why but when I changed it to `event/[node:field-event-date:0:value:custom:Y]/[node:field-event-date:0:value:custom:m]/[node:title]` it worked. I suspect this has something to do with the Date module allowing multiple dates to be attached to an event.

Hopefully this helps someone else!
> 2 votes

# Answer
I had a similar issue, and mine had to do with a bug in the Entity API module. There is a new patch available here: https://drupal.org/node/1440928
> 0 votes

# Answer
For Drupal 8 date fields, use \[node:date\_field\_name:date:custom:Y\]. This is not obvious because it's not in the token browser, but it should work. See https://www.drupal.org/project/token/issues/2786181 for more information.
> 0 votes

---
Tags: datetime, tokens
---


# Question
Title: Unexpected error when trying to view revisions
A website I maintain can't view revisions without receiving an unexpected error. The log file points to this code in the .theme file but I have no idea what it does. When I commented it out, the website seems to function fine and revisions are viewable.

```
function themename_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $path_args = explode('/', $current_path);
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $node_info = \Drupal\node\Entity\Node::load($node->id());
    if($node_info->hasField('field_component')) {
      $paragraph = $node_info->field_component->getValue();
      if($paragraph) {
        foreach ( $paragraph as $element ) {
          $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
        }
        $variables['hero_banner'] = $p;
      }
    }
  }
}

```

The log particularly points to the 6th line above as the error. It mentions "Error: Call to a member function id()".

Does anyone have any clue? Thanks!

# Answer
> 2 votes
You need to add a check and also no need to `$node_info = Node::load` as the node is already loaded. The first two lines inside the function are not even getting used, so I removed them.

```
function themename_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) { // check it's a node
    if($node->hasField('field_component')) {
      $paragraph = $node->field_component->getValue();
      if($paragraph) {
        foreach ( $paragraph as $element ) {
          $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
        }
        $variables['hero_banner'] = $p;
      }
    }
  }
}

```

---
Tags: nodes
---


title: How to create entity within blockForm?

text:
# Question
Title: How to create entity within blockForm?
I would like for users to be able to create new paragraph entities within the form of a custom block instead of going into the linked content type and adding the content.

In the past, I've always used the elements from this list but unfortunately it doesn't seem like there is an option for that.

Has anyone ever built anything similar to what I'm describing?

Thanks.

# Answer
The easiest idea I could come up with would be to define the paragraph type through the UI. Then you'd have 2 options:

1. whether make a custom form with similar fields and create a new paragraph entity on form submission.
2. define a content type which has reference field to the paragraph type. Then you could simply render the node form which would handle all the logic of displaying the fields and saving of the paragraph it self.

I would prefer option number 2 since paragraphs are not meant to be stand-alone entities. They are meant to be parts of content. IMHO I don't think one paragraphs entity should be reused on multiple nodes.
> 2 votes

---
Tags: 8, forms, blocks
---


title: Form Rebuild by Ajax Call

text:
# Question
Title: Form Rebuild by Ajax Call
I have a form which is built using some data which is partially random. Unfortunately, at the first AJAX call (nothing has been submitted yet, neither AJAX, nor in the normal way) the form will be rebuilt so that all random inputs are lost. Is there any way to avoid it?

```
class AjaxTestForm extends FormBase {

  public function getFormId() {
    return 'ajax_text_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = $this->_getOptions();
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
      ],
      '#empty_option' => 'Please select',
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];
    $form_state->set('ajaxoptions', $options);
    return $form;
  }

  private function _getOptions()
  {
    // Actually data from an external Controller
    // But those, too, are random
    $options = [
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
    ];
    return $options;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing
  }

  public function ajaxCallback($form, $form_state)
  {
    print_r($form_state->getValue('select'));
    echo "\n";
    print_r($form['select']['#options']);
    print_r($form_state->get('ajaxoptions'));
  }

}

```

When the user selects an option, in the Ajax callback (or Ajax submit, if I had one) I can't know which options were originally in the select box available. Is there any way to preserve that information?

# Answer
> -1 votes
Get the value from:

`$_temp_var_ = $form_state->getUserInput('_field_name_');`

Use `getUserInput()` instead of `getValue()`.

And then set the value to:

`$form['_field_name_'] = $_temp_var_;`

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


# Question
Title: How to get view name and display ID in template_preprocess_node function
I'm having some trouble in order to get a view's name and the display ID in a `template_preprocess_node function`.
I have a custom content type and a view with two different displays.
My idea is to define a variable in the preprocess function related to the content type (using `theme_preprocess__content_type_name` function), in order to use this variable in the Twig template to switch between the displays, according to the number of results.

I understand that in order to use a variable in the preprocess function, it has to be defined somehow in the template (correct me if I got this wrong).
So my question is: how can I call the view and the display in the node preprocess function?

EDIT 1: Using Hudri suggestion:

```
function theme_name_preprocess_node__content_type(&$variables) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    if($view_id == 'view_name' && $display_id == 'display_name'){
        $counter = count($view_id->result);
        $variables['count'] = $counter;
    }
}

```

Can the variable `count` be used in the Twig template in an if clause?

# Answer
> 4 votes
I'm assuming you're using a view page to display your content type:

```
$route = \Drupal::routeMatch()->getRouteObject();
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');

```

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


title: Create taxonomy terms on the fly

text:
# Question
Title: Create taxonomy terms on the fly
As far as I know, the way to create a taxonomy term is having to go into the taxonomy module and creating on there, and THEN assigning the term to the node.

Is there a way to create taxonomy terms on the fly? When the node is created, if the taxonomy term doesn't exist, it should be created too.

# Answer
> 7 votes
Use the Hierarchical Select module:

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. **You can even create new items and levels through Hierarchical Select!**

Another way is selecting *Autocomplete term widget (tagging)* as field widget, when creating your term reference field

As another option, there is the Simple hierarchical select module.

# Answer
> 2 votes
```
 //see if this term already exists and fetch it if it does
  $term = taxonomy_get_term_by_name($i);

  //if it doesn't exist, make it
  if ($term == array()){
    //make a new class to hold the term for taxonomy 1
    $taxonomy = new stdClass();
    $taxonomy->name = $i;
    // mentioned vid here as of now i placed 1.
    $taxonomy->vid = 1;
    taxonomy_term_save($taxonomy);
    //now fetch it so we have it's tid
    $term = taxonomy_get_term_by_name($i);
  }

  //set $tid as it's returned from  taxonomy_get_term_by_name
  $tid = key($term);

  //tag the node with the appropriate tag
   $node->field_tags['und'][0] = array('tid' => $tid);

  //save the tagged node
  node_save($node);
  $i++;

```

Above code will check for term exist and if not creates new term, when creating new content.

# Answer
> 1 votes
In addition to the above suggestions, once can go for autocomplete\_delux(https://www.drupal.org/project/autocomplete\_deluxe) and entity\_autocreate(https://www.drupal.org/project/entityreference\_autocreate) modules.

These behave in manner just as the above modules; plus they fall under Drupal Security Policy

# Answer
> -2 votes
I'd like to suggest the Manage Multiple Terms module:

> Manage Multiple Terms provides a simple mechanism to add, update, delete many terms in the same time easily and quickly.

---
Tags: taxonomy-terms
---


# Question
Title: Links in stage environments are absolute and send users to live enviroment
This problem has been driving crazy for years. whenever I create a stage environment of a site, I copy the database from the production site. some of the links there - whether in the menus or in the content or in the code, are absolute paths in the production site. so i have links that lead users from one environment to the other.

Ive been looking for a way to alter this behaviour. so that all link as
live-environment.com/some-page ----\> stage-environment.com/some-page

I dont care if it will happen before the render or just after the click. just that the end result will be that the user stays in the stage environment.

How can I do this. (drupal 7)

Thanks a lot for your help

# Answer
So ive solved it with js

```
$('a').each(function() {
    if(!$(this)||$(this)=="undefined") return;
    var href = $(this).attr('href');
    if(!href)return;
    if (href.includes("live-environment.org")){
        var live_env_url = href;
        var stg_url = new URL(live_env_url);
        stg_url.hostname = Drupal.settings.basePath.substring(0, Drupal.settings.basePath.length-1);;
        $(this).attr('href', decodeURIComponent(stg_url.href));
    }
});

```
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: How to create different Filter Criteria which works indipendently for every views (one is "For All" the other is "For this page")
I will post down an image I edited to better help you understand what I'm asking for

The reason is I've more than 50 different views that filters the same objects from a single content type based on their personal taxonomy term that differentiates them in some sub-categories, but I want those views to also have a common filter for the Year in which they were created (for development reasons, the year is a taxonomy term with just a number like "2018" "2019") so that when I want the users to view the content created this year (2019) I just have to modify one filter criteria and update it for everyone else. Currently you can only have a single filter criteria section which can either be "for all" or "for this page", this means I've to manually change the year filter for all 50 of them because I need filter criteria to be Overriden in every single view to introduce a filter for each sub categories. Is there a solution to this? a module? Or were can I find the PHP code which regolates how filters works?

# Answer
> 1 votes
You can't influence all Views that way at one go, that wouldn't make any sense because you can have various Views types (content, user, taxonomy term).

What you can have is a Master display within one View that can be used as a template for creating new displays. But that isn't what you're asking for.

You're asking for partial Filter handling, some Filters applied to all displays, and some Filters overridden for particular displays. But that isn't available AFAICT, at least not without complex code interventions.

But I think you might be helped with Contextual filters. Usually they are used when you need to Filter according to each taxonomy term, for example. It's tedious to create a new display for each term, instead, you let Drupal calculate that on the fly.

The same with the Date, you can use a Contextual filter on Authored on field to show only the ones from a particular year.

Automation is key when dealing with a large number of data.

Here's a couple of quick tutorials about Contextual filters: Using Drupal Contextual Filters in Views, How to use Contextual Filter in Drupal 8

---
Tags: views
---


# Question
Title: Adding JS to field widget being created in my module
Cross-posting to stackoverflow.com

I am creating a custom field to eventually be displayed in a custom paragraph. I need to upload a JS file for the widget view, but can't seem to get it to work. Can anyone see what I am doing wrong or need to do differently?

I can add the field to the paragraph, add the paragraph to a document and see the fields, but I see no evidence of the JS being attached (the file is not downloaded in the browser and does not activate).

Any help or suggestions are appreciated.

file: src/Plugin/Field/FieldWidget/get\_libguides\_listings\_widget.php:

```
<?php

namespace Drupal\get_libguides_listings\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

class get_libguides_listings_widget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(
               FieldItemListInterface $items,
               $delta, array $element, array &$form,
               FormStateInterface $form_state) {
    $element['Subject_IDs'] = [
      '#type'=>'textfield',
      '#title'=>$this->t('Subject IDs to Display'),
      '#description'=>$this->t('BLAH'),
      '#default_value'
           =>isset($items->getValue()[$delta]['Subject_IDs'])
          ?$items->getValue()[$delta]['Subject_IDs']
          :'',
      '#states'=>[
        'visible' => [
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'subject']],
          'or',
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'both']],
        ],
      ],
    ];
    $element['Subject_IDs']['#attached'][]
          = 'get_libguides_listings/get_searchby';
    return $element;
  }
}

```

file: get\_libguides\_listings.libraries.yml:

```
get_searchby:
  js:
    js/get_searchby.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

file: js/get\_searchby.js

```
/**
 * @file
 */
(function(){
  alert('hello there');

  (function ($, Drupal)
  {
    Drupal.behaviors.get_searchby = {
      attach: function (context, settings)
      {
        alert('hello');
      }
    };
  }(jQuery, Drupal));
}());

```

# Answer
> 3 votes
You forgot the `library` key:

```
$element['Subject_IDs']['#attached']['library'][] = 'get_libguides_listings/get_searchby';

```

---
Tags: 8
---


# Question
Title: How to call field label & values in custom content type page template
I have created a custom `page--mycontent-type.page.tpl` for customizing display with html tags classes & attributes.
I'am unable to call that content type fields & their label.
I've tried these to print values but not worked for me.

1. `<?php print render($content['field_name']); ?>`
2. `<?php print render($page['content']['field_name']); ?>`
3. `<?php print render($fields['field_introduction']->content); ?>`

Please suggest me what code call the actual fields & label. Thanks in advance :)

# Answer
For the objective of adding classes to fields in a node (as you made clear in your comment) you can use `hook_node_view` to intercept the node and then you can change the markup of your fields. You can find detailed examples here.
> 0 votes

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


# Question
Title: Behat test fails, unable to find Username field using @javascript
My Behat test fails as soon as I add `@javascript`

Error:

> ```
> Form field with id|name|label|value|placeholder "Username" not found.
>
> ```

When I remove `@javascript`, test is passed without any error.

```
Given I am logged in as a user with the Administrator role

```

To test the Drupal 8 `image_field` I need `@javascript`

Behat.yml:

```
default:
  autoload:
    '': '%paths.base%/tests/behat/bootstrap'
  suites:
    default:
      paths:
        - '%paths.base%/tests/behat/default'
      contexts:
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\DrushContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\MinkContext
        - MyServices\EntityContext
        - FailureContext
        - MyServices\LinkContext
        - My\MenuContext
  extensions:
    Bex\Behat\ScreenshotExtension:
      image_drivers:
        local:
          screenshot_directory: /[SHARED_FOLDER]/screenshots
    Behat\MinkExtension:
      goutte: ~
      base_url: "http://dev.mysite.com"
      files_path: '%paths.base%/tests/behat/files/'
      javascript_session: selenium2
      browser_name: chrome
      selenium2:
        wd_host: "http://localhost:4444/wd/hub"
        capabilities:
          # required by mink-extension 2.3
          marionette: null
          browserName: chrome
          browser: chrome
          version: 63
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drupal:
        drupal_root: '%paths.base%/public'
      text:
        username_field: "Username"
        password_field: "Password"
        log_in: "Log in"
        log_out: "Log out"
      selectors:
        message_selector: '.messages'
        error_message_selector: '.messages--error'
        success_message_selector: '.messages--status'
        warning_message_selector: '.messages--warning'
        logged_in_selector: '.user-logged-in'
        login_form_selector: '#user-login-form'
      region_map:
        comments: '.comments'
        "main navigation": '#block-my-theme-main-navigation'
        "local tasks": '.block--local-tasks-block'
        "main content": '.block--system-main-block'
        "highlights": '.c-highlights__list'

ci:
  extensions:
    Bex\Behat\ScreenshotExtension:
      image_drivers:
        local:
          screenshot_directory: /tmp/artifacts/screenshots
    Behat\MinkExtension:
      base_url: http://localhost

```

# Answer
> 4 votes
I bet you are either one:

1. Testing against a non-English site.
2. Having BigPipe enabled.
3. Missed to tag that scenario with `@api`.
4. Misconfigured Selenium.

---

To solve 1. you need to put the non-English strings into your `behat.yml` like so:

```
Drupal\DrupalExtension:
  text:
    log_out: "Sign out"
    log_in: "Sign in"
    password_field: "Enter your password"
    username_field: "Username"

```

@see docs Override text strings.

---

To solve 2. which can occur when BigPipe somehow changes the markup in an undesired way, you can try out the patch at https://github.com/jhedstrom/drupalextension/pull/325.patch.

@see pull request Big pipe compatibility follow-up

---

To solve 3. simply add an `@api` tag to your scenario.

---

To solve 4. you must point `wd_host` to `http://dev.mysite.com:4444/wd/hub`, since your `base_url` is `http://dev.mysite.com`.

```
wd_host: "http://dev.mysite.com:4444/wd/hub"

```

---
Tags: 8, testing
---


title: Migration with ID already exists

text:
# Question
Title: Migration with ID already exists
My migration is not showing up in `drush migrate-status`. When I try to reimport them with `drush config-import --partial --source="modules/custom/complinetmigration/config/install"` I get the following error message.

> The import failed due for the following reasons:
> Unexpected error during import with operation create for migrate\_plus.migration.complinet\_xml\_to\_node2: *migration* entity with ID *market\_center\_to\_D8* already exists.

# Answer
* Try deleting the existing migration by doing `drush cdel migrate_plus.migration.MIGRATION_ID`
* I think the `id` in your YML file is not the same as the `MIGRATION_ID` part of your YML file name.
> 2 votes

# Answer
You can try some way below:

1. Try import single with drupal cis (this option will override if config exited)
2. Delete config with command:

drush config-delete migrate\_plus.migration.complinet\_xml\_to\_node2

and import again.
> 0 votes

---
Tags: migrations
---


title: drupalSettings cached in page

text:
# Question
Title: drupalSettings cached in page
I have a module that adds functionality to the front-end. The feature can be turned on or off via the configuration page of the module.

I pass the settings to the frontend in the HTML preprocess function using `#attached`. Simplified, the code looks like this:

```
function my_module_preprocess_html(&$variables) {
  $config = \Drupal::config('my_module.settings');
  $settings = ['enabled' => $config->get('enabled')];
  $variables['#attached']['drupalSettings']['my_module'] = $settings;
}

```

This approach is suggested here:

https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/

It works fine when logged in, but for anonymous users changing the setting from the module's configuration page does nothing until I clear caches (as, I assume, the drupalSettings variable is defined within the HTML that makes up the page)

So, my question:

* Is there a way to ensure the settings are fresh with each page load (without disabling the entire page cache, of course), or
* Should I refresh the cache whenever the module's configuration form is submitted? If so, what's the most efficient way to do that? (I've noticed a full cache clear is far slower on D8 than it was in D7)

# Answer
Okay, I found the answer. It was as simple as adding this to `$variables`:

```
$variables['#cache']['tags'] = $config->getCacheTags();

```

My question is basically a duplicate of this:

How do I avoid having to clear the cache when changing a module configuration parameter?
> 3 votes

---
Tags: 8, caching
---


# Question
Title: How to place two Fivestar widgets on the node for voting?
I would like to place the fivestar voting widget both to the beginning and to the end of my node. I do not talk about two different ratings, I'd like to let my readers vote in both positions. I read the code of Fivestar, but I did not find the solution in the module source. I think the JS code would get wrong if two voting widgets were present on the page. Do you have any idea how to solve this problem, how to duplicate the voting widget somehow..?

I'm using Drupal 6 btw and Fivestar 1.19.

# Answer
you can use a PHP code like this

```
$node=node_load($nid);
print fivestar_widget_form($node);

```

the forms will have different ids so the javascript will work

you have to create a custom php/tpl file for this node-CONENENTTYPENAME.tpl.php by copying the contents of your node.tpl.php and include there the custom code...
> 2 votes

# Answer
You could also use Page Manager and enable the node\_view template and set the fivestar field twice or even more wherever you'd like it to go.
> 0 votes

---
Tags: rating
---


# Question
Title: How to use Drupal.displace inside Drupal.behaviors
I want to scroll down the page at page load time to bring a feature that might be below the fold into the viewport. Script works fine for anonymous, but for authenticated user, Toolbar module overlays the content I just scrolled to.

I've read that the way to resolve this is using `Drupal.displace.offsets.top` but when I call that from within my behavior `Drupal.displace` is undefined. I've been using comment-new-indicator.js from comment module as my guide here, and clearly my usecase is a little different because I'm doing this around page load time.

The problem is two fold: Drupal.displace isn't loaded when my script is called AND Toolbar hasn't done its stuff yet. I've cleared caches both in browser and drush numerous times. I've mucked with JS weights in libraries.yml -- nothing works.

One thought was to *delay the initial execution with a 500 ms smudge* to wait for some eventual viewport adjustment milliseconds later (that may or may not ever happen). So far this isn't really working well either, I don't want to delay the smudge longer for normal users because it becomes too noticeable.

Another thought was to register an event listener for `drupalViewportOffsetChange` but for some reason that never gets triggered.

mytheme.libraries.yml

```
custom-scroll-feature:
  js:
    js/custom-scroll-feature.js: { weight: -1 }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.displace

```

js/custom-scroll-feature.js

```
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.customScrollFeature = {
    attach: function (context, settings) {

      console.log(Drupal.displace);
      // outputs 'undefined'

      console.log(Drupal);
      // outputs
      // {behaviors: {…}, locale: {…}, throwError: ƒ, attachBehaviors: ƒ, detachBehaviors: ƒ, …}
      // no mention of Drupal.displace

      var start = time();
      $(document).on('drupalViewportOffsetChange', function () {
        console.log(Drupal);
        console.log(displace);
        var end = time(),
          elapsed = end - start;
        console.log("elapsed: " + elapsed);
        // The above never gets triggered.
      });

    }
  };

})(jQuery, Drupal);

```

With JS aggregation off, I've confirmed that jquery.js, drupal.js, and displace.js are all present in the list of requests on chrome network tab and appear before custom-scroll-feature.js is requested.

After I let the page load, and type the following into the javascript console, i get the expected value:

```
> Drupal.displace.offsets.top
79

```

To be clear I do not want to make a dependency on Toolbar, because then that would *load more javascript for all users* but I want to be sure that this script runs after Toolbar may have run, if it existed in the requests. I would have thought that automagically the weight of js added by themes would be higher than that of core modules, no?

# Answer
> 4 votes
Your thought to use `drupalViewportOffsetChange` is the way to go. The actual event is `drupalViewportOffsetChange.toolbar`. Here is an example:

```
  Drupal.behaviors.myTheme = {
    attach: function attach(context) {
      if (context === document) {
        $(context).on("drupalViewportOffsetChange.toolbar", function (event, offsets) {
          var selectors = [".class-of-thing-i-want-to-offset"];
          selectors.forEach(function (selector) {
            if ($(selector).length > 0 && offsets.top > 0) {
              $(selector).css("top", offsets.top);
            }
          });
        });
      }
    }
  };

```

---
Tags: 8, theming, javascript
---


title: Add paragraphs item to user entity

text:
# Question
Title: Add paragraphs item to user entity
I want to create a new paragraph item to a user bundle. This is the code:

```
$name = "Test";
$userdata = user_load($user->uid);
$paragraph = entity_create('paragraphs_item', array('field_name' => 'field_userdata', 'bundle' => 'userdata'));
$paragraph->setHostEntity('user', $userdata);
$paragraph->field_name[LANGUAGE_NONE][0]['value'] = $name;
$paragraph->save();

```

But nothing happens, no errors, no new entity.. Are there differences to adding to a node bundle?

Thank you!

# Answer
First make sure following things are configured properly:

1. Is Entity API module is enabled in your site?
2. Have you enabled `Logging and errors` from `admin/config/development/logging` page, to see site errors?
3. In second line you have not defined `$user` object, are you defined else where?
4. How are you calling this function?

If everything is configured properly then execute following code:

```
$name = "Test";
global $user;
$userdata = user_load($user->uid);
$paragraph = entity_create('paragraphs_item', array('field_name' => 'field_userdata'));
$paragraph->setHostEntity('user', $userdata);
$paragraph->field_name[$userdata->language][]['value'] = $name;
$entity->save();

```
> 0 votes

---
Tags: 7, users, paragraphs
---


# Question
Title: Drupal 8 CKEditor dynamic internal links plugin?
In Drupal 8 CKEditor WYSIWYG editor when I create a link to an internal page I use this URL path which I type manually: /parent/child/pagename

I then found a few buttons that can be added to the CKEditor interface that allow you to search for existing pages and it autoatically creates these paths.

e.g. These seem to be the best options:

https://www.drupal.org/project/ckeditor\_entity\_link

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

The problem I have is that it inserts the link into the HTML like so which is static:

```
 <p><a href="/parent/child/pagename">test</a></p>

```

When I then change that page name or location to someting else the link breaks.

What I'm looking for is a plugin that inserts dynamic links, similar to this concept using that the page node ID or whatever uniquie identifier Drupal uses never changes:

```
  <p><a href="$PAGENODEID$">test</a></p>

```

so no matter what the page name/path/url is it will always link to the same page.

I know there is the option of setting up page redirects for old URL alias though without going into detail why that is not a solution for me in my case please leave that suggestion aside I already know of that. :)

Thank you

# Answer
> 3 votes
I'm the maintainer for Linkit module.

Linkit 8.x-5.x is solving the problem you describe with static URL:s.

The new version is using data-attributes (UUID and some other values) that calculates the URL in "run time". That solves the issue.

Remember to also enable the Linkit filter in your text format configuration. Also, make sure that the data attributes are added to the HTML filter allowed values if you use that filter.

# Answer
> 0 votes
Whilst it's great that Linkit is adding support for this, you may still have issues with broken links, especially from external sources.

The redirect module handles this by adding a redirection everytime the path for a piece of content changes.

---
Tags: path-aliases, wysiwyg
---


# Question
Title: Is there any security risk to use getenv() inside settings.php to populate databases variable from a .env file?
I am using the Drupal composer project, which doesn't use `getenv()` by default. I wanted to use the following code inside the settings.php file in a production site.

```
  $databases['default']['default'] = array (
   'database' => getenv('MYSQL_DATABASE'),
   'username' => getenv('MYSQL_USER'),
   'password' => getenv('MYSQL_PASSWORD'),
   'prefix' => '',
   'host' => getenv('MYSQL_HOSTNAME'),
   'port' => getenv('MYSQL_PORT'),
   'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
   'driver' => 'mysql',
);

```

I read somewhere we shouldn't use `getenv()` in production sites. What are the downsides of it? Is there any security issue?

# Answer
If the .env file is outside the server document root, using `getenv()` is similar to putting the hash salt in a file and reading it with `file_get_contents()` as the following comments in the default.settings.php file suggest to do. (The same comment is present in the default.settings.php file for Drupal 7, so it's not a matter of which Drupal version is used.)

```
/**
 * Salt for one-time login links, cancel links, form tokens, etc.
 *
 * This variable will be set to a random value by the installer. All one-time
 * login links will be invalidated if the value is changed. Note that if your
 * site is deployed on a cluster of web servers, you must ensure that this
 * variable has the same value on each server.
 *
 * For enhanced security, you may set this variable to the contents of a file
 * outside your document root; you should also ensure that this file is not
 * stored with backups of your database.
 *
 * Example:
 * @code
 *   $settings['hash_salt'] = file_get_contents('/home/example/salt.txt');
 * @endcode
 */
$settings['hash_salt'] = '';

```

If that is considered enhanced security, the same can be said for reading some values using `getenv()`, if the file containing the values of the environment variables is not in the server document root.

Keep in mind that, if somebody would be able to write a PHP file on the server, it would also be possible for them to read the environment variables and the file containing the hash salt.
> 3 votes

# Answer
You may be telling about this **Production environments rarely use .env files.**. Someday I also went through this line. Though still I don't know what is this why it has been written like this ?

```
<?php
/**
 * This file is included very early. See autoload.files in composer.json and
 * https://getcomposer.org/doc/04-schema.md#files
 */
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
/**
 * Load any .env file. See /.env.example.
 */
$dotenv = new Dotenv(__DIR__);
try {
  $dotenv->load();
}
catch (InvalidPathException $e) {
  // Do nothing. Production environments rarely use .env files.
}

```

https://github.com/drupal-composer/drupal-project/blob/8.x/load.environment.php
> 1 votes

---
Tags: installation
---


# Question
Title: Views hook gets ignored after 1 execution
I registered this hook in my module:

```
function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {
        die('hello world');
}

```

I cleared the caches, and ran a view.

Output is "hello world" as expected.

I refreshed the view, and my pre\_render plugin is completely ignored (view is shown normally).

What's happening?

# Answer
Solution is to put the code in a file called MYMODULE.views**\_execution**.inc. I was using MYMODULE.views.inc
> 0 votes

---
Tags: 8
---


# Question
Title: Barrio theme not showing user menu drop-down
I tried to show the multilevel dropdown submenu for the **user account menu** in subtheme using bootstrap\_barrio but it is not showing up. however i did the configuration in the block to show multilevel and put the menu links as expanded.

# Answer
after investing a lot .. i found that barrio theme is only coming with impelemntation for the navigation menu not for the user account menu . what i did is i just copy /templates/navigation/menu--main.html.twig and renamed it menu--account.html.twig

and it works fine
> 4 votes

---
Tags: bootstrap-theme
---


# Question
Title: How do I redirect after saving the user account with $user->save()?
How can I redirect users in a custom module after saving a user account with `$user->save()`? It always goes to the user profile after saving and I want to redirect to a custom page.

```
function user_update_redirect(&$form, $form_state) {
  $value1 = $form_state->getValue('panel');
  $value2 = $form_state->getValue('type_of_user');
  $storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
  $user = \Drupal::currentUser();
  $user = user_load($user->id());
  $user->set('field_panel', $value1);
  $user->set('field_type_of_user', $value2);
  kint($user);
  $user->save();
}

```

# Answer
I suppose you want to remain on your site when redirecting. I don't recommend hardcoded URL's anywhere else but in route.yml files. Call the right service and don't forget to use dependency injection in your services and don't use a trait or directly call it from the container.

```
  private function redirect(string $route) {
    $path = $this->container->get('url_generator')->getPathFromRoute($route);
    return new RedirectResponse($path);
  }

```
> 2 votes

# Answer
```
$form_state->setRedirectUrl(Url::fromUserInput($redirect_path));

```
> 2 votes

# Answer
After `$user->save();` add

```
  $url = Url::fromRoute('route.name');
  $response = new RedirectResponse($url->toString());
  // $response = '/some/path';
  $response = new \Symfony\Component\HttpFoundation\RedirectResponse($response);
  $response->send();

```
> 1 votes

# Answer
In `user_update_redirect()`, which gets a `FormState` object, you can call one of the following methods.

`FormState::setRedirect()` is preferable when the redirecting URL is associated with a route, such as in the case of nodes, user accounts, or other entities. In the other cases, such as redirecting to external URLs, `FormState::setRedirectUrl()` is the method to use.

Returning a `RedirectResponse` object in a form submission handler doesn't have any effect. The method calling (`FormSubmitter::executeSubmitHandlers`) the form submission handlers discard the value returned from them.

```
  $handlers = $form_state->getSubmitHandlers();

  // Otherwise, check for a form-level handler.
  if (!$handlers && !empty($form['#submit'])) {
    $handlers = $form['#submit'];
  }
  foreach ($handlers as $callback) {

    // Check if a previous _submit handler has set a batch, but make sure we
    // do not react to a batch that is already being processed (for instance
    // if a batch operation performs a
    //  \Drupal\Core\Form\FormBuilderInterface::submitForm()).
    if (($batch =& $this->batchGet()) && !isset($batch['id'])) {

      // Some previous submit handler has set a batch. To ensure correct
      // execution order, store the call in a special 'control' batch set.
      // See _batch_next_set().
      $batch['sets'][] = [
        'form_submit' => $callback,
      ];
      $batch['has_form_submits'] = TRUE;
    }
    else {
      call_user_func_array($form_state->prepareCallback($callback), [
        &$form,
        &$form_state,
      ]);
    }
  }

```

Calling `RedirectResponse::send()` from a from submission handler would just interrupt what Drupal is doing when processing a form, including calling other form submission handlers and other hooks.

In the case there is the need to use `FormState::setRedirectUrl()`, the `Url` object should be built from `Url::fromUserInput()` only when the relative URI was given by user input (for example, when users fill a setting form for giving a redirect path). For an external URL well known from the module implementing the form submission handler, `Url::fromUri()` should be used.
> 0 votes

---
Tags: 8, users, redirection
---


# Question
Title: Getting a formatted address component in another field's template
I need to pull the administrative area component from an Address field and place the full text of it it in the template of another field on the content type. I've managed to accomplish this with the following code.

In preprocess:

```
function MYTHEME_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
  $variables['content_type'] = $node->bundle();
  if ($node->bundle() == 'location') {
    $variables['address_state'] = $node->get('field_address')->getValue()[0]['administrative_area'];
  }
}

```

And in the twig template:

```
{% if content_type == 'location' %}
  <h1{{ title_attributes }}>{% spaceless %}{{ title }}{% endspaceless %}{% spaceless %},{% endspaceless %} {{ address_state }}</h1>
{% endif %}

```

This will produce, for example "Boston, MA". But what I want is "Boston, Massachusetts", using the full name of the administrative area rather than the code. According to Drupal Commerce Address docs, you can get the full name in a twig template using `{{ administrative_area.name }}`. But I couldn't get that to work. How can I render the full administrative area name in the template?

# Answer
> 0 votes
How I understand the linked doc you need to configure the plain address formatter in a view mode to use `address-plain.html.twig`. Then you can output the node field as formatted in this twig:

```
   if ($node->bundle() == 'location') {
     $variables['address_state'] = $node->get('field_address')->view('custom_view_mode');
   }

```

---
Tags: 8, theming
---


# Question
Title: admin/commerce/orders/{orderId}/payments/add "You are not authorized to access this page."
When I try to add a new payment to an order (either created by a customer or via the backend) I always encounter the "You are not authorized to access this page." error.

My user has the administrator role.

I'm running core 8.6.7 and commerce 2.11.0

# Answer
To solve this issue, I needed to add one payment method that is not "Offsite"

the error message is just very misleading.
> 1 votes

---
Tags: 8, commerce
---


title: PHP namespace error

text:
# Question
Title: PHP namespace error
I'm using libraries, not using composer, and it's on Drupal 7. I installed and enabled xautoload so that I can use classes from a library that has namespacing. I think I got the xautoload function of this working correctly, because it is not throwing errors anymore when I have a `use SSRS\SSRSReport;` statement at the top of my module file referencing the library's classes.

The problem is that I still seem to have some namespacing fatal error in a libary's class file. This is my `hook_libraries_info()`:

```
/**
 * Implements hook_libraries_info().
 *
 * For defining external libraries.
 */
function ssrs_libraries_info() {
  $libraries['ssrs-sdk'] = array(
    'name' => 'SSRS SDK for PHP',
    'vendor url' => 'https://github.com/EmergencyReporting/ssrsreport',
    'download url' => 'https://github.com/EmergencyReporting/ssrsreport',
    'version callback' => 'ssrs_get_version',
    'files' => array(
      'php' => array('library/SSRS/SSRSReport.php'),
    ),
    'xautoload' => function($adapter) {
      // Register a namespace with PSR-0 root in <library dir>/library/
      // Note: $adapter already knows the <library dir>.
      $adapter->add('SSRS', 'library');
    },
  );
  return $libraries;
}

```

Anyways, the error I get is this:

```
Fatal error: Interface 'SSRS\Interfaces\ISSRSBaseType' not found in /sites/all/libraries/ssrs-sdk/library/SSRS/SSRSType/ExecutionInfo2.php on line 34

```

And the line the error in ExecutionInfo2.php is on the line starting `class ExecutionInfo2 ...`:

```
namespace SSRS\SSRSType;
use SSRS\Interfaces\ISSRSBaseType;

/**
 *
 * class ExecutionInfo2
 */
class ExecutionInfo2 extends SSRSBaseType implements ISSRSBaseType {

```

So I don't get errors from the namespaces' `use` statements, but the interface class doesn't appear to actually be loaded yet.

# Answer
I found out that despite not using composer, I can give the library's provided `composer.json` file to xautoload, and it will get the information it needs.

```
$adapter->composerJson('composer.json');

```

I also found in the composer.json file the information I would have needed to use `$adapter->addPsr4`, with each individual namespace needing to be added separately:

```
"autoload": {
    "psr-4": {
        "SSRS\\": "library/SSRS/",
        "SSRS\\Common\\": "library/SSRS/Common/",
        "SSRS\\Factory\\": "library/SSRS/Factory/",
        "SSRS\\Interfaces\\": "library/SSRS/Interface/",
        "SSRS\\RenderType\\": "library/SSRS/RenderType/",
        "SSRS\\SSRSType\\": "library/SSRS/SSRSType/",
        "SSRS\\TestConnection\\": "library/SSRS/TestConnection/"
    }
}

```
> 1 votes

---
Tags: 7
---


title: Add class to any element with CKEditor

text:
# Question
Title: Add class to any element with CKEditor
Is there a way to add class to any element through CKEditor?

Here is an example: I create a list with CKEditor and I want to add a class to the `ul` tag. Or maybe on one of the `li`.

Everything without opening the source of course.

Is there any way to achieve that? (with CKEditor or with another WYSIWYG)

# Answer
> 5 votes
You can configure custom styles in 'Text formats and editors':

1. Visit /admin/config/content/formats, and click Configure for any format using CKEditor
2. Ensure the 'Styles' button is in your active toolbar
3. Click 'Styles dropdown' under CKEditor plugin settings
4. Add class|style values per the instructions

Using your example, you could add entries like:

```
ul.myListClass|Special List
li.myItemClass|Special List Item

```

This would make the styles 'Special List' and 'Special List Item' appear in the styles dropdown anytime the user's cursor is anywhere in an `ul` or `li`. If they choose 'Special List', the class 'myListClass' would be added to the nearest `ul`. If they choose 'Special List Item', 'myItemClass' gets added to the current `li`.

This assumes current versions of Drupal 8. I'm not sure about Drupal 7, but I assume up-to-date versions would have similar functionality.

---
Tags: wysiwyg
---


# Question
Title: Exporting a custom module from one instance to another
I am new to Drupal. Currently I am using Drupal 7.4.

Hhow to export a custom module from one instance to another instance?

Note: copy the module to the new site didn't work.

# Answer
> 1 votes
Here are the steps you need to do:

* Before you try anything, make sure you have a backup of everything
* Copy the module directory into the correct directory in the other Drupal site
* Enable the custom module
    + from the `/admin/modules` page
    + from the command-line using the `drush en MODULE` command
* If the module requires any configuration, then you will have to do the configuration on the second website as well
    + If you have used the `features` module, it can be helpful in transferring module configuration

---
Tags: 7, views
---


title: How can I wrap HTML list in some div?

text:
# Question
Title: How can I wrap HTML list in some div?
On my drupal 8 website I have created a view, with list of content. As an output format I have chosen HTML list. So currently it looks like following:

```
 <form id="views-form">
   <div></div>
   <div class="item-list"></div>
   <div class="item-list"></div>
   <div class="item-list"></div>
   <div class="item-list"></div>
   <div class="item-list"></div>
    ....
   <div></div>
</form>

```

For formatting I would need to wrap the html list in some other div, is there a way to do it ? Can not find anything in the interface.

Expected:

```
<form id="views-form">
   <div></div>
   <div class="html_list">
     <div class="item-list"></div>
     <div class="item-list"></div>
     <div class="item-list"></div>
     <div class="item-list"></div>
     <div class="item-list"></div>
   </div>
   ....
   <div></div>
</form>

```

# Answer
Another approach would be template files.

The template name depends on the entity you are theming.

For example, with views-view-list.html.twig:

change

```
<{{ list.type }}{{ list.attributes }}>

  {% for row in rows %}
    <li{{ row.attributes }}>
      {{- row.content -}}
    </li>
  {% endfor %}

</{{ list.type }}>

```

to

```
<div class="html_list">
  <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}
      <li{{ row.attributes }}>
        {{- row.content -}}
      </li>
    {% endfor %}

  </{{ list.type }}>
 </div>

```

If you go the template route, it can be general so that any view of that type will inherit your custom markup. Or, it can be specific to that view name or ID.

---

If you want to utilize jQuery, I would recommend being more specific with your class selectors and allow for multiple view instances. For example:

```
$('.views-class ul').each(function() {
  if ($(this).hasClass('item-list')) {
    $(this).wrap("<div class='html_list'></div>");
  }
});

```

---

Here is an example views-view.html.twig, which is one level up really from the above template... which prints the views name as a class... which allows view by view customization to structure and layout by CSS alone:

**views-view.html.twig**

```
{%
  set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id,
    'views-wrapper',
    'view-' ~ css_name,
  ]
%}

<div {{ attributes.addClass(classes) }}>

  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  {{ exposed }}

  {% if attachment_before %}
    <div class="views-attachment views-attachment-before">
      {{ attachment_before }}
    </div>
  {% endif %}

  {% if rows.header %}
    <div class="views-header-wrapper">
      {{ rows.header }}
    </div>
  {% endif %}

  {# add custom wrapper here around rows, or in deeper template files. #}
  {{ rows | without('header') }}

  {{ empty }}

  {% if pager %}
    <div class="views-pager">
      {{ pager }}
    </div>
  {% endif %}

  {% if attachment_after %}
    <div class="views-attachment views-attachment-after">
      {{ attachment_after }}
    </div>
  {% endif %}

  {% if more %}
    <div class="views-more">
      {{ more }}
    </div>
  {% endif %}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}

</div>

```

Plus, this template separates the header and exposed filters making custom templating and individual CSS easier to implement and maintain.

I add this answer because I believe Drupal theming layer should be utilized when possible before jQuery and other front-end technologies.
> 1 votes

---
Tags: views, 8
---


# Question
Title: entityQuery condition for users without a role
In Drupal 8 - Is there a way to do a 'NOT IN' in a user based entityQuery?

```
$uids = \Drupal::entityQuery('user')
      ->condition('uid', 72)
      ->condition('status', 1)
      ->sort('created', 'ASC')
      ->execute();

```

This query ^ yeilds results

```
$uids = \Drupal::entityQuery('user')
  ->condition('uid', 72)
  ->condition('roles', ['testing_user'], 'NOT IN')
  ->condition('status', 1)
  ->sort('created', 'ASC')
  ->execute();

```

This query ^ does not. User 72 doesn't have the role 'testing\_user'

# Answer
> 2 votes
> Is there a way to do a 'NOT IN' in a user based entityQuery?

**Yes, QueryInterface::condition $operator parameter documentation explicitly mentions NOT IN** among other operators.

Operators are supported in several different ways based on the storage for an entity. For instance, "NOT IN" is supported via array\_search in configuration entities and via the same manner as SelectInterface::condition for SQL-based entities.

Regardless of the manner the key is knowing the "field" to search on. You're working with an entity\_reference field, which is more complex than a condition on a single column.

Perform a query with an entity field condition with multiple values shows this a little, but I hesitated to mark this one as a duplicate because it's not in the accepted answer.

Anyway the documentation for Entity QueryInterface mentions that the $field parameter

> Name of the field being queried. It must contain a field name, optionally followed by a column name. The column can be the reference property, usually "entity", for reference fields and that can be followed similarly by a field name and so on. Additionally, the target entity type can be specified by appending the ":target\_entity\_type\_id" to "entity".

So I think `roles.target_id` should work. If user\_role entity was a content entity then the second part of the above statement would apply. Otherwise an exception will be thrown.

However @0-nur is correct: the roles field data stores information users who **have** roles so any query for a user that has the default roles will not be included in the query. You would need to add an additional condition. This is similar behavior to Drupal 7. In this case, since we're testing nullable we can use "roles" as the field.

```
$query = \Drupal::entityQuery('user');
$or = $query->orConditionGroup();
$or
  ->condition('roles.target_id', ['testing_user'], 'NOT IN')
  ->condition('roles', NULL, 'IS NULL');
$query->condition($or);

```

# Answer
> 2 votes
Your original code is correct. The problem is condition of 'not in'. It doesn't give result of users who has no roles. If you give roles to each user you are good to go.

More reading

You can get deeper understanding from class file https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Condition.php/class/Condition/8.2.x

Also there is a Drupal 7 API documentation about conditional-clauses https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses

---
Tags: 8, users
---


# Question
Title: Bulk update pages that use old URL alias by content type
We have a content type, `Basic Page` that recently had the URL pattern changed from `www.example.com/page/page-title` to `www.example.com/page-title`. Under the Pathauto settings found at `/admin/config/search/path/update_bulk` there are options to `Select the types of paths for which to generate URL aliases` which allows for selecting different entities such as `Content`. Additionally there is `Select which URL aliases to generate` where we want `Update the URL alias for paths having an old URL alias` as the choice.

We don't want to update all `Content` entities, but rather we want to update by `content type`.

**How would we update `URL alias` after changing the `path pattern` by `content type` either programmatically or through an existing module?**

The goal is to be able to do update all `Basic Pages` URL alias, but not others.

# Answer
you can disable patterns that you dont want to update. In this way update will only update the patterns belong to content types
> 4 votes

---
Tags: 8, hooks, path-aliases
---


# Question
Title: embed photo album hosted on flickr.com using flickr module not showing photo album
I am attempting to use the Flickr module flickr-8.x-1.0-alpha2 along with Flickr API and Colorbox module to display a album of recent photos from Flickr.com.

I have setup the API keys. and added flickr setings in Text formats and editors, but the it doesnt producing any output for the photoset.

However its working for single `[flickr-photo:id=3711935987].` and when i tried with `[flickr-photoset:id=72157626766436507]` for photo album its not working . giving error in the Flickr module Notice: Undefined index: in Drupal\flickr\Service\Photos-\>photoGetSize();

does i miss any settings ?

# Answer
It's likely you have photos in that set that aren't available in the size you've set the photos to display in.

Flickr module documentation \> Sizes

> TAKE CARE, the c (800px) size is missing on Flickr images uploaded before March 1, 2012. Check if it exists on the Flickr photo page \> Actions \> View all sizes.

More info and debug inspiration in the 7.x documentation: Flickr Editor Guide 7.x-1.7
> 0 votes

# Answer
The documentation is quite confusing in that point, but I think single images have a default size, photosets don't. You have to define it.

```
[flickr-photoset:id=72157626766436507, size=-]

```

or

```
[flickr-photoset:id=72157626766436507, size=z]

```

for example.

I managed to get it working that way. More about sizes in Flickr here: https://www.drupal.org/node/2477263

The default image size can be selected when configuring the Text Editor Format.

Also, try to create a new user and assign content editing privileges to him/her with the "Flickr" editor text format, and add the photos with that user account.
> 0 votes

---
Tags: 8, media, files
---


title: How to refresh a view automatically?

text:
# Question
Title: How to refresh a view automatically?
I have a Drupal 8 site with NodeJS.

I use the following module:

https://www.drupal.org/project/private\_message\_nodejs

For the installation, I followed the instructions in the documentation of the module page :

https://www.drupal.org/docs/8/modules/private-message

I created a page view and want it updated automatically.

I created a JS file in my sub theme :

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

  $('.view-inbox').trigger('RefreshView');

}(jQuery));

```

But it does not work.

How to refresh a view automatically ?

# Answer
> 1 votes
It's all in the `README.md`.

> ```
> ## Installation
>
> ### 1. Install Node.js
>
> Instructions on Node.js installation are not provided here, as they differ per
> system, and instructions are outside the scope of this document. Please see
> the [Node.js homepage](https://nodejs.org/en/) for more information.
>
> ### 2. Install the module
>
> Install the private_message_nodejs module as you would any Drupal module.
>
> ### 3. Install the nodeJS dependendencies
>
> On the command line, navigate to [VENDOR FOLDER]/jaypan/private-message-nodejs
> and run the following command:
>
> `npm install`
>
> ### 4. Create the Nodejs configuration
>
> Navigate to [VENDOR FOLDER]/jaypan/private-message-nodejs/config
>
> Create default.json by copying either http-example.default.json (for HTTP
> connections) or https-example.default.json (for HTTPS connections). Fill in all
> the values in the JSON file. Note that you will need to navigate to the Private
> Message settings form, and copy the Nodejs secret value, to paste into
> default.json. Note that if you are using https, you should start with port 8443,
> and if you are able to get that working, you can try other ports.
>
> ### 5. Start the app
>
> On the command line, navigate to [VENDOR FOLDER]/jaypan/private-message-nodejs
> and run the following command:
>
> `node app.js`
>
> Note: Leave this open and running, as closing the server will stop it from
> working.
>
> ### 6. Enter the URL to the node.js server in the private message configuration
>
> In the web browser, navigate to /admin/config/private_message/config. Expand the
> Private Message Nodejs settings section, and enter the URL to the node JS app.
> It should be found at [your domain]:[port you entered into configuration]. Save.
>
> ### 7. Test
>
> Open up the private message page and check that there has been some output in
> the command line, indicating that connections have been made to the Nodejs
> server.
>
> ```

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


# Question
Title: Rule to check specific field of content every week
I have a content type called change\_note, and within that I have a field called action, action\_owner, a field called action\_date, and one called action status. What I am trying to do, is get the site to check if the action status = pending, and if true send an email to the person listed in action owner.

I can work out how to do this if it is based on someone saving the content (using the rules module in drupal 7) but I can't see how you do it based on just a specific schedule. I've looked at the schedule module also, but am struggling to see how to do it in that.

# Answer
> 1 votes
A possible solution is to transform the rule you already have, into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving the content") ... That Rules Component will then be executed next time cron runs.

If you then also add an extra Rules Action in that Rules Component (as last Rules Action) to reschedule the same Rules Component after 1 week, you should have achieved what your question is about.

Obviously, as soon as at least 1 of the Rules Conditions in your Rules Component are no longer satisfied, its Rules Actions will not be performed anymore, so that is when the weekly rescheduling also stops.

***Easy, no?***

---
Tags: 7, rules
---


title: create custom rule condition

text:
# Question
Title: create custom rule condition
I want to create a custom rule condition and a custom rule action. For this reason I created a custom module. Despite I found some info on creating the custom rule action, I cant find anything about the custom rule condition.

How should I created and what files do I need to create inside the custom module?

# Answer
> 0 votes
I think I found it, instead of creating a new module, I just created a new condition file inside rules/src/Plugin/Condition.

---
Tags: rules
---


# Question
Title: How to build multivalue form elements using Form API
With the 'field collections' module at the form level, you can create a fieldset (or 'field group') that will accept multiple sets of values.

Is there a way to do this with the Form API directly (or with the help 'field collections' or 'field group' module) programmatically. I can make the form fieldset easy enough, but I'm not sure how to set multiple values for this set. In fact, I'm not really sure how you define multiple values for any field with the Form API.

UPDATE: Just to be clear I want to create the form, not the entity itself (at least not yet). I want to use the Form API to accomplish this to make my own `$form` – just the form.

# Answer
Suppose 'field\_page\_collection1' is the field collection for the 'page' content type having two text fields 'field\_page\_collection1\_text1', 'field\_page\_collection1\_text2'.

To attach or create field-collection item for node having node id 1.

```
<?php
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_page_collection1')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // Attach it to the node.
$field_collection_item->field_page_collection1_text1[LANGUAGE_NONE][0]['value'] = 'some value for text field 1'; // Fill value for field_page_collection1_text1.
$field_collection_item->field_page_collection1_text2[LANGUAGE_NONE][0]['value'] = 'some value for text field 2'; // Fill value for field_page_collection1_text2.
$field_collection_item->save(); // Save field-collection item.
?>

```
> 0 votes

# Answer
Unfortunately, there's no straightforward approach in Drupal for doing this. You'll have to get a little creative with validation callbacks in the form API and using AJAX (optionally).

I've just created an example of how to do this on my GitHub (found here).

Drupal has an example already of how to alter forms by adding and removing fieldsets, but I thought it wasn't featured enough. I needed the ability to remove *specific* items, which wasn't included in the example.

**Edit:** Unfortunately, I didn't have the time to divulge into creating an example with drag/drop re-ordering, but there are a couple examples of how to do drag/drop tables in a couple of the Drupal core modules (Text Formats, for example). I imagine it can't be too difficult to get these two concepts working with each other.
> 0 votes

# Answer
I would suggest you to use field API to create your field item with multiple fields. Then you can add this item to your module by using form API. To see example just check core field items from

```
\drupal\core\lib\Drupal\Core\Field\Plugin\Field

```

They are very similar to Form API.

You can also create field item from console:

`drupal generate:plugin:field`
> 0 votes

---
Tags: forms
---


# Question
Title: How can I use postsave method extending WebformHandlerBase for submitting to account fields
I created a webform handler class extending from WebFormHandlerBase: The method, postsave has the following code:

```
public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $account = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($account->id());
    $user->addRole('example');
    $user->save();
  }

```

A boolean and photo value are submitted by the webform submission. I need to submit the boolean and photo to account fields. How do I do it?

# Answer
> 0 votes
$account = \Drupal::currentUser(); $user = \Drupal\user\Entity\User::load($account-\>id()); $data = $webform\_submission-\>getData(); $photo = $data\['picture'\]; $user-\>set('field\_photo', $photo); $user-\>save(); } **The above code, for example, will take a webform element, key is 'picture' and set it to an account field, 'field\_photo'.**

---
Tags: forms, hooks, webforms
---


title: Scaling image using Imagick Module

text:
# Question
Title: Scaling image using Imagick Module
i'm currently using the Imagick module for Drupal 8 and the imagick php extension on the server. Whenever I try to resize images with this tool, using the settings below, I get a really down sampled version of the image, as if the all the meta data is still stripped although I specify to keep them.

As seen below the image gets really pixelated and sort of "over saturated". However I got this to work on a local server using the same settings. I just can't get it to work properly on the remote.

Setting:

Desired result:

The result I get:

So far i have tried already to switch off the meta tags, but this seems what was originally the problem on my localhost. I have also tried some of the other filters and changed the quality, but it all doesn't seem to matter. So what am I doing wrong, or what could I try to get the desired result?

# Answer
> 1 votes
Yes, this module has a critical error for your problem. A week ago an issue was opened and need to be revived. But you can add your own patch to the module by yourself. Here is the issue and solution for **Drupal v7**: https://www.drupal.org/project/imagick/issues/3026933

and you can apply to **Drupal v8** under file imagick\src\Plugin\ImageToolkit\Operation\imagick

```
protected function process(Imagick $resource, array $arguments) {
    $color = $arguments['HEX'];
    $color = empty($color) ? 'none' : $color;
    //return $resource->colorizeImage(new ImagickPixel($color), 1);
    return $resource->colorizeImage(new ImagickPixel($color), 1, true);
  }

```

---
Tags: 8, media
---


# Question
Title: Does an ajax callback work within a Views style plugin?
My module has a custom Views style plugin. In the style settings form, I want to implement an ajax callback, such as described here: https://www.drupal.org/docs/8/api/javascript-api/ajax-forms

However, I haven't had any luck. I can get a spinning effect, but nothing happens afterward. Here's an example of what I've tried:

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

  public function TestCallback(array $form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $text = 'Text to see if this is working';
    $ajax_response->addCommand(new HtmlCommand('#foo', $text));

    return $ajax_response;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['test'] = [
      '#title' => t('TEST!'),
      '#type' => 'select',
      '#options' => [
        '' => t('None'),
        'foo' => t('Bar'),
      ],
      '#ajax' => [
        'event' => 'change',
        'callback' => '::TestCallback',
    // having the line below uncommented seems to help
    //'url' => views_ui_build_form_url($form_state),
      ],
      '#prefix' => '<div id="foo"></div>',
      '#default_value' => '',
    ];
  }

```

If I uncomment the commented 'url', I get this error:

```
Uncaught TypeError: Cannot read property 'settings' of undefined
at resetSize (<anonymous>:34:32)
at later (debounce.js?v=8.6.3:20)

```

If I keep it commented, I get:

```
Failed to load resource: the server responded with a status of 500 ()
/admin/structure/views/ajax/display/view_name/page_1/style_options?
_wrapper_format=drupal_ajax&ajax_form=1&_wrapper_format=drupal_ajax:1
Uncaught Drupal.AjaxError
ajax.js?v=8.6.3:500

```

What's missing and/or incorrect?

# Answer
From what I understand seeing the AJAX docs, I think you're not supposed to return an `AjaxResponse` object. You're supposed to return a renderable array from the Ajax callback.

## Sample Code

```
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
  parent::buildOptionsForm($form, $form_state);
  $form['test'] = [
    '#title' => t('TEST!'),
    '#type' => 'select',
    '#options' => [
      '' => t('None'),
      'foo' => t('Bar'),
    ],
    '#ajax' => [
      'event' => 'change',
      'wrapper' => 'ajax-output-container',
      // Since views style options forms are complex, they're built by
      // Drupal in a different way. To bypass this problem we need to
      // provide the full path to the Ajax callback.
      'callback' => __CLASS__ . '::testCallback',
    ],
    '#prefix' => '<div id="ajax-output-container"></div>',
    '#default_value' => '',
  ];
}

/**
 * This is the AJAX callback.
 *
 * It generates the output for the AJAX request. The output REPLACES
 * the "wrapper" you define in #ajax.
 */
public function testCallback(array $form, FormStateInterface $form_state) {
  // This element will replace the DIV#foo you have in your #prefix.
  $elem = [
    '#type' => 'markup',
    '#markup' => '<div id="ajax-output-container">Is it not working!></div>',
  ];
  return $elem;
}

```

## Debugging

* Make sure that on page load, you're getting a div with the correct ID in your field prefix. You can put some default text in the prefix so that you can see it on page load?
* If HTML tags are being stripped from your `#prefix` markup for some reason, then try injecting a separate item in the form with `#markup`.
> 3 votes

# Answer
$route\_name = "views\_ui.form\_{$form\_key}"; might be the problem.

Try to print somewhere this result under buildOptionsForm function and see if it is the problem: views\_ui\_build\_form\_url($form\_state)-\>toString();

If You keep it commented, error happens because their is no url nor '#wrapper' which is needed for ajax.

Here you can investigate this error deeper: https://api.drupal.org/api/drupal/core%21modules%21views\_ui%21admin.inc/function/views\_ui\_build\_form\_url/8.2.x
> 0 votes

# Answer
I think you maybe experiencing an issue related to this Drupal core issue. See this issue comment and this one about implementing a work-around.
> 0 votes

---
Tags: views, 8, ajax
---


# Question
Title: How do I add secondary tabs to the user (profile) edit tab?
In earlier versions of Drupal, there were categories of users which showed up as tabs on the user (profile) edit page, located at /user/{user}/edit. How can we define new tabs on this page in Drupal 8?

# Answer
> 8 votes
Tabs can be added to the user edit page as follows:

1) Define the route(s) for your tab(s) in \[MODULE\].routing.yml as normal:

```
[MODULE].something.user_defaults:
  path: '/user/{user}/edit/something'
  defaults:
    _controller: '\Drupal\[MODULE]\Controller\SomeController::someSettingsTab'
    _title: 'Some Settings'
  requirements:
    _permission: 'some permission'
    user: \d+
  options:
    parameters:
      user:
        type: entity:user

```

2) In \[MODULE\].links.task.yml, add your tab(s) as you would primary tabs, except rather than using `base_route`, use `parent_id`, and set it to (somewhat unintuitively) the user edit form tab key, which is defined in `user.links.task.yml` as `entity.user.edit_form` (same as the route name):

```
[MOUDLE].something.user_defaults:
  route_name: [MODULE].something.user_defaults
  parent_id: entity.user.edit_form
  title: Some Title
  weight: 10

```

3) You also need to define a tab for the user to switch back to, as tabs are only rendered if there are more than two tabs. In this case, we want to add a tab for the user edit form, using the user edit form route, again using the user edit form tab key:

```
[MODULE].entity.user.edit_form:
  route_name: entity.user.edit_form
  parent_id: entity.user.edit_form
  title: Profile

```

---
Tags: 8, users
---


# Question
Title: How to render a @FormElement in Views area plugin
I am doing a custom plugin area for displaying some data in a views footer (Drupal 8).

I do something about just like this : Create a custom area plugin

The only point is, instead of `#markup` in the return array of `render()` method, I would like to return some more complex stuff. If I try to return a textfield if works:

```
return  [
  '#type' => 'textfield',
];

```

If I try another form API element (defined via a `@FormElement`): it does not render.

```
return  [
  '#type' => 'datetime',
];

```

Two questions:

* Should it render ?
* If not, I can render a block there using this (ViewsBlockArea) how to do the equivalent but with a `FormElement` instead ? (actually rendering a form API render array.)

EDIT: Here a the finality of what I want to render:

```
$element['form'] = [
  '#type' => 'commerce_coupon_redemption_form',
  '#order_id' => $order->id(),
  '#cardinality' => 1,
  '#element_ajax' => [
    [get_class($this), 'ajaxRefreshSummary'],
  ],
];

```

But you may see that more trivial render array like the datetime one given above does not work either.

Also notice that any element defined by a `@FormElement` annotation from within the namespace `Drupal\Core\Render\Element` is okay. But `@FormElement` "from elsewhere" like `datetime` does not render.

# Answer
You can create block Form first. And from View UI, add a view object to your header or footer. And from View object configuration choose the form block you created.
> 0 votes

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


title: What to return from form AJAX Callback

text:
# Question
Title: What to return from form AJAX Callback
I used the examples found here as my AJAX guide.

I have a custom form field

```
$form['elements']['refunded']

```

which is entirely defined in a single line as an array. My `AJAX` `DIV`'s and callbacks work perfectly. In the attributes field, I call a custom function that sets a `CSS` property. No problems at all.

I need to duplicate this same functionality with another field on the same form. The field is '`status`' - but it is defined elsewhere and I don't know where or have access to the code where it is defined directly.

Thus in my code, I append to the array for the form field such as :

```
$form['elements']['status']['#prefix'] = '<div id="ajax_status">';
$form['elements']['status']['#suffix'] = '</div>';
$form['elements']['status']['#disabled'] = myfn_disable_attendance($form_state);

```

When I update the attendance select field, it should update the ability of a user to change the status (i.e. is marked as attended, the student can no longer withdraw from the class).

Disabled should display the status, but not allow the user to modify the field.

The last piece is the callback that runs when the attendance select is changed, that is a single-line return:

```
  return $form['elements']['status'];

```

Which is the same as I use in the working example, however for that it is `['elements']['refunded']` which if you see above, is defined on a single line.

When I modify the attendance field, the status field disappears and displays what appears to be the return code from my function that should be setting the display option to `true/false`.

It appears it is not re-building the entire form field. My call to return `$form['elements']['status']` and Im thinking it may be due to it being defined on multiple lines in multiple `php` files.

Can anyone provide any pointers as to how to accomplish what I'm trying to do or help me identify what the code is actually returning from my callback function so I can better get a grasp on what I need to do here?

# Answer
return $form\['elements'\]\['status'\] is correct.

you need to create your form elements in

public function buildForm(array $form, FormStateInterface $form\_state) {

```
$fields = $form_state->getValues();
if (!isset($fields['status']){
   $form['elements']['status']['#prefix'] = '<div id="ajax_status">';
   $form['elements']['status']['#suffix'] = '</div>';
   $form['elements']['status']['#disabled'] = myfn_disable_attendance($form_state);
}

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: How can I disable or hide warnings and errors shown in the backend?
Is there a way to disable or hide warnings and errors shown in the backend? For example when a user creates a node and some error occurs on the live page (image or helper class not found), then there is a big red box with around 25 lines of error message on each page in the backend.

For my editors who have to write 100 nodes a day it's very annoying.

Edit:

`logging & error -> error messages` is set to display NONE.

# Answer
> 4 votes
You actually should fix the error.

And since it's not a very good idea to globally disable all errors and warnings for all roles, please use Disable Messages to disable error messages based on configurable conditions.

> Gives a site owner options to disable specific messages shown to end users. The core Drupal message system as offered by `drupal_set_message` is an excellent way for modules to send out messages to the end users. However not all Drupal site owners are keen to show all the messages sent out by Drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
>
> ### Features
>
> * Filter out messages that match a full text string exactly
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

---
Tags: 8, debugging
---


# Question
Title: Exposed filters in views with Ajax turned on doesn't generate url
When using an exposed filter in a view while turning on Ajax doesn't generate a unique url.

**Page with Ajax off**

> nl/finder?product%5B284%5D=284&industry%5B269%5D=269&country%5B288%5D=288&country%5B290%5D=290

**Page with Ajax on**

> nl/finder#

Is this normal behavior of drupal or is there some setting i'm missing? I need to link to the page with some filters preset.

# Answer
> 2 votes
Use Views Ajax history to accomplish what you are asking. There are a couple of bugs when using supporting modules such as Views Infinite Scroll, but for the most part this allows you to keep browser history as you add filters and change pages, allowing your user to use the forward and back buttons in their browser.

# Answer
> 0 votes
That is how Ajax is supposed to work, it doesn't refresh the page so it can't change the URL.

But the Exposed filter links should work even with Ajax enabled. Ajax is there just to speed things up, it doesn't provide vital structure.

If you need to provide ready-made Exposed filter links you can add them manually, in Views header, on other pages, or create menus of them. You could even do some Views Contextual filter magic with Summaries to provide the link filter combinations.

---
Tags: 8, views
---


title: How to get the JWT token via webservice

text:
# Question
Title: How to get the JWT token via webservice
After enabling the JWT module. and following Using JSON Web Tokens (JWT) to Authenticate Requests to REST Resources in Drupal 8 on how to use it, it is working.

I know I can access the user JWT token by visiting /jwt/token. My problem is when I try to log in via web services. It returns me the following.

```
{
    "current_user": {
        "uid": "4",
        "name": "cravushedal"
    },
    "csrf_token": "OlTb7fak5ZS-r1BRiGtBh4IWLm_Z7F1xMpY3KYTGkrU",
    "logout_token": "5DiupHgr9iDxIDVmhHTI3PMX2-Shd6sjuN8hNHrHv7E"
}

```

**With postman** In postman, after login, I receive a cookie, and with that cookie, I can access the `jwt/token` route and receive the bearer token.

But, I am using angular 5, and what I want is to access to that rout without the **cookie**, just by csrf token. Is that possible? I mean, I am trying to include it in the header, but not result. Any idea?

Thanks

# Answer
> 2 votes
You may try to use Get JWT on Login module that I have created for the same purpose.

---
Tags: 8, csrf
---


# Question
Title: How do I remove the "Request New Password" link?
When I visit www.example.com/user, there is a page that shows the login/password and as well as a "Request New Password" tab.

How do I remove this "Request New Password" tab from the user page?

# Answer
The No Request New Password module is probably the easiest way to go, though you'll need to dig for the 6.x releases. This disables any request to `user/password`, so this path with neither be accessible directly nor display in menus/tabs/links.

Alternatively, you can put its main function into your own custom module:

```
 /**
  * Implementation of hook_menu_alter().
  */

 function MYMODULE_menu_alter(&$callback) {
     $callback['user/password'] = array('access arguments' => array(FALSE));
 }

```
> 1 votes

# Answer
You can change the permission so the page is not accessible:

```
function hook_menu_alter(&$menu)
{
  $menu['user/password']['access callback'] = FALSE;
}

```

This code will disable the page altogether, so it's not available to anyone.
> 1 votes

# Answer
If you are already using a custom module (called, for example, *custom\_module*) you can hide the user/password tab using the following code.

```
function custom_module_menu_alter(&$items) {
  $items['user/password']['type'] = MENU_CALLBACK;
}

```

This doesn't show the tab, but the path is still accessible to the users who know Drupal has that path.

To hide it and disable it, use the following code.

```
function custom_module_menu_alter(&$items) {
  $items['user/password']['access callback'] = FALSE;
}

```

Setting the access callback to `FALSE`, the tab will not be accessible nor visible to any user, including the user #1.

In the last hook implementation that I shown, using `$items['user/password'] = array('access arguments' => array(FALSE));` is wrong since:

* Setting the access arguments to an array containing the `FALSE` value is **not** the correct way to avoid Drupal checks the user has the permission to see the route/menu.
* Using that code, I am literally setting the route definition to an array containing just `'access arguments' => array(FALSE)` with all the consequences that could happen if there is another module that re-enables the user/password tab for the currently logged-in user, and that module has hooks invoked after the hooks of your module. (With the example code I shown, this simply happens when the other module is called *destiny\_change\_user\_password\_tab*.)
> 0 votes

---
Tags: users, 6
---


# Question
Title: Whats the difference between "Content Type" and "Content Types" on a block configuration form?
Whats the difference between these two tabs? There is no help text here. One has "negate" the condition but the other does not.

# Answer
> 5 votes
"Content type" comes from CTools and "Content types" comes from core.

Use "Content types".

### Simplified summary

"Content types" comes from core and is the preferred condition to use. The "negate" option is also present in core, but it is suppressed by the block module (source). In contrast to core CTools provides this condition not just for nodes but for any entity type (taxonomy terms, custom entities etc.). That's the reason why in case of nodes there is a duplicate set of entity bundle conditions.

### Issues on drupal.org

Now there's this core issue Duplicate node type setting in block visibility which was closed as "works as designed". The problem shall be fixed by CTools (as in remove the duplicate entry).

This leads us to this CTools issue Duplicate node type visibility condition in block settings which was put on hold until core itself replaces CTools functionality to provide block visibility settings for any entity type (not just for nodes) including the "negate" option.

Which finally brings us to this core issue Add entity bundles condition plugin for entities with bundles where the progress to move CTools functionality to core to replace the current node type core condition is being tracked.

---
Tags: 8, blocks
---


# Question
Title: Cannot get subscriptions to send out at correct intervals
I set up the "subscriptions" module and have set it so that all members of the page have access to a number of panels. One allows them to set the frequency of emails, one allows them to pick and choose which nodes to subscribe to. The node choice works well, and so does choosing a 'digest' choice for the emails.

The issue I am having is that the notification emails are sent out at what seems to be the first cron event after the new content has been added, which can be a long time if I don't visit the site, but at the same time too soon if someone has chosen a longer interval.

I am currently the only one 'testing' the site so have two users set up with subscriptions. One I have set for once every 3 hours and one 'once per day'.

As Cron was only running when either entering the site or running manually, I also chose to download the module "Ultimate Cron" which I thought would run Cron more often (i have it set to 30 minutes), but it does not seem to be doing this either, although messages are being sent to both users, even if the one asking for a message no more than once per day has already received one in that 24 hour period.

If I don't visit the site, both now get messages at least, but not at the correct intervals.

One of the main organisers of our organisation says she will not join the forum and member site unless there is a way to get notifications once a day, or once a week, and she is trying to push to use Yahoo forums, but I have everything set up the way I like it and so if I can fix this one issue I can then open it up to members of our small society.

Here are some screenshots of my SUBSCRIPTIONS settings. I have tried to show what I believe is relevant. I have disabled the other subscription modules which I had tried in the past. I DO have some messaging modules though (please see "messaging module" image)

UPDATE: Tested again and still receiving messages on each cron run rather than at the correct intervals. As mentioned below in a comment, it is likely an issue with the Subscriptions module.

If anyone knows how I may be able to fix settings, or even adjust line code to figure this out then I would be very grateful.

Had already tried notifications etc. but Subscriptions is perfect for what I need (if it worked).

Thank you all.

# Answer
> 1 votes
> Setting cron to run every 3 hours does not necessarily mean that cron will actually run every 3 hours. This is because it is not truly automatic. Something needs to trigger cron to run. This trigger happens when a user visits the site. As part of dealing with the page request, Drupal will check for the last time that cron has been run and will run cron as part of the request if it is time to do so. If cron is set to run every three hours and three hours has passed since the last time it has run, it will run as part of the page request for the user that happens to hit the page at that time.
>
> But what happens if you have an extremely low traffic Drupal site, application or intranet? If no one visits the site at all, cron will not run. Or if a user visits the site and cron is run, and another user visits the site 2 hours and 59 minutes later, cron will not run because three hours hasn’t passed yet. If a third visitor visits 3 hours later, then cron will run. But that is almost 6 hours since the previous cron run.
>
> Source: Why Drupal cron is not running as often as you think and how to fix it

The solution to this issue is to instead run/trigger cron from your server using crontab.

You can read about it here Why Drupal cron is not running as often as you think and how to fix it and goes over a solution using C-Panel.

If you don't have C-Panel you will have SSH into your server and manually add an entry to your servers crontab:

> The automated cron module has the disadvantage that it is triggered by a request, and the unlucky user who sends the request may experience a fairly long delay. For this reason, the automated cron is typically used by smaller sites that are unable to create a cron job manually, e.g. using the Linux crontab. If crontab is desired, Drupal console command may be used to simplify the configuration (rather than curling the long url show in /admin/config/system/cron. Here is an example crontab entry:
>
> ```
> 30 * * * * web_user /var/www/html/vendor/bin/drupal --
> root=/var/www/html/docroot cron:execute > /dev/null 2>&1
>
> ```
>
> This would execute Drupal cron once per hour at 30 minutes after the hour.
>
> Source: Automated Cron

# Answer
> 0 votes
I wanted to update this. Once I had corrected the Cron run, I then reset the subscriptions and then it worked fine. For others struggling, it may also be good to ensure that any changes to the intervals are made BEFORE the categories are chosen, as changes to the intervals will only work with subscription choices made AFTER the change. This may have been part of the issue for the account with the daily option too.

Thank you all for your help.

Now if they would just add a way that interval changes would act on all current subscriptions too. :)

---
Tags: 7, emails, cron, notifications
---


# Question
Title: How to redirect from URL with trailing slash to one without
We are using the Redirect module 8.x-1.2 with Drupal 8.5.6. When generating URLs, we are finding that a trailing slash is added to the end of the URL, and this is creating a 503 error code.

How would I redirect the anonymous users from the URL with the trailing slash to the one without trailing slash?

# Answer
Check your .htaccess file in root. There maybe a line that is overriding this rule. Check if this is in your .htaccess file, this forces a trailing slash.

```
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L]

```

To remove the trailing slash use

```
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R]

```

If the Drupal setting is not being enforced then you may have a rule in your .htaccess file that is adding a slash. @usernameabc Try adding the last 2 lines under RewriteEngine on
> 0 votes

# Answer
Select the *Enforce clean and canonical URLs* checkbox in admin/config/search/redirect/settings.

> Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, **removing trailing slashes**, ensure the language prefix is set and similar clean-up.
> 0 votes

# Answer
In my case, whenever I accessed a url, four slashes were automatically appended to the url (`IP////<node_name`).

Following steps resolved my issue:

1. Ensure that following entry is available in Apche configuration file - httpd.conf. `LoadModule rewrite_module modules/mod_rewrite.so`
2. Create a php file **test.php** with the following code. `<?php echo phpinfo(); ?>`
3. Open **test.php** in your browser. Check the **Loaded Modules** section to ensure that **mod\_rewrite** is available.
4. Also open the root Drupal PIP folder and ensure that .htaccess folder is there.
> -1 votes

---
Tags: 8, redirection
---