# Question
Title: Views aggregation of content values across two columns
I have a test content type that has a test name (A or B) and whether the Test is a pre-test or a post-test. Given the following data from that content type:

| Test | Type |
| --- | --- |
| A | Pre |
| A | Pre |
| A | Post |
| B | Pre |
| B | Post |
| B | Post |

I am able to use Views aggregation to get the total number of each Survey, or total by type across two rows:

| Survey | Type | Total |
| --- | --- | --- |
| A | Pre | 2 |
| A | Post | 1 |

But I am trying to use views to aggregate the data so that it shows the total number of pre-tests and post tests for each Survey to look something like:

| Survey | Pre | Post |
| --- | --- | --- |
| A | 2 | 1 |
| B | 1 | 2 |

Any ideas or direction on whether this is possible using Views Aggregate or another Views add-on module?

# Answer
> 1 votes
You can try to do this with the Views Aggregator Plus Module (https://www.drupal.org/project/views\_aggregator).

Try the following steps to achieve your goal:

1. Install the views\_aggregator module.
2. Create the basic table and add a second "Type" column. Name the first one "Pre" and the second one "Post". Don't use the default aggregation. The table should than look like this:

Test Pre Post A Pre Pre A Pre Pre A Post Post B Pre Pre B Post Post B Post Post 3. Select as format the "Table with aggregation options".
4. Use for the "Test" column the "Apply group function" with "Group and compress". For the "Pre" column the "Apply group function" with "Count (having regexp)" and as Parameter "Pre" and for the "Post" column the same with the parameter "Post".
5. After saving your table should look like expected.

---
Tags: views
---


# Question
Title: Converting Node Type to New ECK Content Type
I have a site with several different Node Types. With some of them having different types within them created with a Text(list) fields.

For Example:
**Node Content Type:** Chemicals
**Label:** Chemical Type **Machine Name:** field\_chemical\_type **Field type:** List (text)
**Allowed Values list:**
fertilizer|Fertilizer
fungicide|Fungicide
herbicide|Herbicide
insecticide|Insecticide
surfactant|Surfactant
indicator|Indicator
We would like to convert these to a new ECK Content type with separate bundles for each of the Allowed Values. Of which, we have already created them and the bundle types correspond to the "key" values within the Allowed values list.

Is there a way to migrate the entire content type and have the bundles change according to the value designated in the field\_chemical\_type list?

I have tried the following and it is not working for me:

```
    langcode: en
    status: true
    dependencies: {  }
    id: seward7_chemical_nodes
    class: Drupal\node\Plugin\migrate\D7NodeTranslation
    field_plugin_method: null
    cck_plugin_method: null
    migration_tags:
      - 'Drupal 7'
      - Content
    migration_group: sew7
    label: 'Chemical Nodes'
    source:
      plugin: d7_node
      node_type: chemicals
    process:
      id:
        -
          plugin: get
          source: nid
      type:
        -
          plugin: get
          source: field_chemical_type
      langcode:
        -
          plugin: default_value
          source: language
          default_value: und
      title:
        -
          plugin: get
          source: title
      created:
        -
          plugin: get
          source: created
      changed:
        -
          plugin: get
          source: timestamp
      field_name:
        -
          plugin: get
          source: field_chemical_name
    destination:
      plugin: 'entity:chemical'
    migration_dependencies:
      required:
        - seward7users
      optional: []

```

I have read contradicting info on "default\_bundle" in the destination. So I am confused. One post says you have to designate a default\_bundle another states you don't if you stipulate it in the "type" within the Process side of things.

If I can designate it in the Process, am I using the wrong plugin?

We have several other Node Content Types that we would like to convert into their own entities with separate bundles. So it would be extremely beneficial not to have to create separate yml files for every bundle within the individual entity types.

I am a site builder with a enough coding experience to get myself in trouble. But I want to learn. Any advice or guidance on where to go to learn would be greatly appreciated!

# Answer
> 0 votes
I had updated my development database with what I had thought, just the tables I needed. In doing so I missed the field\_config table in the database. So the field I was trying to reference was not getting seen. Thus causing me a couple days of frustration!

@MikeLutzUS also helped me out by noting that I needed to use `field_chemical_type/0/value` for the type source. The following worked for me:

```
    langcode: en
    status: true
    dependencies: {  }
    id: seward7_chemical_nodes
    class: Drupal\node\Plugin\migrate\D7NodeTranslation
    field_plugin_method: null
    cck_plugin_method: null
    migration_tags:
      - 'Drupal 7'
      - Content
    migration_group: sew7
    label: 'Chemical Nodes'
    source:
      plugin: d7_node
      node_type: chemicals
    process:
      id:
        -
          plugin: get
          source: nid
      type:
        -
          plugin: get
          source: field_chemical_type/0/value
      langcode:
        -
          plugin: default_value
          source: language
          default_value: und
      title:
        -
          plugin: get
          source: title
      created:
        -
          plugin: get
          source: created
      changed:
        -
          plugin: get
          source: timestamp
      field_name:
        -
          plugin: get
          source: field_chemical_name
    destination:
      plugin: 'entity:chemical'
    migration_dependencies:
      required:
        - seward7users
      optional: []

```

Big shout out of Thank You! to @MikeLutzUS You can see our conversation on Here

---
Tags: 9, migrations
---


# Question
Title: Views Exposed filter can't input username to filter. Only works with User ID
I created a custom View, where it shows all of a specific content type. In this content type I have a field that is a user reference called "Assigned to". In this view, I want it exposed so one can search by a username, but this exposed filter only takes in the User ID, but not the user name. What am I missing to make this work?

I added a relationship of User:Assigned\_To and that didn't seem to work or I'm not configuring it properly.

# Answer
> 2 votes
Looks like you're filtering by the actual entity reference field `field_assigned`, which will naturally just take the user ID because the field itself only knows only about the ID of the referenced entity (specifically, it stores the user ID in the `target_id`)

In order for you to filter against usernames, you:

1. Add a filter to the *username* field.
    * When choosing the field the filter, narrow the category down to User. That way you can find and select the username field.
2. When configuring the filter, set the relationship to the one that connects your content type to the user via the `field_assigned` field.
    * This is needed because you can have another entity reference field that also points to User (e.g. something like a "reviewed by"), and Views needs to know which field you meant to use.

---

Added bonus: Enable SQL debugging in Views settings. That way you can see the resulting SQL query done by Drupal. This will tell you if you're filtering against the right columns or missing some joins.

---
Tags: users, 9, views
---


# Question
Title: How can I programmatically add a field to a field group?
I have tried this code but it is not working.

```
$form['field_test'] = [
  '#title' => t('test'),
  '#type' => 'radios',
  '#options' => [t('A'), t('B'), t('C')],
 ];
$form['#group_children']['field_test'] = 'group_1';

```

I also tried with

```
$form['#fieldgroups']['group_1']->children[] = 'field_test';

```

But nothing is working. It works in Drupal 7. Is it changed in Drupal 8?

I have written this code in `hook_form_alter` and I'm altering a node form.

# Answer
> 3 votes
You’re missing `'#group' => $group_id`, add that and it should work.

Like this:

```
$group_id = 'group_1';
$field_name = 'field_test';

$form[$group_id][$field_name] = [
  '#title' => t('test'),
  '#type' => 'radios',
  '#options' => [t('A'), t('B'), t('C')],
  '#group' => $group_id,
];

```

# Answer
> 1 votes
To move an existing field (which isn't set up to show in the Manage Form Display UI) to a defined field group, all that is needed is adding #group property:

```
function ssc_custom_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $form['timezone']['#group'] = 'group_locale';
}

```

but don't forget the & on the $form in the function variables or the value isn't set.

# Answer
> 0 votes
You have to put both.

```
$form['#group_children']['field_test'] = 'group_1';
$form['#fieldgroups']['group_1']->children[] = 'field_test';

```

---
Tags: 8, forms
---


# Question
Title: How to use the flag counter in a twig template of a node?
The version dev of the module "Flag" for "Drupal 8" has added a new sub module "Flag Count":

https://www.drupal.org/project/flag/issues/2708291

I copied the code

```
{% set count = '[' ~ flagcount(flag, flaggable) ~ ']' %}

```

in flag.html.twig and I copy this file into the templates folder of my theme (I did not cache it).

But after I do not know how to do it. Currently to display the flag link in `node.html.twig` I put the following code :

```
{{ content.flag_like_node }}

```

How to add the number of flag ?

I tested the following code and none works

```
{{ content.flag_like_node_count }}
{{ content.flag_like_node.count }}
{{ count }}

```

# Answer
> 2 votes
This will return an array of all the flag counts on a node:

```
\Drupal::service('flag.count')->getEntityFlagCounts($node)

```

(For all flags set for that node) Via: https://www.drupal.org/node/2476349

You can use that in a preprocess function to get your flag counts and send it as a new variable to your template file. Like so:

```
function yourtheme_preprocess_node(&$variables) {

  $flag_counts = \Drupal::service('flag.count')->getEntityFlagCounts($node);
  $variables['like_count'] = $flag_counts['like'];

}

```

Then in your theme file you can output:

```
{{ like_count }}

```

The problem with this is that it doesn't ajax update when someone clicks the flag link. For that to work you have to put the count in the flag template.

# Answer
> 2 votes
For flag count to make it work in AJAX workflow:

1. Use Dev version of Flag which has the flagcount function exposed to twig template.
2. In flag.html.twig Add: {% set count = flagcount(flag, flaggable) %}
3. use {{ count }} to display the counter.

# Answer
> 0 votes
I'm not sure when this moved out of dev, but in 8.x-4.0-beta4 here's how you do it:

1. Copy flag.html.twig into wherever your theme's templates live
2. Add `{% set count = flagcount(flag, flaggable) %}` to it somewhere. Best place is probably right before the line that starts with `<div class="{{classes|join(' ')}}">`
3. Add `{{ count }}` after `{{ title }}` and span tag it, like this...

```
<div class="{{classes|join(' ')}}"><a{{ attributes }}>{{ title }}<span>{{ count }}</span></a></div>

```
4. Flush caches

---
Tags: 8, theming, flags
---


title: Aegir - Debian PGP key has expired

text:
# Question
Title: Aegir - Debian PGP key has expired
I am trying to Install aegir on Ubuntu 18.04 and 20.04 lts to manage drupal sites. Every time I try to update the server and install aegir it displays the following error
me@userpc:# apt-get update

Hit:1 http://et.archive.ubuntu.com/ubuntu bionic InRelease

Get:2 http://et.archive.ubuntu.com/ubuntu bionic-updates InRelease \[88.7 kB\]

Get:3 http://et.archive.ubuntu.com/ubuntu bionic-backports InRelease \[83.3 kB\]

Get:5 http://et.archive.ubuntu.com/ubuntu bionic-security InRelease \[88.7 kB\]

Get:4 http://debian.aegirproject.org stable InRelease \[3,144 B\]

Err:4 http://debian.aegirproject.org stable InRelease

The following signatures were invalid: EXPKEYSIG 5ADF93A03376CCF9 Aegir Debian archive autosigning debian@debian.aegirproject.org Reading package lists... Done

W: GPG error: http://debian.aegirproject.org stable InRelease: The following signatures were invalid: EXPKEYSIG 5ADF93A03376CCF9 Aegir Debian archive autosigning debian@debian.aegirproject.org E: The repository 'http://debian.aegirproject.org stable InRelease' is not signed.

N: Updating from such a repository can't be done securely, and is therefore disabled by default.

N: See apt-secure(8) manpage for repository creation and user configuration details.

I tried to Get the renewed key using the following command but it doesn't seem to work ...

curl http://debian.aegirproject.org/key.asc | sudo apt-key add

sudo apt-get update

Any help will be appreciated.

# Answer
> 0 votes
At the moment, Aegir 3 is minimally-maintained. Vendors offering support are Omega8, Consensus, ThinkDrop, and Symbiotic (who maintains some components at https://github.com/coopsymbiotic). Find them all at https://docs.aegirproject.org/community/services/.

For on-going support (as Debian packages are no longer maintained):

Aegir 5 is a complete rewrite in development (https://gitlab.com/aegir/aegir/), but progress is slow due to insufficient funding. Get in touch if you'd like to help with this initiative.

---
Tags: aegir
---


# Question
Title: Exposed Views Filter of Usernames in a list instead of autocomplete
I have an exposed filter with a relationship to a reference field in my content type to users. Currently this exposed filter lets me filter by inputting a username, but its only autocomplete. Is there a way to have a select list of usernames I can pick from?

# Answer
> 2 votes
If you need a simple approach, you can install the drupal Chosen module, which does the heavy lifting.

With coding, you can use `hook_form_FORM_ID_alter()` as the following:

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Check the views form ID.
  if ($form['#id'] != 'YOUR-VIEWS-FORM-ID') {
    return FALSE;
  }

  // Define the form options array.
  $options = [];

  // Load all user objects.
  $users = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->loadMultiple();

  foreach ($users as $user) {

    // You can add filtration here e.g.
    if ($user->hasRole('anonymous')) {
      continue;
    }
    $options[$user->id()] = $user->getDisplayName();

    $form['YOUR_FILED']['#type'] = 'select';
    $form['YOUR_FILED']['#multiple'] = FALSE;

    // Specify the empty option for our select list
    $form['YOUR_FILED']['#empty_option'] = t('Select user');

    // Add the $options from above to our select list
    $form['YOUR_FILED']['#options'] = $options;
    unset($form['YOUR_FILED']['#size']);
  }

}

```

---
Tags: views, 9
---


# Question
Title: How to redirect to a specific page after submitting password reset?
When a logged in user resets their password at /user/password and clicks the submit button, they are being redirected to the frontpage.

How can I redirect to /user instead?

I've tried the second answer here: How to redirect users after password reset from first time user, but the redirect doesnt happen.

```
function myModule_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_state->get('user_pass_reset')) {
    $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
  }
}

function mymodule_form_submit(array $form, FormStateInterface $form_state){
  $form_state->setRedirect('user.page');
}

```

For the route name I've tried both entity.user.canonical and user.page. I'm not sure if the code just isn't correct for Drupal 9 or I'm getting the route wrong, but I would expect an error in that case instead of the redirect just not happening.

# Answer
> 2 votes
Looks like the form ID changed, its `user_pass` for D9

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_pass_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
}

/**
 * Custom submit.
 *
 * Redirects user to the user page.
 */
function mymodule_form_submit(array $form, FormStateInterface $form_state){
  $form_state->setRedirect('user.page');
}

```

---
Tags: 9, redirection
---


# Question
Title: How can I print user field values in page.html.twig?
I've created a couple of fields for the user in Drupal 8, example: first name. And i'm trying to print it in the home page (page.html.twig) but to no avail. I tried the following:

```
{{ user.field_first_name.0['#context']['value'] }}
{{ user.field_first_name.0.value }}
{{ user.field_first_name }}

```

I even tried adding preprocess functions on mytheme.theme, and still it didn't work.

noting that the below works

```
{{ user.displayname }}

```

Appreciate any help given,

thanks

# Answer
To print user fields on the page template create a Views block and place it in an existing region.

At best you first added a new view mode for *User* under https://example.com/admin/structure/display-modes/view and then on https://example.com/admin/config/people/accounts/display select the newly created view mode and place the fields you like to display.

Then create the view, have it display *Users* and in the very right under *ADVANCED* add a contextual filter for User ID. Select *Provide default value* and choose *User ID from logged in user*, save. Then in the very left under *FORMAT \> Show \> User* select the view mode you created earlier.

---

**Don't print user values on the page template.**

1. `page.html.twig` is for printing regions.
2. `page.html.twig` is cached per user role. Next user with the same role will get displayed initially cached values of another user.
3. The user object with all field values isn't fully loaded by default, you would need to preprocess the user first.
4. Templating should be done when you need to structurally change markup.
> 2 votes

# Answer
Provided that you have Twig Tweak extension installed you could use this method to load any field. It is heavy so use sparingly:

```
{% set user_entity = drupal_entity('user', user.id, 'default') %}
{% set user_field = user_entity['#user'].getFields().field_name %}
{{ user_field.0.value }}

```
> 0 votes

---
Tags: 8, theming, users
---


# Question
Title: path alias OK for default language, but no alias for others
My site is in D9, mainly in French, with some pages in English.

I have an old page (note 553 written in D6 in 2017), which can be correctly accessed in French with https://mysite/myoldpage and in English with https://mysite/en/myoldpage.

I've just written a new page in French (https://mysite/mynewpage) and translated it in English. But the translated page is only accessible with https://mysite/en/node/997.

I don't understand why the old page works perfectly and not the new one.

I see a difference in https://mysite/node/553/translations and in https://mysite/node/997/translations. For the old one, I see a "source language" column. For the new one, There is no such column (but I do see the 2 lines for the 2 languages).

Parts of my conf:

* Language selection is firstly by URL.
* I use pathauto, but not for "pages"

Any hint appreciated!

# Answer
The old node probably has an alias with the language code UND (-not specified-). You can add one in the alias table

```
www.example.com/admin/config/search/path

```

but not in the node edit form. See https://drupal.org/node/2689459.

The column source language only shows when there are translations with a source language other than the original language, but this is not connected to this alias issue.
> 1 votes

---
Tags: i18n-l10n, 9, path-aliases
---


# Question
Title: How to check a boolean value in twig templates?
We have a field\_boolean (boolean field) on an ECK Bundle on the article content type. While doing research we came across the question "How to test for a boolean field in a twig template?" but it does not solve my problem.

What is the appropriate way to check for the boolean value?

We have attempted but they don't work:

```
{% if entity.field_boolean == True %}
{% if '1' in entity.field_boolean[0] %}

```

These appear to work, but not sure it is correct approach.

```
{% if entity.field_boolean[#items].value == '1' %}
{% if entity.field_boolean[#items].value %}

```

# Answer
Time for another promotion of my blogpost from a while ago :)

https://www.md-systems.ch/en/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig

The relevant part:

Only display a field if a checkbox is checked, optionally with custom wrapping HTML.

```
{% if node.field_checkbox.value %}
   <div class="only added when there are values">
  {{ content.field_name }}
  </div>
{% endif %}

```

You don't need `== '1'` or same as or anything like that, because it directly evaluates as to a boolean value. I also wouldn't recommend to use type safe checks with content entities because they are not type safe. Values are stored in the database and anything coming out from there is a string but sometimes values might not be. The boolean field is actually the perfect example for that, it is a string one, aka a nice mix of 3 different data types.
> 24 votes

# Answer
Checkbox fields value check in Twig templates for drupal 8:

```
{% if node.field_checkbox['#items'].value == '1' %}
  <div class="only added when there are values">
    {{ content.field_name }}
  </div>
{% endif %}

```

Thats works fine for me.
> 8 votes

# Answer
If you create the Boolean field in the content type then this worked for me

{% if node.field\_boolean.value == 1 %} {{ page.contact\_form }} {% endif %}

and also if you have boolean field in a paragraph then this worked for me

{% if content.field\_boolean\['#items'\].value == 1 %} {{ content.field\_description }} {% endif %}
> 5 votes

# Answer
For me, one test did not work consistently. However, the following condition seems to have covered all the use cases.

```
{% if content.field_boolean is not empty and node.field_boolean.value == '1' %}

```
> 4 votes

# Answer
For me too, to only safest is using both:

> {% if content.field\_boolean is not empty and node.field\_boolean.value == '1' %}

Other cases might fail. You can find more information on this thread: https://www.drupal.org/project/drupal/issues/3203038
> 0 votes

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


# Question
Title: Why does this code to create a dependent dropdown not work?
I am trying to implement the dependent dropdown option in Drupal 7 from this URL http://w3shaman.com/article/creating-ajax-dropdown-drupal-7. When changing the first dropdown value, it is showing the loading indicator but no value is fetching in dependent dropdown.

Here is the code I have tried so far.

This is the code of form alter module

```
function xyz_mod_alter(&$form, &$form_state, $form_id) {
          $form['sandbox_ajax_dropdown']['province'] = array(
        '#title' => t('Province'),
        '#type' => 'select',
        '#options' => _load_province(),
        '#ajax' => array(
          'event'=>'change',
          'callback' =>'sandbox_ajax_dropdown_city',
          'wrapper' => 'city-wrapper',
        ),
      );

      // Wrapper for city dropdown list
      $form['sandbox_ajax_dropdown']['wrapper'] = array(
        '#prefix' => '<div id="city-wrapper">',
        '#suffix' => '</div>',
      );

      // Options for city dropdown list
      $options = array('- Select city -');
      if (isset($form_state['values']['province'])) {
        // Pre-populate options for city dropdown list if province id is set
        $options = _load_city($form_state['values']['province']);
      }

      // Province dropdown list
      $form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
        '#title' => t('City'),
        '#type' => 'select',
        '#options' => $options,
      );
}

```

Code for loading the default value of province and fetching city data function

```
function sandbox_ajax_dropdown_city($form, $form_state) {
    return $form['sandbox_ajax_dropdown']['wrapper'];
}

function _load_province() {
        // fetch the data
        return $province;
}

function _load_city($province_id) {
        // fetch the data
        return $city;
}

```

I am not sure about the mistake I am doing. I copied the exact code from the given link. Even I tried to change as per my need but it is not working.

# Answer
> 0 votes
Without some kind of content, a prefix and suffix are not rendered. That means this element will not render anything on the page:

```
// Wrapper for city dropdown list
  $form['sandbox_ajax_dropdown']['wrapper'] = array(
  '#prefix' => '<div id="city-wrapper">',
  '#suffix' => '</div>',
);

```

As this is not rendered, the Ajax wrapper does not exist on page load to insert your content into. The solution is to add empty markup to force rendering of the prefix and suffix:

```
// Wrapper for city dropdown list
  $form['sandbox_ajax_dropdown']['wrapper'] = array(
  '#prefix' => '<div id="city-wrapper">',
  '#suffix' => '</div>',
  // Add empty markup to force rendering.
  '#markup' => '',
);

```

---
Tags: 7, forms, hooks
---


# Question
Title: Difference between ContainerInjectionInterface and ContainerFactoryPluginInterface?
Both `ContainerInjectionInterface` and `ContainerFactoryPluginInterface` provide a `create()` function and are used for dependency injection.

I would like a clear description of their differences and their use cases, such that it's clear which interface a class should implement.

* Which should I use if I only need to use injected services in a class?
* Which should I use in a service class that will be injected in other classes and defined in the module.services.yml?

# Answer
> 3 votes
The first one is typically used for controllers and the second one is for plugins. If you only need to inject services in service classes defined in module.services.yml you need neither of them.

---
Tags: dependency-injection
---


title: Add text to user login page

text:
# Question
Title: Add text to user login page
I'm attempting to add text to user login page, with general info about accounts rather than only displaying the login form.

I have a page.html.twig template like so

```
{{ page.header }}
<h2>This is my page template</h2>
{{page.content}}
{{ page.footer }}

```

I then can create content in page--user--login.html.twig like so.

```
{{ page.header }}
<h2>This is my page template</h2>
<p>Enter your login information here</p>
{{page.content}}
{{ loginform }}
{{ page.footer }}

```

But is there anyway to just add text to the login form without recreating page.html.twig. Since it would just be a copy I'd rather consolidate everything so any change wouldn't have to be made to both. Is there a template I could use like node--user--login.html.twig. So that the content would use page.html.twig and use the page.content block?

I understand that you can make changes to the form using a theme\_form\_alter hook but I'm not sure how to add html to the form from there. I can only change things like placeholder text, and submit values.

# Answer
You can create a custom block that appears only on /user.

After you create the custom block, configure it to appear in the content region. You could also need to set a condition for anonymous users.
> 6 votes

# Answer
You can do this very simple way using hook\_form\_FORM\_ID\_alter.

Paste following code in your themename.theme file and clear the cache

```
function YourThemeName_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
    $form['newline'] = array(
      '#type' => 'markup',
      '#markup' => t('<h2>Enter your login information here!</h2>'),
      '#weight' => -10,
    );
}

```

## Image output:

**Before:**

>

**After:**

>

This way you do not need to worry about anything, it will only show in Login page.
> 7 votes

# Answer
Place this hook in your **.theme** file and replace **HOOK** with your theme name. You can change your heading and paragraph text accordingly.

```
/**
 * Implements hook_form_alter().
 */

function HOOK_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#form_id'] == 'user_login_form') {
    $form['forgot'] = array(
      '#type' => 'markup',
      '#weight' => -10,
      '#markup' => '<h2>This is my page template</h2><p>Enter your login information here</p>',
    );
    }
}

```

This hook will work properly. That is working fine for me.

Thank you
> 0 votes

---
Tags: theming, 8
---


# Question
Title: get the value of a drupal token inside a twig code
does anybody knows how to get the value of a drupal token inside a twig code(global text field) block in the views's header? I can get the value of the token outside the twig code block, but not inside ...

```
[view:page-count]/*token works outside*/

{% set count = [view:page-count]  %} /*does NOT work*/
{% if count == 1 %}
    <p class="text-danger">Atención: en esta región sólo debe haber un artículo  </p>
{% endif %}

```

greetings

# Answer
> 1 votes
Enclosing the token in apostrophes solved the problem, but apart from that I had to create a special text filter using the contrib module Twig input filter to be able to use full twig code in a views Global text area.

As it seems, Global text area with minimal filtering(also availeble in views), which I was using, does NOT fully support twig.

```
[view:page-count]/*token works outside*/

{% set count = '[view:page-count]'  %} /* this WORKS inside*/
{% if count == 1 %}
    <p class="text-danger">Atención: en esta región sólo debe haber un artículo  </p>
{% endif %}

```

---
Tags: views, tokens
---


# Question
Title: Is it possible to "group" a Views field when using the "Content" display format?
We have a View using the Content display format (not Fields) because we're using a theme template to output the nodes. This works great but we also need to group to nodes by a field on the node (category). When using the Fields display output for a View it gives you the "group by" field option but (for obvious reasons) not when using the Content display format.

Is there a workaround to allow grouping Nodes by a field (category) when using View's Content display formats?

D9.5

# Answer
To accomplish this, you can use the "rendered entity" as a field. You need to:

* Switch the Formate -\> show to fields
* In the fields section, add a new "rendered entity" field
* You can then activate the "Group by" function
> 2 votes

---
Tags: views
---


# Question
Title: How can I change the development version of a module?
Originally, the Link Allowed Hosts module, which I'm a maintainer of (with "administer releases" permission), started with a default branch of `1.0.x`. This branch was released and appeared since then as development version `1.0.x-dev`.

This was wrong, the default branch needs to be `1.x`. So I created a `1.x` branch, set it as default on the project's GitLab page and also released it. Still the development version stayed `1.0.x-dev`.

I also can't enable this branch in the project's "Releases" page as the matching checkbox is disabled.

How can I fix this? Or where can I file this issue?

---

---

# Answer
There is no way to select that branch as supported, as the *Supported* checkbox for the *1.\** series is disabled by code. That is done by `project_release_project_edit_releases()` which contains the following code. (drupal.org is still running on Drupal 7.)

```
// Check if the maintainer is allowed to mark the branch as supported.
if (($supportable_branch_pattern = variable_get('project_release_supportable_branch_pattern_' . $node->type, variable_get('project_release_supportable_branch_pattern'))) && !preg_match($supportable_branch_pattern, $branch)) {
  $form['branches'][$branch]['supported']['#disabled'] = TRUE;
  $form['branches'][$branch]['supported']['#value'] = 0;
  $form['branches'][$branch]['recommended']['#disabled'] = TRUE;
  $form['branches'][$branch]['recommended']['#value'] = 0;
}

```

That is probably done because the settings for *1.\** would also be valid for *1.0.\**; using settings for the *1.\** and the *1.0.\** series would cause "conflicts" between two different settings.

As for in which queue you could file an issue, that is the *Project* issue queue, the queue for the project that handles projects and their releases on drupal.org. Probably this is seen as *works as designed*, but the *Project* maintainers are the only ones who can change that code and decide for any change.
> 2 votes

# Answer
The easiest way to have this resolved is to as in the #drupal-infrastructure channel in Slack.
> 1 votes

---
Tags: community-official-site
---


# Question
Title: Why does “ Nesting level too deep - recursive dependency?” occur in a compiled template?
After upgrading from 9.4.8 to 9.5.3 a problem came up (see below) so when I add more than one image in articles media field node-image, I get a 500 error.

```
PHP Fatal error:  Nesting level too deep - recursive dependency? in /home/www/sites1/mysite.gr/astrosnews/web/sites/default/files/php/twig/63dee130963f5_field--field-node-image.h_OFwaH9BedIr0dxUMjz2WTf6If/M-GDNVdt5tDdsesr-7jYR7Xyr_xWOPal71qHp-7K3yk.php on line 89

```

The line 89 mentioned above is the below but is not produced by theme code.

```
if (((($__internal_compile_2 = ($context["items"] ?? null)) && is_array($__internal_compile_2) || $__internal_compile_2 instanceof ArrayAccess ? ($__internal_compile_2[0] ?? null) : null) != $context["item"])) {

```

Do you have any idea how to solve this?

**Update**

code which might be the source of the problem although it is not changed

```
  {% if items|length > 1 and view_mode == "full" %}
    <div class="image-listing-items clearfix">
      {% for item in items %}
        {% if items[0] != item %}
          <div class="image-listing-item">
            <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
          </div>
        {% endif %}
      {% endfor %}
    </div>
  {% endif %}

```

# Answer
> 3 votes
This code line is expensive to calculate and could even cause a fatal error when the arrays/objects are very large:

```
{% if items[0] != item %}

```

Instead, use the Twig loop variable:

```
{% if not loop.first %}

```

---
Tags: theming, media
---


# Question
Title: Can I use Price Resolvers for dynamic product pricing?
All cart items are adding programmatically. I am trying to set a product cost based on various factors that change for each instance of an item added to the cart.

I discovered Price Resolvers and it seemed like it was working until I ended up adding 2 of the same "dynamically priced" items to my cart. Each was passed different prices and in my resolver I can see that the price is set correctly for each item. However, in the cart, they both have the same cost (the cost of the last item added to the cart).

My guess is that I can only set the price of an item per php session and not per cart item add. Is this correct? Is there some other way to dynamically set price of a product as it is added to a cart?

# Answer
Eventually sorted this out on my own. Simple answer is NO, this is not the purpose of Price Resolvers. Price Resolvers can be used to "statically" set a price based on something which does not change during the php session - such as location, year, etc. But if you need to modify the price due to user input at the time; the correct solution is to set the Unit Price.

Before looking at Resolvers I already had this code:

```
  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $my_dynamic_price,
  ]);

```

and I have seen posts and had been given suggestions that this works. It does not. Setting the unit\_price at the time of OrderItem::create has no impact on the item's price. The correct way to do this is with the setUnitPrice() method like this:

```
  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $variation->getPrice(),  // may be overwritten by $options['cost']
  ]);

  // If we are setting a custom cost, override unit_price now.
  if (isset($options['cost']) && $options['cost']) {
    $order_item->setUnitPrice($options['cost'], TRUE);;
  }
  $order_item->save();

```
> 1 votes

---
Tags: commerce, 9
---


title: Alter all webform fields

text:
# Question
Title: Alter all webform fields
If we want to alter webform item e.g. add a colon `:` to a label of a specific field, we use this:

`$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";`

But what if we want to apply that colon to all field labels and not just that one `my_form_component`?

Current code:

```
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    $form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";
  }
}

```

# Answer
You should be able to do it with a recursive function, looping through the render array and adding a colon to any elements that have a #title element.

```
function addColonsToTitles(&$element) {
  if (isset($element['#title'])) {
    $element['#title'] .= ':';
  }

  foreach (element_children($element) as $index) {
    addColonsToTitles($element[$index]);
  }
}

function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    addColonsToTitles($form['submitted']);
  }
}

```
> 1 votes

---
Tags: 7, theming, webforms
---


# Question
Title: Run custom php code or file in drupal content type form submission
I have this drupal site, there is a candidate registration page where anyone can fill the details (name, gender, address, mobile no etc) and submits and a success node page is displayed with all details applicant fills, then at admin side applications will be used for further offline processing. Everything is working fine.

What i am trying to do now is, after filling the details - like **mobile number** and other details applicant will click on submit button and all will be saved to database as usual but **an sms will be sent to that mobile number**.

I have my php sms script ready, but can't really add / embed it on form submission where i guess it will catch the mobile number and my php sms script will be run.

```
<?php
$mobile = '10 digit mobile number';
$entityID = 'xxxxxxxxxxxxxxx';
$uname = "xxxxx";
$pass = "xxxxxxxxx";
$senderID = 'xxxxxxx';
$destination = urldecode($mobile);
$smsContent = urlencode(addslashes($smsbody));

$URL = "https://smsgateway.in/link?username=$uname&pin=$pass&message=$smsContent&mnumber=$destination&signature=$senderID&dlt_entity_id=$entityID&dlt_template_id=$tmpltID";

if ($destination != 0) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, '/ca-bundle.crt');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (stristr($response, "info=Platform accepted")) {
   // $messageArray[] = $mob;
}
curl_close($ch);
}
?>

```

# Answer
> 0 votes
You can use hook **hook\_ENTITY\_TYPE\_insert** https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_ENTITY\_TYPE\_insert/8.4.x

You also can use **hook\_form\_alter** or **hook\_form\_FORM\_ID\_alter** and put the SMS script on that hook.

**Note:** Remember to restrict the send SMS on first time submit / or some conditions to avoid spam sms. Those hooks run on every submit though.

---
Tags: 8, nodes, forms
---


# Question
Title: How can I check with if my site is running?
Is there a way with Drush or something else to check if a specified Drupal site is still up and running, means fully normal functioning, after automated maintenance/updating in an external script?

Sometimes an update can fail in a script and then there is a none-functional site left. I want to detect that situation. So have a command and the output is the status of the site? E.g.

```
drush <command> <site>

```

yields down/up or something.

The `drush status` command doesnt seemed to have such functionality.

## Edit

When I was searching for the tools suggested in the comments I see that i was unspecific in the beginning, sorry for that. I mean the script is updating Drupal core and modules via Composer and Drush e.g.

```
~/bin/composer.phar update drupal/core "drupal/core-*" --with-all-dependencies
drush updatedb -l $WEBSITENAME
drush cache:rebuild

```

So I don't speak about updating whole servers and systems, just automated updating Drush, core and modules.

# Answer
> 3 votes
The simplest definition of a running site is that it returns a status code 200. From the command line or a script, you could use wget or curl.

If you want to avoid these tools a Drush only solution would be using the built-in guzzle client:

```
drush ev "echo Drupal::httpClient()->head('www.example.com')->getStatusCode();"

```

---
Tags: drush
---


# Question
Title: D8 Install/uninstall custom module - 'field_storage_config' entity with ID already exists
I created a custom module which essentially is a replica of the `Article` CT .yml files which come with the D8 standard install-profile.

When I installed the custom module, it successfully created everything i expected it too. I then disabled it, then re-enabled and the module will not re-install giving the following error:

> Drupal\Core\Entity\EntityStorageException: 'field\_storage\_config' entity with ID 'node.custom\_field' already exists.

I originally solved this issue by declaring the module as a Enforced dependency on the node.type.yml

```
langcode: en
status: true
dependencies:
   module:
    - menu_ui
   enforced:
     module:
       - custom_module

```

This worked for the body field and allowed me to enable/disable the module without getting the duplicate ID error. but as soon as i added the image field the ID is a duplicate and I cannot re-enable the module. The id is unique, and module will enable if i change the ID prior to enabling, but thats unacceptable.

> EDIT: appears after removing the image field from the CT, the body field now is now being affected by the same error. So enforcing the module doesnt work.

I would assume this is because it is inside of the `config/install` folder, but there are no examples on custom modules that install content types when installed. at least I cannot find any at the moment.

My question would be: **What is the proper way to add content types when enabling a custom module?**

**how to avoid the duplicate ID error when installing content types when disabling/enabling the custom module?**

# Answer
Try putting the files in the config/optional directory either at first install or after uninstalling (because they will already exist). They should get installed even on first install if all dependencies are met. From the docs:

> > For example, in the scenario that module A has optional configuration which requires module B, but module A is installed first and module B some time later, then module A's config/optional directory will be scanned at that time for newly met dependencies, and the configuration will be installed then. If module B is never installed, the optional configuration item will not be installed either.

https://www.drupal.org/docs/8/api/configuration-api/configuration-storage-in-drupal-8
> 1 votes

# Answer
Similar problem here: one field storage configuration and three entity field instances.

I had the field storage ID looking like:

```
id: <entity_type>.file_name

```

And I had the field instance IDs looking like

```
id: <entity_type>.<bundle>.field_name

```

but that was causing `'field_storage_config' entity with ID '<entity_type>.field_name' already exists.` errors.

It seems that the `<bundle>` part of the configuration ID was being ignored.

Fixed by renaming the IDs of the field instances to look like:

```
id: <entity_type>.<bundle>_field_name

```

Hope this helps if anyone else gets this problem :)
> 0 votes

---
Tags: installation-profiles, installation, 8
---


# Question
Title: How to Fix drush installation - path or alias to drupal root
I had 10.6.2 working - on Centos 7 and today it is just GONE. I had to remove phpunit and apparently it took the drush pathing setup for drush with it. Now it says it is installed but the command is not found if I run " composer require drush/drush:10.6.2 "

If I go to /public\_html/vendor/drush/drush and run ./drush it is there but gives the error " ! \[NOTE\] Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands. "

How do I get this pathed back to the drupal root ??

# Answer
> 1 votes
Best solution was to straight use Drush Launcher ( https://github.com/drush-ops/drush-launcher ) If you use WinSCP it is really easy to move it into the path, rename it "drush", make it executable and it will find the version of drush when executed via command line from inside the Drupal installation. The nice thing is there can be different versions of drush in different Drupal verson installations - like version 8 drush installed in Drupal 7 and inside that Drupal it will use that version of drush installed Fast and easy

# Answer
> 0 votes
Make sure you have a composer.json file in the site root.

If there is no composer.json you always get the error "! \[NOTE\] Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands. "

---
Tags: drush, composer
---


# Question
Title: Dynamically generate Form API select list of routes to page displays of a known View
Given a known View, how would one dynamically generate a Form API select list of the routes to its Page Displays?

In my case, I have a Search API View (`view.search`) with a default site-wide search page (`view.search.page_1`) and separate search pages for different site sections, or "micro-sites" (*e.g.*, `view.search.page_2`, `view.search.page_3`, etc.)

I have coded a custom block to replace the Drupal core Search form, which redirects to the site-wide search page, passing the fulltext query parameters as `$link_options`:

```
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Redirect to a search page, appending search keys.
    $search_route = 'view.search.page_1';
    $search_url = Url::fromRoute($search_route);
    $link_options = [
      'query' => [
        'search_api_fulltext' => $form_state->getValue('keys')
      ],
    ];
    $search_url->setOptions($link_options);

    $form_state->setRedirectUrl($search_url);
  }

```

Next, I would like to provide per-block configuration in the Block Plugin class implementation, so that the redirect route can be selected by a site admin when placing an instance of the block.

I'm about to hard-code this form select element, but it would be nice if the list would automatically update later if a new display were to be added to the View.

In a `drush php:cli`, I can use the entity type manager to load the View storage:

```
>>> $view = \Drupal::entityTypeManager()
  ->getStorage('view')
  ->load('search')
  ->getExecutable();

```

And I can call a specific display as long as I know its machine name:

```
>>> $display = $view->getDisplay('page_2');

```

But there does not seem to be a `$view->getDisplays()` method:

```
>>> $displays = $view->getDisplays();
PHP Error:  Call to undefined method Drupal\views\ViewExecutable::getDisplays() in Psy Shell code on line 1

```

In my module, I don't need to actually deal with any of the usual Views API stuff (e.g., filter and sort criteria, rendering a display, etc.). I just need the machine names of valid page displays so I can concatenate them with `'view.search.' . $displayname` and pass that to `Url::fromRoute()` so my new Form knows where to redirect its query.

# Answer
> 2 votes
Assuming a recent version of Drupal (I checked 9.5 and 10.1 on api.drupal.org), you should be able to `$view->get(‘display’);` and have it return an array of all the displays. Don’t forget to typecheck $view, or at least check that it’s not null, before trying to call one of its methods.

NB: I haven’t tried it myself, so this is just what I gleaned from api.d.o. YMMV.

---
Tags: views, forms, routes
---


# Question
Title: I'm not able to fully disable caching during development
I'm currently developing a new Drupal 9 website. I build quite a few custom modules for this but for some reason the changes I make in the modules during development are not visible immediately.

I disabled caching as described in this post.

The strange thing is that, even when I run `drush cr` the changes are not active. I also have my chrome development window open so the browser is not caching the pages either. I have to empty cache and save the page a few times to get it to work.

What can I do to further disable caching so I don't have to empty the cache after I made a change?

# Answer
The post (Disable Drupal (\>=8.0) caching during development) had been updated, you may consider use the Mix module to **disable caches** during development.

By toggling "Enable development mode" checkbox, you can switch between Dev/Prod modes easily without editing any settings\*.php and \*services.yml files.
> 0 votes

---
Tags: 9
---


title: Twig cache won't disable

text:
# Question
Title: Twig cache won't disable
I've set up my development setup and it works great but for some reason I can't get the twig cache to disable. I tried everything, but I have to run drush cr every time I change anything in twig templates, and it's driving me insane.

settings.php:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

settings.local.php AND setting.php:

```
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

services.yml AND development.services.yml

```
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

```

I am running Drupal 8.4

# Answer
In Drupal 8.4 you have to set the null cache backend for an additional cache bin, so now there are three:

*settings.local.php:*

```
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

This is because the cached pages for anonymous users moved to a separate cache bin, see the change record *The internal page cache now has a dedicated cache bin*.
> 14 votes

# Answer
Use the Mix module to **disable drupal caches** during development by just toggling an "Enable development mode" checkbox, which will saving us a lot of time in settings\*.php and services\*.yml files.
> 0 votes

---
Tags: caching
---


# Question
Title: Get Video URL from Media Entity reference field
I have an entity reference field to Media Video.

I'm trying to get the uri to the video file in node template.

Most of the solution I found around is regarding Image/File. But not Video.

Tried Twig Field Value module but it doesn't work.

# Answer
> 11 votes
If you use the media type *Video* installed by core, you'll find the URL in the field `field_media_video_file`:

```
{{ file_url(node.field_media.entity.field_media_video_file.entity.uri.value) }}

```

# Answer
> 1 votes
To display the raw url of a remote video field in twig (Drupal 9): `{{ node.field_media.entity.field_media_oembed_video.0.value }}`

# Answer
> 0 votes
to display the raw url of a **remote video** :

```
{{ content.field_media_oembed_video.0 }}

```

# Answer
> 0 votes
I obtained the raw url using the following.

```
content.field_video_link.0['#media'].field_media_oembed_video.0.value

```

Where field\_video\_link was my custom field.

---
Tags: 8, media
---


# Question
Title: Can a Rules action send an email to all users that have set a flag?
I've found some older Drupal 7 info on this, but not much for Drupal 8+ yet. What I want to do:

* Give users the ability to set a 'notify me' flag on nodes
* When a comment is added to the flagged node, all users who have flagged it get an email notification

So far...

* I have the rule set up correctly to allow users in role x to set the flag. It has another action on it that is tested and working.
* I can select the 'Send email' action.
* I arrive a set of fields to specify, including the "To" field for an email address. It looks like I can select a flagging uid of users who set a flag.
* There doesn't appear to be any way to get the email address of a user who flagged into the "To" field.

Maybe this isn't yet possible, but am I perhaps missing something?

# Answer
> 1 votes
## Custom code approach

I know you asked about Rules module, but I don't think this can be done in Rules. To code this, check out FlagServiceInterface, specifically `getFlaggingUsers()`.

Basically,

* hook\_comment\_insert() to act on comment creation.
* Call `getFlaggingUsers()` on the node the comment is attached to.
* Email the users.

Some more hints on coding with Flag 4.x and caveats here.

---
Tags: rules, 9, emails, flags
---


# Question
Title: How to add advanced CKEditor dialog tab for iframe?
```
<?php

namespace Drupal\custom_ckeditor\Plugin\CKEditorPlugin;

use Drupal\editor\Entity\Editor;
use Drupal\ckeditor\CKEditorPluginBase;

/**
 * Defines the "dialogadvtab" plugin.
 *
 * @CKEditorPlugin(
 *   id = "dialogadvtab",
 *   label = @Translation("dialogadvtab"),
 *   module = "custom_ckeditor"
 * )
 */
class CustomDialogAdvTab extends CKEditorPluginBase {

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  public function getFile() {
    return drupal_get_path('module', 'custom_ckeditor') . '/js/ckeditor_plugins/dialogadvtab/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return [];
  }

}

```

This is my code which is not working. This file I have added in drupal8/modules/custom/custom\_ckeditor/src/Plugin/CKEditorPlugin as CustomDialogAdvTab.php

Same like, adding fakeobjects addon for iframe, CustomFakeObjects.php

```
namespace Drupal\custom_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "fakeobjects" plugin.
 *
 * @CKEditorPlugin(
 *   id = "fakeobjects",
 *   label = @Translation("FakeObjects"),
 * )
 */
class CustomFakeObjects extends CKEditorPluginBase {
  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return drupal_get_path('module', 'custom_ckeditor') . '/js/ckeditor_plugins/fakeobjects/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return [];
  }
}

```

in page view-source, I can able to see fakeobjects plugin.js where as advanced tab plugin has not been loaded

If I try to add plugin via CKEDITOR.scriptLoader.load, like below,

```
        CKEDITOR.scriptLoader.load(basePath + modulePath + '/js/ckeditor_plugins/fakeobjects/plugin.js');
        CKEDITOR.scriptLoader.load(basePath + modulePath + '/js/ckeditor_plugins/dialogadvtab/plugin.js');

```

fakeobjects/plugin.js file is loading but not dialogadvtab/plugin.js, file is in place, both have same permission, no error to debug.

# Answer
Try to implement getButtons()

```
public function getButtons() {
    return [
      'dialogadvtab' => [
        'label' => $this->t('AdvancedTabDialog'),
        'image' => drupal_get_path('module', 'module_name') . '/icon/dialogadvtab/dialogadvtab.png',
      ],
    ];
  }

```

Then admin/config/content/formats add button to your ckeditor. You can find any icon 16x16 png on this site https://www.iconfinder.com
> 0 votes

# Answer
There is a Drupal contrib module CKEditor Advanced Tab.

Check the README.md file to add the js plugin to your composer.

And don't forget to add the button (look the same as the link button) to your toolbar, even if this is not logical. The button will not be show when you edit content later.
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to set an error message with Javascript?
I was wondering how to set an error message from js to Drupal ? something like

```
<?php
    drupal_set_message('mplampla);
?>

```

but in Drupal object in js

```
jQuery(document).ready (function(){
    Drupal.setErrorMessage('mplampla');
})

```

is this even possible?

# Answer
The `drupal_set_message()` works by storing the messages into a session and displays when the page is reloaded.

If you want to show an error message through javascript, include js in your module (if working with some module).

You could simply append an error message on some event

```
    jQuery(document).ready (function(){
    jQuery(".error-message").append('<div class="messages error">Error message to be displayed</div>');
});

```

It will simply display an error message. You can apply further Js code as desired output.
> 9 votes

# Answer
If you want to attach the message above the form you can do

```
jQuery("form").prepend('<div class="messages error">Error message to be displayed</div>');

```

Based on Adrian Cid Almaguer answer.
> 1 votes

# Answer
In Drupal 8 and later you can use core/drupal.message library for that.

Add the core/drupal.message as a dependency for your custom library.

To add a message using Drupal messages API you need:

```
const message = new Drupal.Message();
message.add('Please enter your name', {type: 'error'});
message.add('Something happen', {type: 'warning'});

```

To clear the messages use the `message.clear();`
> 1 votes

# Answer
you can use jQuery Validate plugin. it populates the HTML errors containers with proper messages.

regards

Sudheesh
> 0 votes

---
Tags: status-messages, javascript
---


# Question
Title: How to get the current running Drush command?
I would like to detect from code the current running drush command. I have some hooks that will be run when I exec some drush commands and want to detect which command is triggering the hook.

I manage to get the info from input() but I want to know if there is a more appropriate way:

```
  if (PHP_SAPI === 'cli') {
    $command = \Drush\Drush::input()->getArguments()
  }

```

I would like to have something similar to this:

```
  if (PHP_SAPI === 'cli') {
    $command = \Drush\Drush::...getCurentCommand();
  }

```

Similar to Drupal::routeMatch()-\>getRouteName() in someway.

Thank you

# Answer
> 3 votes
A more appropriate way would be to use the object data you get as arguments. Most hooks receive $commandData from where you can get the first argument (the command):

```
$input = $commandData->input();
$command_name = $input->getFirstArgument();

```

Similar to the route name of the matched route you could get the full command name of the matched command via the annotations:

```
$full_command_name = $commandData->annotationData()->get('command');

```

If you need to use static code then get the command name as the first argument like in the question and convert it to the full command name:

```
$command_name = \Drush\Drush::input()->getFirstArgument();
$full_command_name = \Drush\Drush::getApplication()->find($command_name)->getName();

```

---
Tags: drush
---


# Question
Title: I am trying to add a simple pager to my controller, I have managed to get the row limit (5) to be printed but not to see the next or the previous
```
<?php

namespace Drupal\drupal_block\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Query\PagerSelectExtender;

class DrupalBlockController extends ControllerBase {
  protected $connection;

  public function __construct(Connection $connection) {
      $this->connection = $connection;
  }

  public static function create(ContainerInterface $container)
  {
      return new static(
          $container ->get('database')
      );
  }

  public function mymodule()
  {
    $data = $this->connection->select('custom_table', 'ct')
      ->fields('ct', ['name', 'lastname', 'sexo', 'email']);

  $pager = $data->extend(PagerSelectExtender::class)->limit(5);
      //$pager->setCurrentPage($page);
      $data = $pager->execute()->fetchAll();
      $rows = array();

      foreach ($data as $row){
        $rows[] = [
          'name' => $row->name,
          'lastname' => $row->lastname,
          'sexo' => $row->sexo,
          'email' => $row->email,
        ];
      }

    return [
      '#theme' => 'table',
      '#pager' => [
        '#type' =>'pager'
      ],
      '#header' => [
        $this->t('Name'),
        $this->t('Last Name'),
        $this->t('Gender'),
        $this->t('Email')
      ],
      '#rows' => $rows,
      ];
      }
    }

```

# Answer
> 1 votes
This:

```
return [
  '#theme' => 'table',
  '#pager' => [
    '#type' =>'pager'
  ],
  '#header' => [
    $this->t('Name'),
    $this->t('Last Name'),
    $this->t('Gender'),
    $this->t('Email')
  ],
  '#rows' => $rows,
];

```

Should be this:

```
return [
  'pager' => [
    '#type' =>'pager'
  ],
  'table' => [
    '#theme' => 'table',
    '#header' => [
      $this->t('Name'),
      $this->t('Last Name'),
      $this->t('Gender'),
      $this->t('Email')
    ],
    '#rows' => $rows,
  ],
];

```
1. Elements with hashtag prefixes are not rendered, they are metadata. So the hashtag needs to be removed from the array key.
2. The pager needs to be a separate render array from the table.

---
Tags: 9, paging
---


# Question
Title: "Missing class doc comment" when using attribute on class
I recently updated PHP from 8.1 to 8.2.

This resulted in a bunch of deprecation notices about use of dynamic properties in PHPUnit tests.

So, based on the docs, I added the AllowDynamicProperties class.

```
/**
 * Unit tests for the myModule class (timing).
 *
 * @group myModuleSuite
 *
 * @coversDefaultClass \Drupal\myModule\Class
 *
 * @property \DateTimeZone $timezone_utc
 * @property \DateTimeZone $timezone_nyc
 */
#[\AllowDynamicProperties]
class MyModuleTimingTest extends UnitTestCase {

```

This fixes the deprecation notice for PHP 8.2, but now the Drupal coding standards check complains about a "missing doc comment" for my MyModuleTimingTest class.

How am I supposed to write this so that I can use the attribute and not violate the coding standards?

## How I'm checking the coding standards

Using Coder module 8.3.16.

`/vendor/bin/phpcs -p --colors --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,test,profile,theme,info,txt,md --ignore=node_modules,vendor ./web/modules/custom ./web/themes/custom`

# Answer
**Update**: This is now fixed as of Coder 3.17.

**Original**:

Sure enough, as pointed out by @Clive, this is a bug with Coder and a fix is in progress.

So right now, there is no good way to declare PHP attributes on classes without the coding standards check complaining.
> 0 votes

---
Tags: coding-standards
---


# Question
Title: How to get the parameters from a URL and a route that is not the current one?
Route from a custom module :

```
custom.route:
  path: /the/{id}/path

```

Hypothetical url : `/the/53/path`

The goal is the get the id value ("53").

---

So far, I managed to get the route name from the url with

```
$url = "/the/53/path";

$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($url);

```

In $found\_routes, I can find the "custom.route" route name.

Now, I need to find the parameters value, but I can't achieve it.

```

use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

/**
 * Returns the parameters of a given URL.
 *
 * @param string $url
 *   The URL.
 * @param string $route_name
 *   The name of the route.
 *
 * @return array
 *   An array of parameters for the URL.
 */
function getUrlParameters(string $url, string $route_name): array {
  // Create a URL object from the given URL string.
  $url_object = Url::fromUri('base:/' . ltrim($url, '/'));

  // Create a request object from the URL object.
  $request = \Drupal::requestStack()->getMasterRequest();
  $request = $request->duplicate();
  $request->setMethod('GET');
  $request->attributes->set('_route', $route_name);
  $url_object->mergeOptions(['query' => $request->query->all()]);
  $request->server->set('REQUEST_URI', $url_object->toString());

  // Use the route matcher to get the route matching the URL.
  /** @var \Drupal\Core\Routing\RouteMatchInterface $route_match */
  $route_match = RouteMatch::createFromRequest($request, \Drupal::service('router'));

  // Return the parameters of the URL.
  return $route_match->getParameters()->all();
}

```

# Answer
You can use the `router.no_access_checks` service for this.

```
$router = \Drupal::service('router.no_access_checks');
$parameters = $router->match($url);

```

It works on both path aliases as well as unaliased paths. Example for a specific node with id 5 and an alias of `article/routing-in-drupal`:

```
$router = \Drupal::service('router.no_access_checks');
$url = 'node/5';
$parameters = $router->match($url);
// $parameters['node']->id() gives 5

$url = 'article/routing-in-drupal';
$parameters = $router->match($url);
// $parameters['node']->id() gives 5

```
> 1 votes

---
Tags: routes
---


# Question
Title: How can I get the node ID from a path alias?
I want to be able to get the nid but the only information I have is http://example.com/this-is-the-alias.

Is there a way to get either the internal path of /node/\* for that alias if I am not on the page? Or is there a way to just get the nid from that alias right away?

# Answer
I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on:

```
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');

if (preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}

```

## Drupal 9

In Drupal 9 the service has been renamed.

```
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/this-is-the-alias');

```
> 37 votes

# Answer
You can use the following code to get and load an entity and have access to its values.

```
  use \Drupal\Core\Url;

  $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/etapes-de-la-vie');

  $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
  $entity_type = key($params);
  $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
  //to use dpm you need the devel module
  dpm($node->nid->value);

```

### References
> 14 votes

# Answer
Install the devel module and then use the devel toolbar item *Current route info*.

This results in this url, which you can type in directly and provide any path known to your drupal installation as query parameter:

```
/devel/routes/item?path=alias

```

When it is a node you find the node id in the raw parameters at the end of the listed route variables.
> 3 votes

# Answer
This is what I do, so you avoid direct regexs.

```
$parsed_url = UrlHelper::parse($alias);
$path = \Drupal::service('path_alias.manager')->getPathByAlias($parsed_url['path']);
$params = Url::fromUserInput($path)->getRouteParameters();
$entity_type_id = array_key_first($params);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type_id)->load($params[$entity_type_id]);

```
> 0 votes

---
Tags: 8, nodes, path-aliases
---


# Question
Title: How can I modify/edit/change the media video controls?
I was wondering how could I modify the controls from a media video. In my particular case, I want to remove the "Download" button from the controls, see:

# Answer
> 1 votes
The easiest workaround I could find was:

* Create a template on your custom theme for the video field such as `file-video.html.twig`.
* Inside the template, create a video tag and place videos inside a `<source />`, then set a new attribute for the video tag called `ControlsList` with a value of `nodownload`, like this:

```
<video {{ attributes.setAttribute('controlsList', 'nodownload') }}>
  {% for file in files %}
    <source {{ file.source_attributes }} />
  {% endfor %}
</video>

```

You could also set the attribute manually: `<video ControlsList='nodownload'/>`

---
Tags: media, files
---


title: Allow empty tags

text:
# Question
Title: Allow empty tags
I need help to allow CKEditor empty tags. I know that I need to add something like `CKEDITOR.dtd.$removeEmpty['i'] = false` in a config file, but I can't find this file in Drupal 8.0.0 installation.

I just want to know where is the right place to add this line to allow CKEditor empty tags.

# Answer
> 5 votes
Rather than modify the Drupal 8 core, you should do this using some Javascript like the sample below. This can be loaded from your admin theme or other module.

```
(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
      CKEDITOR.dtd.$removeEmpty['i'] = false;
      CKEDITOR.dtd.$removeEmpty['span'] = false;
console.log(CKEDITOR.dtd);
      }
    }
  }
})(jQuery, Drupal);

```

For some more details see: Drupal 8 CKeditor behaves LTR in an RTL site

# Answer
> 1 votes
Not sure this works for CKE5 anymore.

I had to write my own plugin with its own upcasting & downcasting due to the drupalEmphasis plugin.

Otherwise when italics are enabled in the toolbar it will convert the `<i>` to an `<em>` regardless of allowing "empty" tags.

I posted a module that might help someone else;

https://www.drupal.org/project/ckeditor\_svg\_icon

and more specifically;

https://git.drupalcode.org/project/ckeditor\_svg\_icon/-/blob/main/js/ckeditor5\_plugins/svgIcon/src/svgicon-editing.js#L58

---
Tags: 8, wysiwyg
---


# Question
Title: What is the backend_overridable service tag usable for?
On some core services, I see they have a tag of `backend_overridable`. I see this changelog, but is there an example?

https://www.drupal.org/node/2306083

Is that essentially what something like Memcache is doing?

```
$settings['cache']['default'] = 'cache.backend.memcache';

```

# Answer
> 0 votes
This is an example:

*views/views.services.yml*

```
  views.date_sql:
    class: Drupal\views\Plugin\views\query\MysqlDateSql
    arguments: ['@database']
    tags:
      - { name: backend_overridable }
  pgsql.views.date_sql:
    class: Drupal\views\Plugin\views\query\PostgresqlDateSql
    arguments: ['@database']
    public: false
  sqlite.views.date_sql:
    class: Drupal\views\Plugin\views\query\SqliteDateSql
    arguments: ['@database']
    public: false

```

Which makes it possible to query dates differently depending on the default backend.

Cache bins can have a default backend, too. But this has a different meaning and can be overridden as described here https://www.drupal.org/node/2754947.

---
Tags: 9, symfony-services
---


# Question
Title: How to add complete value programmatically with Smart Date module?
Iam using module Smart Date on Drupal 9.

And required programmatically add value to node in field with recurring rule *(like Repeats every 1 year on xxxx-xx-xx)*. Technically, for this action also creating record in Rule table... But I understand, how this do... It seems like the smartdate module itself should make an entry in this additional table.

I used like this operation:

```
// Create new node:
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type'        => 'event',
  'title'       => 'My new note title',
]);

// Assign value to field_date:
$node->set('field_date', '2022-03-01');
// ...needed add here also rule of yearly recurring...

```

field\_data - its name of smartdate field, but how add field value with complete data (repeats every, until and etc.)? Like in field widget on node edit with admin panel, there are more options available for this field.

Any ideas?

# Answer
> 0 votes
When adding a *Smart date range* field to a content type, a table node\__*field\_name* will be added to the database. You have to fill in both the start (*field\_name*\_value) and end date (*field\_name*\_end\_value) with a timestamp.

For example with your field name:

```
$node->field_date->value = 1676039400;
$node->field_date->end_value = 1676046600;

```

For all day events you can fill in the duration as well:

```
$node->field_date->value = 1675983600;
$node->field_date->end_value = 1676069940;
$node->field_date->duration = 1439;

```

Smart date fills in the number of days in minutes -1 minute for all day events as duration.

---
Tags: nodes, 9
---


title: Passing variables to template rendering

text:
# Question
Title: Passing variables to template rendering
I want to render "file-video.html.twig" template.

This is the documentation: https://api.drupal.org/api/drupal/core%21modules%21file%21templates%21file-video.html.twig/9.3.x

This is my code:

```
 return [
                        '#theme' => 'file_video',
                        '#attributes' => ['TEST ATTR'],
                        '#files' => [
                            [
                                'file' => $file,
                                'source_attributes' => [

                                ]
                            ]
                        ]
                    ];

```

Where $file is Drupal\file\Entity\File. I tried 'source\_attributes' =\> \['src' =\> $url\], ... But everything in this array throws an error.

The problem seems that those are not variables passed to the correct template I want. The #attributes TEST ATTR goes into block div id instead of the template.

The correct template IS rendered, but nothing is passed to is. How should I format the return array in order to pass the variables into the template I want? I searched for couple hours and did not find any documentation whatsoever about this.

# Answer
I think you should check: `core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php` where 'source\_attributes' is a `Drupal\Core\Template\Attribute` object.

```
 * @return array
 *   Numerically indexed array, which again contains an associative array with
 *  the following key/values:
 *     - file => \Drupal\file\Entity\File
 *     - source_attributes => \Drupal\Core\Template\Attribute

```

I forgot about your '#attributes'

Try:

```
'#attributes' => ['TEST' => ['ATTR']]

```
> 0 votes

# Answer
I've just tested this out in a block and can 100% confirm it works:

```
use Drupal\Core\Template\Attribute;
use Drupal\file\Entity\File;

$file = File::load(60);
$attributes = new Attribute();
$attributes->setAttribute('src', '/sites/default/files/MYVIDPATHHERE.mp4');
$build['vid'] = [
  '#theme' => 'file_video',
  '#attributes' => ['asda' => 'aa'],
  '#files' => [
    [
      'file' => $file,
      'source_attributes' => $attributes,
    ],
  ],
  '#cache' => ['tags' => []],
];

```

Which results in HTMl of:

```
<video asda="aa">
  <source src="/sites/default/files/MYVIDPATHHERE.mp4">
</video>

```

Obviously you could retreive the video src from $file, rather than just hard coding it like I have.

If the above code isn't working for you then you've got something else going on interferring with the rendering
> 0 votes

---
Tags: blocks
---


title: Why does my JS file not get loaded?

text:
# Question
Title: Why does my JS file not get loaded?
I am a beginner with Drupal. I want to include a JavaScript file using a custom module.

I created the .libraries.yml file, *hello\_world.libraries.yml*.

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

```

The module .info.yml file (*hello\_worl.info.yml*) contains a reference to the library.

```
name: Hello World
type: module
description: Say Hello World
package: Custom
core: 8.x
libraries:
  - hello_world/hello_world_js

```

The JavaScript code in the *basic.js* file is the following one.

```
(function($,Drupal){
  Drupal.behaviors.addAccessionBehavior = {
    attach: function(context, settings){
      $(".query_button").click(function(){
        console.log("works");
      });
    }
  };
})(JQuery, Drupal);

```

When I click on a button using the *.query\_button* CSS class, nothing happens and I don't know what the problem is.

# Answer
If you look in a JavaScript console you can get more information. You probably have an error in your console that says `JQuery is not defined`. This is because you declared `JQuery` but the variable is `jQuery`. So this:

```
})(JQuery, Drupal);

```

Should be this:

```
})(jQuery, Drupal);

```

Also, when you want to test if your file has been attached, you should add a debugging command directly into behaviors.attach(), rather than a sub-function that requires a click (as you've done). So you can test if your script has been added like this:

```
Drupal.behaviors.addAccessionBehavior = {
  attach: function(context, settings){
    console.log("works");
    $(".query_button").click(function(){
      // Do stuff on click
    });
  }
};

```

This will log something on page load, which tells you that the script has loaded (and contains required variables).
> 1 votes

# Answer
Module info files have no `libraries` key. That key is only for themes.

You need to attach the module library yourself. Read the docs; there are numerous ways to attach the library at the right place to be loaded at the right time, depending on where you need the JS to fire.

Finally fix this typo: JQuery with uppercase J is wrong. It needs to be `jQuery` with lowercase j.
> 0 votes

---
Tags: javascript
---


# Question
Title: "This theme is missing a 'content' region".?
while creating my custom theme i am getting a error "This theme is missing a 'content' region.".please have a look on screen attached(designed by manoj kumar).any help would be appricated.

# Answer
Looks like you need to indent your region names 2 spaces. See https://www.drupal.org/node/2349827 for more information on defining a theme with an .info.yml file.

Also the link in your description is missing a closing tag.

You should also be quoting some of your strings. There is a link on the page above to read the quick introduction to the YAML file format that takes you to http://symfony.com/doc/current/components/yaml/yaml\_format.html . That page provides good information on quoting strings.
> 2 votes

# Answer
**Indentation is very important here.**
After **regions** make sure you have spaces before **branding** and the other lines

```
regions:
  branding: 'Branding'
  navigation: 'Main navigation'
  search: 'Search'
  featured: 'Featured'
  content: 'Content'
  right_sidebar: 'Right sidebar'
  footer_first: 'Footer First'
  footer_second: 'Footer Second'
  footer_third: 'Footer Third'
  footer_bottom: 'Footer Bottom'

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to get contextual filter in hook_views_query_alter or hook_views_pre_execute?
I want to alter contextual filter before executing the sql query of views. Is there any way to get current contextual filter in hook\_views\_query\_alter or hook\_views\_pre\_execute? Or which is the better hook to alter contextual filter for views?

# Answer
> 12 votes
The contextual filters are in $view-\>args.

$view-\>args is an array of arguments (contextual filters).

So you can do things like this:

```
/**
 * Implements hook_views_pre_execute().
 */
function MODULENAME_views_pre_execute(&$view) {
  // Set the first contextual filter value.
  $view->args[0] = 1;
}

```

# Answer
> 3 votes
Using hook\_views\_pre\_view() may be more reliable than hook\_views\_pre\_execute(). Based on https://www.drupal.org/node/2438623, hook\_views\_pre\_execute() is too late in the query build processs. In contrast, https://codedrop.com.au/blog/programatically-altering-contextual-filters-views-drupal-7 provides an example of hook\_views\_pre\_view().

For my own situation, the below code works:

```
/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYNAME') {
    $url = arg();
    if (isset($url[1])) {
      // YOU MIGHT HAVE TO ADJUST $url[1] TO MATCH YOUR URL ALIAS.
      if ($normal_path = drupal_get_normal_path($url[1])) {
        $path_args = explode('/', $normal_path);
      }
    }
    if (isset($path_args[1])) {
      $view->args[0] = $path_args[1];
    }
  }
}

```

# Answer
> 0 votes
I think the best option is use ***hook\_views\_pre\_execute***

Below I share a code that alters the contextual filter by a field that comes from a node:

```
function hooks_views_pre_build(\Drupal\views\ViewExecutable $view) {
  // Get the node entity by the URL parameter
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($view->id() == 'ViewName' && $view->getDisplay()->display['id'] == 'DisplayName') {
    $filterValue = $node->get('field')->first()->get('entity')->getTarget()->getValue();
    $view->args[0] = $filterValue;
  }
}

```

And that's it!

---
Tags: views
---


# Question
Title: View of Node revisions exclude first revision of each node
I have a view of Node revisions. I want to only show revisions that are edits. I want to exclude the first revision of each node.

I think filtering for created \<\> changed would work, but I could find a filter in views, or a contrib module that does this.

Is there a way to do this without writing a custom view filter plugin?

# Answer
> 2 votes
> Is there a way to do this without writing a custom view filter plugin?

I'm afraid not.

> I am only looking to exclude the first revision.

mymodule/**mymodule.module**

```
<?php

/**
 * Implements hook_views_data().
 */
function mymodule_views_data() {
  $data = [];

  $data['node_revision']['exclude_first_node_revision_filter'] = [
    'title' => t('Exclude first node revision'),
    'help' => t('Excludes the first node revision.'),
    'filter' => ['id' => 'exclude_first_node_revision_filter'],
  ];

  return $data;
}

```

mymodule/src/Plugin/views/filter/**ExcludeFirstNodeRevisionFilter.php**

```
<?php

namespace Drupal\mymodule\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\views\ViewExecutable;

/**
 * @ViewsFilter("exclude_first_node_revision_filter")
 */
class ExcludeFirstNodeRevisionFilter extends FilterPluginBase {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

    $this->valueTitle = t('Exclude first node revision');
    $this->definition['options callback'] = [$this, 'generateOptions'];
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    $this->ensureMyTable();

    // Exclude the first revision of each node.
    $this->query->addWhereExpression($this->options['group'], "node_revision.vid <> (SELECT MIN(vid) FROM {node_field_revision} WHERE nid = node_revision.nid)");
  }

  /**
   * {@inheritdoc}
   */
  public function adminSummary() {
  }

  /**
   * {@inheritdoc}
   */
  protected function operatorForm(&$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function canExpose() {
    return FALSE;
  }

}

```

---
Tags: views, 9
---


title: How do you access user profile fields?

text:
# Question
Title: How do you access user profile fields?
In D7, using profile2 module, you would load the entity\_metadata\_wrapper from user object then access profile fields as such: $userWrapper-\>profile\_XXX-\>field\_XXX

Given that Profile2 is replaced by Profile module in Drupal 8, what is the Drupal 8's equivalent of accessing profile module's fields from a user object?

# Answer
Profile module add a base field to the user entity for every profile type. so it's quite easy to get all the referenced profiles then access any field you want :

```
$profiles = $user->get($profile_type_id . '_profiles)->referencedEntities();

```

if you want the first profile.

```
$profile = $user->get($profile_type_id . '_profiles)->entity;

```
> 2 votes

# Answer
This is late, but other people will come here (just like I did).

I had to go into the profile module source code to find this, but I guess it's obvious when you think about it:

```
$list = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->loadByProperties([
    'uid' => $account->id(),
    'type' => 'profile_type',
  ]);

```

You'll probably want to wrap it up in a service - and if you don't, you should take a long hard look at yourself as to why not :-)
> 5 votes

# Answer
Profile storage offers a helper method to load a profile by user.

```
$profile = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->loadByUser($account, 'profile_type');

```
> 2 votes

# Answer
You can access the value of profile field values as below

```
$user = \Drupal\user\Entity\User::load(2);
$test1_value = $user->field_profile->entity->field_test1->value;

```

Before that make sure there is value in the user data
> 0 votes

---
Tags: 8, users
---


# Question
Title: Initial server response time for different cached pages
I have been trying to speed up a Drupal site and measuring speed through page speed insight. What really has puzzled me for last few weeks of experiments is that node pages score an average of 170-200ms on 'initial server response time' while taxonomy pages (which are far more important from SEO speed point of time) take an average of 720-750ms in terms of initial page response time.

(Drupal 7, Nginx, Php-fpm, large site with over 100K nodes).

These are all cached pages (tried both Database and Memcache) using Page cache for anonymous users. Why is it taking 4 times more longer for Drupal to serve cached HTML of a term page versus cached HTML of a node page?

I am really stumped. Only time this changes is when I restart the Php-fpm. For a few minutes, term pages are close to 300ms before going back to 700+ms in few minutes.

Any ideas on what could be causing this? Could it be a php configuration issue?

# Answer
Finally got it to work.

Mistake I made was following.

While setting Cache for views, in the block setting page, I had selected 'Cache for every page'. This was generating and saving a copy of cache for lots of utm parameters/tracking variables and filled up Memcache instance.

Due to amount of views present on term pages, it was slowly them down.
> 1 votes

---
Tags: 7
---


# Question
Title: Inserting <span> tags into plain text fields
I've been given a content type with content already populated.

There are a number of headings/title fields in the content type and I have been asked to style a sub-section of those fields.

ie:

```
<h1>Title for your local service is styled</h1>

```

has to become:

```
<h1>Title for your <span class="myclass">local service</span> is styled</h1>

```

or something like that.

Is there a way to insert span tags like this into plain text fields? Maybe with a token?

I would like to avoid changing all such fields to formated text fields if possible. Not to mention I've been asked to do this for the node Title which I don't think I can recreate in such a way.

I can add the span to the WYSIWYG editor but would like someway to do this in the plain text fields.

# Answer
> 1 votes
If you add a span tag to a plain text field, it will be output as text, not a tag-- that's why it's a "plain text" field.

If you want your text to be formatted, use a formatted text field.

If the requirements have changed and a field which used to contain plain text now needs to have HTML tags, the field type needs to change, too.

## Handling the title

For the node title, there may be some hacky way to add the tags, but I would not try that. Instead, add another field such as **Formatted page title** to the content type(s) and then put the formatted title there.

The **Title** is also to print the `<title>` of the page, which does not support HTML tags, and having metatags there will also mess up Metatags and other modules using such info. So if you want a formatted title, that is best as a separate field.

---
Tags: 9, wysiwyg
---


# Question
Title: Programatically sort a merged view by a row value
I am using the following `hook_views_pre_render` to merge 2 views\_data\_export views.

```
function hook_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'commerce_orders' && $view->current_display == 'data_export_1') {
    $first_extra_results_view = Views::getView('commerce_orders');
    $first_extra_results_view->setDisplay('data_export_2');
    $first_extra_results_view->execute();
    $first_extra_results_view->result;
    $view->result = array_merge($view->result, $first_extra_results_view->result);

  }
}

```

Both of the views are sorted by order\_number, but array\_merge is just stacking them on one another (as expected).

```
$view order_1
$view order_2
$first_extra_results_view order_1
$first_extra_results_view order_2

```

I would like to know how to take the new `$view->result` and re-apply the sort criteria so that the output of the `$view->result` would be this:

```
$view order_1
$first_extra_results_view order_1
$view order_2
$first_extra_results_view order_2

```

I am able to get the order number for each result, but I don't know how to sort the view results by those order numbers:

```
foreach ($results as $key => $value) {
  $order_number = $value->commerce_order_order_number;
}

```

# Answer
I was able to work this out quite simply. I put the `array_merge()` into a `$results` variable:

```
$results = array_merge($view->result, $first_extra_results_view->result);

```

To get the `$order_number` for each of the `$results`, I used array\_column():

```
$order_number = array_column($results, 'commerce_order_order_number');

```

Then to sort the `$results` by `$order_number` I used array\_multisort().:

```
array_multisort($order_number, SORT_DESC, $results);

```

I did also have to re-sort the entire array for some reason, but all in all this is what I came up with:

```
function hook_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'commerce_orders' && $view->current_display == 'data_export_1') {
    $first_extra_results_view = Views::getView('commerce_orders');
    $first_extra_results_view->setDisplay('data_export_2');
    $first_extra_results_view->execute();
    $first_extra_results_view->result;
    $results = array_merge($view->result, $first_extra_results_view->result);

    // Sort the rows by order number.
    $order_number = array_column($results, 'commerce_order_order_number');
    array_multisort($order_number, SORT_DESC, $results);

    // Sort the rows so that shipping items are back on the bottom.
    krsort($results);
    $view->result = $results;
  }
}

```
> 1 votes

---
Tags: views, 9
---


# Question
Title: How can we limit the end date selection to +90 days from now on core Date Range widget?
We're using Drupal 9's core Date Range module and need to limit the end date selection to no more than 90 days from today.

I've searched far and wide and have not come up with a workable solution. Seems like it should be simple but I'm stumped.

# Answer
> 0 votes
Solved it with hook\_form\_alter():

```
 $limit = date("Y-m-d", strtotime("+" . 90 . " day"));
 $form['field_job_posting_date']['widget'][0]['end_value']['#attributes']['max'] = $limit;

```

---
Tags: entities, 9
---


# Question
Title: How can I get the URL to the public files directory?
I can get the *path* to the public files directory by using `Filesystem::realpath`:

```
$path = $filesystem->realpath('public://');

```

But how can I get the URL of `public://`?

# Answer
```
$my_path = file_create_url("public://");

```

Will definately work, however it's not coming from a service. Let me investigate more on this!

**Okey I found it!** This is how file\_create\_url works:

And this is the corresponding line specific to "public://" resolving (if you are sure you are trying to resolve a "public://..." uri):

```
  if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

```

Which means you will have to use StreamWrapperManager service, and after calling the getViaUri, you will able to get the external url. So this is **service based solution**!
> 14 votes

# Answer
After Drupal 9.3.3, you can do this with the `field_url_generator` service.

```
$url = \Drupal::service('file_url_generator')->generate('public://basename.ext');

```

This returns a path to the file like `/sites/default/files/basename.ext`.
> 2 votes

# Answer
Another way to achieve it.

```
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme(file_default_scheme());
return $wrapper::baseUrl();

```

will return DOMAIN/sites/default/files for my case. For 'public', $wrapper belongs to class "PublicStream", you can check other methods inside.

I've added it because this works for me:

```
$my_path = file_create_url("public://");

```

But this not work:

```
if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

```

in my project, it returns "public://".

Maybe it's related to update of Drupal Core or some settings. Unfortunately, it's not easy to find the root cause. I hope this information will be helpful for somebody.
> 0 votes

# Answer
I was having -

```
public://2019-03/YxoEy6.png

```

and I got the image by -

```
<img class="item-logo" src="{{file_url(restricted_item.logo_name.logo )}}" alt="logo" />

```
> 0 votes

# Answer
**Drupal 9 and 10**

Use the `FileUrlGenerator` service:

```
$urlEntity = \Drupal::service('file_url_generator')->generate($file->getFileUri())
$url = $urlEntity->toString();

// or

$url = \Drupal::service('file_url_generator')->generateString($file->getFileUri())

```
> 0 votes

---
Tags: 8, uri, files
---


# Question
Title: Modules are not updating to the latest version
I have some websites in the drupal. I need to update the security modules in the old version to the latest version. The list of security modules I tried to attempt is as below

1)colorbox (current - v2.15, updated version - v2.17)

2)colorbox\_node (current - v3.5, updated version - v3.8)

3)link (current - not sure, updated v1.11)

4)wysiwyg (current - v2.6, updated v2.9)

currently using **drupal **v7.78****

For the site1 I have tried to update all the 4 modules. but it only updated the colorbox(v2.17), link(v2.9) and the colorbox\_node(v3.5) and wysiwyg(v2.6) modules versions are not updated and remains at the same version

For site2 I have tried to update colorbox and colorbox\_module but it only updated the colorbox\_node(v3.8) and colorbox stayed at the same version(v2.15)

For the site3 I have tried to update all 4 modules and it updates only colorbox\_module(v3.8) and link(v1.11). colorbox(v2.5) and wysiwyg(v2.6) modules stayed at the same version

I have replaced the new module files directly into the module folder in the server(/home/centos/public\_html/site-x/sites/all/modules) ad then restarted the webserver(I found some other ways like updating via the admin interface, FTP but at the end, modules are only replaced in the server. So as an admin I directly replaced in the server)

Then tried the below steps to resolve the issue

* Applied 'flush all caches' in admin user
* Cleared all cached via 'configuration-\>developement-\>performance-\>clear all caches'
* Loaded with update.php (site/update.php) and updated from there(but here the modules are not showing as upgradable. only 'link' module is appeared and updated that module from update.php)
* Redeployed in the server many times
* Checked the module info file and verified that whether the replaced versions are correct

Note: Before attempting on the server, I tested locally, and all modules were properly updated, without any issues. But when updated in the live it is not updating. So in my perspective, I dont think it is a compatibility issue.

Any suggestions and troubleshooting are greatly appreciated; please guide me if I was incorrect in any of the above ways. If anyone needs more info please post in the comment. Honestly I dont know which tag to use for this question please feel free to edit if you want. Thanks for your support.

# Answer
> 0 votes
I have fixed the issue by following the below troubleshoots

* Before replacing the modules What I have done is, rename the module files like module-bkp in the same path(sites/all/modules/)
* So the site has taken the old file with the backup name(module-bkp)
* I have checked the 'system' table of the all the above sites which store the information about the modules
* There I found that all the modules are configured with the old file name(modules-bkp) which are renamed in the same path
* So I just moved the old module files to the other path. Then restarted the web server and cleared the cache in the admin panel

Now all the modules are updated to the latest version

---
Tags: views, updating, security
---