title: How do I add icons to taxonomy terms?

text:
# Question
Title: How do I add icons to taxonomy terms?
I have a sample site running Drupal 8.1.x, I want to add icons to the taxonomy term.

Example.

I have a term called Animals with the following list in it

Cats Dogs Fish

i want to assign an icon for each terms, a picture of a cat for Cats and so on and will be using it as exposed filter. So i want the pictures/icons instead of the the words Cats - Dogs - Fish.

I have looked into template\_preprocess\_field(&$variables, $hook). I dont know how to go about it, also tried assigning an image filed for each term but the pictures are not showing up on the exposed filter menu.

Please help.

# Answer
You can add image field in taxonomy.You can find option like this.

Then add image field instant of title.
> 2 votes

# Answer
You have added the image field to the taxonomy. In your view you are displaying the content either using a view mode or a fields. If you are using fields then add the field to the view itself. If you are using view modes then you will go to your taxonomy vocabulary and click Manage Display. Then drag the image to up into the manage display.

To know what view mode you are using on the view you can click on settings under Content.
> 2 votes

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


# Question
Title: Throw error for required field in hook_form_alter?
I have a node type that can be created by authenticated users. In the node create form, I added a terms-of-service checkbox via a form hook like so:

```
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_nodetype_form') {
    $form['field_tos_accept'] = array(
      '#type' => 'checkbox',
      '#title' => t('I agree to the terms of service.'),
      '#weight' => '999',
      '#required' => TRUE,
    );
  }
}

```

This gives me the ability to have this checkbox in the node create form, but not in node edit form since it isn't needed there. When I add

```
'#required_error' => t('Please accept the terms of service.'),

```

This should - in my understanding - throw an error message when the form is submitted. But instead the required state of the field prevents the form from beeing submitted. So, there's also no error message thrown.

Is there any way to set this in a form\_alter? Or should I just validate the checkbox state via JS? What would be considered best practise? Thank you very much in advance!

# Answer
*Is there any way to set this in a form\_alter? Or should I just validate the checkbox state via JS?*

You could replace `#required` by setting a custom validation handler in the form alter hook, if you want to generate the error message server-side:

```
$form_state->setErrorByName('field_tos_accept', $error_message);

```

---

*When I add '#required\_error', this should - in my understanding - throw an error message when the form is submitted.*

`#required_error'` was introduced in 2011, but when Drupal 8 was released it seems to have stopped working in browsers supporting HTML5 form validation and so it was never really adopted.

However, you can use the HTML5 form attribute `novalidate` to disable client-side form validation, then this property works again and you get the custom error message without a custom validation handler:

```
function themename_form_alter(&$form, &$form_state, $form_id) {
  // for entity forms $form_id consists of
  // ENTITY_TYPE_BUNDLE_FORM_MODE_form
  // BUNDLE only if entity has bundles
  // FORM_MODE only if not default
  // Examples:
  // node_article_edit_form - node edit form for the content type article
  // node_page_form - node create form for the content type page
  // nodes use for the create form the form mode default
  if ($form_id == 'node_nodetype_form') {
    $form['#attributes']['novalidate'] = 'novalidate';
    $form['field_tos_accept'] = [
      '#type' => 'checkbox',
      '#title' => t('I agree to the terms of service.'),
      '#weight' => '999',
      '#required' => TRUE,
      '#required_error' => t('Please accept the terms of service.'),
    ];
  }
}

```

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-novalidate
> 1 votes

---
Tags: forms, hooks, 9
---


title: Output field with double quotes in twig

text:
# Question
Title: Output field with double quotes in twig
We have a field, `field_text`, that we are displaying on the `Basic Page` content type. It needs to display with double quotes `"` using `twig` template. We tried the following below, but it is displaying without the `"` in the beginning and end.

**How can we display the `field_text` with double quotes (`"`) in `twig`?**

What we tried:

**node--page--full.html.twig**

```
<script type="application/ld+json">
  {# None of the following worked #}
  "name" : {{ content.field_text.0 }}
  "name" : {{ '\"' ~ content.field_text.0 ~ '\"' }}
  "name" : {{ '\"' }} {{ content.field_text.0 ~ '\"' }} {{ '\"' }}
</script>

```

# Answer
Try with the value of the field and then concatenated with `"` like the second way: I tested it with the following:

```
"name" : {{ content.field_text_test.0['#context']['value'] }} <br>
"name" : {{ '\"' ~ content.field_text_test.0['#context']['value'] ~ '\"' }} <br>
"name" : {{ '\"' }} {{ content.field_text_test.0['#context']['value'] ~ '\"' }} {{ '\"' }}

```

Here is the result:
> 0 votes

# Answer
you saved my life, too :-)

you also have this double double quote problem, when setting up an inline svg in inline css in a twig template.

it finally works! thank you! :-)

```
{# in twig template for a block type #}

{% set style_begin =
  "background-image:url("
  ~ '\"'
  ~ "data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' class='h-6 w-6' fill='none' viewBox='0 0 24 24' stroke='%2386bbd8'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' "
%}
{% set style_end = '/%3E%3C/svg%3E'
  ~ '\"'
  ~ ');'
%}

{% set fragment = content.field_block_bg_right_svg.0 %}

{# the "fragment" is from a text field in drupal that
   contains the actual svg paths from heroicons.com
   for example:
   d="M15 13l-3 3m0 0l-3-3m3 3V8m0 13a9 9 0 110-18 9 9 0 010 18z"
   this makes it a little easier for content-authors to choose
   their desired svg-background for this block...
#}

<div class="bg-brand4-900 bg-no-repeat bg-right bg-contain"
    style="{{ style_begin }} {{ fragment }} {{ style_end }}">

```
> 0 votes

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


# Question
Title: Remove authentication in custom REST API resource
I have a custom module to create a custom Rest API resource. I want to remove the authentication and make it without required authentication. In my file `custom_moudle/config/install/rest.resource.custom_resource.yml`

this is my code

```
id: custom_resource
plugin_id: custom_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth

```

This is working fine but with authentication. When trying to remove this lines

```
supported_auth:
  - basic_auth

```

I got an error. So what is the correct way to remove this authentication?

# Answer
REST module plugins must have an authentication plugin. Try using the `cookie` plugin, which is the default one that core uses.
> 1 votes

# Answer
You can skip the authentication for any rest API by Altering the route of that rest resource. there are various examples available on the web.

```
      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('rest.lost_password_resource.POST')) {
          $requirements = $route->getRequirements();
          if (!empty($requirements['_csrf_request_header_token'])) {
            unset($requirements['_csrf_request_header_token']);
            unset($requirements['_permission']);
            $options = $route->getOptions();
            unset($options['_auth']);
            $route->setOptions($options);
            $route->setRequirements($requirements);
          }
        }
     }

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I filter the path aliases by node id?
On this page `admin/config/search/path`, we can only filter the results by URL alias.

I want to filter the results by node id as well?

How can I do that?

It is not possible with form alter. As the original form submit is redirecting to the `entity.path_alias.collection` route with the url alias filter only.

Is there any way, I can filter them by node id?

# Answer
The **URL alias** page it's not a view so, there is no way to add new filter via UI, but you can add a new filter programmatically:
Here is an article explaining how to do so DRUPAL 8 ADD ANOTHER FILTER TO URL ALIASES PAGE
you need to adjust a little bit the code provided in the article it's for path field and you need nid field !
> 0 votes

---
Tags: forms, path-aliases, 9
---


title: Accessing menu protected data

text:
# Question
Title: Accessing menu protected data
How can the protected data of a menu object, pictured below, be accessed ?

using `$menu->id()` works and returns the menu ID. But neighter `$menu->values` nor `$menu->get('values')` work.

# Answer
> 0 votes
It's a content entity so you access fields using magic methods, e.g.

```
$x = $menu->field_foo->value;

```

---
Tags: 9
---


# Question
Title: Perform an action after each step in a multi-step Webform
I'm trying to figure out how to grab data from the previous step of a multi-step webform after a user progresses and I'm coming up blank.

Is there a particular hook that gets fired whenever a users progresses forward in a multi-step form or do I need to add a custom submit handler?

Thank you!

# Answer
> 3 votes
I was able to get this working.

In my `hook_form_alter()` function I had to add a custom submit handler to the `wizard_next` action:

```
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if($form_id == 'my_form') {
        $form['actions']['wizard_next']['#submit'][] = 'my_module_custom_submit';
    }
  }

function my_module_custom_submit(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
 // Custom submit behavior
}

```

---
Tags: webforms, 9
---


# Question
Title: Block changes do not save in admin/structure/block/ page
I have a large number of blocks in a Drupal website. Now I can not save changes in region and order of blocks in admin/structure/block/ page.

There is no message at the top of the page, no Javascript error in console and no error in the error log of my cpanel.

I have increased max\_input\_vars in php.ini file to 5000 or upper and checked the changes in admin/reports/status/php/ to be sure about it but still block changes does not save.

How can I get out of this problem?

# Answer
From my experience, this happens when you disable the `Main page content` block and save the changes. After doing this, clicking save will not do anything.

The simple fix is to enable the `Main page content` block, you should put it back under the Content region.
> 1 votes

# Answer
I had the same issue with Drupal 7. How to understand the issue? This happens when in a given region, you have used all allowed weight numbers from -55 to 55. Number 0 can be used for multiple blocks but the system will not behave the right way. Some people suggest you remove few blocks. That works, but what if you do not want to delete blocks?

In my case, I went to admin/structure/block then Show row weights. I manually started the numbering from -500 to 500 leaving free large slots between rows. After saving the page, you will notice the changes. Let me know if this solves your issue. Cheers.
> 0 votes

---
Tags: 7, blocks
---


title: Auto create a feed when a node is added

text:
# Question
Title: Auto create a feed when a node is added
I am looking for a way to automatically add a feed (of a specific feed type), whenever a node is added (for a specific content type) using the node fields to auto-create the feed.

I have searched this site and globally; the closest solution I could find is the one described in Programmatically create and trigger feeds importer, for Drupal 7, although I cannot see why a template should be needed.

I think I should be able to do this in a custom module, but I am a bit stuck.

Does anyone know how this could be done in Drupal 8?

# Answer
> 0 votes
I think the solution for you is hook\_ENTITY\_TYPE\_update(). Below is a simplified code sample; as always, use dependency injection and other best practices in your production code.

```
/**
 * Implements hook_ENTITY_TYPE_update().
 */
function mymodule_node_update(\Drupal\node\Entity\Node $node) {
  if ($node->bundle() === 'my_content_type') {
    $feed = \Drupal\feeds\Entity\Feed::create([
      // Name the new Feed after the node; or anything you want!
      'title' => "{$node->label()} importer",

      // Assign the ID of the Feed Type to use for generating this Feed.
      'type' => $feed_type_id,

      // This will vary depending on the type of importer.
      'source' => 'https://www.example.com/data.csv',

      // Optionally, set uid to 1 to always belong to the Drupal superuser.
      'uid' => \Drupal::currentUser()->id(),
    ]);
    // Kick off the import after successfully saving the Feed.
    if (in_array($feed->save(), [SAVED_NEW, SAVED_UPDATED], TRUE)) {
      $feed->import();
    };
  }
}

```

---
Tags: 8, nodes
---


# Question
Title: How to get a field value of custom block?
I have a custom block type, called "Features block". I added a field as alternative title (field\_block\_alt\_title is that machine name).

I would like to display this alternative title on frontpage programmatically.

Now, I have this code so far that is displaying the title of blocks:

```
<?php

use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Element;

function neft_preprocess_region(&$variables) {
  if ($variables['region'] == 'flick') {
    $titles = array();
    $ids = array();
    $block_ids = Element::children($variables['elements']);
    foreach ($block_ids as $block_id) {
      $block_title = Drupal\block\Entity\Block::load($block_id)->label();
      $titles[] =  Html::escape($block_title);
      $ids[] = 'block-' . Html::getUniqueId($block_id);
    }
    if (count($titles) && count($ids)) {
      $tabs = '<ul>';
      foreach ($titles as $key => $title) {
        $tabs .= "<li><a href=\"#$ids[$key]\">$title</a></li>";
      }
      $tabs .= '</ul>';
      $variables['tabs'] = $tabs;
    }
  }
}

```

# Answer
Fields of custom blocks are in block content. So you have to load the block content first, before you can get the field value:

```
$block = \Drupal\block\Entity\Block::load($block_id);
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
if ($block_content) {
  $field_value = $block_content->field_block_alt_title->value;
}

```
> 10 votes

# Answer
I was trying to do the same today and this is the only one that worked for me on the latest Drupal version (8.6.12).

```
use \Drupal\block_content\BlockContentInterface;

function HOOK_preprocess_block(&$variables)
{

    $content = $variables['elements']['content'];
    if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {
        $blockType = $content['#block_content']->bundle();

        if ($blockType === 'CUSTOM_BLOCK_TYPE') {
            $variables['FIELD_VALUE_ACCESSIBLE_VIA_TEMPLATE'] = $content['#block_content']->get('FIELD_NAME')->value;
        }

    }
}

```

Then in your template file.

```
{{ FIELD_VALUE_ACCESSIBLE_VIA_TEMPLATE }}

```
> 4 votes

# Answer
You can load the field like:

```
$alt_title = Drupal\block\Entity\Block::load($block_id)->get('field_block_alt_title')->value;

```

or

```
$alt_title = Drupal\block\Entity\Block::load($block_id)->field_block_alt_title->value;

```
> 2 votes

# Answer
This is how I get field values from custom block in Drupal 8

```
  $block_id = 6;
  $block_content = \Drupal\block_content\Entity\BlockContent::load($block_id);

  $facebook_link = $block_content->get('field_facebook_link')->getString();
  $instagram_link = $block_content->get('field_instagram_link')->getString();
  $twitter_link = $block_content->get('field_twitter_link')->getString();
  $youtube_link = $block_content->get('field_youtube_link')->getString();

```
> 2 votes

# Answer
You need to expose the fields from Node to Block variables.

```
function MYTHEME_preprocess_block(&$variables) {
    if(isset($variables['elements']['content']['#view'])){
        $node = $variables['elements']['content']['#view']->result[0]->_entity;

    if($node){
      if ($node instanceof \Drupal\node\Entity\Node) {

        if ($node->hasField('field_name_1')) {
          $variables['field_name_1'] = $node->get('field_name_1')->value;
          }

        if ($node->hasField('field_name_2')) {
          $variables['field_name_2'] = $node->get('field_name_2')->value;
          }
       }
    }
}

```

}\`

To use in your block--views-block--block-custom.html.twig

```
<div>
     {{field_name_1}}
</div>

<div>
     {{field_name_2}}
</div>

```

Tested on Drupal 8.5.3
> 0 votes

---
Tags: 8, entities, blocks
---


# Question
Title: How can the custom files copied by code to the private directory be accessible through URL for authenticated users?
In my project, I am using headless Drupal with .Net on the front end.

I have to use private and encrypted file systems for the project requirements. The files which I am uploading through Drupal private file field from content type are accessible through URL, but as encrypted files aren't accessible through direct URL, I thought of copying the decrypted files from the encrypted folder to the private folder so they become accessible. Strangely, these files aren't accessible for authenticated users, who get access denied for this particular case.

I can't copy these files to the public folder as it is accessible to anonymous users too. So here I am facing two problems:

* Is there any way to restrict public files(sites/default/files/\*) to authenticated users only so that anonymous users can't view them? I tried the rewrite rules in the .htaccess file, but it isn't restricting the URL to particular users, and it redirects users to a private URL.
* Is there any way to access the copied files from the private folder via URL?

These files aren't uploaded through Drupal private file field, but they are copied from the encrypted folder to the private folder through custom code.

# Answer
I would suggest using a Controller whose route parameter(s) can be used to specify the desired file. Then your controller (either directly or by delegating to another service) can access the file, decrypt it, then return the contents. The route that you define for your controller supports permissions, so you can easily apply access control.

Drupal console is a fantastic resource for generating Drupal assets, such as controllers. To generate a new controller with Drupal console: `drupal generate:controller`.
> -1 votes

---
Tags: files
---


# Question
Title: How can I programmatically replace a string on the front page?
I create a custom module which replaces some string on the front page. For nodes, it work correctly, but it doesn't work on the front page. I wrote this code.

```
function my_module_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
    $generateBlock = NULL;
    $block_manager = \Drupal::service('plugin.manager.block');
    $block_config = [];
    $block_plugin = $block_manager->createInstance('id_block', $block_config);
    $block_build = $block_plugin->build();
    $block_content = render($block_build);

    $block = \Drupal\block_content\Entity\BlockContent::load(4);
    $render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    $body = $render['body'][0]['#text'];
    $newContent = str_replace('---*block*---', $block_content, $body);
    // I don't know how render the new modified content from $newContent.
    return $variables;
  }
}

```

I need modify the content with a new string in `$newContent`, but I cannot save this content to variables. My content is not modified.

# Answer
Have you considered using the Custom Token and Token Filter modules together?

There's also this brief tutorial on implementing your own custom tokens: https://codimth.com/blog/web/drupal/how-create-custom-token-drupal-8-9

And here is Token Filter's Readme: https://git.drupalcode.org/project/token\_filter/-/blob/8.x-1.x/README.txt
> 0 votes

---
Tags: 8
---


# Question
Title: Add custom font to mpdf while using PDF using mPDF module
I made a custom module to create a PDF from a views page. This module depends on PDF using mPDF. I'm now trying to add a custom Google font. This should be the default font when generating a pdf. But I can't find out what I should do to have a custom font used in the PDF.

The mPDF documentation gives me an example of what I should do to load the custom font. I tried adding this in a custom function called right before generating the pdf but it doesn't work.

I both tried adding the font as default font to the setting (as shown in the example) or/and via css just using `font-family: aller`, none of it worked till now.

So my question is, am I using the code snippet in the right way? Or what can I do to get this to work?

My code:

GenerateViewsPdf.php -\> Controller

```
<?php

namespace Drupal\views_pdf\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\pdf_using_mpdf\Conversion\ConvertToPdf;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GenerateViewsPdf extends ControllerBase
{
  /**
   * @var ConvertToPdf
   */
  protected $convertToPdf;

  /**
   * Inject ConvertToPdf service
   *
   * GeneratePdf constructor.
   * @param ConvertToPdf $convert
   */
  public function __construct(ConvertToPdf $convert)
  {
    $this->convertToPdf = $convert;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('pdf_using_mpdf.conversion')
    );
  }

  public function generateviews($arg = NULL, $views_name = NULL, $display_id = NULL)
  {
    addFont();
    $settings = $this->convertToPdf->getConfig();
    $settings["pdf_font_size"] = '10mm';
    $settings["default_font"] = 'aller';
    $settings["orientation"] = 'landscape';
    $settings["pdf_css_file"] = __DIR__ . "/../../css/style.css";

    $rendered_view = \Drupal::service('renderer')->render(views_embed_view($views_name, $display_id, $arg));
    $this->convertToPdf->convert($rendered_view, $settings);
    return true;
  }
}

function addFont(){
  $defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
  $fontDirs = $defaultConfig['fontDir'];

  $defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
  $fontData = $defaultFontConfig['fontdata'];
  $mpdf = new \Mpdf\Mpdf(
    [
      'tempDir' => __DIR__ . '/../../upload',
      'fontDir' => array_merge($fontDirs, [
        __DIR__ . '/../../fonts'
      ]),
      'fontdata' => $fontData + [
          'aller' => [
            'R' => 'aller_rg-webfont.ttf',
            'I' => 'aller_it-webfont.ttf',
          ],
        ],
      'default_font' => 'aller'
    ]
  );
}

```

——UPDATE——

I just tried adding the fontdata directly to the mpdf code in the vendor folder and this works perfectly so the font files work fine. And the idea of adding the fontdata is fine. But I don't know where to inject this code to make it work.

# Answer
Using the method I tried didn't work because I added the font to the other mPDF object than used when generating the pdf. The trick is to add the *fontdata* and *fontDir* to the setting when the `new Mpdf()` is created in the `ConvertToPdf.php` file in the PDF using mPDF module. This can simply be done by adding the *fontdata* and *fontDir* to the `$settings` before calling `$this->convertToPdf->convert($rendered_view, $settings);`

So the final solution looks like this:

```
<?php

namespace Drupal\views_pdf\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\pdf_using_mpdf\Conversion\ConvertToPdf;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GenerateViewsPdf extends ControllerBase
{
  /**
   * @var ConvertToPdf
   */
  protected $convertToPdf;

  /**
   * Inject ConvertToPdf service
   *
   * GeneratePdf constructor.
   * @param ConvertToPdf $convert
   */
  public function __construct(ConvertToPdf $convert)
  {
    $this->convertToPdf = $convert;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('pdf_using_mpdf.conversion')
    );
  }

  public function generateviews($arg = NULL, $views_name = NULL, $display_id = NULL)
  {
    $settings = $this->convertToPdf->getConfig();
    $settings["pdf_font_size"] = '10mm';
    $settings["default_font"] = 'aller';
    $settings["orientation"] = 'landscape';
    $settings["pdf_css_file"] = __DIR__ . "/../../css/style.css";

    //start adding custom font
    $settings["fontDir"] = __DIR__ . '/../../../../custom/views_pdf/fonts';
    $settings["fontdata"] = ['aller' => [
        'R' => 'aller_rg-webfont.ttf',
        'I' => 'aller_it-webfont.ttf',
    ]];
    //stop adding custom font

    $rendered_view = \Drupal::service('renderer')->render(views_embed_view($views_name, $display_id, $arg));
    $this->convertToPdf->convert($rendered_view, $settings);
    return true;
  }
}

```
> 1 votes

---
Tags: 9, files
---


# Question
Title: Translation of a multilingual site into English
Note: This question is only focused on strings inside source files (PHP files).

When you are creating a Drupal site in a non English country (let say France), you will create all your PHP files with French strings inside.

After that, you can translate this site, let say in Dutch. You will extract PO files, send them into translation an re-import them.

Until this point, everything is fine.

Now, your client wants to have the site also translated into English.

As you may know, all the source files (with French strings) are in fact considered to be in English by the system.

This means that to handle this fact, I have to:

1. Extract the PO files to translate into French
2. Convert all source files with french strings into the same source files but with English strings (using the translation created at step 1)
3. Revert the languages of the PO file created at step 1 (source language becomes target language and the opposite)
4. Import the reverted file created at step 3 into the site

If you think I am completely wrong with this process, feel free to explain me why. The most complicated step is step 2: Do you know a smooth process or a nice tool to handle it?

I assume I will find something for step 3, but any idea is welcome.

# Answer
It is indeed best practice to have the strings in your code being written in English (I will not discuss that point).

Yet, I had a similar issue once with a website (Drupal 7) a colleague of mine developed. The customer initially wanted to have the website in NL and FR and only many years later decided to add an EN version.

Problem: Strings in the code were a mix of NL and FR...

The workaround I found was to activate the "English, British" language (and deactivate the "English" core language since default language was NL). That way, all your strings can be translated into en-gb from the interface translation or from import of a .po file.

In Drupal 8/9, it is even easier as there is a box labelled "Enable interface translation to English" on page `admin/config/regional/language/edit/en`.
> 1 votes

# Answer
As mentioned in the comments, Always start with English string and translate that even if it's a one language only website, to ease the pain here's what I always do to keep the strings and translations contained to the theme itself:

**open your `THEMENAME.info.yml` file and add the following**:

```
'interface translation project': THEMENAME
'interface translation server pattern': 'themes/custom/THEMENAME/translations/%language.po'

```

then create a `translations` directory within your theme and there you can add your translation `.po` files, eg. `fr.po` for french or `nb.po` for Norwegian

**This is the syntax you need to have within your `.po` file**:

```
msgid "Hello World"
msgstr "Bonjour le monde"

```

So whenever you write `Hello World` string in a `t()` function or as a filter in twig file like so: `{{ Hello World|t }}` it would know to import the translations from there

**But how to trigger the translation import?**

`drush locale:check` \- not necessary, but checks if there are any new strings added

`drush locale:update` \- Imports the translations and you're done

Note that you can add/run this to your deployment procedure as well and make your life easier, no need for UI translation, just add your string to your `.po` file whenever you write hardcoded string into your files

**Update**: Didn't even notice we are talking Drupal 7, this refers to Drupal 8 for future readers
> 1 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: How do I programmatically set the view title?
In D8, I have a need to dynamically set the title of a views page display.

I've tried implementing both `hook_views_pre_render` and `hook_views_post_build` and setting the value of `$view->build_info['title']`, but Drupal seems to be ignoring it when setting the page title.

It seems like the code in Views where the title is set is in `Drupal\views\Plugin\views\display\Page::execute()`

The #title property on the render array in that method IS receiving my overwritten value from one of my hooks, but it's still ignore and is using the manually specified title on the display config.

What is going on!?

# Answer
> 9 votes
If someone else is looking for an answer, this is how I achieved this. I implemented `hook_views_pre_render()` where I called `ViewExecutable::setTitle()`. This allowed me to set the page title.

```
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'ABC') {
    $view->setTitle('MY CUSTOM TITLE');
  }
}

```

# Answer
> 4 votes
If you want to change page title too you can use this snippet

```
\Drupal::routeMatch()->getRouteObject()->setDefault('_title', $title);

```

Hope this helps.

# Answer
> 3 votes
Setting only the `_title` property to set the page title tag was not enough in my case.

Overriding the `title_callback` property did the trick :-)

```
$title = 'something';
$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$route->setDefault('_title_callback', function() use ($title) {
  return $title;
});

```

# Answer
> 1 votes
Implemented using `hook_views_post_render()`. In this example the contextual filter is just added to the title.

```
/**
 * Implements hook_views_post_render().
 */
function THEME_views_post_render(&$view) {
    /** @var \Drupal\views\ViewExecutable $view */
    if ($view->id() === 'events' && isset($view->args[0])) {
        // Get year from contextual argument of the view.
        $year = $view->args[0];

        // Prefix year to title.
        $title = (string) t('@year Events', ['@year' => $year]);

        // Set view and page titles.
        $view->setTitle($title);
        \Drupal::routeMatch()->getRouteObject()->setDefault(
            '_title',
            $title
        );
    }
}

```

---
Tags: views, 8
---


title: entity_autocomplete for custom entity

text:
# Question
Title: entity_autocomplete for custom entity
There is the entity\_autocomplete field type which I expect should just work for core entities. I have created my own entity using Drupal console and would like to query those entities with an autocomplete field. I understand that you need some sort of callback to query the correct field and return the response.

I've had a good search but can't find any good examples of how to do this. Is there somewhere in core, contrib module or elsewhere that has a good example?

# Answer
> -1 votes
Your custom entity needs to specify a "label" key in the annotation. e.g.:

```
/**
 * @ContentEntityType(
 *   id = "example",
 *
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "revision" = "revision_id",
 *     "label" = "title",
 *   },
 * }
 */

```

---
Tags: entities, forms
---


# Question
Title: How can I generate thumbnails for PDF files?
I am working on this website which has a documents gallery that will be updated periodically. One of the core requirements is to generate a thumbnail from the uploaded PDF file(First Page of the PDF file) and to be displayed in the documents gallery page(Implemented with views). I have installed Imagemagick on my test server and configured it in PHP.ini and also installed the drupal module successfully. But I have not been able to go beyond that because of the following:

* I can't upload a pdf to an image field so there is no way of applying an image style to the uploaded pdf
* I can't find any Drupal 8 Module that can generate the thumbnail and attach it to an image field in the content type.
* I tried installing spatie/pdf-to-image, which is supposed to be able to do that, via composer but it doesn't show in the admin/modules page and I can't find any folder with it's name in the modules directory

Please can anyone point me in the right direction on this? A module which can perform this task or how I can create one myself. This is my first drupal website and this requirement has made life hell for me in the past two weeks. Any help on this will be really appreciated.

# Answer
It's an old question but a still living problem. Maybe some recent visitors (as I am) can use a hint. Drupal has a lot of potential, but an ordinary thumbnail other than the "text"-icon for pdf-files? This module claims the answer for it. https://www.drupal.org/project/media\_thumbnails with some submodules. Caveat: imagemagick has to be enabled as php-extension. Hopefully it helps. I'm still struggling to make it work.
> 0 votes

# Answer
For similar purpose i was using Media Entity in Drupal 8, so on this way you can use reference field to upload document and get preview like thumbnail.
> -1 votes

---
Tags: views
---


# Question
Title: How to keep similar custom services from conflicting?
I have two modules, each of which is defining a normalizer service

module\_one.services.yml

```
services:
  module_one.normalizer.node_entity:
    class: Drupal\module_one\Normalizer\ModuleOneEntityNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 10 }

```

module\_two.services.yml

```
services:
  module_two.normalizer.node_entity:
    class: Drupal\module_two\Normalizer\ModuleTwoEntityNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 10 }

```

For each module, I am creating a distinct normalizer and presumably defining a separate namespace, ex:

```
<?php

namespace Drupal\module_one\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Converts the Drupal entity object structures to a normalized array.
 */
class ModuleOneEntityNormalizer extends ContentEntityNormalizer {
...

```

The problem is that with both modules enabled, one service is blocking the other - the serializer / normalizer fires as expected for the first one but not for the second. The only way to get the other one to be recognized is to increase its priority but that blocks the first.

What am I missing in the definitions that would prevent these two services from conflicting with each other?

**Update**: Thanks for the really helpful comments, starting to dial in on this. Both normalizers have the same protected $supportedInterface, ex:

```
  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface'
  ];

```

Which is flagged in the Drupal Serialization API handbook as an issue

# Answer
Found a working answer with the helpful guidance from the comments here. The key is that in both Normalizer classes, I was not using the supportsNormalization function

```
 /**
 * Checks whether the given class is supported for normalization by this normalizer.
 */
   public function supportsNormalization($data, $format = NULL) {
      if (!is_object($data) || !$this->checkFormat($format)) {
        return FALSE;
      }
      if ($data instanceof NodeInterface && $data->getType() == 'myContentType') {
        return TRUE;
      }
        return FALSE;
      }
    }

```

With the above function, I can continue to have the priority for both normalizers in the services.yml set to the same value (ex. '10'), it will fire for both but return false if it doesn't match the particular content type.
> 1 votes

---
Tags: 8, services
---


# Question
Title: How to fill a form field of type fieldset with values from an array
How can I fill a formfield type fieldset with more than one markup value from an array?

```
foreach ($drugis_postgis_connection->tableNames() as $table) {
    $form['tables'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Tables'),
      '#markup' => $table,
      '#collapsible' => TRUE, // Added
      '#collapsed' => FALSE,  // Added
  ];

```

I don't need more fields i want to markup all values from the array in the field. Actually there is only one value, from the array displayed.

---

Sorry if my question is not clear, i want something like this.

# Answer
If you overwrite `$form['tables']` on each iteration, you're only going to end up with one `tables` on the form. Each element on the `$form` needs to have a unique name. Try something like this:

```
foreach ($drugis_postgis_connection->tableNames() as $key => $table) {

  $form['table' . $key] = [
    /** ... **/
  ];

}

```

If you want only one fieldset, then trying something like this:

```
$tables = $drugis_postgis_connection->tableNames();
$form['tables'] = [
  /** ... **/
  '#markup' => implode('', $tables),
  /** ... **/
];

```
> 0 votes

# Answer
The code shown in the question doesn't work for two reasons.

* The `foreach` loop is overriding `$form['tables']` each time, with the effect that `$form['tables']['#markup']` contains only the last table name found from `$drugis_postgis_connection->tableNames()`
* A *fieldset* element doesn't use `#markup`

You need to use code similar to the following one.

```
$tables = $drugis_postgis_connection->tableNames();

$form['tables'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('Tables'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
];

$form['tables']['list'] = [
  '#markup' => implode(',', $tables),
];

```

I assume `$drugis_postgis_connection->tableNames()` returns an array of strings; otherwise, `implode(',', $tables)` needs to be changed.
> 0 votes

---
Tags: forms
---


title: REST API calls are always cached

text:
# Question
Title: REST API calls are always cached
In Drupal 9.2.6 I have a caching issue.

The code I am using is the following.

```
$returnValues = [
  'value' => 'test',
  'time' => time(),
];

$response = new ResourceResponse($returnValues, 200, []);
$disable_cache = new CacheableMetadata();
$disable_cache->setCacheMaxAge(0);
$response->addCacheableDependency($disable_cache);
return $response;

```

This leads to this error.

> TypeError: Argument 1 passed to Symfony\Component\Serializer\Encoder\ChainEncoder::getEncoder() must be of the type string, null given, called in /webspace/public/vendor/symfony/serializer/Encoder/ChainEncoder.php on line 49 in Symfony\Component\Serializer\Encoder\ChainEncoder-\>getEncoder() (Zeile 80 in /webspace/public/vendor/symfony/serializer/Encoder/ChainEncoder.php)

This is also doesn't work.

```
$response = new ResourceResponse($returnValues);
$response->addCacheableDependency($returnValues);
return $response;

```

What's wrong?

# Answer
Use Drupal\rest\ModifiedResourceResponse instead of ResourceResponse, then it won't be cached.
> 1 votes

---
Tags: 9
---


# Question
Title: Render responsive image inside form fields programmatically
I am trying to figure out how to render a responsive image programmatically inside a form field. I am doing maintenance in a code on my current job, and sometimes there are form fields using the '#markup' property. Now I need to change all images to be responsive.

The code example:

```
$form['markup1'] = [
     '#markup' => '<div class="rating_reminder"><img src="'.file_create_url($order->campaign_id->entity->product_id->entity->image->entity->getFileUri()).'"><div>'
];

```

It is very hard to find anything explaining how to use responsive images that are in code in PHP.

I'll be very grateful if you can help me.

# Answer
> 1 votes
Build render elements instead of HTML markup:

```
$form['markup1'] = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['rating_reminder'],
  ],
  'image' => [
    '#type' => 'responsive_image',
    '#responsive_image_style_id' => 'big',
    '#uri' => $order->campaign_id->entity->product_id->entity->image->entity->getFileUri(),
    '#attributes' => [
      'alt' => $order->campaign_id->entity->product_id->entity->image->alt,
    ],
  ],
];

```

Available render elements: https://api.drupal.org/api/drupal/elements

---
Tags: forms, 9
---


title: How to make a custom entity fieldable?

text:
# Question
Title: How to make a custom entity fieldable?
This has been asked here before; but question is closed and the few replies do not provide sufficient information.

I am trying to use a contrib module (sitewide\_alert) which provides its own custom entity. I am trying to figure out how to patch this module to make it fieldable (and how to do this in general).

In other posts I have seen suggestions to add the follinwg to the ContentEntityType annotation:

* fieldable = TRUE;
* bundle\_entity\_type = ??
* field\_ui\_base\_route -\> different suggestions but already exists for this module pointing to the module's config form.

But none of those seemed to fix this.

the full annotation for the entity is:

```
* @ContentEntityType(
 *   id = "sitewide_alert",
 *   label = @Translation("Sitewide Alert"),
 *   label_plural = @Translation("Sitewide Alerts"),
 *   label_collection = @Translation("Sitewide Alerts"),
 *   handlers = {
 *     "storage" = "Drupal\sitewide_alert\SitewideAlertStorage",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\sitewide_alert\SitewideAlertListBuilder",
 *     "views_data" = "Drupal\sitewide_alert\Entity\SitewideAlertViewsData",
 *     "translation" = "Drupal\sitewide_alert\SitewideAlertTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\sitewide_alert\Form\SitewideAlertForm",
 *       "add" = "Drupal\sitewide_alert\Form\SitewideAlertForm",
 *       "edit" = "Drupal\sitewide_alert\Form\SitewideAlertForm",
 *       "delete" = "Drupal\sitewide_alert\Form\SitewideAlertDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\sitewide_alert\SitewideAlertHtmlRouteProvider",
 *     },
 *     "access" = "Drupal\sitewide_alert\SitewideAlertAccessControlHandler",
 *   },
 *   base_table = "sitewide_alert",
 *   data_table = "sitewide_alert_field_data",
 *   revision_table = "sitewide_alert_revision",
 *   revision_data_table = "sitewide_alert_field_revision",
 *   show_revision_ui = TRUE,
 *   translatable = TRUE,
 *   admin_permission = "administer sitewide alert entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "vid",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "published" = "status",
 *   },
 *   revision_metadata_keys = {
 *     "revision_user" = "revision_user",
 *     "revision_created" = "revision_created",
 *     "revision_log_message" = "revision_log",
 *   },
 *   links = {
 *     "canonical" = "/admin/content/sitewide_alert/{sitewide_alert}",
 *     "add-form" = "/admin/content/sitewide_alert/add",
 *     "edit-form" = "/admin/content/sitewide_alert/{sitewide_alert}/edit",
 *     "delete-form" = "/admin/content/sitewide_alert/{sitewide_alert}/delete",
 *     "version-history" = "/admin/content/sitewide_alert/{sitewide_alert}/revisions",
 *     "revision" = "/admin/content/sitewide_alert/{sitewide_alert}/revisions/{sitewide_alert_revision}/view",
 *     "revision_revert" = "/admin/content/sitewide_alert/{sitewide_alert}/revisions/{sitewide_alert_revision}/revert",
 *     "revision_delete" = "/admin/content/sitewide_alert/{sitewide_alert}/revisions/{sitewide_alert_revision}/delete",
 *     "translation_revert" = "/admin/content/sitewide_alert/{sitewide_alert}/revisions/{sitewide_alert_revision}/revert/{langcode}",
 *     "collection" = "/admin/content/sitewide_alert",
 *   },
 *   field_ui_base_route = "sitewide_alert.settings",
 *   constraints = {
 *     "ScheduledDateProvided" = {}
 *   }
 * )
 */

```

In my trial/error approach I did notice I created the Manage Fields/Display/etc UI for each entity I had previously created. So I think this is possibly related to not having a bundle defined? My use case doesn't require making new bundles (similar to the User entity).

Despite the other posted answers; my guess is modifying the annotation is not enough to add this functionality.

# Answer
> 1 votes
There is nothing wrong with the entity type annotation. After you have removed this code intentionally disabling the field UI routes

https://git.drupalcode.org/project/sitewide\_alert/-/blob/8.x-1.6/src/Routing/RouteSubscriber.php

the entity should be fieldable at *admin/content/sitewide\_alert/settings/fields*.

This is a very cool module. After playing around a little bit I've found out the module has two settings routes, the mentioned dummy form in an odd place under content and the official module settings form in configuration. If you attach the field UI to this form it's easier to find I think:

```
field_ui_base_route = "sitewide_alert.sitewide_alert_config_form"

```

---
Tags: 9
---


# Question
Title: Importing uid of the author into article nodes fails
My custom Drupal 7 to Drupal 8 migration correctly follows dependencies and first migrates users, then articles. The problem is that it fails to import user IDs into the 'uid' field and leaves it at '0'. For uid processing, I use the following YAML snipped. Note that 'luxus\_users' is the user migration that works fine.

```
process:
    uid:
         plugin: iterator
         source: uid
         process:
           target_id:
               plugin: migration
               migration: luxus_users
               source: uid

```

I hoped would work for me as similar one for file migration already works for me.

```
field_logo:
     plugin: iterator
     source: field_logo
     process:
       target_id:
         plugin: migration
         migration: luxus_files
         source: fid

```

# Answer
The following piece of code works for me now:

```
uid:
  plugin: migration
  migration: luxus_users
  source: node_uid

```

Dont know why all the examples refer to 'uid' which is nto part of the $row...
> 1 votes

# Answer
The difference is that the fid you're migrating is part of a reference field with an internal structure, which makes 'iterator' appropriate. For nodes, however, uid is a simple property, not a field array, so you can map it more directly:

```
process:
  uid:
    plugin: migration
    migration: luxus_users
    source: uid

```
> 1 votes

# Answer
Accepted answer did not solve my issue . But the answer from @Mike-Ryan helped me to go into right direction.

`migration` plugin is deprecated so I used `migration_lookup` plugin which helped me to solve the issue.

My migration mapping definition as follows :

```
  uid:
    -
      plugin: migration_lookup
      migration: luxus_users
      source: uid

```
> 0 votes

---
Tags: entities, migrations
---


title: Using Authentication API module

text:
# Question
Title: Using Authentication API module
I'm trying to use the User Authentication API module. My goal is to add some post-processing after successful Drupal 7 login that posts JSON to an external web service. This would be work very similar to the Webform Remote Post module, but for the login page.

My problem is that even though the module is installed fine, and things look good on the page which displays detected plugins, nothing seems to fire at login. What do I need to add to see this plugin framework interact with a user login event?

This screenshot shows I have all the pieces in place.

>

# Answer
The *User Authentication API* only provides an API. It doesn't provide any authentication class that can be used to really authenticate users.

What the screenshot in the question shows are the classes used by the tests implemented by the module, whose purpose is only testing the module works correctly.

You need to find a module that uses the *User Authentication API* module, or a totally different module, that doesn't what you trying to do.
> 0 votes

---
Tags: 7, authentication-authorization
---


# Question
Title: How do I list all users in a view that have created a node with certain taxonomy terms?
The goal is to create a view to list users on a page with url /search/\[category\]/\[topic\]/\[location\] where "category" "topic" and "location" are taxonomy fields in nodes that users can create.

I want to list all users that have a node were the "search" queries apply.

***/search/all/all/all*** should list all users

***/search/all/topic1/all*** should list all users that created at least one node with topic "topic1".

***/search/category1/topic2/location3*** should list all users that have created at least one node with taxonomy terms "category1", "topic2" and "location3".

Edit: I have machine names for my taxonomy terms and that is how I would like to use in the url.

# Answer
> 0 votes
I ended up making a relationship between the user and nodes. then I added each taxonomy term as a relationship through the nodes. Then I added 3 contextual filters for each taxonomy term. Finally I switched on aggregation and aggregated the usernames.

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


# Question
Title: How to retrieve #tree values inside a form?
I am new at Drupal 8 and I am creating a module that has a #tree form. I chose #tree form to create multiple forms which has the same textfields and button.

I came across one document in drupal about #tree.
https://www.drupal.org/docs/7/api/form-api/tree-and-parents
I have made a researched about it and can't find any documentation, post or blog on how to get a specific value from #tree.

I have implemented the #tree in my form. The only problem is that I can't retrieve a specific value from the form.

```
for($counter = 0; $counter < $rowCount; $counter++){
   $form['firstname']['#tree'] = TRUE;
   $form['firstname'] => [
        '#type' => 'textfield',
        '#title' => 'First name',
   ];
   $form['secondname'] => [
        '#type' => 'textfield',
        '#title' => 'Second name',
   ];
   $form['save'] => [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#submit' => ['::submitForm'],
   ];
}

```

The rowCount pertains to the row in my database. The process is to acquire firstname and lastname from the user and those variables will be saved inside the database.

How can I get the 2nd firstname inside the #tree form?

# Answer
> 0 votes
`#tree` denotes a hierarchy in the form, you still need valid and logical PHP to make it work, e.g.

```
// In the build...
$form['parent'] = [
  '#type' => 'container',
  '#tree' => TRUE,
];

for($counter = 0; $counter < $rowCount; $counter++){
  $form['parent'][$counter] = [
    'firstname' => ['#type' => 'input', ...],
    'lastname' => ['#type' => 'input', ...],
  ];
}

// In the submit...
// '0' is the key you set with $counter previously.
$first_firstname = $form_state->getValue('parent')[0]['firstname'];
$first_lastname = $form_state->getValue('parent')[0]['lastname'];

```

# Answer
> 0 votes
`#tree` Creates a hierarchy of values in the submit handler of a form.

Compare:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['container'] = [
    '#type' => 'container',
  ];
  $form['container']['some_value'] = [
    '#type' = >'textfield',
  ];

  // Submit buttons etc. not shown

  return $form;
}

```

This will create a form element. After clicking submit, the key of the form element is used to return the value. in this case, the key is `some_value`, meaning validation and submit handlers can retrieve the submitted value with `form_state->getValue('some_value')`.

Now, add `#tree` to the container:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['container'] = [
    '#type' => 'container',
    '#tree' => TRUE,
  ];
  $form['container']['some_value'] = [
    '#type' = >'textfield',
  ];

  // Submit buttons etc. not shown

  return $form;
}

```

With this change, `$form_state->getValue('some_value')` will return nothing, as the value is now part of the container element (the `#tree` element) and needs to be retrieved relative to that:

```
// Returns an array with a single key, 'some_value', that contains the
// submitted value.
$form_state->getValue('container')

// Returns the submitted value:
$form_state->getValue(['container', 'some_value'])

```

---
Tags: 8, forms
---


# Question
Title: Where does the drush installtation command set the PROMPT_COMMAND variable?
I installed drush and as part of the installation it makes some changes to the command prompt.

```
...
# Optional. Enrich the bash startup file with completion and aliases.
drush init
...

```

Whenever I execute an command at the prompt I get the message:

```
bash: __drush_ps1: command not found

```

The `env` command displays `PROMPT_COMMAND` as

```
PROMPT_COMMAND=__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "

```

I think somewhere at the global level the PROMPT\_COMMAND variable is set to that value but I can't locate it in any of the global environment variables and profile scripts.

Because `drush` was installed as `root` commands executed as `root` don't produce that error message. `root` has a `.drush` directory with some `drush` scripts.

# Answer
The function that changes the .bash\_profile or .bashrc file is `drush_init_core_init()`. The shell script that effectively sets the prompt is `$home/.drush/drush.prompt.sh`, where `$home` is the value returned from `drush_server_home()`. If the file doesn't exist, `drush_init_core_init()` creates it from the content of `DRUSH_BASE_PATH . "/examples/example.prompt.sh"`, which contains the following line. (See example.prompt.sh.)

```
export PROMPT_COMMAND='__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "'

```

There is also the following line, which sets `PS1` and that is is commented out by default. (See the comment before it.)

```
  # PROMPT_COMMAND is used in the example above rather than PS1 because neither
  # Git nor Drush color hints are compatible with PS1. If you don't want color
  # hints, however, and prefer to use PS1, you can still do so by commenting out
  # the PROMPT_COMMAND line above and uncommenting the PS1 line below:
  #
  # export PS1='\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ '

```

As for the error message you see, `__drush_ps1()` is a bash function used to change the prompt, defined in drush.complete.sh. bash completion/prompt broken explains exactly when and why you get that error. TLDR; in some circumstances, the shell script is not sourced, and the Bash function results not defined.
For what I understand it, the error has been has been fixed in recent versions, though, so you should just need to update Drush to fix the error.
> 2 votes

# Answer
Kind of simpler work-around to remove that error message - edit:

```
~/.drusysconfig/bash_prompt

```

i.e.

```
nano ~/.drusysconfig/bash_prompt

```

and remove row:

```
PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]:\[$GREEN\]\w \[$PURPLE\]\$(__git_ps1 '(%s)')\[$ORANGE\]\[$WHITE\]\n\$ \[$RESET\]"

```
> 0 votes

---
Tags: drush
---


title: ANDs within OrConditionGroups

text:
# Question
Title: ANDs within OrConditionGroups
I'm trying to use entityQuery in Drupal 8 to perform an "and" within an "or" group. A simplified version of what I'm trying to do is this: Query for all apples, oranges and bananas that are ripe. The code I'd like to be able to use would look like this code.

```
$oQuery = \Drupal::entityQuery('node');
$oOrGroup = $oQuery->orConditionGroup();
$oOrGroup->condition('type',['apple','orange'],'IN');
$oAndGroup = $oOrGroup->andConditionGroup();
$aAndGroup->condition('type','banana')
  ->condition('field_ripe',1);
$oOrGroup->condition($oAndGroup);
$oQuery->condition($oOrGroup);

```

This doesn't work because `andConditionGroup()` isn't a method of `ConditionInterface`.

Is there a way to do this with `\Drupal::entityQuery()`, or do I have to revert to using `db_query()`?

# Answer
What you need to do is create both groups from the query, using the `condition()` method to plug the groups into the right places. Casting the query to a string will allow you to inspect the generated SQL to verify that it is what you would have created by hand (perhaps without some of the superfluous but harmless parentheses).

```
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery();
$bananas = $query->andConditionGroup()
  ->condition('type', 'banana')
  ->condition('field_ripe', 1);
$fruit = $query->orConditionGroup()
  ->condition('type', ['apple', 'orange'], 'IN')
  ->condition($bananas);
$query->condition($fruit);
echo (string) $query . "\n";

```

I've reformatted the output to make it a bit more legible, but otherwise it's exactly as the API created it.

```
   SELECT "base_table"."vid" AS "vid", "base_table"."nid" AS "nid"
     FROM "node" "base_table"
LEFT JOIN "node_field_data" "node_field_data"
       ON "node_field_data"."nid" = "base_table"."nid"
LEFT JOIN "node_field_data" "node_field_data_2"
       ON "node_field_data_2"."nid" = "base_table"."nid"
LEFT JOIN "node__field_ripe" "node__field_ripe"
       ON "node__field_ripe"."entity_id" = "base_table"."nid"
    WHERE (
            "node_field_data"."type" IN ('apple', 'orange')
          )
       OR (
            ("node_field_data_2"."type" = 'banana')
            AND
            ("node__field_ripe"."field_ripe_value" = '1')
          )

```
> 0 votes

---
Tags: 8, database
---


# Question
Title: I installed Solr for the Search API Solr can someone can give me hints what i could have done wrong?
I'm currently running a CentOS 7 server with cPanel and Drupal 8. I installed Solr 8.8.1 and I can access the administratrion page where I an able to create cores. I installed the *Search API* module with Composer.

When I try to use the Solr server via the *Search API* module, I get a server connection error.

I tried a lot of Drupal configuration, with Basic Auth and standard, via localhost, IP and domain name, but I'm still not able to connect to the Solr server.

Everything I do gets me the following error.

> The Solr server could not be reached or is protected by your service provider.

I am the service provider. I verified the firewall isn't blocking the connection.

Can someone tell me what I could have done wrong?

# Answer
@hotwebmatter's answer above helped me with this issue, so I'll add instructions:

1. Check the status of SELinux: `getenforce`. In my case, the status was `enabled`, so I needed to disable it.
2. Disable SELinux: `sudo nano /etc/selinux/config`, then change `SELINUX=enabled` to `SELINUX=disabled`.
3. Reboot: `systemctl reboot`

Check the status of your Solr server again at `/admin/config/search/search-api/server/scs_solr`.
> 0 votes

---
Tags: 8, search, installation
---


# Question
Title: Conditionally display headers on web page in page.html.twig
We have a header which contains a secondary menu on top bar, search, main menu and logo in page.html.twig.

We would like to implement a new header with quite a few changes and so would like to add a bool field or some field, somewhere for example all Content Types. So the user, adds a page sees this field and if checked to display new header. Is this possible?

# Answer
> 1 votes
You can actually access nodes directly from page.html.twig.

It's not as clean as a preprocess approach, but you could do something like this:

```
{% if node is not empty %}
  {% if node.field_some_field is not empty and node.field_some_field.value == true %}
    {# Output new header #}
  {% endif %}
{% endif %}

```

---
Tags: theming
---


# Question
Title: How to send send an image inside html email using swiftmailer?
in my Drupal 8 installation I'm using mailsystem module in combination with swiftmailer module. Everything works fine so far, my swiftmailer twig template inside the templates folder of my custom theme is recognized and works as it should in general.

**Problem:**

When I want to embed a logo inside my template (as inline image), the image can't be loaded. It renders the template and shows a broken image placeholder. I used the code mentioned in readme.txt (see point 3.2.2) of swiftmailer module:

```
<img src="image:/themes/MYTHEME/logo.png">

```

Same error when I use

```
<img src="image:{{ base_url }}/themes/MYTHEME/logo.png">

```

Logo path is generally working, use the same for my theme in general.

The image is embedded also inside the email (using MailHog to check it):

```
Content-Type: image/png; name=logo.png

Content-Transfer-Encoding: base64

Content-ID: <f8a965e25fc041c5af9318b9d71cd3d1@mysite.site>

Content-Disposition: inline; filename=logo.png

.... image code following ....

```

How can I get my logo image inside my email correctly? Would like to avoid simply setting a linked image it to my webserver if possible,to minimize webserver traffic.

Thanks in advance :)

# Answer
> 1 votes
I was able to generate the base path for absolute links by using this twig filter in my template file:

`{{ base_url ~ directory }}`

There is more detail on the swiftmailer issue page here: https://www.drupal.org/project/swiftmailer/issues/2809359

# Answer
> 1 votes
The trailing slash was not added to the preprocess function so you need to do something like this:

```
<img src="{{ base_url ~ '/' ~ directory }}/img/mail-logo.png" />

```

---
Tags: 8, emails
---


# Question
Title: Import multiple images with sub_process and image_import
I have some nodes with multiple images I want to import. How can I combine `sub_process` plugin with `image_import`?

```
"field_image":[
    {"src":"https://example.com/image1.png","alt":"Image 1","title":"Image one."},
    {"src":"https://example.com/image2.png","alt":"Image 2","title":"Image two"}
]

```

What can I do to loop throw the array of images and import them later.

Here is example of my YML migration process configuration

```
process:
  nid: nid
  title: title
  field_image:
    plugin: sub_process
    source: field_image
    process:
      plugin: image_import
      source: src
      destination: constants/file_destination
      title: title
      alt: alt

```

# Answer
The YAML looks good although I fundamentally disagree with all these modules that try to inline several migrations into one.

I am not sure what your source plugin is. If I were doing this, I'd write a custom one by copying EmptySource and changing `id = "empty",` to `id = "my_json_source"` and change `initializeIterator` to `return new \ArrayIterator(json_decode($this->configuration['json_path'], TRUE)['field_image']);` and then

```
source:
  plugin: my_json_source
  json_path: path/to/my/json/file

```

That ought to work.
> -1 votes

---
Tags: migrations
---


# Question
Title: Injecting a NEW instance of a service into another service class
I have a service (for sending error alerts) which is used by multiple other services.

The alert service is injected into those classes via the relevant services.yml files and through their constructors.

However, both classes share the same instance of the service (something I actually didn't realise until now). If I set a property from one class, it's available for the other class to use later.

In some cases this will be great, but in my use case I want each class to start with a fresh instantation of the alert service class.

Is there a way, through services.yml, the constructors, or any other means, to achieve this?

# Answer
> 2 votes
There are a couple options that come to mind:

1. Create a factory service that provides instances of your non-service alert class
2. Implement your alert class as a plugin

Which one you choose really depends on your architecture.

# Answer
> 3 votes
The direct answer is quoting the Symfony documentation:

> In the service container, all services are shared by default. This means that each time you retrieve the service, you’ll get the same instance. This is usually the behavior you want, but in some cases, you might want to always get a new instance.
>
> In order to always get a new instance, set the shared setting to false in your service definition:
>
> ```
> # config/services.yaml
> services:
>     App\SomeNonSharedService:
>         shared: false
>         # ...
>
> ```

https://symfony.com/doc/current/service\_container/shared.html

Discussing Drupal intentions is difficult because there aren't many references. When Drupal 8 was designed this service setting didn't exist and the predecessor was back then already disputed because of the now removed request scope. I couldn't find any references that Drupal is biased against using non-shared services. In the contrary, here a discussion where core finally switched from a factory to a non-shared service, which in fact is also a factory based solution, only that this is a factory already implemented in Symfony:

https://www.drupal.org/project/drupal/issues/2660124#comment-12318542

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: How to add anti csrf token to the forms (No Anti-CSRF tokens were found in a HTML submission form.)
When i was testing my drupal 9 website for security i got the error as "No Anti-CSRF tokens were found in a HTML submission form." solution is given as "use anti-CSRF packages such as the OWASP CSRFGuard." but how to use these in drupal forms.

# Answer
Drupal's form API already implements CSRF protection. If your form is not using the form API, you should convert it to do so, and you will automatically have the protection you need.

If your form *is* using the form API, and there are no tokens in the markup, then check custom code/templates/etc that might be removing it.

If you're not going to use Drupal's form API, you'll need to approach this as a standard development task, and implement it in the way that makes most sense for the details of your custom form implementation.
> 0 votes

---
Tags: forms, 9, csrf
---


# Question
Title: Can't import webform settings after creating / testing a form
On server I already have site setup with webform module installed. If I i.e. create and test some webform and after that try to import webform configuration with `drush cim` I get error:

"*There are entities of the type Webform submission and Webform Kontakt form These entities must be deleted before importing*".

That issue is also reported here: https://www.drupal.org/project/webform/issues/3076341 But I didn't find solution for it yet.

And by: https://www.jrockowitz.com/blog/managing-webform-configuration Webforms should be configuration entities.

So any idea why is this happening and how to solve the issue?

# Answer
> 1 votes
What you're describing sounds inevitable to me.

You've created a configuration entity (webform), you haven't exported it, and now you're running a config import. Drupal is syncing your config, so correctly tries to delete the webform because it isn't in the config you've told it to import.

The webform however has submissions, so can't be deleted, hence the error message.

Available solutions are:

1. Export the config for your new webform before trying the config import again.
2. Delete the submissions so the webform can be deleted by the import.
3. Add a suitable config ignore pattern so your work-in-progress webforms aren't considered during config imports

---
Tags: webforms
---


# Question
Title: Where to define custom entity caching rules of detail pages
When you have a larger project you probably have both internal page cache as internal dynamic page cache module enabled. In my case I do. But I have a section on my website containing custom entities ('Contest') where I would like to have custom-tailored control of caching of the detail page (contest/1). This is what I found so far:

```
/**
 * Implements hook_entity_view_alter()
 * Disable caching on all contest entity types
 */
function mymodule_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  $types = ['contest'];
  if (in_array($entity->bundle(), $types)) {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

```

Is this the only way? I'd expect to have a more clean way, in my **Contest.php** perhaps? Looking forward to possible answers!

# Answer
> 2 votes
> I was just wondering if there is a more OO way to define the caching of the custom entity detail pages.

This would be extending the route provider you are using now (DefaultHtmlRouteProvider or AdminHtmlRouteProvider), specifying it in the custom entity class

```
*     "route_provider" = {
*       "html" = "Drupal\mymodule\MyEntityRouteProvider",
*     },

```

and overriding `getCanonicalRoute` to add the no\_cache option:

```
protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
  $route = parent::getCanonicalRoute($entity_type);
  $route->setOption('no_cache', TRUE);
  return $route;
}

```

---
Tags: entities, caching, 9
---


title: Export Paragraph bundles

text:
# Question
Title: Export Paragraph bundles
I know `drupal config:export:content:type` is for exporting a content type. Is there a way to do this for a Paragraph bundle?

`drupal config:export:paragraph:type` doesn't work/exist.

# Answer
Turns out it can be done with the `config:export:entity` command.

`drupal config:export:entity paragraphs_type [PARAGRAPH_TYPE] --module="[YOUR_MODULE]" --optional-config --remove-uuid --remove-config-hash --include-module-dependencies`
> 6 votes

# Answer
Does anyone have a Drupal 9 way of doing this now that Drupal console is not moving across to Drupal 9?
> 1 votes

---
Tags: 8, importing-exporting, paragraphs, console
---


# Question
Title: How to add inline CSS style in Custom Text of Views?
I have already setup fields for user to input color code (e.g. "#123000") to a content type. Now I need to modify the inline style color / background-color with the given value. I tried to do this in my Custom Text field:

```
    <div class="box" style="color: {{ color_field }}">
        <h2>{{ title }}</h2>
        <span class="description">{{ body }}</span>
    </div>

```

But the rendered output would become:

```
    <div class="box">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

```

I went as far as creating my own Twig function implementation:

```
    <div class="box" {{ my_dummy_function(color_field) }}>
        <h2>{{ title }}</h2>
        <span class="description">{{ body }}</span>
    </div>

```

The function would supposedly output `style="color: color_field_value"`, but the whole attribute would be "eaten" by Drupal's rendering chain. Even adding a `| raw` filter after that would not change a thing.

```
    <div class="box">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

```

In desperate, I modified my dummy Twig function to output `hello="world"`, and the attribute would be rendered normally:

```
    <div class="box" hello="world">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

```

But if it output something like `hello="color: world"`:

```
    <div class="box" hello=" world">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

```

So it seems there are some keyword-based filtering going on. And I can't seem to have a way to render anything resembling inline CSS. Is there anyway I can achieve my goal?

# Answer
This is a problem I've encountered numerous times, and personally I've never had any luck outputting inline styles in a Views field that's been rewritten through the UI.

My solution has always been to create a template file that takes responsibility for rendering the view fields, as that does allow you to use inline styles.

In your case, you could have the file in your theme's /templates folder (I have them in a /views subdirectory), with a filename like:

```
views-view-fields--your-view-name.html.twig

```

You'd then just need to slightly tweak the markup you already have:

```
<div class="box" style="color: {{ fields.field_color_field.content }}">
    <h2>{{ fields.title.content }}</h2>
    <span class="description">{{ fields.body.content }}</span>
</div>

```
> 1 votes

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


# Question
Title: How to retrieve #tree values inside multiple containers?
I am using Drupal 8 and I am creating multiple forms that are made of a #tree hierarchy.

I need to retrieving the value of the "first name" from the #tree using the below code and it doesn't get the value.

```
$firstName = $form_state->getValue('userBoxArea')[$count]['userBox']['nameBox']['firstName'];

```

This is my code:

```
protected static $formID;

public function getFormId() {
    if (empty(self::$formID)) {
        self::$formID = 1;
    }
    else {
        self::$formID++;
    }

    return 'formID' . self::$formID;
}

public function buildForm(array $form, FormStateInterface $form_state){

    $database = \Drupal::database();
    $result = $database->select('user_details', 'u')
    ->fields('u', ['uid']);
    $row = $result->execute()->fetchAll();
    $rowCount = count($row);

    $form['userBoxArea' ] = [
        '#type' => 'container',
        '#tree' => TRUE,
    ];

    for($counter = 0; $counter < $rowCount; $counter++){
        $form['userBoxArea'][$counter] = [

            'userBox' => [
                '#type' => 'container',

                'nameBox' => [
                    '#type' => 'container',

                        'firstName' => [
                            '#type' => 'textfield',
                            '#title' => 'Enter your first name',
                        ],

                ],

                'save' => [
                    '#type' => 'submit',
                    '#value' => $this->t('Save'),
                    '#name' => 'save-' . $counter,
                    '#submit' => ['::submitForm'],
                    '#validate' => ['::validateForm'],
                    '#limit_validation_errors' => [],
                ],

            ],

        ];
    }

    return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
    $firstName = $form_state->getValue('firstName');

    if (strlen($firstName) == NULL) {
        $form_state->setErrorByName('firstName', $this->t('The First Name should not be empty.'));
    }
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    $submitString = $form_state->getTriggeringElement()['#name'];
    $submitNumber = explode("-", $submitString);
    $count = $submitNumber[1];
    $firstName = $form_state->getValue('userBoxArea')[$count]['userBox']['nameBox']['firstName'];

    $this->messenger()->addMessage($this->t('Your first name is %firstName has been saved.', ['%firstName' => $firstName]));
    $this->messenger()->addMessage($this->t('Button number: @num', ['@num' => $count]));
}

```

The rowCount pertains to the row in my database. The process is to acquire firstName from the user and those variables will be saved inside the database.

I have researched articles from Drupal if there is a limitation of the #tree containers and found nothing about it.

Any suggestions if I am missing something. How do you retrieve the value of "firstName"?

Thanks in advance.

# Answer
> 0 votes
The error comes from `validateForm()`, where you use the following line.

```
$firstName = $form_state->getValue('firstName');

```

You need to retrieve the first name values using the tree.

---
Tags: 8, forms
---


# Question
Title: How can we restrict the access of files in public folder from anonymous users?
In my project, I am using headless Drupal with .Net on the front end.

I have to use encrypted file system for the project requirements. I am encrypting the files and then decrypting using oauth token and storing them in public folder so that .Net application can get the file as API response. But the problem starts here. As these files are in public folder, if a user logs in to the site and then copies this url and pastes that in another browser, he can easily view that file. But this is not the desired requirement and it creates a major security breach. So my question is how can we restrict public files from getting accessed by anonymous users?

# Answer
> 1 votes
Drupal provides a private file system mode for files ( https://www.drupal.org/docs/8/core/modules/file/overview#s-managing-file-locations-and-access ) that allows restricting access via hook\_file\_download ( https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21File%21file.api.php/function/hook\_file\_download/8.9.x )

If you can’t use private file system mode for storage then you’ll need to restrict access in your web server, such as nginx.

---
Tags: console
---


# Question
Title: How to prevent a node from being deleted while performing a delete operation?
I want to prevent a node from being deleted while a delete operation is performed on it. For example in administration panel if user clicks "Delete" on the node, the node shouldn't be deleted if he is not an administrator. Permissions and user roles are not a problem for me, the problem is "stopping" delete operation.

I found `hook_entity_predelete()`, which is perfect, it runs exactly just before deleting the node, but I don't know how to stop delete operation. I want to do some things inside that hook and prevent deleting the node.

I saw also this issue: How do I prevent a Node from being deleted? with `hook_node_access()`, but it is not working as I need.

`hook_entity_delete()` is also not ok, because `This hook runs once the entity has been deleted from the storage`. I need to prevent it.

Thanks for your help.

# Answer
> 1 votes
I found a solution that satisfies me: I use `hook_form_alter()`. When you always try to delete a node there is a confirmation form, with "Delete" and "Cancel" buttons. I'm altering that form - in some cases (which depend of users permissions) I am unsetting "Delete" button (with `unset($form['actions']['submit']`, so delete is not possible) and adding my own button instead of it, with a callback function. I am also altering title of that form and description.

---
Tags: nodes, 9
---


# Question
Title: ConstraintValidator fails to validate constraint on Taxonomy Term reference field
Client has a simple and consistent hierarchical taxonomy.

Cities at the top level and Schools at the second level.

```
.
├── City1
│   ├── School1
│   ├── School2
│   └── School5
└── City2
    ├── School3
    └── School4

```

The User account entity bundle contains an Entity Reference field to the School taxonomy terms.

I am trying to enforce a constraint to prevent creating or saving a user account if the term selected is at the top level of the hierarchy (and hence a City, not a School).

Here's some example code, skipping the dependency injection of `$this->entityTypeManager` for brevity.

`TermParentConstraint.php`:

```
<?php

namespace Drupal\entity_validation_examples\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Prevent account creation if School taxonomy term has no parent.
 *
 * @Constraint(
 *   id = "TermParent",
 *   label = @Translation("Prevent account creation if term has no parent", context = "Validation"),
 *   type = "entity"
 * )
 */
class TermParentConstraint extends Constraint {

  /**
   * Message shown when trying to create account if School has no parent City.
   *
   * @var string
   *   School message.
   */
  public $schoolMessage = 'You must select both a City and a School.';

}

```

`TermParentConstraintValidator.php`:

```
<?php

namespace Drupal\entity_validation_examples\Plugin\Validation\Constraint;

use Drupal\user\Entity\User;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the TermParent constraint.
 */
class TermParentConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($entity, Constraint $constraint) {
    if (!isset($entity)) {
      return;
    }

    if ($entity->getEntityTypeId() == 'user') {

      $school = $entity->get('field_select_a_school')->getValue();

      // Orphaned school taxonomy terms must be Cities, not Schools.
      $parent = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->loadParents($school[0]['target_id']);
      if (empty($parent)) {
        $this->context->addViolation($constraint->schoolMessage);
      }
    }
  }

}

```

**Expected behavior:** When I create a new user account and select `City1` as the value of `School`, account creation should fail and an error message should be displayed.

**Actual behavior:** When I create a new user account and select `City1` as the value of `School`, account creation succeeds and no error message is displayed.

Drupal Watchdog logs contain some errors, but I am not sure they are relevant:

```
 drush ws
 --------- -------------- ------ ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  ID        Date           Type   Severity   Message
 --------- -------------- ------ ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  5298867   18/Oct 22:57   php    Warning    Warning: Illegal offset type in isset or empty in Drupal\Core\Entity\EntityStorageBase->load() (line 246 of /app/docroot/core/lib/Drupal/Core/Entity/EntityStorageBase.php) #0 /app/docroot/
  5298866   18/Oct 22:57   php    Notice     Notice: Array to string conversion in Drupal\Core\Entity\EntityStorageBase->buildCacheId() (line 126 of /app/docroot/core/lib/Drupal/Core/Entity/EntityStorageBase.php) #0 /app/docroot/core
  5298865   18/Oct 22:57   php    Warning    Warning: array_flip(): Can only flip STRING and INTEGER values! in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 261 of /app/docroot/core/lib/Drupal/Core/Entity/EntityStorageB
  5298864   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298863   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298862   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298861   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298860   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298859   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
  5298858   18/Oct 22:57   php    Notice     Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1009 of /app/vendor/twig/twig/src/Extension/CoreExtension.php) #0
 --------- -------------- ------ ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

```

I've been seeing the `iconv()` errors since upgrading this project from Drupal 8 to Drupal 9, so I do not think they are relevant. The top three error messages here may be related to the constraint validation, but they are also rather common errors in this project (and debugging them is a much lower priority than essential functionality due very soon).

Any ideas? Am I at least on the right track?

# Answer
In this case, it turns out that the quickest solution is to configure the Simple Hierarchical Select widget correctly. (The SHS module is already installed, so I may as well use it!)

For the record, this is the problematic widget configuration.

**BEFORE:**

**AFTER:**

Thanks for all the answers, everybody! I learned quite a bit about constraint validation and hierarchical taxonomy, which will help me next time I have to deal with taxonomy trees or implement a `ConstraintValidator` class.
> 0 votes

# Answer
The `loadParents()` method calls `loadMultiple()`, and that is where the `array_flip()` error is happening:

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 261 of /app/docroot/core/lib/Drupal/Core/Entity/EntityStorageB

```

So most likely something going on there.

The `loadParents()` method is different depending on your Drupal version.
> 1 votes

# Answer
The problem is you are loading parents in an array and then check for an empty value. Terms at the top level can have a root parent (ID=0), so this would be an item in the array as well, even if not pointing at an existing term.

You can try to simplify the code, since D8.6 you don't need to use the term storage anymore to handle the parent field. empty() on the target ID catches `NULL` for an empty field and `0` for the root parent.

```
 public function validate($entity, Constraint $constraint) {
    if (!isset($entity)) {
      return;
    }

    if ($entity->getEntityTypeId() == 'user') {
      $term = $entity->get('field_select_a_school')->entity;
      if ($term) {
        if (empty($term->parent->target_id)) {
          $this->context->addViolation($constraint->schoolMessage);
        }
      }
    }

  }

```
> 1 votes

---
Tags: entities, 9
---


# Question
Title: Using both Drupal Core Contact Form and contributed Webform module
I have a Drupal 8 site already utilizing core Contact Form. However, we now need a more complex form and thinking about installing a contributed module: Webform (https://www.drupal.org/project/webform).

My concern is that having both Contact form and Webform enabled, will there be an issue like one impacting the other?

Thanks.

# Answer
It is fine to use both. If you are not using the Contact Storage module, it should be very easy to convert your contact forms to webforms.
> 1 votes

---
Tags: forms, webforms
---


# Question
Title: How do I create multilingual user path aliases?
I'm setting up a multilingual site, and I need the user path aliases to be multilingual.

Users are set up as translatable:

Language Detection: URL (path prefix)

* English: `/en`
* Japanese: No prefix

Pathauto patterns:

* English: `/en/users/[user:name]`
* Japanese: '`/users/[user:name]`

Example:

* Username: Admin

Expected paths:

* English: `/en/users/admin`
* Japanese: `/users/admin`

Actual:

* English: `/en/user/1`
* Main language: `/users/admin`

I've cleared the registry, regenerated the URLs, manually unset path aliases on the user then checked the box and re-saved, but I have not found any combination that results in multilingual path aliases.\]

## Update

I've tried the following, which also did not work:

# Answer
I followed your setup on a vanilla D9 and can report on the following:

* Pathauto aliases are created as expected  but only for translated users  That is an expected outcome looking at Pathauto's code, since it will start generating language specific aliases based on a pattern only for the translated languages of each entity during bulk updates and only for the active language of an entity during hook\_entity\_update.
* A manually created path alias  for an untranslated language of a user entity does work and resolves properly.

In short, the answer is:

Multilingual user aliases are created automatically by Pathauto for each translated language of a user entity, or can be added manually for non-translated languages of a user entity.
> 1 votes

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


# Question
Title: Not allowing the user to access the website within the given time period
My client want to offline the site for 12:00 AM to 06:00 AM and show this message to users. How can I achieve this in drupal8

# Answer
> 1 votes
and welcome to StackExchange.

As stated in the comments on your question, you are essentially asking for Maintenance Mode, which is part of Drupal core. In your site, go to `/admin/config/development/maintenance` and look at the settings there. You can turn on Maintenance mode, and set the text that is shown to unauthorized users. There is also a permission setting (found on the permissions page) to still use the site in maintenance mode, in case you want to make edits while others cannot access the site.

To have this happen automatically based on time, you will want to use Cron. That is what Cron was built to do, so it is a perfect fit. In order to use Cron for this, you will need a handy bit of code that can do the same thing as the checkbox in the maintenance ui. Drush is a very powerful tool, and can do almost anything. To turn maintenance mode on, you could run this:

```
drush state:set system.maintenance_mode 1 --input-format=integer

```

That command is found and explained on this page. Now, you need to have that command run by cron instead of by a human on the server command line. Fortunately for you, Drupal has a long history of dynamically using custom code that you add, as long as the name matches. That is the hook system, where custom modules and functions matching certain patterns are called at certain times. You will want to create a custom module that uses hook\_cron() to run that drush command at the designated times.

And finally, always clear cache before thinking something is broken.

---
Tags: configuration, maintenance-mode
---


# Question
Title: Can't migrate files that contain spaces and underscore
I'm migrating my D7 site to D9 and I'm getting 2K+ fail migrations for my `files` directory. It's failing because the file names contain `Spaces` and `Underscores`.

Does anyone know what I need to do to decode the `Spaces` and `Underscores`?

Here's my file.yml file:

```
uuid: 56fb6b6b-7cbe-44b6-808e-a548b8173a7b
langcode: en
status: true
dependencies: {  }
id: upgrade_d7_file
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Content
migration_group: migrate_drupal_7
label: 'Public files'
source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: 'C:wamp64/www/sseto-741'
process:
  fid:
    -
      plugin: get
      source: fid
  filename:
    -
      plugin: get
      source: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    -
      plugin: file_copy
      source:
        - '@source_full_path'
        - uri
  filemime:
    -
      plugin: get
      source: filemime
  status:
    -
      plugin: get
      source: status
  created:
    -
      plugin: get
      source: timestamp
  changed:
    -
      plugin: get
      source: timestamp
  uid:
    -
      plugin: get
      source: uid
destination:
  plugin: 'entity:file'
  source_base_path: C:wamp64/www/sseto-741/sites/default/files/
migration_dependencies:
  required: {  }
  optional: {  }

```

# Answer
> 1 votes
You can replace Space, Underscores with '**%20**' and '**%5f**'. You can use module migrate\_plus with process plugin str\_replace like this:

```
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
    -
      plugin: str_replace
      search: [" ", "_"]
      replace: ["%20", "%5f"]

```

---
Tags: migrations, 9
---


# Question
Title: Why doesn't the Status Report page show any information?
I've just done an upgrade of my site from Drupal 8.9.16 to Drupal 9.2.6. Everything looks fine but when I go to /admin/reports/status there is no information as per the screenshot. I've never come across this before, can anyone help?

I cleared the cache multiple times, ran Cron, without any effect.

>

# Answer
> 1 votes
The issue was that the PHP version on the server was set to 7.2 when it should have been 7.3 or higher.

---
Tags: 9
---


# Question
Title: How can I access the parent entity values inside a custom paragraph formElement?
I created a select custom field that must be inserted inside a paragraph and the options values are dynamically inserted based on another reference field present in the paragraph itself. How can I access the actual paragraph instance to read the value of the reference field, so I can manage the right values inside the formElement function of the custom field?

# Answer
> 2 votes
You can get the parent entity of the field, in your case the paragraph, from the field object `$items`.

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  // get the parent entity of the field
  $entity = $items->getEntity();

```

---
Tags: 9, paragraphs
---


# Question
Title: How can I add a single taxonomy term label as a body class?
I'd like to add a single taxonomy term into the body tag as a class in drupal 8 - so I page styles can be controlled easily. I have tried (path and ID as class in body How can I dynamically add URL or taxonomy to body class and https://www.drupal.org/node/2634364) which only get me part way there, taxonomy term would provide a future proofed solution.

# Answer
i found a solution which worked perfectly for me. Add this in your .theme file and replace **mytheme**\_preprocess\_html by your theme name and field\_section by name of your taxonomy field.

\[https://gist.github.com/awasson/d8ef8d7c1b64b2ccb8a0\]\[1\]

```
<?php

    /**
     * Prepares variables for the html.html.twig template.
     */

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

    function mytheme_preprocess_html(&$variables) {

      if ($node = \Drupal::routeMatch()->getParameter('node')) {

        /**
         * Get the term id from the 'field_section' taxonomy field.
         * If greater than zero, load the term and acquire the name value
         * as a css safe value.
        */
        if($node->hasField('field_section')) {
          $tid = $node->get('field_section')->target_id;
          if($tid > 0) {
            $term_object = Term::load($tid);
            $variables['attributes']['class'][] = 'terms--' . Html::getClass($term_object->get('name')->value);
          }
        }

        /**
         * Get the node id from the node object.
         * If greater than zero, add the node id to body classes
        */
        $nid = $node->get('nid')->value;
        if($nid > 0) {
          $variables['attributes']['class'][] = 'page--node-' . $nid;
        }
      }

    }

```
> 4 votes

# Answer
Here it is my snippet for `field_razdel` with transliteration (as my site is not english). Finally I have these body classes (other elements are added with another piece of code):

```
  <body class="no-sidebars terms--obrazovanie path-node page-node-type-article">

```

**terms--obrazovanie** is added by next snippet:

```
// Add taxonomy term from field_razdel as body class.
if ($node = \Drupal::routeMatch()->getParameter('node')) {
  // Get the term id from the 'field_section' taxonomy field.
  // If greater than zero, load the term and acquire the name value
  // as a css safe value.
  // Use the current default interface language.
  $langcode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();

  // Instantiate the transliteration class.
  $trans = \Drupal::transliteration();

  if ($node->hasField('field_razdel')) {
    $tid = $node->get('field_razdel')->target_id;
    if ($tid > 0) {
      $term_object = Term::load($tid);
      //$variables['attributes']['class'][] = 'terms--' . Html::getClass($term_object->get('name')->value);
      $transformed = $trans
        ->transliterate(Html::getClass($term_object->get('name')->value), $langcode);
      $variables['attributes']['class'][] = 'terms--' . $transformed;
    }
  }
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Meta Tags Module: Set of available meta tags is different for certain node types
I have a behaviour, which I don't understand: using Meta Tags and a couple of sub modules (like twitter cards, schema.org: JobPosting, etc.) On `/admin/config/search/metatag/add` I see them for certain node types and for others not. Does anybody know why this is and how to fix it?

Expected for all content types:

Not Expected, I just switched the type and everything under twitter-cards vanishes:

The node type config has no structural difference I can detect, so I guess it must be something else.

# Answer
> 2 votes
Check the metatag settings at `/admin/config/search/metatag/settings` for each type.

Note the description on the settings page:

> Identify which metatag groups should be available on which entity type / bundle combination. Unselected groups will not appear on the configuration form for that entity type, reducing the size of the form and increasing performance. If no groups are selected for a type, all groups will appear.

It's possible that someone selected some of the metatag groups for certain node types, **which will cause the other types to be hidden**.

This is one of those annoying Drupal forms where the rule is:

* If you select some items, they will be selected.
* If you select no items, all items are selected.

---
Tags: 9, meta-tags
---