title: Set local actions - disabled/inactive

text:
# Question
Title: Set local actions - disabled/inactive
I am currently searching for a possibility to set an action to "inactive" depending on *something*. I have found the `hook_menu_local_actions_alter(&$local_actions)`, but do not know how I could use it to set a task to disabled/inactive.

What I have tried for now is:

```
function my_module_menu_local_actions_alter(&$local_actions) {
  $local_actions['entity.my_module.add_form']['options']['attributes']['disabled'] = 'disabled';
}

```

This adds `disabled="disabled"` to the action html element, but the element is not disabled.

I have posted a Workaround: https://drupal.stackexchange.com/a/303740/9586

# Answer
This is not the perfect solution, but since I did not found another way to solve this I did the following:

```
function my_module_menu_local_actions_alter(&$local_actions) {
    $local_actions['entity.my_module.add_form']['options']['attributes']['class'] = ['is-disabled'];
    $local_actions['entity.my_module.add_form']['route_name'] = 'entity.my_module.collection';
}

```

What I did here is that I added a class to the action item which shows it as disabled. Just by doing this does not disable it, but just adds a "grey" style.

In addition to that I have overwritten the route to point to the same route as the action is shown on so that the user just gets redirected to the same url as he/she has been on before.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Purpose of "views_date_format_sql" module
i got back a projet which is using the module views\_date\_format\_sql. This module is not compatible with D9, so I'm trying to find a replacement

But I don't get what this module is supposed to do. If I disable it, it doing a cascade of disabling config views/node etc...

Can anyone tell me what's the purpose of this plugin ?

# Answer
From the Views Date Format SQL project page:

> **The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.**
>
> **The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date.** This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's built in views\_handler\_field\_date.

After a review of the module, you'll see that this new default handler is "views\_date\_format\_sql\_field".

As far as how this is being used on your site, you'll need to figure that out for yourself. I'd start by reviewing the views that get disabled when you would uninstall the module - check for any timestamp fields, e.g. 'created' or 'changed'. The fastest way might be to scan the config files for "views\_date\_format\_sql\_field", the new default handler the module adds. Once you know where the module is being used, you can determine what effect removing it would have.

---

Alternatively, it may be simpler to make the module D9 compatible. Many Drupal 8 modules are Drupal 9 compatible after a simple change to their .info.yml file - replacing `core: 8.x` with `core_version_requirement: ^8 || ^9`.
> 0 votes

---
Tags: 9, plugins
---


title: How can I send HTML newsletters?

text:
# Question
Title: How can I send HTML newsletters?
I have developed websites using Drupal since 1998. Getting Simplenews to send HTML formatted emails in D8 has been the most frustrating experience I've had in all those years. I am very upset. I find the current state of D8 documentation to be quite shoddy overall, not just Simplenews. Here's a glaring example of what I'm talking about: I'm building a D8 site using D8 modules. I go to the README file in the simplenews directory and I'm reading all about how.

> You can customize the theming of newsletters. Copy any of the \*.tpl.php files from the simplenews module directory to your theme directory. Both general and by-newsletter theming can be performed. Theme newsletter body:
>
> * simplenews-newsletter-body.tpl.php (for all newsletters)
> * simplenews-newsletter-body--\[newsletter\_id\].tpl.php
> * simplenews-newsletter-body--\[view mode\].tpl.php
> * simplenews-newsletter-body--\[newsletter\_id\]--\[view mode\].tpl.php

Here's some news for the module developers: None of that exists in the D8 module! WTF, really? These are D7 instructions. Not very helpful esp since that README file contains some of the most complete and detailed instructions on this aspect of simplenews-- if you're using the D7 version, that is..

I have spent an all-nighter and several full days on configuring this. I'm using sipmplenews Version: 8.x-1.0-alpha2, mailsystem Version: 8.x-4.1, mimemail Version: 8.x-1.x-dev and smtp Version: 8.x-1.0-beta2. No matter what recipe I follow from the myriad of posts on this subject, this is what my HTML email messages look like when they arrive in my inbox: HTML tags visible and absolutely no formatting.

```
<h2>Testing 1234</h2> <span>Testing 1234</span> <div><div style="background: rgb(51, 102, 0) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"> <div style="color: #fff; text-align: center;">View this message in your browser <a href="http://example.com/phpList/archive/FTS-10-16-2016.htm" style="color: #fff;">HERE</a>.</div> <table border="1px solid" cellpadding="2" cellspacing="2" style="border-collapse: collapse; background-color: rgb(255, 255, 204); width: 75%; text-align: left; margin-left: auto; margin-right: auto; padding-top: 15px;"><tbody><tr><td style="background-image: url(http://example.com/sites/default/files/images/PosterBackground-web.jpg); width: 50%;"> <div style="text-align: center;"> <p><img src="http://example.com/sites/default/files/images/new-fot-logo-270-2.png" style="width: 85%; height: auto;" /></p> </div> </td> <td colspan="2"> <div style="float: right;"> <p><img alt="Skeeter Photo" src="http://example.com/sites/default/files/images/skeeter.image_.jpg" style="border: 1px solid ; margin: 4px; width: 50%; height: auto;" /><br /><small><small><b><small><small> MICHAEL “SKEETER” PILARSKI </small></small></b> </small></small></p> </div> <p> <a href="http://www.example.com"><img alt="Friends of the Trees Masthead" src="example.com/sites/default/files/images/top-fts.jpg" style="width: 100%` ...

```

If anyone has this working or if there is a sympathetic developer out there, hear my plea: Someone please create a step-by-step basic simplenews configuration that anyone can follow to get simplenews to successfully send HTML formatted emails from a D8 website. If it was a configuration that was just enough to get it to work (with a designated theme and any other variables set), user customization could follow once a successful email has been sent This whole thing has worn me out.

# Answer
Outdated documentation is one of the reasons why Simplenews is only in Alpha. Sorry you had a frustrating experience, but a lot of work of porting modules and writing documentation is done in (my) free time. It is one of the *many* contrib modules that I help maintain.

You're more than welcome to help improving the module and documention so the next person will be able to figure this out faster. Patches or simply by writing documentation on drupal.org.

The template extension is now .html.twig, which you should quickly see in the templates folder of the module.

Also, the very first paragraph on the project page contains this:

> Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module for D7 and **Swiftmailer for D8**.

Swiftmailer requires a composer dependency and is a bit more complicated to install due to that, but it is what we've been using in our projects and should work well.

Also, make sure you enable HTML in the newsletter settings. And possibly try the latest dev versions if you have problems.
> 6 votes

# Answer
Yes. Need to improve the module & Documentation. For HTML, Actually Simplenews module depends Swiftmailer and swiftmailer requires mailsystem module.
> -1 votes

---
Tags: 8, emails
---


# Question
Title: Pass current langage to twig on custom blocks
my custom module block, with supposely no cache

```
<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  /**
   * @return int
   */
  public function getCacheMaxAge() {
    return 0;
  }
}

```

the language context i am trying to add on internal urls

```
<ul class="social-icon menu socialicon-nav">
      {{ dump(language) }}
  {% for icon in icons %}
    {% if icon.url is not empty %}
          {% if icon.url starts with '/' %}
                <li><a href="/{{ language }}{{ icon.url }}" aria-label="{{ icon.aria_label }}"><i aria-hidden="true" class="{{ icon.icon }}"></i></a></li>
          {% else %}
                   <li><a href="{{ icon.url }}" aria-label="{{ icon.aria_label }}"><i aria-hidden="true" class="{{ icon.icon }}"></i></a></li>
    {% endif %}
      {% endif %}
  {% endfor %}
</ul>

```

i understood the variable passed by hook\_theme are static so i have tried to override it on preprocess block

```
function amu_social_icon_theme($existing, $type, $theme, $path) {
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'language' => \Drupal::languageManager()->getCurrentLanguage()->getId()
      ],
    ],
  ];
}

function amu_social_icon_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'amu_social_icon_block') {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vars['language'] = $language;
  }
}

```

None of these works. I need to empty drupal cache so that

> {{ dump(language) }}

display the correct current language

# Answer
> 0 votes
a default value seems to be needed in hook\_theme

```
 */
function amu_social_icon_theme($existing, $type, $theme, $path) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'lang' => $language,
      ],
    ],
  ];
}

```

as well as a #cache entry in the block build method

```
<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#lang' => $language,
      '#cache' => [
        'max-age' => 0,
      ],
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  public function getCacheMaxAge() {
    return 0;
  }
}

```

# Answer
> 3 votes
> I understood the variable passed by hook\_theme are static

Yes, you can consider default values defined in hook\_theme as static, they are set when you install the module. To help developers clearing the cache also clears most things which are installed by modules, so that you don't need to re-install the module all the time, but this has nothing to do with render caching.

`language` is a variable of your custom theme, not of the block. Then you don't need a preprocess hook, you can add it directly to the block build containing this template:

```
  public function build() {
    return [
      '#theme' => 'amu_social_icon_block',
      '#language' => $language,

```

Caching of the current language works out-of-the-box. This is one of the three default contexts. However, you can't debug caching by debug output. Most times you have a cache hit, serving the content from cache, without running the code building the content.

---
Tags: theming
---


# Question
Title: How can I add a node template suggestion by node title?
Twig debugging is suggesting *node--4.html.twig* as template file for a node whose ID is 4. Since the node ID changes when changing environment, I would need to use a template file whose name is based on the node title.

Is there a straightforward way to achieve this?

I am using Drupal 9.

# Answer
> 3 votes
Following MrD's comment, hook\_theme\_suggestions\_hook\_alter is the key (see documentation about this hook) or hook\_theme\_suggestions\_alter() if you wish to add suggestions to several entity types.

It will allow you to add the template suggestions you are missing.

```
function yourTheme_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  // Use $variables variable to get data related to your node
  // e.g. $node = $variables["elements"]["#node"] to get your Node object

  // Use $suggestions array variable to add your custom suggestion(s) to the list
  // e.g. $suggestions[] = "node__" . "myawesomesuggestion";
}

```

Then, add your template file node--myawesomesuggestion.html.twig to your theme and you should be done with it.

# Answer
> 0 votes
The Node module doesn't add template suggestions that include the node title, in `node_theme_suggestions_node()`. Modules and themes can alter the existing suggestions implementing hook\_theme\_suggestions\_HOOK\_alter().
A point to keep in mind is that the suggested template name should only contain characters allowed in a PHP function name.

For the node title, I would use the following code.

```
function mymodule_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node_title = \Drupal::transliteration()->transliterate($variables['elements']['#node']->getTitle());
  $suggestions[] = 'node__' . preg_replace('/[^a-z0-9_]+/', '_', mb_strtolower($node_title));
}

```

The code to replace characters that shouldn't be in a PHP function name is the same used from `media_theme_suggestions_media()` for `$provider_id`.

---
Tags: nodes
---


# Question
Title: Notice: Undefined index: provider in *_preprocess_block()
I am in the process of upgrading a site to Drupal 9. I finally have 9.2.0 in place, but I started seeing a very large number of notices, that all fit the pattern:

> Notice: Undefined index: provider in block\_theme\_suggestions\_block() (line 203 of core/modules/block/block.module).

This isn't limited to just the block module, it seems to generate a notice in every implementation of `hook_preprocess_block()` (which is a lot).

It very well may be one of the custom blocks on this site, but I've compared those to the D9 documentation, and I don't see anything amiss. I've also tried clearing the twig cache.

Update: I dropped a breakpoint in the spot where the error. The element in the variables array. The #plugin\_id value is just "broken" and the content is a TranslatableMarkup with the value "This block is broken or missing. You may be missing content or you might need to enable the original module."

So I'm going to try the advice in How to fix a broken or missing block?

# Answer
> 8 votes
I figured it out. I was using the twig\_tweak module, and using `drupal_block()` to place blocks in templates manually. As a part of the updateto the twig\_tweak module, you need to replace those with calls to `drupal_entity()`.

So for example, if you called:

`drupal_block('footer_meta_menu')`

Then that becomes:

`drupal_entity('block', 'footer_meta_menu')`

Additionally, a common technique in Drupal 8 was to place blocks in the disabled region, which allowed you to render them in templates. If that is what you are doing then you need to pass an additional parameter for access, e.g.

`drupal_entity('block', 'footer_meta_menu', check_access=false)`

I thought I had gotten them all, but I overlooked one, which was only visible in a popover element, and not readily on page load.

---
Tags: 9
---


# Question
Title: Using template variations from the modules folder
I have the usual theming solution for a custom entity:

```
function module_theme($existing, $type, $theme, $path) {
  return [
    'customentity' => [
      'render element' => 'elements',
      'template' => 'customentity',
    ],
  ];
}

function template_preprocess_customentity(array &$variables) {
  $variables['content'] = [];
  ...
}

function module_theme_suggestions_customentity_alter(array &$suggestions, array $variables) {
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  $suggestions[] = 'customentity__' . $sanitized_view_mode;
}

```

The only problem is that when I want to use a twig specific to the view mode, `customentity--viewmode.html.twig`, it only works if the twig file is inside the theme. If it's in the module `templates` folder, it isn't picked up (carefully checked all cases with twig debugging).

So, in this regard, it's functioning. Still, I'd need the twig in the module itself because in this case, it's not a mere theming question, the view mode is both logically and programmatically a radically different way to present the contents. It's for internal use, not a contrib module, so normal user expectations don't apply.

# Answer
> 2 votes
You have to add the path to your theme hook like so:

```
'my_entity__mailteaser' => [
        'render element' => 'elements',
        'base hook' => 'my_entity',
        'template' => 'my-entity--mailteaser',
        'path' => drupal_get_path('module', 'asdentbase') . '/templates',
      ],

```

---
Tags: theming
---


# Question
Title: When updating or creating a node of a specific type, I want to save a PDF version into files
I have a node of a particular type that I would like to save as a pdf file (using Entity\_print) upon creation or update (whenever a content is saved). The issue I am running into is that some of the variable data used in the template is determined in the preprocessor but the preprocessor has not yet been run at the time. I have a PDF view mode and corresponding templates. When I enter something similar to http://example.com/print/pdf/\[entity\_type\]/\[entity\_id\] I get exactly what I want but that's just at run time. I need this setup 'behind the scenes' and saved into the files. I can generate the pdf file but it is missing the preprocessed variable data. Is the only way to get variable data into twig via preprocessor? Is there a hook that will do this? I have played with a few of them but none seem to be able to capture the variables for the twig templates. By the way I do not want to override the regular preprocessor theme which will be used for page rendering.

# Answer
> 1 votes
I had exactly the same problem. I tried the following simple solution but as it's an intranet with content not available to anonymous users it doesn't work:

```
$url = "https://{$_SERVER['HTTP_HOST']}/print/pdf/node/" . $node->id();
$pdf_data = file_get_contents($url);
$file = file_save_data($pdf_data, 'private://' . $filename) ;
$node->field_pdf_document->setValue($file);

```

So I came up with this function, which will return a File object:

```
function mymodule_entity_print_saver($nid, $filename, $scheme = 'private') {
  $pb = new Drupal\entity_print\PrintBuilder(
    \Drupal::service('entity_print.renderer_factory'),
    \Drupal::service('event_dispatcher'),
    \Drupal::service('string_translation')
  );

  $node = Drupal\node\Entity\Node::load($nid);
  $path = $pb->savePrintable(
    [$node],
    \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf'),
    $scheme,
    $filename
  );

  $file = File::create([
      'uri' => $path,
      'uid' => \Drupal::currentUser()->id(),
      'status' => FILE_STATUS_PERMANENT,
    ]);
  $file->save();
  return $file;
}

```

You could play around with the exists/replace constant as well if needs be.

---
Tags: 8, nodes
---


# Question
Title: how to get webform title and category with no submissions in view or hook?
I have a survey form created with webform module.i have to display all survey form title with submissions and without submissions with webform category on home page.but it displaying only submitted survey forms title.how can i display webform title with zero submission in drupal8?

# Answer
> 0 votes
use below code as a function in your module file and call it on your custom block.

```
  function module_name_webformtitle(){
    $query = Drupal::service('entity.query')->get('webform');
    $query->condition('category', 'survey_name');//your survey name
    $entity_ids = $query->execute();
    $webform_id=array();
     foreach($entity_ids as $webid){
       $webform_id[]=$webid;
     }
    $webform = Webform::loadMultiple($webform_id);
     foreach($webform as $webforms){
        $webformtitle=$webforms->get('title');
    }
  }

```

# Answer
> 3 votes
```
$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('my_form');
$title = $webform->label();

```

---
Tags: webforms
---


# Question
Title: MInified CSS file isn't loaded on a page where I have a webform with the "file upload" component
I added a webform with the *Upload file* component on a page.
When I visit that page without minifying CSS files, everything works fine; when CSS files are minified, this page doesn't load them, the page seems a WSOD. The other pages work fine.

When I remove the *Upload file* component, everything works fine.

# Answer
> 1 votes
I've run into a similar situation (though I can't remember if it was for all pages or a subset of pages). For me, the issue was with one css include in my custom theme. (I think my issue might have been that the css file was a mix of minified and unminified css - I don't know why that was the case - but I never got to the bottom of it.)

My workaround solution was to prevent the one css file from being aggregated. To do this, you can set `preprocess: false` for the css file. See the Library options and details documentation on d.o.

My library ended up looking something like:

```
my_library:
  css:
    theme:
      assets/css/app.css: { preprocess: false }
      assets/css/theme.css: { }
  js:
    'assets/js/app.js': { }
    'assets/js/theme.js': { }
  dependencies:
    - core/jquery

```

which allows all of my theme's files to be aggregated except for app.css.

---

To debug this issue, I did roughly the following:

1. Tested with a different theme, e.g. bartik or your base theme (to determine where the issue is)
2. Once I verified that my theme was the issue, I first excluded all items from aggregation (using `preprocess: false`).
3. Once I verified that pages loaded fine with none of my theme's files aggregated, I re-enabled aggregation for them one by one.

---
Tags: 8
---


# Question
Title: Adding select list to tableselect output
I'm trying to add a select-list to some table output but the markup is rendering as text.

```
$header = [
  'col1' => t('COL1'),
  'col2' => t('COL2'),
];
$rows = [
  1 => [
    'col1'  =>  'row-1-cell-1',
    'col2'  =>  'row-1-cell-2',
  ],
  ['col1' => 'test'],
  ['col2' => 'test'],
  ['col1' => 'test'],
  2 => [
    'col1'  =>  'row-2-cell-1',
    'col2'  =>  $form['example_select'] = [
                  '#type' => 'select',
                  '#title' => $this->t('Select element'),
                  '#options' => [
                    '1' => $this->t('One'),
                    '2' => $this->t('Two'),
                    '3' => $this->t('Three'),
                  ],
                ]
  ],
];
$form['test'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
];

```

I have been experiementing with the code above in the `buildForm(array $form, FormStateInterface $form_state)` function of my controller class. The class renders a form for some custom configuration in the administration area.

Can anyone please help me understand what I need to do so my select list renders as markup instead of text ?

# Answer
> 1 votes
Some general advice: Don't assign numeric keys like 1 and 2 to your rows - let PHP generate the keys. Or, if you really need to set your own keys, then use string keys and give EVERY row a key. What you show above has the first row numbered 1, then the second, third and fourth row don't have keys (so PHP will assign them sequentially 2, 3, 4), then you give the fifth row the key 2 which overwrites the second row (which had an automatically-generated key of 2) - thus you end up with four rows even though you wanted five. Assigning row keys consistently from the beginning will avoid problems like this.

Likewise, when you do something like this:

```
'col2'  =>  $form['example_select'] = [ ... ]

```

you are adding a new form element to the form in TWO places - once in the table and once outside the table. If that is what you intend, then declare the form element outside the table first and just use the variable inside the table.

Anyway, the following will do what you want:

```
$header = [
  'col1' => $this->t('COL1'),
  'col2' => $this->t('COL2'),
];
$rows = [];

$rows[] = [
  'col1' => 'row-1-cell-1',
  'col2' => 'row-1-cell-2',
];
$rows[] = [
  'col1' => 'row-2-cell-1',
  'col2' => ['data' => [
    '#type' => 'select',
    '#title' => $this->t('Select element'),
    '#options' => [
      '1' => $this->t('One'),
      '2' => $this->t('Two'),
      '3' => $this->t('Three'),
    ],
  ]],
];

$form['test'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
];

```

---
Tags: forms, 9, page-controller
---


# Question
Title: How to get Automation testing results of Drupal contributed module through Drupal.org rest API?
I am trying to get automated testing results of contributed modules through https://www.drupal.org/drupalorg/docs/apis/rest-and-other-apis.

I am able to get nid and vid of any contributed module through the node info API.

And I want to access DrupalCI jobs: pift\_ci\_job.json or pift\_ci\_job.xml

Which returns a specific job: https://www.drupal.org/api-d7/pift\_ci\_job/\[jobid\].json

But, there is nowhere mentioned of `jobid` required for getting the automation testing results, can anyone tell me if there is any way for getting `jobid` of a contributed module?

# Answer
> 1 votes
https://www.drupal.org/api-d7/pift\_ci\_job.json returns a list of all the DrupalCI tests, in the same way https://www.drupal.org/api-d7/node.json returns a list of all the nodes.

That's the only way to get a list of the tests associated to an issue because there isn't a comment/node field for tests, which would otherwise be returned in https://www.drupal.org/api-d7/node/3220733.json (the RESTWS URL for \[PHP8\] Tests are failing in PHP 8 / Drupal 9.2.x) or https://www.drupal.org/api-d7/comment/14145081.json (the RESTWS URL for comment #3 in that issue).

The information about tests shown in the attached file table is added by the Project issue file test in `pift_nodechanges_file_changes_element_alter()`.

You can filter the job list, though. For example, you could filter by:

---
Tags: 9, community-official-site
---


title: How to check if a path is for a view?

text:
# Question
Title: How to check if a path is for a view?
I have a list of paths and I would like to identify which ones are associated to view routes.

Is there any Drupal 8 method I can use? Do I need to get all the view routes and then check which ones are associated to the paths I have?

# Answer
I think the best way to do this is to use the router.route\_provider service. Specifically, you may want to use `RouteProvider::getRoutesByPattern()`. See the following code, adapted from code shown in joachim's comment in Get route name by path in Drupal 8.

```
function getViewPaths(array $paths_to_check = []): array {
  /** @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
  $route_provider = \Drupal::service('router.route_provider');

  $view_paths = [];
  foreach ($paths_to_check as $path) {
    $path_route_collection = $route_provider->getRoutesByPattern($path);
    foreach ($path_route_collection->all() as $route_name => $route) {
      if (strpos($route_name, 'view.') === 0) {
        $view_paths[] = $path;
      }
    }
  }

  return $view_paths;
}

$my_view_paths = getViewPaths([
  '/about',
  '/some/other/path',
  '/one-more-path',
]);

```
> 4 votes

# Answer
Supposing the list contains paths like /node/2, /user/1, or admin/content, and you need to get the route name for those paths handled by the Views module, you could use code similar to the following one.

```
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\Url;

function _view_routes(array $paths) {
  $view_routes = [];
  $path_validator = \Drupal::service('path.validator');

  foreach ($paths as $path) {
    $view_route = '';
    if ($url = $path_validator->getUrlIfValid($path)) {
      $route_name = $url->getRouteName();
      if (strpos($route_name, 'view.') === 0) {
        $view_route = $route_name;
      }
    }
    $view_routes[$path] = $view_route;
  }

  return $view_routes;
}

```

`PathValidator::getUrlIfValid()` returns a `Url` object if the path it gets as argument is valid and accessible from the currently logged-in user. To understand which paths are for pages handled by the Views module, independently from which users have access to that page, the code should be similar to the following one.

```
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;

function _view_routes(array $paths) {
  $view_routes = [];
  $router = \Drupal::service('router.no_access_checks');

  foreach ($paths as $path) {
    try {
      $match = $router->match($path);
    }
    catch (\Exception $e) {
      // The path isn't valid or the HTTP method to access the
      // path isn't allowed.
      $view_routes[$path] = '';
      continue;
    }

    $view_routes[$path] = (strpos($match['_route'], 'view.') === 0 ? $match['_route'] : '');
  }

  return $view_routes;
}

```
> 1 votes

---
Tags: 8, views
---


title: How to fix view with no ID

text:
# Question
Title: How to fix view with no ID
I get WSOD when I try to access the views page (admin/structure/views).

I get the notice below in the error log followed by the error.

```
Notice: Undefined index: id in Drupal\Core\Config\Entity\Query\Query->Drupal\Core\Config\Entity\Query\@closure() (line 92 of /home/pierost0/public_html/core/lib/Drupal/Core/Config/Entity/Query/Query.php).

Drupal\Core\Entity\EntityMalformedException: The "view" entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\Entity->toUrl() (line 189 of /home/pierost0/public_html/core/lib/Drupal/Core/Entity/Entity.php).

```

I have disabled all views through Drush but there's seems to be one empty view. Take notice on the screenshot. An empty view is enabled.

Is that view my problem? Where are the views files, or entries in the db so I can have a look for the solution there.

# Answer
I had this very issue.

It turned out to be a corrupt view configuration.

For me this was views.view.media\_entity\_browser

I only found this by deleting views one by one until the views listing page at /admin/structure/views started working again.

Not sure how or when the view got corrupted.
> 3 votes

# Answer
If you have access to the database check the table `config` for all entries starting with `views.view.*`
One of these entries might be empty or with a corrupt `uuid`. If so, take a backup of your database and try to manually delete this entry and see what happens.

---

Update According to coments below I suggest taking a database backup and then delete views one by one from the database until the error is gone
> -1 votes

---
Tags: views, 8
---


# Question
Title: How can I print the Layout builder in a node twig template?
After enabling Layout builder for Page content. I can see in Manage fields, a new field called layout\_builder\__layout. I want to print this inside node--page twig template. This should work but it does not. `{{ content.layout_builder__layout }}`. Printing all the content does display it like this `{{ content }}` How can I print only the layout builder?

# Answer
> 1 votes
`Layout builder` and `Manage fields` (moving fields inside Manage Display) are mutually exclusive, you use either the first or the second, you can not mix them. As soon as you activate Layout Builder for a node type, the entire Twig render array is only the Layout builder.

So just render `{{ content }}`, which renders its one and only child `{{ content._layout_builder }}`

---
Tags: 8, theming
---


# Question
Title: Why this code doesn't send an email with drupal_email()?
I am developing a Drupal 6 module that should send an email after a form is submitted. So far, I wrote the following code.

```
function mailform_mail($key, &$message, $params) {
  $headers = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
  );

  foreach ($headers as $key => $value) {
    $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

/**
 * Form submission handler.
 */
function mailform_form_submit($form, &$form_state) {
  $valid_email = $form_state['values']['email'];
  $subject = $form_state['values']['Subject'];
  $body = $form_state['values']['body'];
  $params = array(
    'email'=> $valid_email,
    'body' => $body,
    'subject' => $subject,
  );

 // The first argument of drupal_mail() function must match the first part of the hook_mail function.
 // Therefore the first argument is  'mailform_form' and the the mail hook is 'mailform_form_mail'
 // For more infoormation see:
 // - http://api.drupal.org/api/function/drupal_mail/6
 // - http://api.drupal.org/api/function/hook_mail/6
 if (drupal_mail('mailform','reply', $valid_email, language_default(), $params, $from, TRUE) {
    drupal_set_message('An email has been sent to ' . $valid_email);
  }
  else {
    drupal_set_message('There was an error sending your email');
  }
}

```

Using this code, I can get the values after a form is submitted, but the mail is not sent out.

Is there anything wrong with the code? The module machine name is *mailform*.

# Answer
> 0 votes
The answer's in your comments

```
//Therefore the first argument is  'mailform_form'

```

But you're using the string `mailform` as the first argument.

If your module is called `mailform_form` as your comments suggest, use this code:

```
drupal_mail('mailform_form','some_mail_key', $valid_email, language_default(), $params, $from, TRUE)

```

If it's named `mailform`, use your original call to `drupal_mail`, but change the name of your hook function to the correct one:

```
function mailform_mail($key, &$message, $params) {

```

# Answer
> 0 votes
The first argument of `drupal_mail()` is the module machine name, not the first part of the name for the function calling `drupal_mail()`.

Since in the shown code there is a `mailform_mail()` function (which a `hook_mail()` implementation) and a `mailform_form_submit()` function (which is a form submission handler), I take the module machine name is *mailform*. Therefore, those function names are correct, and the email isn't sent because other issues.
For example, `mailform_form_submit()` is called as form submission handler if the form has a submission module and the form builder is `mailform_form()`. Otherwise, the submission handler won't be called and the email won't be sent.

To verify which is the module machine name, look at the name of the file that has .module as extension.
If that file is mailform.module, the code is correct.
If that file is mailform\_form.module, the code needs to be changed, since:

* All the hook implementations for that module needs to have a name starting with *mailform\_form\_*. Instead of `mailform_mail()`, it must be `mailform_form_mail()`.
* `mailform_form()` as form builder should be avoided, as the function name would only contain the machine name. For example, I would call the form builder `mailform_send_form()` and the form submission handler `mailform_send_form_submit()`.
* The code sending the email should use `drupal_mail('mailform_form','reply', $valid_email, language_default(), $params)`. I omitted the last two parameters, as:

+ The default value of the last parameter is `TRUE`; it's useless to use that value
    + `$from` hasn't been initialized; it's like passing `NULL` for the sixth parameter, which uses that value as default one

---
Tags: 6, emails
---


# Question
Title: Is there a way to output the machine name of a taxonomy term?
I've been to figure out how I can output the machine-name of a taxonomy term on my entity field to my twig template. using `.label` prints out the name of the taxonomy term. `.id` get a numerical value, was actually hoping to get the machine term instead. Using `kint` I can't seem to find it

```
{% for themes in node.field_themes %}

        <span>{{ themes.entity.id }}</span>
{% endfor %}

```

# Answer
> I see, the output I'm looking for somewhat like the key value of a list field. For example *Taxonomy term* it becomes *taxonomy-term*

As discussed the correct way is

```
{{ themes.entity.label|lower|replace({' ':'-'}) }}

```

It's suitable for other entity types as well
> 3 votes

# Answer
I found this to work in the taxonomy term individual twig template: taxonomy-term.html.twig :

```
{% set term_machine_name = term.name.value|raw|lower|replace({' ':'-'})|replace({',':'-'}) %}

```

Then use `term_machine_name` as required.

If you are outputting the *Taxonomy term: Name* field in a View, I found this to work, in the rewrite results setting in the Views Display Config, when editing a View in the site's admin pages:

```
<a href="#{{ name |lower|replace({' ':'-'})|replace({',':'-'}) }}">{{ name__value }}</a>

```
> 3 votes

# Answer
Taxonomy terms are content entities, and don’t have machine names.

They have IDs, that’s how they’re generally identified.
> 1 votes

---
Tags: theming
---


# Question
Title: Restrict Menu Item Visibility by Permissions
I have a module-generated menu (using yaml file) with 5 menu items. My requirements don't allow me to restrict menu item visibility by role because roles can be dynamically added. So I have to do this using permissions only.

**What I've tried**
(1) Restricting menu item access using route permissions - this shows a page forbidden but still allows the restricted menu item to be visible

Please see my actual files below:

**portal\_hrm\_core.links.menu.yml**

```
portal_hrm_core.hrm_link:
  title: 'HR Manager'
  route_name: portal_hrm_core.hrm_link
  menu_name: hcm
  expanded: TRUE

```

**portal\_hrm\_core.routing.yml**

```
portal_hrm_core. hrm_link:
path: '/admin/hrm'
defaults:
  _controller: '\Drupal... systemAdminMenuBlockPage'
  _title: 'HRM'
requirements:
  _permission: 'access hrm_core_job+access_hrm_core_employee'

```

(2) Contrib modules - `Menu Item Visibility` and `Menu Item Per Role` Both of these are only role-based and can't support permissions

I know I can go really low-level and use something like `hook_preprocess_menu` but seems to heavy for such a simple requirement considering how many times that hook may be called.

So folks, please any further suggestions?

Thanks

# Answer
Works now. Thanks Hudri for pointing me in the right direction. I re-checked your suggestion about clearing the cache. In the process I discovered that the following line was commented out in my `lazyBuilder()` method (these menu items are in my toolbar and are generated in code)

```
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkAccess']
]

```

The absence of those lines were causing my menu to ignore access checks, apparently. Uncommenting them out solved the problem. Thanks.
> 0 votes

---
Tags: 8, navigation
---


title: Maestro workflow status block

text:
# Question
Title: Maestro workflow status block
After adding the Maestro status block to my homepage-content region, it doesn't display the status bar nor the status messages which were set in the workflow. It displays only the workflow title.

3 of my workflow Participate in Setting the Workflow Stage and Status Message yet it displays only the title of my maestro workflow.

I took time to inspect the "Maestro Insurance Site" a demo site created by nextide creators of Maestro to tales check out the html being displayed.

# Answer
The reason for status bar not showing is , maestro validation check throws an informative error: "The default number of stages you wish to show this workflow having" option is set to zero.

To solve this, select Edit Template button in the Template builder and set the value to the number of stages you would like to show, in my case it's 3

After update template and select validity check; error should be gone

status bar shows
> 0 votes

---
Tags: blocks, workflows
---


# Question
Title: Controller on /taxonomy/term/{taxonomy_term} route
I have a regular Controller on the taxonomy term page (the original view is disabled). It works all right to show what I want it to show, however, neither its `getTitle` nor its `access` is ever called (the second being more vexing, of course). The problem is not with my controller, because using a different route works just fine:

```
example.content.documents_list:
  path: '/taxonomy/term/{taxonomy_term}'
  defaults:
    _controller: '\Drupal\example\Controller\DocumentListController::content'
    _title_callback: '\Drupal\example\Controller\DocumentListController::getTitle'
  requirements:
    _custom_access: '\Drupal\example\Controller\DocumentListController::access'

example.content.documents_list2:
  path: '/xxx/{taxonomy_term}'
  defaults:
    _controller: '\Drupal\example\Controller\DocumentListController::content'
    _title_callback: '\Drupal\example\Controller\DocumentListController::getTitle'
  requirements:
    _custom_access: '\Drupal\example\Controller\DocumentListController::access'

```

I can create a `RouteSubscriber` if needed but is it really needed? Are those settings never really picked up?

# Answer
> 1 votes
It was partly my mistake, I did have a `RouteSubscriber` already in place but not fully engaged yet, as the comment of 4k4 pointed out. The final solution is: yes, it has to be overridden because it's a system route:

```
class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.taxonomy_term.canonical')) {
      $route->setDefault('_controller', 'Drupal\example\Controller\DocumentListController::content');
      $route->setDefault('_title_callback', 'Drupal\example\Controller\DocumentListController::getTitle');
      $route->setRequirement('_custom_access', 'Drupal\example\Controller\DocumentListController::access');
    }
  }

}

```

---
Tags: routes
---


# Question
Title: is it possible to deactive twig cache for a single theme custom template?
i am having a custom template for rendering a medialink url from a paragraph media entity ref field. In production with twig cache activated, modifiying the media attached file , does not update the content making reference to that media, unless the render cache is emptied.

paragraph--link-media.html.twig

```
{% set classes = [
  'paragraph',
  'paragraph-link-media',
] %}
{% set link_classes = [] %}
{% set aria_label = "" %}
{% set aria_describedby = "" %}
{% if content.field_aria_title|field_value %}
  {% set aria_label =  content.field_aria_title|field_value|render %}
{% endif %}
{% if content.field_link_description|field_value %}
  {% set aria_describedby = "link-description-"~paragraph.id() %}
{% endif %}
{% if content.field_link_style|field_value %}
  {% set link_classes = link_classes|merge(['cta-link']) %}
  {% set classes = classes|merge([content.field_link_style.0["#options"].entity.field_class_name.value]) %}
{% endif %}
{% if content.field_link_extra_styles|field_value %}
  {% for extra_style in content.field_link_extra_styles|field_value %}
    {% set classes = classes|merge([extra_style["#options"].entity.field_class_name.value]) %}
  {% endfor %}
{% endif %}
{% if content.field_link_fa_style|field_value %}
  {% set classes = classes|merge(['link-fa']) %}
{% endif %}
{% block paragraph %}
  {% block content %}
    {% if content.field_link_style|field_value %}
      {% if content.field_cta_align|field_value %}
        {% set class_cta_align = content.field_cta_align|field_value %}
      {% else %}
        {% set class_cta_align = "cta-center" %}
      {% endif %}
      <div class="{{ class_cta_align }}">
    {% endif %}
    <span{{ attributes.addClass(classes) }}>
      {% set attributes_link = create_attribute() %}
      {% if aria_label != "" and content.field_link_description|field_value and not content.field_link_style|field_value %}
        {% set attributes_link = attributes_link.setAttribute('aria-label', aria_label).setAttribute('aria-describedby', aria_describedby) %}
      {% elseif content.field_link_description|field_value and not content.field_link_style|field_value %}
        {% set attributes_link = attributes_link.setAttribute('aria-describedby', aria_describedby) %}
      {% elseif aria_label != "" %}
        {% set attributes_link = attributes_link.setAttribute('aria-label',aria_label) %}
      {% endif %}

      {% if link_media.url|length>0 %}
        <a {{ attributes_link.addClass(link_classes) }} href="{{ link_media.url }}">
      {% endif %}
      {% if content.field_link_fa_style|field_value %}
        {{ content.field_link_fa_style.0["#options"].entity.field_fa_code.value|raw }}
      {% endif %}

```

How can i fix that ?

The auto\_reload: true does not seem to be recommended in production and specific conf to a theme does not seem to be possible https://www.drupal.org/project/drupal/issues/2002606

# Answer
In any entity template (like `node.html.twig` or `paragraph.html.twig`, but not `field.html.twig`), you *must* render `{{ content }}` at least once, otherwise the cache tags to not bubble up. A `{{ content.field_something }}` is not enough. You'll notice this problem everytime you need to render a nested entity (e.g. a media entity inside a paragraph or a node.)

If your design does not allow a blanket `{{ content }}`, do somehing like `{% set dummy_force_cache_bubbling = content|render %}`. This doesn't render anything visually, but it triggers the cache processing.
> 6 votes

---
Tags: theming, caching
---


# Question
Title: ?_format=json does not produce JSON for files, REST
I am using Drupal 9.3 with REST UI, RESTful Web Services, and Serialization enabled. For the REST UI, I have the following configuration for files:

Methods: GET, POST, DELETE, PATCH

Accepted request formats: json, xml

Authentication providers: cookie,

but when I try to get a json for a file (by appending `?_format=json` to the url), I just get the file itself back (in other words the page is the same as without `?_format=json`). This only happens for files, both media and nodes generate the json as usual.

Has anybody experienced this or knows how to fix it?

# Answer
> 1 votes
This is because Drupal delivers the file from filesystem without any processing.

If you want a file delivered as JSON (whatever that means). You need a controller that loads the file, then does a json\_decode on the content and returns the result as Symfony\Component\HttpFoundation\JsonResponse.

And you also need a route for that controller method.

# Answer
> 0 votes
You cannot add `?_format=json` to a file url at `www.example.com/sites/default/files` because that is just the directory of site files.

So why does Drupal give you json when you add `?_format=json` to `www.example.com/node/123?_format=json` or `www.example.com/media/123?_format=json`? That's because these are entities.

So, how can you use `?_format=json` with files? You'll need to use entities.

The easiest way to do this is with the Media module, which is built into core.

To try this out:

1. Install the media module.
2. Go to `/admin/structure/media`.

By default, some basic media types will be created (audio, document, image, remote video, and video).

Check out the **Doument** media type as it is a good example of using files.

You can also easily create new media types for your specific use case.

Then you can use `?_format=json` on the media URLs that you create.

The downside of this approach is that you still can't get the json from the file directory path; you will have to use the media entity url instead.

To set the media entity urls automatically based on a pattern, you can use Pathauto.

---
Tags: files
---


# Question
Title: Adding Theme Suggestions Programmatically For Views (Rows & Fields)
For a site I'm currently building I've got a variety of views, all with multiple display modes for different pages.

For example, I have a `venues` view, one block is named `listing` which lists all of my `venues` content type. I have another block which has some more specific contextual filters.

My issue is, this different block is styled the same, and has the same markup as my `listing` block so I don't want to have to duplicate my Twig templates for the rows and fields, for each display mode I have.

What my idea was is to add a function to my `.theme` file that would allow me to list display modes for a certain view, and add a single theme suggestion off that back of that. This way I can rename my Twig templates, and re-use the same ones for row and field level, on as many display modes as I'd like.

As I'm not using a theme suggestions alter hook, I'm not sure how I actually add theme suggestions.

**Here's what I've got so far:**

```
/**
 * Theme suggestions for views.
*/
function spve_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $id = $view->storage->id();

  // Venues
  if($id === 'venues') {
    // Venues grid
    switch($view->current_display) {
      case 'single_occasion_type_listing':
        $suggestion = 'views-view--venues-grid';
        break;

      default:
        $suggestion = null;
        break;
    }
  }
}

```

Obviously I'd need to replace either `$suggestion` with the correct function to add a theme suggestion, or add a bit at the end of my function to add a theme suggestion based of my `$suggestion` variable.

# Answer
> 16 votes
Had a similar question, and though answers were good, they didn't provide everything for my case. Plus it's been a minute, adding my 3 cents to help expansion...

Add views template suggestions:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Add views template suggestions.
 *
 * @inheritdoc
 */
function HOOK_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  return [
    'views_view__' . $variables['view']->id()
  ];
}

```

---

Add views display template suggestions???:

```
/**
 * Implements hook_theme_suggestions_HOOK().
 *
 * Add views template suggestions.
 *
 * @inheritdoc
 */
function HOOK_theme_suggestions_views_view(array $variables) {
  return [
    'views_view_display__' . $variables['view']->current_display,
  ];
}

```

---

Add views unformatted template suggestions:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Add views unformatted template suggestions.
 *
 * @inheritdoc
 */
function HOOK_theme_suggestions_views_view_unformatted_alter(array &$suggestions, array $variables) {
  return [
    'views_view_unformatted__' . $variables['view']->id()
  ];
}

```

---

Add views field template suggestions:

```
/**
 * Implements hook_theme_suggestions_HOOK().
 *
 * Add views field template suggestions.
 *
 * @inheritdoc
 */
function HOOK_theme_suggestions_views_view_field(array $variables) {
  return [
    'views_view_field__' . $variables['field']->field
  ];
}

```

---

And I also want to add that if you're working in a custom module you may need to add the template files to your theme registry using `hook_theme()`:

```
/**
 * Implements hook_theme().
 *
 * Add template files to the theme.
 *
 * @inheritdoc
 */
function HOOK_theme($existing, $type, $theme, $path) {
  return [
    // Field templates.
    'views_view_field__my_field_name' => [
      'template' => 'views-view-field--my-field-name',
      'base hook' => 'views_view_field',
    ],
    // Views templates.
    'views_view__my_views_block' => [
      'template' => 'views-view--my-views-id',
      'base hook' => 'views_view',
    ],
    // Views unformatted templates.
    'views_view_unformatted__my_views_block' => [
      'template' => 'views-view-unformatted--my-views-id',
      'base hook' => 'views_view_unformatted',
    ],
  ];
}

```

And the above `HOOK_theme()` would correspond to the following Twig template files:

1. `views-view-field--my-field-name.html.twig`
2. `views-view--my-views-id.html.twig`
3. `views-view-unformatted--my-views-id.html.twig`

# Answer
> 11 votes
Your Solution is good, but there is a cleaner one. You can use the `hook_theme_suggestions_HOOK_alter`, so you do not have to check if it's a `view` or whatever you want to check.

In your case it would look like this:

```
    function spve_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
        // If you want you can add a template suggestion for all views
        // based on their ID:
        $suggestions[] = sprintf('views_view__%s', $variables['view']->id());

        // Or you can check the ID, add suggestions, do whatever you want
        // ...
    }

    function spve_theme_suggestions_views_view_field_alter(array &$suggestions, array $variables) {
        // Check here the id, add suggestions, do whatever you want
        // ...
    }

```

More informations in the Drupal Theme API

# Answer
> 6 votes
So, eventually I came up with the following solution. Basically I'm checking if the current `$hook` is a view, and then checking if the view is the view I wish to add the suggestions for, and then checks for both row and field levels.

If you find/know a better solution, please share it!

```
function spve_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  /**
   * Venues Grid Twig Template Suggestions
   */
  // Firstly check it's a view
  if($hook === 'views_view') {
    // Check if it's the 'venue' view
    if($variables['view']->id() === 'venues') {
      // Check the display mode
      switch($variables['view']->current_display) {
        case 'listing':
        case 'single_occasion_type_listing':
          $suggestions[] = 'views-view--venues-grid-rows';
          break;
        default:
          break;
      }
    }
  }

  // Firstly check it's a view field
  if($hook === 'views_view_field') {
    // Check if it's the 'venue' view
    if($variables['view']->id() === 'venues') {
      // Check the display mode
      switch($variables['view']->current_display) {
        case 'listing':
        case 'single_occasion_type_listing':
          $suggestions[] = 'views-view--venues-grid-field';
          break;
        default:
          break;
      }
    }
  }
  /**
   * E/O Venues Grid Twig Template Suggestions
   */
}

```

# Answer
> 2 votes
(Cross-post from I don't see Views Theme Suggestions)

This is a bug in Drupal 8 core, currently being worked on for version ~~8.6~~ 8.7

If you need the functionality now, you have two options:

1. Try the patches from comment #22 (or more recent) on Issue #2923634 and the patches on Issue #2752443. Read the comment thread on #2923634 to get a full understanding of what's going on here.
2. Or use the well-vetted patch from comment #139 on Issue #2118743 which has been postponed in favor of option 1 above.

I'm using the patch from option 2 (#2118743) successfully. Please note that this does go against the standard core contributor recommendations. But the reason is because #2118743 has a single, well-vetted and working patch for something that is only enabled / used during development, and instead of needing to test out various combinations of two separate patches that are still under development. Once the better solution (#2923634 and #2752443) get fixed in core, #2118743 should be obviated and no longer required.

# Answer
> 0 votes
Just to add to Daniels answer that suggestions should be formatted with underscores instead of dashes: `$suggestions[] = 'views_view__venues_grid_rows';`

# Answer
> 0 votes
My problem was a little different, but I think it is relevant here. I need to provide a theme hook suggestion for an entity that is rendered through the field plugin "Rendered Entity". Here's my solution.

* My module is named "entry"
* My view id is "entries"

In the entry.module file:

```
/**
 * Adds theme suggestions for Field in a View
 *
 * @see hook_theme_suggestions_HOOK_alter()
 * @param array $suggestions
 * @param array $variables
 */
function entry_theme_suggestions_views_view_field_alter(array &$suggestions, array $variables) {
  /** @var \Drupal\views\Entity\View $view */
  $view = $variables['view'];
  if ($view->id() == 'entries') {
    $field = $variables['field'];
    if ($field instanceof \Drupal\views\Plugin\views\field\RenderedEntity) {
      $suggestions[] = 'views_view_field__' . $field->options['view_mode'];
    }
  }
}

```

# Answer
> 0 votes
> This answer is true - Adding Theme Suggestions Programmatically For Views (Rows & Fields)

```
/**
 * Implements hook_theme_suggestions_alter().
 */
function hayly_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  $template = '';
  $view_id = $variables['view']->id();
  switch ($hook) {
    case 'views_view':
      $template = 'views_view__' . $view_id;
      break;

    case 'views_view_unformatted':
      $template = 'views_view_unformatted__' . $view_id;
      break;

    case 'views_view_fields':
      $template = 'views_view_fields__' . $view_id;
      break;
  }
  return [$template];
}

```

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


# Question
Title: How to export 1 or several specific rules?
I want to export one or more specific rules or components using Drush.
I do have a script to export all the rules and components.

```
drush --pipe rules-list | xargs -I{}  sh -c "drush rules-export '{}' > '20210623-new-Rules-export-offline/{}.txt'"

```

*20210623-new-Rules-export-offline* is the directory where the exported rules are saved.

Is there something I need to change to this code in order to export the specific rules I want to export?

I created a Rules VBO View to have better access to all those rules, but the export to a file feature doesn't seem to be provided.

# Answer
> 1 votes
`drush rules-list` is used to list all the Rules on your site.

`drush rules-export <rule-machine-name>` will export a specific Rule.

The command you show above simply takes the output of the rules-list command and passes it to rules-export, in effect looping over all the Rules and exporting each one.

# Answer
> 0 votes
To export more than one rule, but only the rules whose name is given in a list, I would use the following code.

```
#!/usr/bin/bash

# The list of item names to export
items=(item1 item2 item3)
for item in "${items[@]}"; do
  drush rules-export "$item" > "${item}.txt"
done

```

This is simpler than getting the list of existing rules from `drush rules-list --pipe`, remove the items in that list that don't match the rule names you want to export, and then run `drush rules-export` on the left items.

If you had a list of names, which could be either component names or rule names, and you wanted to export only rules, the code would be similar to the following one.

```
#!/usr/bin/bash

# The list of items to export, which could include component names
names=(name1 name2 name3)

# Get a list of rule names only, and convert it in an array.
rules=( $(drush rules-list --pipe --type=rule) )

# Create an array with items that are in both the arrays.
exports=( $(comm -12 <(printf '%s\n' "${names[@]}" | LC_ALL=C sort) <(printf '%s\n' "${rules[@]}" | LC_ALL=C sort)) )

# Export the items whose names are in the exports array, which contains only rule names.
for export in "${exports[@]}"; do
  drush rules-export "$export" > "${export}.txt"
done

```

---
Tags: 7, rules, drush
---


# Question
Title: How to log actual SMTP Authentication module communication with server?
We are using SMTP Authentication module. Our SMTP provider claims we are whitelisted. Configuration works. When Drupal is supposed to send email, proper entry appears in Watchdog, claiming succesful sending.

Sadly, these days only 2 kinds of email ever arrive to our users: "Account disabled" and "Account deleted" notifications, and SMTP Authentication module test email. Password restore mails, email confirmation ones, user awaiting moderator's approval etc does not.

**How can we log actual communication with SMTP server and have it stored for future reference?** Now we don't know if we have to look for a bug in Drupal, or is it SMTP server's fault. With real data, we could tell for sure, and fix / have fixed the part that really needs it.

Enabling "debug" in SMTP Authentication is not practical - it debugs to screen, so it breaks AJAX calls and most of these emails are password recovery or new user ones, so they are triggered by anonymous - who obviously will not see debug data.

# Answer
> 2 votes
I guess a simple answer would be to change the SMTP module's debugging output to use the watchdog, in addition to/instead of to the screen.

Unless the module offers a hook to do that you'll probably need to patch it temporarily, but if you need to debug on the live server you don't really have another option (not an easier one that I can think of, anyway).

The usual advice would be "get it reproduced on dev, then relax devel permissions temporarily for anon users to test", but of course with emails, getting problems reproduced is often hit and miss between different servers.

# Answer
> 0 votes
I could not find an event to break on that would allow me to view the SMTP log before it disappeared during page reload. But slowing down the network speed in Chrome Developer Tools worked.

I created a network speed profile named Slow at 6 kb/s up and down, and used that when sending a test email from the SMTP configuration page.

When the SMTP log appeared I had time to select all the text and copy it before it disappeared. Changing the network speed back to No throttling allowed the page to load as normal.

In DevTools, click Network and select the desired network speed. Look for the drop down that says No throttling.

---
Tags: emails, debugging
---


# Question
Title: drupal9 dev mode local settings : non existing cache.backend.null
In drupal9 my drupal8 local.settings.php conf generate an error when i empty cache

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have \[error\] requested a non-existent service "cache.backend.null". Did you mean one of these: "cache.backend.apcu", "cache.backend.memory", "cache.backend.php"? in /data-platforms/platforms/drupal9-dev/core/lib/Drupal/Component/DependencyInjection/Container.php:156

this has to do with

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

```

what do i have to change here for drupal9 ?

# Answer
As Clive mentioned, this is the same for D8 and D9 and `cache.backend.null` is defined in development.services.yml so the easiest way to use it is to add development.services.yml to your container ymls.

To do this add the following near the top of your settings file (code taken from core's default example.settings.local.php) :

```
/**
 * Enable local development services.
 */
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

```

Additionally, example.settings.local.php tells you that you must do this to use cache.backend.null:

```
/**
 * Disable the render cache.
 *
 * Note: you should test with the render cache enabled, to ensure the correct
 * cacheability metadata is present. However, in the early stages of
 * development, you may want to disable it.
 *
 * This setting disables the render cache by using the Null cache back-end
 * defined by the development.services.yml file above.
 *
 * Only use this setting once the site has been installed.
 */
# $settings['cache']['bins']['render'] = 'cache.backend.null';

```

If, for some reason, you don't want to use the default development.services.yml file, you could instead use a custom.services.yml file as long as it includes the cache.backend.null definition.

To do this, you'd need to add the following to your settings file:

```
/**
 * Enable custom services.
 */
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/custom.services.yml';

```

And then in your sites/custom.services.yml file:

```
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

```
> 11 votes

---
Tags: caching, 9
---


title: Get title from Route

text:
# Question
Title: Get title from Route
I am trying to print out a few links on a custom page template. I would like to use the title and url from each route.

I am trying to print out the title from the route.

I know I can get the url from:

```
$url = Url::fromRoute('route.name');

```

and I know I can get the current page title from

```
$request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route); }

```

but I am not sure how to request the title from a specific/ different route.

Thanks in advance.

# Answer
> 2 votes
The only way to get the page title of any URL/route would be to actually request the page and see what the title is. The reason is that any module or the theme could alter the title from what it normally would be, like fx metatags module.

# Answer
> 1 votes
There are many reasons why this would be a bad idea, but if you're OK with ignoring the current request context or any dynamic arguments, there is a default title stored in the route object:

```
$title = $route->getDefault('_title');

```

(this is more or less the fallback functionality of the TitleResolver)

This works, for instance, for a plain text Views page title.

# Answer
> 1 votes
Expanding on @ahebrank's answer, if you have the route name 'my.route.name', but not the route object itself (and taking into account the caveat's mentioned by @ahebrank's) here's how you can do it:

```
    $route = \Drupal::service('router.route_provider')->getRouteByName('my.route.name');
    $title = $route->getDefault('_title');

```

# Answer
> 0 votes
```
$route = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');

```

---
Tags: 8, navigation, routes
---


# Question
Title: Create a view showing all nodes tagged with the same term
I'm trying to create a view that shows all nodes tagged with the same term as the current node. Note that the field only allows a single term. So each node (of this type) will only have a single term (of this vocabulary) attached to it.

I have a node ID in the URL for my contextual filter. I cannot figure out the right combination of relationships and contextual filters to show only nodes that have the same term, and NOT show the node referenced in the URL. Can anyone provide assistance?

# Answer
> 2 votes
I figured out the problem. I had built my view correctly, I was testing it incorrectly on the page however. The view had two contextual filters, both set to pull a value from the same key in the URL when the argument wasn't present. I was only testing it with a single argument, eg `5`, thinking that this would cover both contextual filters, as they were set to get their value from the same source. However, when testing the view, the argument needs to be entered twice, eg `5/5`, and returns the correct values.

---
Tags: views, 9
---


title: Connect React/AJAX to custom module

text:
# Question
Title: Connect React/AJAX to custom module
I am trying to create a mini-CRUD component on the Drupal 8 site. I am fetching data from an external source, and rendering it using ReactJS.

**I wish to update the database when a user clicks a button in the React component**.

```
<button
    onClick={() =>
        $.ajax({
            type: "POST",
            url: "../path-to-file/script.php",
            data: { id: 'some data' },
        })}
>
    click me
</button>

```
* I have written the React component (`index.js`),
* I have connected the React component to a custom PHP script with an AJAX script (`script.php`).
* I have written a custom Drupal 8 module to handle the database updates (`mymodule.module`).

However, I can't figure out how to connect the custom PHP script (`script.php`) to the module (`mymodule.module`) to perform the updates.

Any help would be greatly appreciated!

# Answer
Using AJAX to let the user arbitrarily insert data into your database via a custom PHP script seems like a really bad idea because it opens a backdoor into Drupal by circumventing Drupal's security.

To do this the "Drupal" way, you can use the JSON:API module in core to handle CRUD operations. This is way too broad a topic to describe in depth here, but Drupalize.me has a good (paid) tutorial.

This allows you to use JSON:API do CRUD on Drupal entities (nodes, media, taxonomy terms, and so on) using the same access permissions as the Drupal website.

To use this approach, you will need to configure the entities within Drupal so that they receive the data correctly when updated via JSON:API.

Instead of using a custom PHP script, I would create a new JSON:API Resource, which lets you do whatever kind of processing you want via a custom JSON:API endpoint. By doing it this way, you get all the data sanitization benefits that are built into Drupal core.
> 3 votes

---
Tags: 8
---


# Question
Title: Optimize fetching data from entity objects
Currently we are using EntityTypeManager to either load or loadMultiple :

```
$this->entityTypeManager->getStorage('node')->loadMultiple($nids);
$this->entityTypeManager->getStorage('node')->load($nid);

```

This creates and returns objects of nodes which I think uses much resource on the server (since it fetches all fields). **We're also trying to fetch around 500 nodes, and each has over 80 fields.** We only want to fetch certain fields.

Does anyone know a way to query and fetch only the certain fields needed?

# Answer
> 2 votes
You may use a custom query to be more efficient, here is an exemple :

```
$connection = \Drupal::service('database');
$select = $connection->select('node_field_data', 'n');
$select->fields('n', ['nid', 'type', 'title']);
$select->condition('n.status', 1, '=');
$select->condition('n.type', ['page', 'article'], 'IN');
$select->leftJoin('node__body', 'body', 'body.entity_id = n.nid');
$select->fields('body', ['body_value', 'body_summary']);
$result = $select->execute()->fetchAll();
//  print $result[0]->body_value;

```

You have to join table for each field you need to get. Note that `$result` does not contain hydrated `Node` objects but stdClass; this could work with all kind of database entities (i.e `User` or whatever).

---
Tags: 8, entities, database
---


# Question
Title: Why isn't the Highcharts library, defined from a custom module, loaded in every page?
I am running Drupal 9.1.7 on lando on a Mac. I am writing a custom module and I want to include the Highcharts library. The .libraries.yml file looks like this.

```
stats_degrees:
  js:
    https://code.highcharts.com/highcharts.js: { type: external, minified: false }
  dependencies:
    - core/jquery

```

From reading the documentation, I believe I should see the Highcharts library at the bottom of every page when I view the source, but I don't see it anywhere.

Am I missing something?

I have already validated the YAML content. I also installed the Charts module, if that makes any difference.

# Answer
Defining the library is only half of the process. Libraries are not loaded on every page by default - you need to tell Drupal when it should include your library.

For full details, see the Attaching a library to page(s) section of the Adding stylesheets (CSS) and JavaScript (JS) to a Drupal module documentation on drupal.org.

I bet you want to attach the library to a render array:

```
$build['the_element_that_needs_asset_library']['#attached']['library'][] = 'your_module/library_name';

```

Or attach the library in a twig template (the template that produces your chart markup):

```
{{ attach_library('your_module/library_name') }}

```
> 2 votes

---
Tags: javascript, 9
---


# Question
Title: How can I create a simple dropdown to allow users the select an attribute (like ring size) from a Commerce 2 product page?
This seems like it should be simple but despite reading docs and watching videos I cannot figure this out.

I have a Commerce 2 product variation type that I need to add a dropdown on to allow users to select a ring size. This will not affect the price.

I've been trying to use attributes but it doesn't seem to work correctly.

I've created a new attribute type (Ring Size) and add the sizes to it. But then I have to go into the variation edit form and it only allows me to select one of the ring sizes and then this one ring size shows up in a dropdown on the product page.

I'd like to have a list of ring sizes and for them to all be available on the product page for the user to select from.

Any direction on how to achieve this would be greatly appreciated. See the screenshot for an example of what I'm trying to accomplish.

# Answer
I figured it out. Instead of using attributes I needed to create a new Order Item Type and put the ring size field on there. Then, set the product variation to use this new order item type. Easy.
> 1 votes

---
Tags: commerce
---


title: Underscore JS Not Loading

text:
# Question
Title: Underscore JS Not Loading
I am writing code that uses Underscore JS in Drupal 9 that should be loaded from /core/assets/vendor/underscore.

I am using Chrome DevTools to see the sources and though jquery, jquery-once, and modernizer are all loading from /core/assets/vendor/ the underscore library is not.

I am almost positive that this was working last week. I have updated my code since then but it is the same use of underscore. I do this in Drupal 8 and it works for sure.

I have cleared the cache multiple times. I have verified that the files for underscore are in my filesystem.

Thanks, Josh

# Answer
> 0 votes
Since the library was not loaded by the theme in my case I needed to do a form alter and then load the library. You can use something like this:

```
    //Load JS
    $form['#attached']['library'][] = 'core/underscore';
    $form['#attached']['library'][] =
           'my_module/my_forms.js';
}

```

If you are adding your own library will need to define that in my\_module.libraries.yml. Something like this:

```
my_module.js:
  js:
    js/my_forms.js: {}
  dependencies:
    - core/jQuery
    - core/underscore

```

Hope this helps.

---
Tags: javascript
---


title: Translation of a video URL

text:
# Question
Title: Translation of a video URL
I have a content type Book with a field called demo that references to a media (remote video - we must provide a youtube URL). As a first step I create a new node in french and I put a youtube URL ex: www.youtube.com/abc and I save. then I add a new translation to english and I put another youtube URL for this demo field ex: www.youtube.com/zyx. Now when I go back to the firstly created node in french, I see that the video that is displayed is the one whose URL is /zyx instead of /abc ! Any idea why? PS: the field is listed as translatable here : /fr/admin/config/regional/content-language

# Answer
> 1 votes
You translated the wrong part. Your node has a reference field to a media. This field must not be translatable, it will always reference the same media ID.

Instead enable translation for the media entity, and the remote video source URL field.

Translate the media. Translate the node (e.g. title, but not the media reference). Done.

At the end you have got one node with two translations, one video media with one ID and two translations. Both node translations point to the same the media ID, and Drupal will automatically pick the correct translation for the video.

---
Tags: 8
---


# Question
Title: Programatically create paragraphs entity form
I am in a situation where I would like to split out Paragraph entities to separate forms.

Edit forms are no problem:

```
$entity = Paragraph::load($entity_id);
return \Drupal::service('entity.form_builder')->getForm($entity);

```

But how do I get the create form? So far I have this:

```
$entity = Paragraph::create();
return \Drupal::service('entity.form_builder')->getForm($entity);

```

... but the information about the node and field to attach the paragraph entity to is needed.

Thank you

# Answer
The only information you need to get the create form of a content entity is the bundle (if the entity has bundles):

```
$entity = Paragraph::create(['type' => 'my_paragraph_type']);
return \Drupal::service('entity.form_builder')->getForm($entity);

```

You can do the rest after submitting, but you need to update both, the information of the parent entity in the paragraph and vice versa. Paragraphs references are bi-directional.
> 2 votes

---
Tags: entities, paragraphs
---


title: Access denied at all pages

text:
# Question
Title: Access denied at all pages
Suddenly, I can not access any of my pages, any page I try to visit tells me "Access Denied" and only show me site's logo, at all admin's pages and front pages. Everything happens when I install the "menu per role" module and turn it on.

Any idea what could cause this behavior?

# Answer
I had a similar problem with a different module. In my case it was the permissions in certain translations that were causing this to happen, if your site is using multiple languages you might want to give it a try by changing the user's language or the content's language.
> 0 votes

---
Tags: 8
---


# Question
Title: Making custom template & variables in module
I am working with D8, and don't usually do themeing, so I am stuck on a problem.

I have a custom route in a custom module that calls a method checkinConfirmation() on a controller.

Inside that controller, I have this:

```
public function checkinConfirmation() {
  $output['items'] = [
    '#type' => 'fieldset',
    '#title' => t('Checked in items'),
  ];
  $output['items']['name'] = [
    '#prefix' => '<h2>',
    '#suffix' => '</h2>',
    '#markup' => t('Name'),
  ];
  $output['#theme'] = 'circulation_confirmation';
  $output['#output'] = $output;

  return $output;
}

```

and inside of my theme, I have this inside of hook\_theme()

```
public function mytheme_theme() {
  $theme['circulation_confirmation'] = [
    'template' => 'page/circulation--confirmation',
    'variables' => [
      'output' => [],
    ],
  ];
}

```

In my template, I have a `{{ output }}` variable to print the rendered output provided from $output. The problem is though, I do not get the items in the template, and I cannot figure out why. The template is getting pulled in, as the wrapper in the template file is being applied on the page, and the main container is the width it should be.

In using this instead (in the controller):

```
return [
  '#theme' => 'circulation_confirmation',
  '#output' => $output,
];

```

I at least get the data, but it doesn't appear to be using the template I provided as the wrapper is now gone and the main container is full width instead of the width it should be.

I don't usually do themeing or templating, and when I do it's usually forms so I can just pass it 'render element' =\> 'form', to get it to pass the form items to the theme. I am not sure what I am doing wrong.

Please help?

# Answer
You can try this:

In your custom\_module.module:

```
function custom_module_theme() {
    return [
        'circulation_confirmation' => [
            'render element' => 'output',
            'variables' => [
                'output' => [],
            ],
        ],
    ];

```

And in your controller:

```
public function checkinConfirmation() {
    $rtn = [
        '#theme' => 'circulation_confirmation',
        '#output' => [],
    ];

    $rtn['#output']['items'] = [
        '#type' => 'fieldset',
        '#title' => t('Checked in items'),
    ];

    $rtn['#output']['items']['name'] = [
        '#prefix' => '<h2>',
        '#suffix' => '</h2>',
        '#markup' => t('Name'),
    ];

    return $rtn;
}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How can I render a webform submission on a different page after loading it using a submission id?
I'm trying to render the content of the webform submission programmatically onto a different page. I can load the webform submission using the sid, but is it possible to embed the submission in another page similar to the way a webform can be embedded? I can iterate through the submission data and print it out manually, but I want to avoid it since my webform uses various conditionals.

I've tried embedding it similar how a webform object is embedded, but it doesn't seem to be working.

Any hints or pointers for this are really appreciated.

Thanks!

# Answer
One thing you could do, is use Webform Content Creator to create the content after the submission. And then use entity reference to embed the submission content into your desired page.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Drupal 8 Image Styles Not Generating - LEMP on CentOS 7
* Centos 7
* Nginx 1.10.2
* PHP Version 7.1.5
* Database 5.5.52-MariaDB
* Drupal 8.3.2

I have exhausted just about every possible google result and every forum post I can feasibly find. Thank you in advance for any help you can offer me.

**PROBLEM:** Images are uploading to the appropriate folders under /sites/default/files/WHATEVER-SUBDIRECTORY

Image styles are not generating under the /styles folder and I am getting broken images whenever they should appear on-page.

**I HAVE TRIED:**

* Rewriting my Nginx config.
* Setting all permissions to 777 (for testing purposes).
* Adding $conf\['image\_allow\_insecure\_derivatives'\] = TRUE; to settings.php.
* All directories and files are owned by the correct user/group.
* Flushing cache as well as image stores.
* The only type of errors I have been able to find are in my nginx access.log: "GET /sites/default/files/styles/large/public/2017-05/my\_image.jpg?itok=Ax9jzc70 HTTP/1.1" 404 571 "https://mysite.mysite.come/node/1" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36" "-"Safari/537.36" "-"

**nginx.conf:**

```
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    server {
        listen 443 ssl http2;
        server_name     mysite.mysite.com;
        root /var/www/drupal;
        ssl_certificate SSL CERT HERE;
        ssl_certificate_key SSL CERT KEY HERE;
        ssl_session_cache shared:SSL:100m;
        ssl_session_timeout 30m;
        ssl_protocols TLSv1.1 TLSv1.2;

    location / {
        try_files       $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ /vendor/.*\.php$ {
        deny    all;
        return  404;
    }

    location ~ \.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param   HTTP_PROXY "";
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param   PATH_INFO $fastcgi_path_info;
        fastcgi_param   QUERY_STRING $query_string;
        fastcgi_intercept_errors        on;
        fastcgi_pass    127.0.0.1:9000;
    }

    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found   off;

    }

    location ~* /sites/.*/files/styles { # For Drupal >= 7
        access_log      off;
        expires         max;
        try_files $uri @rewrite;
    }
    }

server {
listen       80 default_server;
server_name  mysite.mysite.com;
root         /var/www/drupal;
return 301 https://$server_name$request_uri;
}
}

```

Everything else seems to be working like a dream, but I can't for the life of me seem to figure out these image styles. Any guidance would be greatly appreciated. Thanks again.

# Answer
I had a very similar problem to yours, and found out that to image URL was added "?h=xxxxxxx&" before "itok=", so after deleting this string and pasting URL in browsers, these files were created without any problems.

The only way I found out how to remove this strings from being added was to add in settings.local.php (or settings.php depend on how You config your website) this line:

`$config['image.settings']['allow_insecure_derivatives'] = TRUE;`
> 1 votes

# Answer
as for me, this one was caused by nginx config issue just replace "location" directive with one below:

```
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            try_files $uri @rewrite;
            expires max;
            log_not_found off;
        }

```

and reload nginx `sudo systemctl start nginx` ( on cent os )

it helped me

rights on `sites/default/files` 775 owner `nginx`
> 0 votes

# Answer
inside de `server` you have to add rewrite rule and use it inside assets location. You can see bellow:

```
server {
    # MY OTHER NGINX SERVER CONFFS GOES HERE

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }
    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        try_files $uri @rewrite;
        expires max;
        log_not_found off;
    }
}

```
> 0 votes

---
Tags: media, 8
---


# Question
Title: How do I add link to Edit and Delete in a column in a view table item list?
I've trying to add a link to Edit and Delete column to perform desirable actions. I need help in implementing it. I've tried several suggested methods on the internet, but none did the job for me. Maybe I am doing something wrong.

**Here is my Controller.php**

```
public function getAdList(){
            $limit = 3;
            $query = \Drupal::database();
            $result = $query->select('ad_form_submissions','u')
                    ->fields('u',['id','name','crop_category','crop_type','quantity','price'])
                    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit($limit)
                    ->execute()->fetchAll(\PDO::FETCH_OBJ);

            $data = [];
            $count = 1;

            $params = \Drupal::request()->query->all();

            if(empty($params) || $params['page'] == 0){
                $count=1;
            }else if($params['page'] == 1){
                $count = $params['page'] + $limit;
            }else{
                $count = $params['page'] * limit;
                $count++;
            }

            foreach($result as $row){
                $data[] = [
                    'S_no'=> $count.".",
                    'ID'=> $row->id,
                    'Name'=> $row->name,
                    'Crop Category'=> $row->crop_category,
                    'Crop Type'=> $row->crop_type,
                    'Quantity'=> $row->quantity,
                    'Price'=> $row->price,
                    'Edit' => 'Edit',
                    'Delete'=>'Delete'
                ];
                $count++;
            }

            $header = array('S_no','ID','Name','Crop Category','Crop Type','Quantity','Price','Edit','Delete');

            $build['table'] = [
                '#type'=>'table',
                '#header'=>$header,
                '#rows'=>$data,
                '#empty' => t('No users found'),
            ];

            $build['parger'] = [
                '#type'=>'pager'
            ];

            return [
                $build,
                '#title'=> 'Submit Ad List'
            ];

        }

```

Clarification: I want to perform the Edit and Delete Task on the selected row.

# Answer
> 0 votes
I believe you are looking for Entity Operations. Soul you'd have to load the enity by ID, and then use the getoperations methods. Looking at your code though, I would suggest you use EntityTypeManager to instead load your entities with a EntityListController or something equivalent, it's all baked into core.

---
Tags: views, forms, database
---


# Question
Title: How do I programmatically publish the latest revision?
1. My workflow is draft and publish.
2. I create and publish a page.
3. I create a draft of the page.

There is now the published page, but the latest revision is the draft.

How do I programmatically set as published the latest revision?

This code publishes the node.

```
$node = Node::load(nid);
// Publish and save the node.
if ($node->hasField('moderation_state')) {
  $node->set('moderation_state', 'published');
}
$node->setPublished();
$node->save();

```

The node is already published. I want to publish the draft/latest revision of the node.

This query has some possibilities.

```
// Publish the draft of a node.
$query = \Drupal::database()->select('content_moderation_state_field_revision', 'cm');
// $query->fields('cm', ['moderation_state']);
$query->fields('cm');
$query->condition('cm.content_entity_id', $node->id());
$query->condition('cm.moderation_state', 'draft');
$result = $query->execute();
$record = $result->fetchAssoc();
print_r($record);

```

Since nodes can have more than one draft, I could add a LIMIT and an ORDER BY to the query. Simply changing the moderation\_state in the content\_moderation\_state\_field\_revision table and rebuilding the cache doesn't publish the latest revision.

This code, altered slightly from EntityModerationForm.php worked once, but then didn't work again.

```
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = \Drupal::entityTypeManager()->getStorage($node->getEntityTypeId());
$entity = $storage->createRevision($node, $node->isDefaultRevision());

$new_state = 'published';

$entity->set('moderation_state', $new_state);

if ($entity instanceof RevisionLogInterface) {
  $entity->setRevisionCreationTime(\Drupal::time()->getRequestTime());
  $entity->setRevisionLogMessage('Draft created automatically');
  $entity->setRevisionUserId(\Drupal::currentUser()->id());
}
//    $node->setNewRevision(FALSE);
$entity->save();

```

# Answer
> 11 votes
```
  // get latest revision ID
  $latest_vid = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->getLatestRevisionId($nid);

  // load latest revision
  $latest_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision($latest_vid);

  // set latest revision to published if is draft
  $is_draft = $latest_revision->moderation_state->value == 'draft';
  if ($is_draft) {
    $latest_revision->set('moderation_state', 'published')
      ->save();
  }

```

---
Tags: nodes, 9
---


# Question
Title: No results behavior not showing on a view
I have a view, and the no results behavior is not showing even when there are no results. The view shows all nodes tagged with the same term as the current node.

This is done with two relationships

* One from the node to the taxonomy term
* Another from the taxonomy term back to the content type

And two contextual filters

* One on the node connected through the two relationships, to filter for all nodes tagged with the same term
* One on the original source node, eliminating the node referenced in the URL from the results

The results are fields of the node (no relationship), shown in a table. I have checked the 'show the empty text in the table' box in the table settings, and I have added a global text area for the empty results behavior, showing a no-results message.

With the 'show the empty text in the table' box unchecked, nothing shows up on the page other than the page title. With the 'show the empty text in the table' checked, the table headers show up, but no empty results message.

Does anyone know what could be holding back empty results messages?

# Answer
Thanks to debugging support from commenters in this issue, I discovered the problem. The default view required input for exposed filters before showing results. This setting had propagated to other views, including the ones without exposed filters. This created a weird bug where input would be required to show the user any result, including that there were no results. And with no exposed filters, there was no input to trigger this.

Solution: Advanced Settings -\> Exposed Form Settings -\> Exposed Form Style: basic
> 1 votes

---
Tags: views, 9
---


# Question
Title: Is is possible to call a function inside a .inc file of a module via drush eval?
I have a module with additional (.inc) files containing functions I need to run via Drush. I know it is possible to run `drush eval`, but when I try to do it for those functions I get the following error:

> PHP Fatal error: Call to undefined function my\_module\_my\_function() in /usr/share/php/drush/commands/core/core.drush.inc(1037) : eval()'d code on line 1

This command works (the function is in the .module file).

```
drush eval 'my_module_cron();'

```

This command does not work (the function is in the .inc file).

```
drush eval 'my_module_my_function();'

```

Is there any workaround, besides moving the function in the module?

# Answer
> 20 votes
You could add module\_load\_include() to your eval code like you would anywhere else.

Like this:

```
drush eval "module_load_include('inc', 'my_module', 'INCLUDE_FILE_NAME_WITHOUT_EXTENSION'); my_module_my_function();"

```

# Answer
> 1 votes
For Drupal 8 you can use the following method.

```
drush php-eval "module_load_include('install', 'my_module', 'my_module'); my_module_update_8020();"

```

I used it for running updates that were already run.

---
Tags: 7, drush
---


# Question
Title: How can I use core's WebP support instead of the WebP module?
According to the change record, Drupal 9.2 supports WebP for better image compression.

I've been using the WebP module on my 9.1 site to serve WebP images, but it has a performance-killing bug and I would like to use Core if possible.

So when I upgrade to 9.2, **how can I replace the WebP module with core's WebP support?**

I upgraded to 9.2, uninstalled WebP, and searched for WebP options, but couldn't find anything.

This Lullabot post said it should be supported in the **Convert** effect, but I don't see the option.

# Answer
> 8 votes
WebP is supported in the GD image toolkit.

As noted in the change record, you can check whether your version of PHP has WebP support by going to `admin/reports/status/php#module_gd`.

## What if I am using Imagemagick?

If you do a lot of image processing on your site, you may be using the ImageMagick toolkit via the ImageMagick contrib module. In this case, it doesn't matter if the GD support is enabled because Drupal is using Imagemagick, not GD.

So first, check your image toolkit at `/admin/config/media/image-toolkit`. If you are using ImageMagick, you need to do the following:

1. Click **Image formats** accordion title on `/admin/config/media/image-toolkit`.
2. In **Enable/disable image formats**, scroll down to **WEBP** and set `enabled: true`.
3. Save.

This will now let you convert to WebP for your image styles. (`/admin/config/media/image-styles`)

## What if I am using responsive images?

**If you are using responsive image styles on your site via the core **Responsive Image** module, and you convert all your image styles to WebP, you will break support for older versions of Safari and Internet Explorer, which do not support WebP.** (caniuse webP)

This is something the WebP module handles automatically, but core does not. So if you convert everything to WebP and call it a day, you will break your site for some users.

Unfortunately, core's Responsive Image module only supports breakpoints based on viewport size, but the correct approach is to set the `type` on the tag, which core does not allow you to do. There is a drupal.org issue about this.

Workarounds:

* Use the WebP or ImageOptimize WebP modules instead of core.
* For each responsive image style (`/admin/config/media/responsive-image-style/MY_STYLE`), use image styles converted to WebP for all the breakpoints, and then use a non-WebP image style as the **Fallback image style**.

---
Tags: media, 9
---


# Question
Title: How do I get the (integer) uid from the User entity?
On the odd chance there was a "getUid()" method for the user entity, I tried it, but got:

> Call to undefined method Drupal\user\Entity\User::getUid()

Is there a way to get the uid from the user entity, without loading the full User object?

# Answer
If you have the user entity, it's already loaded, and you can get the ID from it.

* Drupal 7

```
$user->uid

```
* Drupal 8 and later

```
$user->id()

```
> 3 votes

---
Tags: 8, users
---


# Question
Title: Can't add an image extension to the field_image of the Article content type
I need to upload an image with the `webp` extension and add it as the main image of a content item with the "Article" content type. Since its `field_image` doesn't have the `webp` extension by default, I've added the extension to the "Allowed file extensions" input at the managing tab of the `field_image`.

When I check the row with the `name='field.field.node.article.field_image'` in the `config` DB table, I see that the extension was successfully added to the `data` array under the keys `['settings']['file_extensions']`.

But when I try to upload and add an image with the `webp` extension on the editing page of the article I still receives the error that only png, gif, jpg and jpeg are allowed.

How to resolve the problem?

ps. Drupal 8.7.3

# Answer
Drupal 8.7 does not support WebP.

You can:
> 1 votes

---
Tags: 8, nodes, media
---