# Question
Title: How to use wysiwyg text editor (text_format) in a system configuration form
I couldn't find any documentation or examples about this. The implementation is very problematic. Do you a means to do this?

## Problems

While trying to create a `system settings form` with `text_format` input, I get following errors while displaying the form. The form is being submitted normally and the values are being saved but when the page refreshes the text editor is not populated with the saved values and the errors are always there.

> User error: "value" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).
>
> User error: "format" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

The code in `buildForm()` is as follows:

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('commerce_distance_terms.distanceterms');
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#description' => $this->t('Title for the terms'),
      '#maxlength' => 64,
      '#size' => 64,
      '#default_value' => $config->get('title'),
    ];
    $form['distance_selling_terms'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Distance Selling Terms'),
      '#description' => $this->t('Enter Distance Selling terms'),
      '#default_value' => [
        'value' => $config->get('distance_selling_terms.value'),
        'format' => $config->get('distance_selling_terms.format'),
//         '#tree' => FALSE,
        '#printed' => TRUE,
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

```

## Background information

* This is the error as it links from the code.
* The errors are thrown because of the `#default_value` part of the array. Adding a `#value => array()` reduces the errors. But nothing changes.
* What I got from the stacktrace is that the form is being rendered, then the textarea is being rendered, and then the source of the error is being rendered (There are small elements inbetween). So I think the source of the error is the `#default_value` element of the `textarea` which is copied and pasted from the above array part while the compound text editor is being created.
* In one of the rendering iterations, the `Element::children()` thinks that it should render the `value` and the `format` elements of the above array. Since they don't start with `#`.
* There is a word here that system settings form doesn't support `text_area` input from Drupal 7. Also that and some linked issues tell that there are some automatic defaults for system\_settings\_form but I couldn't find the equal.
* The `text_format` input is a compound element that includes a `textarea` (to hold and populate the actual value), a dropdown format element to select from, etc. The `textarea` element comes with the exact `#default_value` that I put above (as an array). I tried to `preprocess` this `textarea` and change that value to the related string to populate the field but whatever I do `textarea` comes always empty.
* The `#printed` and `#tree` elements of the array don't change anything. I also put them inside the `textarea` array in the `preprocess` function but nothing changed.
* The textarea's `data-editor-value-original` property comes with the above array flattened even tough I change the `#default_value` and `#value` in the preprocess.
* The text editor not being able to be populated may not be related to above errors. I know nothing.

# Answer
> 11 votes
```
$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
];

```

And if you want to limit the wysiwyg editor to only the one format, add #allowed\_formats as in:

```
$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
  '#allowed_formats' => [
    $config->get('distance_selling_terms.format') => 'Description of format'
  ],
];

```

# Answer
> 2 votes
In order to make your configuration translatable when it uses a text\_format you need to have the following mapping:

```
your_custom_form_field:
  type: mapping
  label: 'Free text with text format support'
  translatable: true
  mapping:
    value:
      type: text
      label: 'Custom Text'
    format:
      type: string
      label: 'Text format'

```

Have a look at this core patch and thread:
https://www.drupal.org/files/issues/2144413-185-config-translation-text-format.patch
https://www.drupal.org/node/2144413
for a more detailed example and discussion.

# Answer
> 1 votes
In your **builForm()** method, your text\_format form/render element usage is wrong.

You can see the text format render element properties and usage on drupal.org: Text format render element

So you can use like this:

```
/**
 * Provides a text format render element.
 *
 * Properties:
 * - #base_type: The form element #type to use for the 'value' element.
 *   'textarea' by default.
 * - #format: (optional) The text format ID to preselect. If omitted, the
 *   default format for the current user will be used.
 * - #allowed_formats: (optional) An array of text format IDs that are available
 *   for this element. If omitted, all text formats that the current user has
 *   access to will be allowed.
 *
 * Usage Example:
 * @code
 * $form['body'] = array(
 *   '#type' => 'text_format',
 *   '#title' => 'Body',
 *   '#format' => 'full_html',
 *   '#default_value' => '<p>The quick brown fox jumped over the lazy dog.</p>',
 * );
 * @endcode
 */

```

In your case your code should be modified to this:

```
 $form['distance_selling_terms'] = [
   '#type' => 'text_format',
   '#title' => $this->t('Distance Selling Terms'),
   '#description' => $this->t('Enter Distance Selling terms'),
   '#format' => $config->get('distance_selling_terms.format'),
   '#default_value' => $config->get('distance_selling_terms.value'),
 ];

```

In the **submitForm()** method you should update the configuration:

```
/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  // This parent class's submitForm method only shows
  // "The configuration options have been saved." message
  parent::submitForm($form, $form_state);

  // You can get all submitted values in array format with $form_state->getValues()
  $values = $form_state->getValues();

  // Update the configuration
  $this->config('commerce_distance_terms.distanceterms')
    // Set the title to the configuration
    ->set('title', $values['title'])
    // Set the value of the textarea to the configuration
    ->set('distance_selling_terms.value', $values['distance_selling_terms']['value'])
    // Set the format of the textarea to the configuration
    ->set('distance_selling_terms.format', $values['distance_selling_terms']['format'])
    // Save the configuration
    ->save();
}

```

# Answer
> 1 votes
Also, the the mapping section for the module's schema file, the field should be something like:

```
YOUR_MODULE.settings
  type: mapping
  label: Settings or whatever
  mapping:
    distance_selling_terms.value:
      type: text
    distance_selling_terms.format:
      type: string

```

Similarly, your settings.yml file will look something like:

```
 distance_selling_terms:
     value: "whatever"
     format: basic_html

```

# Answer
> 1 votes
I was facing on this problem recently, thanks to @bserem for have to shared : https://www.drupal.org/files/issues/2144413-185-config-translation-text-format.patch cuz I found the answer in this patch. So I used this on my mymodule.schema.yml

```
block.settings.myblock:
  type: block_settings
  label: 'Myblock configuration'
  translatable: true
  mapping:
    text:
      type: text_format
      label: 'Text'

```

---
Tags: 8, forms, input-formats, configuration
---


title: How to add Pager to a custom page?

text:
# Question
Title: How to add Pager to a custom page?
I have a list of items which is fetched from an REST API and displayed in a page **10** at a time. These items are not stored in Drupal database in any way. I managed to have a basic pager which is just a **Previous** & **Next**. But as per design the list should have a full pager.

So, how can I add a Full Pager in such page?

# Answer
> 15 votes
There are some examples on drupal.org of adding a pager to the page, if you want to use the one that core uses:

https://api.drupal.org/api/drupal/core%21includes%21pager.inc/function/pager\_default\_initialize/8.2.x

The second example should work for you:

```
  $page = pager_find_page();
  $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
  $offset = $num_per_page * $page;
  $result = mymodule_remote_search($keywords, $offset, $num_per_page);

  // Now that we have the total number of results, initialize the pager.
  pager_default_initialize($result->total, $num_per_page);

  // Create a render array with the search results.
  $render = [];
  $render[] = [
    '#theme' => 'search_results',
    '#results' => $result->data,
    '#type' => 'remote',
  ];

  // Finally, add the pager to the render array, and return.
  $render[] = ['#type' => 'pager'];
  return $render;

```

I have done this before in my own wired up search pages, it should solve your issue.

You can replace $num\_per\_page above with 10, if you do not have a custom module to store the setting.

You could go further, and in your code create a service that handles just attaching the pager. I was doing some sandboxing exploring the search API, and came up with this. First, you need to define your service and inject it to your controller (I refer to mine as pager\_service).

```
  /**
   * @var \Drupal\velirsearch\Service\PagerService
   */
  private $pager_service;

  /**
   * SearchResults constructor.
   * @param \Drupal\velirsearch\Service\PagerService $pager_service
   */
  public function __construct(PagerService $pager_service) {
    $this->pager_service = $pager_service;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    $pager_service = $container->get('velirsearch.pager_service');
    return new static($pager_service);
  }

```

Then, a method that attaches a pager:

```
     /**
       * Convenient method to obtain a pager to attach from the pager service.
       * @param $totalRows
       * @param $limit
       * @return array
       */
      protected function attachPager($totalRows, $limit) {
        return $this->pager_service->getPager($totalRows, $limit);
      }

```

Then, the service:

```
namespace Drupal\velirsearch\Service;

use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class PagerService implements ContainerAwareInterface {

  use ContainerAwareTrait;

  /**
   * @var \Symfony\Component\HttpFoundation\Request
   */
  private $requestStack;

  /**
   * PagerService constructor.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $requestStack = $container->get('request_stack');
    return new static($requestStack);
  }

  /**
   * @param $totalRows
   * @param $limit
   * @return array
   */
  public function getPager($totalRows, $limit = 10) {
    pager_default_initialize($totalRows, $limit);
    return ['#type' => 'pager'];
  }
}

```

Then, when you need it...

```
  $render[] = $this->attachPager($results->getResultCount(), 10);

  return $render;

```

You don't necessarily have to go that far, I was just looking for ways to reduce the code needed to attach a pager to different instances of search result controllers. YMMV.

Note that I did not use the third argument to pager\_default\_initialize, `$element`, which you will need if your page will have multiple pagers on it.

`getResultCount()`, by the way, is a method provided from Search API ResultSet class.

edit: now looking at my answer, your pager service does not need to inject the RequestStack at all. I was probably thinking of another idea and never finished it or figured I did not need it.

# Answer
> 2 votes
As per change record `pager_default_initialize()` has been deprecated and new `pager.manager` service is created.

```
$current_page = \Drupal::service('pager.manager')->createPager($total_count, $results_in_page)->getCurrentPage();

```

Sample Code using new pager service.

```
<?php

namespace Drupal\controller_examples\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Component\Serialization\Json;

/**
 * Class CustomPagerController.
 *
 * @package Drupal\controller_examples\Controller
 */
class CustomPagerController extends ControllerBase {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The pager manager.
   *
   * @var \Drupal\Core\Pager\PagerManagerInterface
   */
  protected $pagerManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->messenger = $container->get('messenger');
    $instance->logger = $container->get('logger.factory')->get('controller_examples');
    $instance->moduleHandler = $container->get('module_handler');
    $instance->pagerManager = $container->get('pager.manager');
    return $instance;
  }

  /**
   * Returns a render-able array for a location import.
   */
  public function import() {

    $header = $decoded = [];

    $header = ['State Id', 'State Name', 'Country Id'];

    $moduleExist = $this->moduleHandler->moduleExists('controller_examples');

    if ($moduleExist) {

      $modulePath = $this->moduleHandler->getModule('controller_examples')->getPath();
      $file = $modulePath . '/data/states.json';
      $locationData = file_get_contents($file);
      $decoded = Json::decode($locationData);
      $this->logger->notice($this->t('States count is %count', ['%count' => count($decoded['states'])]));
    } else {
      $this->logger->error('Controller Examples Module Not Exist');
      $this->messenger->addError("Controller Examples Module Not Exist");
    }

    $rows = $decoded['states'];

    $rowPiece = $this->pagerArray($rows, 50);

    $build['table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rowPiece,
      '#empty' => $this->t('No content has been found.'),
    ];
    $build['pager'] = [
      '#type' => 'pager',
    ];
    return $build;
  }

  /**
   * Returns pager array.
   */
  public function pagerArray($items, $itemsPerPage) {
    // Get total items count.
    $total = count($items);
    // Get the number of the current page.
    $currentPage = $this->pagerManager->createPager($total, $itemsPerPage)->getCurrentPage();
    // Split an array into chunks.
    $chunks = array_chunk($items, $itemsPerPage);
    // Return current group item.
    $currentPageItems = $chunks[$currentPage];
    return $currentPageItems;
  }
}

```

---
Tags: 8, paging, page-controller
---


# Question
Title: Display title, based on exposed filter of view
I've read these questions:

But it did not help.

My Drupal version is 9.1.9. I have views displaying Taxonomy terms. Each taxonomy term has fields, for example "Genre". I have 16 different genres with "key|value" type.

I have exposed filter, based on genre field. I've added this field to **Contextual filters** and override the title, when filter value is in URL.

But!

1. If there is no value in URL title displays "All", but it should display default view title.
2. If filter is applied and there is value in URL, title displays field's KEY, but not it's VALUE, for example "2" (not the name of the genre).

What am I doing wrong?

# Answer
1. Did you enable the override title under `Exceptions` when the `Display all results for the specified field` is chosen under `When the filter value is NOT available`? Then it's doing what it's supposed to do, that override is only for the Exception, and you most likely have the value `All` there. Turn that title override **off**, and the default Title will be shown in the case when there is no argument for the filter.
2. List fields only store key, not the value! That is why the Contextual is using and showing they key. If your value isn't complex maybe you can use it as the key as well? You don't need to enter both key and value into Field settings, if you enter only one it will be used as both the key and value. If you're dealing with phrases you can maybe construct the keys with "-" or "\_" and keep the values properly capitalized. This will give you predictable Contextual filter arguments.
> 1 votes

---
Tags: views
---


# Question
Title: How do I organize the display of product variation fields?
I have a new site with Drupal 9 and Commerce 2. I am trying to display my products with:

* Title
* Photo
* Price
* Delay
* Options
* *Add to cart* button
* Description

I tested all the possible settings in manage display, but nothing works. What I get is inconsistent with the configuration.

How do I organize the display of product variation fields?

>

>

>

# Answer
> 1 votes
This is a known difficulty in Commerce 2.x. You can review the options in this issue https://www.drupal.org/project/commerce/issues/2928139

The best solution I have found is clicking show row weights in manage display for the product, the product variation, and the order item type - add to cart form - form display. You can then manually set the weights rather than drag and drop. For example set the weight of the field you want to be first to -50, and the field you want to be last to be 50. Then adjust the fields in the middle.

You will have to jump back and forth between the 3 displays I mentioned, and this won't fix all your problems, but it will help.

You can overwrite the twig template in your theme as seen here: https://www.drupal.org/project/commerce/issues/2928139#comment-13444854

You could also hack and hide all the fields, and build custom view of fields, and use display suite to add the block view to your product display.

It really depends on what exactly you want to do.

---
Tags: commerce, 9
---


# Question
Title: How do I stop a node submission programmatically?
i'm using Drupal 8. I would like to stop the user to submit a node when he tap save, and show some message. How can I do it programmatically?

Thanks!

# Answer
> 1 votes
You can hide the form submit button using hook\_form\_alter() and show a link `Save and Publish` on form. And include a jQuery snippet to show message, which will be triggered when user clicks on a link `Save and Publish`.

# Answer
> 1 votes
If you want to prevent form submission and show message, you can add form validation to your form (using hook\_form\_FORM\_ID\_alter):

```
function MYMODULE_form_node_MYNODETYPE_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = '_node_MYNODETYPE_form_validate';
}

function _node_MYNODETYPE_form_validate($form, $form_state) {
  // add some logic to show or not show message here
  $form_state->setErrorByName('field_MYFIELD', 'Message to show by my field');
}

```

# Answer
> 0 votes
To avoid saving the results, you must remove (or override) the save function from the form. Try this:

```
function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
        $form['actions']['submit']['#submit'][0] = "_custom_submit";
        unset($form['actions']['submit']['#submit'][1]); //Avoid save results
}

```

---
Tags: 8
---


# Question
Title: How to silently prevent Webform spam (specific names, email addresses)?
I am using Webform on Drupal 8; I have a few spambots that fill out the exact same form in the same way every day.

I want to do some kind of validation that automatically blocks these postings. For example, if the name given is "Spambot 1", I want to discard the webform submission automatically.

Drupal 7 has the **Webform Validation** module but this has not yet been ported to Drupal 8.

I found a code snippet on adding custom validation to a webform element, but this seems to be for providing helpful errors to allow the user to re-submit the webform, whereas I want to make it seem like the form was submitted but silently discard the submission.

# Answer
All the available SPAM protection modules for Drupal 8 are listed on the Webform Add-ons documentation page.

Text inputs now support patterns, you could explore creating a negative lookahead pattern like ^(?!.*spam).*$,
> 3 votes

# Answer
To Avoid spam keywords on Webforms with field. just check this out, https://www.drupal.org/project/webform\_spam\_words

Administrators can provide the ability to add spam keywords, Error message, Webform field name.
> 1 votes

---
Tags: 8, webforms
---


title: html Form within a block

text:
# Question
Title: html Form within a block
I have a form within custom block in drupal 8 and I know that this is not the right method to write a form within a block but someone wrote it and I am trying to fix it without changing the method. In the return of the  `public function build()` , he rendered the html of a form within the markup.

```
 return array(
      '#markup' => '<form>
//we have here many inputs
//then at the end:
 <input  type="hidden" name="form_id" value="country_language_form">
  <div class="yellow"><a class="btn button button--primary js-form-submit form-submit" id="edit-submit--2">'.t("Submit").'</a> </div>
</form>',

```

I was wondering how does this code work (the form is actually submitted) when the user is anonymou s and it doesn't work (click on submit doesn't do anything) when the user is logged in as admin.

# Answer
My first guess would be an incorrect targeting of the submit button when the user is logged in (be aware that Drupal adds a lot of elements to the DOM when being logged in).

I'd highly recommend you to use the right method and build your form with the form API, though. Your block build code would look like this:

```
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\your_module_name\Form\YourForm');
    $build['content'] = $form;
    return $build;
  }

```

And all your form-related code would be in the YourForm.php file.
> 3 votes

---
Tags: 8
---


# Question
Title: How to create a dblog record from a views exposed form submission
I am trying to create a log record of searches made though my Search API View exposed form block in Drupal 9.

For some reason on a brand new search I get 2 duplicates (3 total entries), and it seems like I remember reading somewhere that the forms can be submitted multiple times. So I would like to know how I could eliminate that.

Update: here is an issue for Drupal 7 https://www.drupal.org/project/views/issues/2088549

Also, on searches for keywords that result in "no results" I am not seeing an entry in the log This behaviour seems hit and miss. I am using the following code with limited success:

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_form_views_exposed_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // Create a search_log submission function for watchdog
  $view_names = array('search_api_view');
  $view = $form_state->getStorage('view');
  if ($form_id == 'views_exposed_form' && in_array($view['view']->id(), $view_names)) {
    if ($form['#id'] == 'views-exposed-form-search-api-view-page-1') {
      $form['#submit'][] = 'MY_search_api_log';
    }
  }
}

function MY_search_api_log(&$form, FormStateInterface $form_state) {
  if ($form_state->getValue('search_api_fulltext') != "") {
    // Create a link
    $link = Url::fromRoute('view.search_api_view.page_1', [], ['query' => ['search_api_fulltext' => $form_state->getValue('search_api_fulltext'), ], ]);
    // log the submission
    \Drupal::logger('search_api_results')->info($form_state->getValue('search_api_fulltext'), ['link' => Link::fromTextAndUrl('results', $link)->toString()]);
  }
}

```

I am trying to convert this function from a hook I am using in D7 which works fine:

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  //Create a search_log submission function for watchdog
  if($form_state["view"]->base_field == 'search_api_id') {
    $form['#submit'][] = 'MY_search_api_log';
  }
}

function MY_search_api_log(&$form, $form_state) {
  if ($form_state['values']['search_api_views_fulltext'] != "") {
    $link = l('results', '/search-results', ['query' => ['search_api_views_fulltext' => $form_state['values']['search_api_views_fulltext'], ], ]);
    watchdog('search_api_results', $form_state['values']['search_api_views_fulltext'], [], WATCHDOG_INFO, $link);
  }
}

```

# Answer
> 0 votes
Two thoughts:

1. Instead of doing this on form submit handler, maybe just try doing the logger right in the alter hook or a preprocess hook before the page is rendered.
2. Then, to avoid the duplicate call, if the preprocess or alter hook is still getting executed multiple times, you need a way to ensure your log message is only called logged once.

For this, there might be two approaches.

* Use drupal\_static to set a boolean.
    * Attach a key/value to the $form object after you print the watchdog message, and then prevent duplicate logging if the $form already has the key.

---
Tags: forms, search, 9
---


# Question
Title: Parent node needs to display the scheduled date that is referenced in the child node
I'm not sure how best to approach this problem and I'm hoping someone can point me in the right direction.

Quick summary of the setup of some nodes: Node A is the parent node. Node B is a child of Node A. Node B also houses/displays webforms. We have a "form" field in Node B where we can call existing webforms and Node B will then display the webform and any additional information (entered in Node B) to the user.

Now to the problem: The nodes are displayed via a carousel (using jQuery Cycle2). Editors add content (Node A) to the carousel using Entity Queue. The entity queue is tied to a view, which is set up to display the required fields from Node A in each "card". If a webform exists, and Node A references Node B with the webform, the webforms' scheduled date needs to display on that particular carousel card.

In my view, I have a contextual filter on the "Content: Webform Reference", but this only displays the webform date if Node B is entered in the Entity Queue. Since Node B will NEVER be used in the Entity Queue, I need to find a way to get to the webform schedule date from Node B when Node A is called.

Is it possible to do something like this within the view? Or would this require a custom plugin block?

# Answer
> 1 votes
**UPDATE**

I went and followed Clive's suggestions. Since Node A and Node B use the same content type, I added in a relationship on the entity field where Node A references Node B. Then I added in a contextual filter on the content type form field (which is used in Node B), making sure the filter uses the relationship defined under Relationship. Finally I had to tweak the webform field called under Fields to use the relationship. All of these modifications now allow me to call and display the webforms needed.

---
Tags: views, nodes, webforms
---


# Question
Title: form_set_error Not displaying error after invalid form submission
I've created a form using my custom module. At the validation handler, I'm calling `form_set_error()` but no error messages are being displayed.

Also, I've marked several fields as `'#required' => true`; do I need to validate them manually? I thought Drupal will be validating them automatically and displaying error messages. But I see no error message for them, when I submit invalid data (i.e. not providing any value for the default fields).

This is the code in the implementation of `hook_menu()` that defines the callback for the page containing the form.

```
function myModule_menu() {
  $menu['user/signup'] = array(
    'title' => 'Signup',
    'description' => 'Sign Up',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myModule_signup'),
    'access callback' => TRUE,
  );

    /// Others
}

```

The rest of the code is the following one.

```
function myModule_signup($form, &$form_state) {
  $form['user_email'] = array(
    '#type' => 'textfield',
    '#size' => 15,
    '#required' => true
  );

  $form['user_name'] = array(
    '#type' => 'textfield',
    '#size' => 15,
    '#required' => true
  );

  $form['user_passwd1'] = array(
    '#type' => 'password',
    '#size' => 15,
    '#required' => true
  );

  $form['user_passwd2'] = array
        (
    '#type' => 'password',
    '#size' => 15,
    '#required' => true
  );

  $form['user_gender'] = array(
    '#type' => 'select',
    '#options' => array('male', 'female')
    // '#size' => 15,
    // '#required' => true
  );

  $form['user_age'] = array
        (
    '#type' => 'select',
    '#options' => range(18, 26),
    // '#size' => 15,
    // '#required' => true
  );

  $form['user_country'] = array(
    '#type' => 'select',
    '#options' => array('Bangladesh', 'USA'),
  );

  $form['user_state'] = array(
    '#type' => 'select',
    '#options' => array('Dhaka', 'Chittagong', 'Mymensing'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up')
  );

  return $form;
}

function myModule_signup_validate($form, &$form_state) {
  $formValues = $form_state['values'];
  if (empty($formValues['user_email'])) {
    form_set_error('user_email', t('Email can not be empty'));
    dsm('I can see this message...');
  }
}

```

And I'm also calling `<?php print $messages; ?>` in my custom theme's `page.tpl.php` file.

# Answer
> 9 votes
I made a quick test module using your code, and I was also not getting any error messages. The error message problem was solved when I added '#title' fields to each of the elements in your form array. Drupal is using those to figure out what messages to display.

The reason form\_set\_error message isn't getting set is because drupal displays at most one error message per field, and it is already detecting that the user\_email field is required and setting its own error message because of that. If you want additional validation, you'll have to check for more than just the existence of the field, and also pass in some malformed data.

# Answer
> 4 votes
`form_set_error()` only works in the context of a form validate handler, it's too late to set an error by the time the submission handler has been run.

Drupal will definitely handle validation for `#required` fields for you, so you should be getting the error messages. Sometimes if you're building the form too late in the page build process though, the validation messages will get delayed for a page. This might account for what's happening in your case.

If you're building the form using `drupal_get_form()`, make sure you're doing it in a module file, not in a template file, which is normally what causes this problem. I think you'd get away with doing it in a preprocess function at the theme level as well, but I haven't tried that.

# Answer
> 0 votes
```
function myModule_signup_validate($form, &$form_state) {
  $formValues = $form_state['values']['user_email'];
  if (empty($formValues)) {
    form_set_error('user_email', t('Email can not be empty'));
  }
}

```

or

```
function myModule_signup_validate($form, &$form_state) {
  $formValues = $form_state['values']['user_email'];
  if ($formValues === " ") {
    form_set_error('user_email', t('Email can not be empty'));
  }
}

```

This is the right function validate for your question

# Answer
> 0 votes
Very late to the party but this might help somebody.

I didn't want to add titles to all my fields because I'm validating many fields, in a table with headers.

The required fields that weren't filled are all highlighted, so simply adding the following to HOOK\_form\_validate() worked for me.

```
if (count(form_get_errors()) > 0) {
    form_set_error('', 'You must enter all the highlighted fields');
}

```

---
Tags: 7, forms
---


# Question
Title: How can I get the current user role in my web app?
I'm working on web app with a Drupal 8 back-end which is accessed by the D8 REST API. I need to get the current user role so I can manage some options by role. Is there an existing REST route for getting the role and/or ID of the currently authenticated user. I've had success with other REST routes like http://example.com/drupal/user/1?\_format=hal\_json, but this returns the user with id=1. What i'd like is http://example.com/cms/user/me?\_format=hal\_json

Any suggestions?

# Answer
I have just used views to get this working.

1. Duplicate the default people view and rename it `current_user`.
2. Add a rest export route eg. `rest/users/current_user`.
3. Add a filter for current user. (User: Current = yes)
4. Save all.
5. Retrieve the current user via http get request on `example.com/rest/user/current_user?_format=hal_json`

Thanks to QueenVictoria for the advice.
> 3 votes

# Answer
I've used Views to do this as you can customise your permissions, path and fields. Roles aren't available on the native ReST path to anonymous users.

For example here is the role stanza for user 200 when logged in as user 1. This is missing when logged out. I presume that is a factor of

```
roles: [
  {
    target_id: "student"
  }
],

```

BTW isn't the default ReST path `user/200?_format=hal_json`?
> 1 votes

# Answer
The JSON API entrypoint contains data about the currently logged in user in `meta.links.me`. The core JSON API module needs to be enabled. The key `meta.links.me` won't exist for anonymous users. Visit `/jsonapi`, and get more information about the current user from the link at `meta.links.me.href`. Example output from `/jsonapi`:

```
{
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
        "self": {
          "href": "http://jsonapi.org/format/1.0/"
        }
      }
    }
  },
  "data": [

  ],
  "meta": {
    "links": {
      "me": {
        "meta": {
          "id": "ba4f782f-2c5d-4280-8897-9e883f36711c"
        },
        "href": "https://example.com/jsonapi/user/user/ba4f782f-2c5d-4280-8897-9e883f36711c"
      }
    }
  }
}

```
> 0 votes

---
Tags: users, 8
---


# Question
Title: How to programmatically create a node on user registration with the user as author?
I want to create a single node of content type **XYZ** for each user upon registration.

I tried to use `hook_user_insert()` (`hook_entity_insert()`), but this doesn't work because when I set the nid to the uid, the uid is still 0 (anonymous user), and the node needs to be assigned to the newly created account. (**NOTE: This was my misunderstanding, see below.**)

I want to create the nodes upon account creation because each user should have only one node of this content type.

In Drupal 7, I managed to do this in Rules using a rule set in which I saved the user account and then created the new node. Since Rules isn't in beta for Drupal 8 yet, I am trying to do this programmatically.

Here is the code I am using:

```
function MYMODULE_user_insert(Drupal\Core\Entity\EntityInterface $entity) {
  $user = \Drupal::currentUser();
  $profile = Node::create(['type' => 'userprofilenode']);
  $profile->set('uid', $user->id());
  $profile->enforceIsNew();
  $profile->save();

```

As noted in 4k4's answer, $entity already has a UID. The problem is that I mistakenly introduced the current user, which is 0 (anonymous).

# Answer
> 13 votes
In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem:

```
/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 *
 * Adds a first node for a new user
 */
function mymodule_user_insert(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' => 'XYZ',
    'title' => 'First node for user #' . $user->id(),
    'uid' => $user->id(),
  ])->save();
}

```

# Answer
> 1 votes
This is very easy to do in D8 Rules. The advantage you get from using Rules is that you don't have to write code and it doesn't take a custom module or developer to change the action if your needs change in the future. In this way Rules is like Views - you can either program this functionality or you can make it available to the UI for easy building and maintaining.

Here is an export of a Rule which does what you asked - when a new user is created, it creates a new node (of type article, as an example). It then sets the node author to be the new user. It then sets a field of the new node (the body field, in this case) to a value take from the user (the user's email address, in this case). As you can see, Rules are stored in YAML files, and are imported/exported like any other configuration in D8. So you can just import this and you will immediately have a working example which you can then modify to use the specific fields you've defined on your user entity and node type. This Rule additionally displays a system message, which is a very useful way to debug Rules.

```
langcode: en
status: true
dependencies: {  }
id: create_a_node_for_each_new_user
label: 'Create a node for each new user'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Node fields will be populated from values entered on the user form.'
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: c9428f2d-c0b9-47bf-a7e5-3f2cc8af9f54
  conditions:
    id: rules_and
    uuid: 47b8d622-ed38-4977-8e58-4cca6d89260a
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: d96fd6b5-1638-4b15-adde-5f5d7673fb8f
    actions:
      -
        id: rules_action
        uuid: e09cd52d-76fe-4682-91de-bfed58a651ab
        context_values:
          message: 'Node created using information entered by <em>{{ user.name }}</em> when registering'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: fe2acb55-9234-4754-9d2b-3d1889d1775c
        context_values:
          type: article
          title: 'Article created by Rules for {{ user.name }}'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: 743be03f-d1b7-4251-a1ac-80b17aa5c86e
        context_values:
          value: '{{ user.mail.value }}'
        context_mapping:
          data: entity.body
        context_processors:
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 91f3c8f2-eb47-46e6-a9dd-2affc90e15d2
        context_values: {  }
        context_mapping:
          data: entity.uid.target_id
          value: user.uid.value
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set

```

---
Tags: 8, nodes, users, hooks
---


# Question
Title: How do I dump variables to the screen when running PHPUnit tests?
I'm trying to put together some PHPUnit tests in Drupal 8. I'm running the tests from the command line, using /vendor/bin/phpunit, but I'm having troubles figuring out how to dump a variable to the screen for debugging purposes.

For that matter, I'm using this:

```
$this->assertEquals(2, $this->currentUser->id(), 'ID is correct');

```

And when it passes, the message 'ID is correct' is not shown in the console. Does anyone know how to make the error messages properly show?

# Answer
Recent versions of PHPUnit swallow output. To get around this, you need to run with the `--debug` flag, eg

```
$ ../vendor/bin/phpunit --debug modules/migrate/tests/src/Unit/process/FormatDateTest.php

```

Then you can see printed output.

Also note that PHPUnit will skip tests with output in them with the default phpunit.xml file, because it will deem them risky. To avoid this update the `beStrictAboutOutputDuringTests="false"` setting and your tests will run.

You can also use the `$message` parameter to output something when an assertion fails.
> 9 votes

# Answer
Well, I found a solution that works. I'm not sure if it is the best way to do it, but actually, it its own way it seems like it is probably the way it's supposed to be done.

First, I discovered that while the assertion message is not output for successful assertions, it is output for failures. So you can append your value to the assertion message, to see what it is:

```
$b = 'some other value';
$this->assertEquals('some value', $b, '$b is not equal to "some value", instead it is instead: ' . $b);

```

Since 'some value' does not equal 'some other value', the output is:

*$b is not equal to "some value" it is instead: some other value*
> 3 votes

# Answer
It seems almost impossible to make any output appear on the screen. Jaypan's answer does work but is no good if you want to write output from a file that is not extending BrowserTestBase.

dd() also fails to output to /tmp/drupal\_debug.txt so I've written my own function:

```
if(!function_exists('mylog')) {
  function mylog($var, $label = NULL) {

    $tmp_file = '/tmp/my_debug.log';

    $output = '';
    if(!is_null($label)) {
      $output = $label . ': ';
    }

    $output .= print_r($var, 1) . PHP_EOL;

    file_put_contents($tmp_file, $output, FILE_APPEND);
  }
}

```

I paste this into every file I need to create debug output and then simply tail `/tmp/my_debug.log`.
> 3 votes

# Answer
```
$this->assertEquals('some arbitrary value', print_r($thing_i_want_to_see, TRUE));

```

This causes the assertion to fail, and shows you the difference between your 'arbitrary value' and the actual value. You can then read the actual value. Watch out for complex and recursive data structures.

You can also do `error_log()` and watch your log file, but Drupal functional tests will swallow that. Works great for unit tests, though.
> 3 votes

# Answer
I've made a rough start on getting Symfony's dump() command to work in tests. There's a patch at https://www.drupal.org/node/2795567, though I'm stuck on how to take it further.
> 1 votes

# Answer
If you want to be efficient about it, just copy paste before and output it on the terminal.

Any PHP File

```
file_put_contents('a.txt', 'contents = '.(getenv('APP_ENV')));
dd('a');

```

```
vendor/bin/phpunit --debug; cat a.txt

```
> 0 votes

---
Tags: 8, testing
---


# Question
Title: Access a user entity reference in a commerce-product template file
I have a *field\_intervenant*field which contains a user entity reference. In the commerce-product template file, I want to access the description field of each intervenant.

How can I achieve it?

I tried reading the following values, but none of them returns what I am looking for.

* `product.field_intervenants.entity.field_description`
* `product.field_intervenants.0.entity.field_description`
* `product_entity.field_intervenants.0.entity.field_description`
* `product_entity.field_intervenants.field_description`
* `product_entity.field_intervenants.field_description.value`

Do I need to loop through it, or am I missing something else?

# Answer
You should definitely use a loop, as the referenced entity fields returns an array, you can see an example here and adjust it by you own needs https://stackoverflow.com/questions/58291698/drupal-8-twig-entity-reference-sub-fields-templating
> 0 votes

---
Tags: 8, entities, commerce
---


# Question
Title: How can I re-organize the user account tabs?
I have a Drupal 9 site. I can't find how to rearrange or rename the user account tabs.

How can I re-organize the user account tabs?

>

# Answer
> 0 votes
I haven't tried it myself, but the Tab Manager module may help.

---
Tags: navigation, 9
---


title: How to get current user jwt token?

text:
# Question
Title: How to get current user jwt token?
In a custom module, I need to get the jwt token (access\_token) related to the current user. Following this issue I've tried to get it, but without success, because get\_jwt\_key() and jwt\_token\_params() are not defined and I can't find where they are defined:

```
use \Firebase\JWT\JWT;
...
public function getAccessToken() {
  $uid = \Drupal::currentUser()->id();
  // Add JWT access_token
  $key = get_jwt_key(); //key for generate jwt token
  $token = jwt_token_params($uid); // parameters to be added in token.
  $access_token = JWT::encode($token, $key);
  return $access_token;
}

```

I've tried only with:

```
$access_token = $this->jwtAuth->generateToken();

```

But I haven't found how to initialize $jwtAuth service to generate the token. Any suggestion?

# Answer
The code shown on comment #2 in Get the token bearer with the JWT module after log in rest method is the code for an event subscriber class. What that comment doesn't show is the definition of the event subscriber service.

As described in Subscribe to and dispatch events / Drupal 8 Events, the .services.yml file should contain lines similar to the following ones. (Replace *YOURMODULE* with the module machine name, and *YOURCLASS* with the class name.)

```
services:
  YOURMODULE_YOURCLASS:
    class: '\Drupal\YOURMODULE\Listener\YOURCLASS'
    tags:
      - { name: 'event_subscriber' }
    arguments:
      - '@path.current'
      - '@jwt.authentication.jwt'

```

Contrary to what the comment says, the file containing the `\Drupal\YOURMODULE\Listener\YOURCLASS` class isn't the *src/Listener/yourfile.php* file, but the *src/Listener/YOURCLASS.php* file contained in the module directory.

As side notes:

* As described in Events, the file containing an event subscriber class isn't required to be in a specific directory. Drupal core modules normally put those files in the *EventSubscriber* directory.
* The *JSON Web Token Authentication (JWT)* module doesn't define neither `get_jwt_key()` nor `jwt_token_params()`. The comment doesn't show the code for those functions, but they need to be implemented from the module. (In that case, their names should be prefixed by the module machine name.) -The `YOURCLASS` class shown in that comment initializes `$this->jwtAuth` in its constructor, but `onHttpLoginResponse()` doesn't even use it.

```
/**
 * Add JWT access token to user login API response
 */
public function onHttpLoginResponse(FilterResponseEvent $event) {
  // Halt if not user login request
  if ($this->currentPath->getPath() !== '/user/login') {
    return;
  }
  // Get response
  $response = $event->getResponse();
  // Ensure not error response
  if ($response->getStatusCode() !== 200) {
    return;
  }
  // Get request
  $request = $event->getRequest();
  // Just handle JSON format for now
  if ($request->query->get('_format') !== 'json') {
    return;
  }
  // Decode and add JWT token
  if ($content = $response->getContent()) {
    if ($decoded = Json::decode($content)) {
      $uid = $decoded['current_user']['uid'];
      // Add JWT access_token
      $key = get_jwt_key(); //key for generate jwt token
      $token = jwt_token_params($uid); // parameters to be added in token.
      $access_token = JWT::encode($token, $key);
      $decoded['jwt_access_token'] = $access_token;
      // Set new response JSON
      $response->setContent(Json::encode($decoded));
      $event->setResponse($response);
    }
  }
}

```

Clearly, the code shown in that comment is incomplete.
> 2 votes

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


# Question
Title: How do I programmatically set a taxonomy term for a node?
I got some difficulties setting a taxonomy for a node. Currently I am using this code.

```
$node = Node::create(array(
    'type' => 'detailseite',
    'title' => $data[$headlineIndex],
    'langcode' => 'de',
    'uid' => '1',
    'status' => 1,
    'field_headline' => $data[$headlineIndex],
    'field_intro' => $data[$introIndex] . $categories[$data[$categoryIndex]],
    'created' => $data[$dateIndex],
    'field_autor' => $data[$autorIndex],
    'field_teaser_text' => $data[$shortIndex],
    'field_fields' => array(),
));
$node->save();

```

Which works fine so far (below an image of the fields of "detailseite").

Everything gets set correctly and I can find the newly created nodes in the admin area that work correctly. Now I need to set 'field\_meldungstyp' which is an Entity-Reference to a Taxonomy:

which already contains three entries:

I want to get the node(s) I created programmatically to have "field\_meldungstyp" set to "Artikel" of the "Meldungstyp"-Vocabulary.

I already tried adding:

```
'field_meldungstyp' => array( 'tid' => 19 ),

```

where 19 is the tid of "Artikel" of the earlier mentioned vocabulary. And that's where I'm stuck. Also https ://www.drupal.org/node/2402811 didn't work for me. As well as

```
$node->field_meldungstyp[$node->language][]['tid'] = 19;

```

didn't work either.

simply adding

```
$node = Node::create(array(
    ...
    'field_meldungstyp' => 19,
    ...
));

```

results in crashing with the following error:

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value: 'datetime' for column 'created' at row 1: INSERT INTO {taxonomy\_index} (nid, tid, status, sticky, created) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> 343 \[:db\_insert\_placeholder\_1\] =\> 19 \[:db\_insert\_placeholder\_2\] =\> 1 \[:db\_insert\_placeholder\_3\] =\> 0 \[:db\_insert\_placeholder\_4\] =\> datetime ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php). Drupal\Core\Database\Statement-\>execute(Array, Array) (Line: 610) Drupal\Core\Database\Connection-\>query('INSERT INTO {taxonomy\_index} (nid, tid, status, sticky, created) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4)', Array, Array) (Line: 81) Drupal\Core\Database\Driver\mysql\Connection-\>query('INSERT INTO {taxonomy\_index} (nid, tid, status, sticky, created) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4)', Array, Array) (Line: 32) Drupal\Core\Database\Driver\mysql\Insert-\>execute() (Line: 371) Drupal\Core\Database\Query\Merge-\>execute() (Line: 525) taxonomy\_build\_node\_index(Object) (Line: 479) taxonomy\_node\_insert(Object) call\_user\_func\_array('taxonomy\_node\_insert', Array) (Line: 402) Drupal\Core\Extension\ModuleHandler-\>invokeAll('node\_insert', Array) (Line: 167) Drupal\Core\Entity\EntityStorageBase-\>invokeHook('insert', Object) (Line: 418) Drupal\Core\Entity\ContentEntityStorageBase-\>invokeHook('insert', Object) (Line: 470) Drupal\Core\Entity\EntityStorageBase-\>doPostSave(Object, ) (Line: 304) Drupal\Core\Entity\ContentEntityStorageBase-\>doPostSave(Object, ) (Line: 395) Drupal\Core\Entity\EntityStorageBase-\>save(Object) (Line: 761) Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save(Object) (Line: 364) Drupal\Core\Entity\Entity-\>save() (Line: 46) Drupal\awo\_importer\Controller\T3ImporterController-\>import() call\_user\_func\_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 574) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() call\_user\_func\_array(Object, Array) (Line: 144) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 64) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 98) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 77) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 628) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

# Answer
> 14 votes
It needs to be a nested array.

```
'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]

```

Try this:

```
$node = Node::create(array(
    'type' => 'detailseite',
    'title' => $data[$headlineIndex],
    'langcode' => 'de',
    'uid' => '1',
    'status' => 1,
    'field_headline' => $data[$headlineIndex],
    'field_intro' => $data[$introIndex] . $categories[$data[$categoryIndex]],
    'created' => $data[$dateIndex],
    'field_autor' => $data[$autorIndex],
    'field_teaser_text' => $data[$shortIndex],
    'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]
));
$node->save();

```

# Answer
> 16 votes
In Drupal 7, taxonomy reference fields existed which used the pattern `['tid' => NUMBER]`. These are entity reference fields. The EntityReferenceItem has the property definitions: `target_id` and `entity`. The former is a either an integer or string depending on the entity reference item's settings (basically config/content entity type).

This is also a similar question to How to set value for multivalue field in drupal 8 programmatically

So try to use the pattern

As part of Entity::create

```
Node::create([
  'field_meldungstyp' => [['target_id' => 19]]
]);

```

Using FieldableEntityInterface::set

```
$entity->set('field_meldungstyp', ['target_id' => 19]);

```

Using TypedDataInterface::setValue on the field item directly.

```
$entity->field_meldungstyp->setValue(['target_id' => 19]);

```

With magic method

```
$entity->field_meldungstyp->target_id = 19;

```

Note that this overwrites any current values of the field.

# Answer
> 4 votes
Here is how i did it for D8.

```
use Drupal\node\Entity\Node;

//To create new node
$node = Node::create(['type' => 'YOUR_CONTENT_TYPE_HERE']);

//To load a node by its ID
//$node = \Drupal\node\Entity\Node::load(NODE_ID);

$nodeTerms = [1,2,3...]; // 1,2,3 = terms IDs
$node->set('YOUR_FIELD_OF_TERMS', $nodeTerms);
$node->save();

```

//To create new tax

```
use Drupal\taxonomy\Entity\Term;

$new_term = Term::create([
    'vid' => "YOUR_VOCABULARY_MACHINE_NAME",
    'name' => "NAME_OF_YOUR_TERM",
]);
$new_term->save();

```

# Answer
> 2 votes
Another approach would be to update the node after creation, like this:

```
$node = Node::create(array(
    ...
));
$node->save();
$node->field_meldungstyp->target_id = 19;
$node->save();

```

# Answer
> 1 votes
Here's how I got this working in D9:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'content type',
  'title' => 'node title',
  'field_tax_ref' => ['target_id' => '3'],
]);
$node->save();

```

field\_tax\_ref is a taxonomy entity reference field.

'3' is the tid of the term I want to reference.

---
Tags: nodes, 8, taxonomy-terms
---


# Question
Title: Format of callback arguments in YAML files
For instance, for the Filter module, in filter.permissions.yml, custom permissions are defined:

```
permission_callbacks:
  - Drupal\filter\FilterPermissions::permissions

```

That looks like a static function, but it isn't. How does that work? Is the format for this kind of callback argument documented or defined anywhere?

# Answer
> 3 votes
I believe that this is a Symfony format. I can't find it in the documentation, but this talks about it https://symfonycasts.com/screencast/deep-dive/controller-setup

I found the code (or some code) in https://api.drupal.org/api/drupal/vendor%21symfony%21http-kernel%21Controller%21ControllerResolver.php/9.1.x

The Symfony Controller code explodes the string around the '::' into $class and $method and figures out if it's $classobject-\>$method() or $class::$method().

# Answer
> 0 votes
Documentation is here: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21PermissionHandler.php/class/PermissionHandler/9.1.x

> If your module needs to define dynamic permissions you can use the permission\_callbacks key to declare a callable that will return an array of permissions, keyed by machine name. Each item in the array can contain the same keys as an entry in $module.permissions.yml.

---
Tags: 9
---


# Question
Title: How can I view the list of referenced nodes when viewing a node?
I have a content type with a *Related pages* field, which an entity reference field for nodes.

How can view those nodes while still on the current node?

I tried to achieve this by creating a block view, but this shows all the nodes, whereas I want only the nodes referenced by the *Related pages* field.

>

# Answer
> 2 votes
You don't need Views to do this, although it is possible to make it work with the correct configuration.

The easiest way is to configure what your Entity Reference field should display.

## Configure "Manage display" for the ER field

Go to the `Manage display` page of your Content Type (`admin/structure/types/manage/[myCT]/display/`) and change your "Related pages" field to `Rendered entity` instead of `Label`.

---

## Use Display modes

If you want to limit which fields of the referenced pages are shown on the page that references them, you can create a new Display mode (under Structure menu) where only the fields you want are enabled. Then use that mode on the ER field settings instead of the "Rendered entity".

---

## Use Views Block with ER Relationship and Contextual filter

If you want to do it through Views to show the Parent fields on the Child node you need to add the Relationship for the ER field, then add the Contextual filter for the `ID` and Provide default value Content ID from URL, and when using fields make sure they use the Relationship to show the data from the referenced pages and not the (child) page you're currently viewing.

---
Tags: views, nodes
---


# Question
Title: Redirect Search API view result (Leaflet map) to display in a pane
The particular Search function starts as Full Panel Page in a style to a Google Maps Location Search page; Search Input (Block) to the top left overlaid on a current Leaflet map based on the logged-in users Postcode. (It is overlaid with CSS using z-Index).

I'm confused over what is required to make the required Search Result Data View (Leaflet map) show in the same Panel Pane Window.

The user can after the above viewpoint window, again Search via the Search Block with the following next results this time to display in the same Panels Page or a Variant (As it will show the Views Context Pane) again full page Leaflet display with the said results and again with the Search Input Block again the the top left. (I'm not bothered if is the same window or a second Variant)

For example, an initial Panel Page is named: \<dealers/local/mapping\> which is a a two pane layout (left/Right). The Search input block is to the left whilst the initial map is to the right (set at 12 columns). The additional search results (as a View (Indexed) would show again in the right Column Pane as a 12-column full page display. So the path would result asL \<dealers/local/mapping/search-api-results/cheshire\*\> \*cheshire being the locality the user entered to search for and displays the relevant mapping which I can add Facets/Proximity etc to it.

Currently, the search results only show the Results Page View by itself and not in any panel pane, which I require.

For hours (and I'm mean over some 8 hours over 2 days!) I have tried to get my head around what needs to be 'plugged in to what' to get the second stage Search API results to display in a second Panel Page so I can also include Search API Facets.

I've looked for hints, tips across Stack and Drupal.Stack, old 'tutorials' online (harking back to 2010!) and simply cannot find any hint, tip, or workout. Somebody please help!

# Answer
Yes, I appeared not to have the used the \</search-page-name-api/!keywords\> 'enabled' into my Panel Pages relevant to the custom API Search Page I had made and at first I was trying to build via a standard Panel Page. You have to use the \</search-page-name-api/!keywords\> which works by first creating a custom Search API page (for example, trade-shops-page-api, if based ona Search DB/Index called similar) then, after which that named api-page will appear in the Pane Page lists as a new page \</search-page-name-api/!keywords\> albeit not enabled. Once enabled, you can work around that pages' Variants to create what you need and in order to my question, the Search API results will appear after you have done some Views Pane etc. In my case, I was able to do the Search API Results on the Pages Right Column Pane and 3-Facets in the Left Pane, with a 'floating' Search Input Box which sat 'Absolute' top left of the map. A certain amount of CSS work also was needed.
> 0 votes

---
Tags: 7, views, search, panels
---


# Question
Title: Configuration overrides have unpredictable results
I'm setting up configuration splits with Drupal 9 and encountering unexpected results.

None of my splits are marked as Active in the active configuration or the exported configuration YAML.

I want to set the default Local split in `settings.php` and then use `settings.local.php` to override it on `dev`, `stg`, `prd` environments.

My local development environment is DDEV-Local v1.17.5. The three remote environments are all set up on one remote server in the client's private AWS, in three different Apache VirtualHosts.

I can't use environment variables to differentiate the `dev`, `stg`, `prd` environments since they are all on one host. It's been a challenge differentiating the environments without the usual Acquia or Pantheon environment variables.

(Note: I understand if `config_split` is off-topic here since it is not a core module. I have created an issue queue on Drupal.org, but I'm still hoping that someone will see the question here and offer an insight.)

This is the default override in `settings.php`:

```
  $config['config_split.config_split.local']['status'] = TRUE;
  $config['config_split.config_split.prd']['status'] = FALSE;
  $config['config_split.config_split.stg']['status'] = FALSE;
  $config['config_split.config_split.dev']['status'] = FALSE;

```

So far, so good. The Local split is "active (overwritten)".

Things get weird when I edit this to enable another split in my Local environment:

```
  $config['config_split.config_split.local']['status'] = FALSE;
  $config['config_split.config_split.prd']['status'] = TRUE;
  $config['config_split.config_split.stg']['status'] = FALSE;
  $config['config_split.config_split.dev']['status'] = FALSE;

```

After editing `settings.php` (and clearing cache, of course) the Production split is "active (overwritten)", as expected.

Unfortunately, the Local split is also "active (overwritten)" despite setting its `['status'] = FALSE;`,

Things get weirder when I attempt to logically negate the values of all the splits:

```
  $config['config_split.config_split.local']['status'] = FALSE;
  $config['config_split.config_split.prd']['status'] = TRUE;
  $config['config_split.config_split.stg']['status'] = TRUE;
  $config['config_split.config_split.dev']['status'] = TRUE;

```

Now, the Local split is *still* "active (overwritten)" despite setting its `['status'] = FALSE;`,

The Stage and Production splits are "active (overwritten)" to match their `['status'] = TRUE;`,

And the Dev split remains "inactive" despite setting its `['status'] = TRUE;`,

Any idea what is happening here?

# Answer
> 1 votes
I changed the machine names of the splits (e.g., `dev_split`) and everything works as expected.

Therefore, the problem was being caused by the `acquia/blt` package, which uses the `acquia/drupal-environment-detector` package to set the active split based on Acquia environment variables.

Since `$_ENV['AH_SITE_ENVIRONMENT']` is unset, the Local environment split will always be active.

I'm not sure why the Dev split cannot be activated, but that is probably related as well.

I could remove BLT from the project entirely since we are not using Acquia hosting, and therefore we are no longer using it for much, but I was reluctant to set up the automated testing stuff again without all that Robo goodness.

Instead, I made `acquia/blt` a Composer dev dependency so it would not be installed in higher environments. Apparently, that was not enough -- it still messes with my config splits, and may have other unpredictable side effects.

The quick fix is to change machine names for splits. Probably ditching BLT altogether is a better solution in the long run.

Closed (works as intended)

P.S.: If your BLT project is hosted on Acquia, then the environment detection will work correctly, and this problem will not arise. No wonder this is such a rare problem -- most people probably do not use BLT outside of Acquia's environments.

---
Tags: configuration, 9
---


title: Tokens in menu link and title

text:
# Question
Title: Tokens in menu link and title
`menu_token` module is working fine to achieve the purpose. Does the module `token_filter` has this functionality? I can use tokens in wysiwyg using `token_filter` but cannot make it working for menu title or url since there is no setting I could find. Since the comment in drupal issue says that it was solved using `token_filter` module, I want to know the way it was achieved.

# Answer
> 1 votes
No, not by itself. The Token Filter module's functionality adds a token *input filter* to text formats in Drupal. The only field types that can use text formats are the 3 *Text (formatted)* field types, not the *Link* field type.

One can only speculate on the comment's solution you refer to. Text Formats/Input filters are designed to allow HTML input that should be filtered for presentation. It would be an odd-use-scenario to apply that to a link field.

# Answer
> 0 votes
Approach to solve the problem-

1. Loop through menu links (optionally title) in custom module
2. Process the tokens using `\Drupal::token()->replace()` method

---
Tags: navigation, 9, tokens
---


# Question
Title: Limit avaliable dates in a event where user can sign up mutiple people in multiple dates in one single form
**Problem context**

I'm bulding a site where parents can sign-up their childrens for a summer camp. Parents can choose one or more weeks for sign-up one or more children in the same form.

There are 20 seats for each week, and 8 weeks to choose, so parents should know how many seats are avaliable in each week to manage to sign-up their children (usually they prefer their children go together but if is not possible they could sign-up childrens in different weeks).

**So far my best approach is:**

* A single form for camp registration (Webform, what a great module/s)
* Weeks are options in a "checkboxes" element, so multichoice selection of weeks is possible.
* Duplicate the previous element for each child. I did it 5 times, so parents can register up to 5 children per submission.
* Then I set an "Option/Checkbox Limit" handlers to set 20 as limit in each week.
* Duplicate the previous handler for each children (5 times) and asociate it to correspondent "checkboxes" element.

The problem with this approach is that limits are independent beetween elements, so in the same form you can sign-up five childrens in first week and 19 seats are still avaliable instead 15 (20-5).

**Comments**:

* I'm site builder, not developer, with an upcoming deadline, so I discard to develop a module.
* I try "custom composite" element but handlers are not avaliable for it.
* Module "Webform Demo: Event Registration System" has a "global" limit defined as a field in a content type "Demo: Event" controlled by a handler but I dont realize how to apply it to this case.

# Answer
> 0 votes
I'd do this with two content types, rather than webform:

1. Available slot-dates
2. Sign-ups

You create the content for the available slot-dates (one node per date-slot), parents create the sign-up content. The Sign-up content includes the basic information that you need for kid's background context. After, you can add a paragraph to this content type that allows parents to specify the week that they sign their kids up for. Do this through an entity reference to your content, Available Slot-Dates. The benefit of this is that paragraphs on the node/add form allows the user to add another paragraph (in your case, this lets them select another week and/or add additional kids, without seeing extra form fields, or being limited to 5 kids/submission).

Then, you can track which of the Available Slot-Dates have been claimed by creating a rule that changes a field on the available slot-dates content that was referenced by the parent-created sign-ups.

Finally, you can only show parents dates that are available by creating a view for the entity reference. Filter for available slot-dates that are still available using the indicator field from the prior step. If you use this view on the entity reference field, then parents will only be able to select dates not yet claimed.

---
Tags: webforms
---


# Question
Title: Send an email to a group of users after new content has been created
In Drupal 9, I need to notify all users belonging to a role by sending them an email about the new created content.

Everything's fine, but I don't know how to put together the email addresses of these users in the *Send to data* selector of the Rules module.

# Answer
In Rules there's a "Send email to all users of a role" action you can use for this purpose. There is no "Send to" input for this action because all you need to do is specify the role, not the email addresses.
> 0 votes

# Answer
As anonymous indicated, use the "Send email to all users of role." I believe roles are identified by number. If you go to /admin/people/permissions/roles, and hover over 'edit permission,' the number at the end of the url should indicate the id for the role.
> 0 votes

---
Tags: rules, 9
---


# Question
Title: Set a default integer value with #ajax, according to a form state value in the same form
There is an integer field: "Number of pitches" Another integer field: "Maximum people allowed". These will usually be the same values.

I am trying to set the value of the field specified in the pitches, as the default value for the maximum number of people.Whatever combination I try, no results. In a hook\_form\_alter I try to realize this with Ajax.

```
function zaal_condities_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'node_bedrijf_form' || $form_id == 'node_bedrijf_edit_form'){
   $form['field_staanplaatsen']['widget'][0]['value']['#ajax'] = [
      'callback' => 'zaal_condities_AjaxCallback',
      'event' => 'change',
      'wrapper' => 'edit-field-staanplaatsen-0-value',
    ];
  }
}

function zaal_condities_AjaxCallback(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_state->getValue('field_staanplaatsen') != false){
    $inputValue = $form_state->getValue('field_staanplaatsen');
    return $form['field_bezetting_tot']['widget'][0]['value']['#default_value'] = $inputValue;
  }
}

```

# Answer
> 0 votes
JavaScript API / AJAX Forms is quite complete and good. Plus, there are many examples around.

Anyway, tthere are various errors.

1. The ajax callback should be attached with code like `$form['your_field']['widget']['#ajax']= [...];`
2. You should set the wrapper using an ID that's kept the same even after AJAX calls. A common solution can be to set up it using `#prefix` and `#suffix`

```
$form["field_second_field"]["#prefix"] = '<div id="my-id">';
$form["field_second_field"]["#suffix"] = '</div>';

```
3. The AJAX callback should return a renderable array or an AJAX command; in this case, `return $form['field_second_field']`

Written as the following, it should work.

```
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['your_field']['widget']['#ajax'] = [
    'callback' => 'custom_callback',
    'event' => 'change',
    'wrapper' => 'custom-id',
  ];

  $form["second_field"]["#prefix"] = "<div id='custom-id'>";
  $form["second_field"]["#suffix"] = "</div";
}

function custom_callback(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //your logic
  return $form["second_field"];
}

```

Please note, I never changed the `#default_value` inside the AJAX callback, but I see no reason why it should not work.

# Answer
> 0 votes
The problem was solved with the code below.

In the hook form alter :

```
$form['field_custom_name']['widget'][0]['value']['#ajax'] = [
      'callback' => 'my_AjaxCallback',
      'event' => 'change',
      'wrapper' => 'edit-field-custom-name-0-value',
    ];
  }
}

```

In the AjaxCallback :

```
if (!empty($form_state->getValue('field_custom_name')[0]['value'])) {

    $myvariable = $form_state->getValue('field_custom_name')[0]['value'];

        $response = new AjaxResponse();

        $response->addCommand(new InvokeCommand('#edit-field-custom-name-0-value', 'val', [$myvariable]));

        return $response;

```

---
Tags: ajax, 9
---


# Question
Title: How to add contextual fields to breadcumb links?
How can contextual fields be added to breadcrumb links?

For example, I have a hierarchical taxonomy vocabulary like this:

```
Animalia
--Chordata
----Vertebrata

```

On the Vertebrata page, the default breadcrumb looks like this:

```
Home >> Animalia >> Chordata

```

Each taxonomy term in the vocabulary has a "common name" field, so for Animalia it would be "animals", and for Chordata it would be "chordates". I would like the breadcrumb to look like this:

```
Home >> Animalia (animals) >> Chordata (chordates)

```

A similar example can be seen on this page, where a taxonomic rank field appears after each link in the classification breadcrumbs.

Besides achieving this with taxonomy breadcrumbs, I would be interested to know if a similar solution is achievable for menu breadcrumbs generated by the Menu Breadcrumb module.

# Answer
I'm not aware of any contrib module that is capable of adding custom fields as suffix to breadcrumb links.

Fortunately, Drupal 8's modular architecture enables you to add your own breadcrumb builder service with a little bit of custom programming.

You will have to **create an own module** (within the following example, I'll call it `my_module` or `MyModule` respectively; you'll have to replace it accordingly) and add a **my\_module.services.yml** file to its root directory.

Within this file you can define your own breadcrumb builder service. Make sure to let Drupal know, that it is a breadcrumb builder and in which order it should be processed by adding the relevant tags (read more about service tags here):

```
services:
  my_module.breadcrumb:
    class: Drupal\my_module\Service\MyModuleBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 10001 }

```

Now that Drupal knows about your breadcrumb builder and will process it fairly early because of the high priority given, you will have to create the according class.

Create a service class `MyModuleBreadcrumbBuilder.php` in your `my_module/src/Service/` folder. Apart from the convention to letting its name end on `BreadcrumbBuilder`, you can actually name it to your liking. Just make sure to change the class name within the `.services.yml` file and the follwing example accordingly.

As you are up to creating a taxonomy breadcrumb builder, a good starting point is the TermBreadcrumbBuilder of the taxonomy core module, which we will extend in our example:

```
namespace Drupal\my_module\Service;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\taxonomy\TermBreadcrumbBuilder;

/**
 * My custom breadcrumb builder for Animalia.
 */
class MyModuleBreadcrumbBuilder extends TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {

}

```

As your requirements seem to apply to a certain taxonomy vocabulary only, you should implement the BreadcrumbBuilderInterface::applies() method to check whether you are on a term page of that vocabulary.

This assures your breadcrumb builder won't run on other entities/vocabularies that don't feature your custom field (I used the ID `my_vocabulary` for your vocabulary; you will have to replace it accordingly):

```
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\taxonomy\TermInterface;

[...]

/**
 * {@inheritdoc}
 */
public function applies(RouteMatchInterface $route_match) {
  return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
    && ($term = $route_match->getParameter('taxonomy_term')) instanceof TermInterface
    && $term->getVocabularyId() == 'my_vocabulary';
}

```

The next step is to implementing the BreadcrumbBuilderInterface::build() method, that returns the actual breadcrumb. Here, we'll add your custom field value to the shown parent term link labels.

As we extended the taxonomy breadcrumb builder before, we already have the entity manager and term storage available, which enable us to loading the localized versions of the terms.

Most of the proceedings match the TermBreadcrumbBuilder::build() method, so that I added a comment only where the term field value is added:

```
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;

[...]

/**
 * {@inheritdoc}
 */
public function build(RouteMatchInterface $route_match) {
  $breadcrumb = new Breadcrumb();
  $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
  $term = $route_match->getParameter('taxonomy_term');
  $breadcrumb->addCacheableDependency($term);
  $parents = $this->termStorage->loadAllParents($term->id());
  array_shift($parents);

  foreach (array_reverse($parents) as $term) {
    $term = $this->entityManager->getTranslationFromContext($term);

    // The 'magic' happens here by loading the field value and
    // adding it to the link title; alter 'field_common_name' to
    // match your custom field ID.
    $my_field = $term->get('field_common_name');
    $term_name = $term->getName() . (!empty($my_field->getValue()[0]['value']) ? ' (' . $my_field->getValue()[0]['value'] . ')' : '');

    $breadcrumb->addCacheableDependency($term);
    $breadcrumb->addLink(Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
  }

  $breadcrumb->addCacheContexts(['route']);
  return $breadcrumb;
}

```

After enabling the module (or flushing the caches, if you already enabled it before), you should now see your custom breadcrumbs when you open a term of your vocabulary.
> 1 votes

# Answer
Here are the components of Mario's module in the accepted answer after updating for Drupal 9.0-9.1 compatibility. This module will still work in Drupal 8.

**breadcrumb\_extra\_field.info.yml**

```
name: Breadcrumb Extra Field
description: 'Add an extra field after terms in a breadcrumb'
package: Custom
type: module
core_version_requirement: ^8.7.7 || ^9

```

**breadcrumb\_extra\_field.services.yml**

```
services:
  breadcrumb_extra_field.breadcrumb:
    class: Drupal\breadcrumb_extra_field\Service\BreadcrumbExtraFieldBreadcrumbBuilder
    arguments: ['@entity_type.manager', '@entity.repository']
    tags:
      - { name: breadcrumb_builder, priority: 10001 }

```

**src\Service\BreadcrumbExtraFieldBreadcrumbBuilder.php**

```
<?php

namespace Drupal\breadcrumb_extra_field\Service;

use Drupal\Core\Link;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\taxonomy\TermBreadcrumbBuilder;
use Drupal\taxonomy\TermInterface;

/**
 * My custom breadcrumb builder for the living_things taxonomy.
 */
class BreadcrumbExtraFieldBreadcrumbBuilder extends TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {

    /**
     * {@inheritdoc}
     */
    public function applies(RouteMatchInterface $route_match) {
        return $route_match->getRouteName() == 'entity.taxonomy_term.canonical' && ($term = $route_match->getParameter('taxonomy_term')) instanceof TermInterface && $term->bundle() == 'living_things';
    }

    /**
     * {@inheritdoc}
     */
    public function build(RouteMatchInterface $route_match) {
        $breadcrumb = new Breadcrumb();
        $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
        $term = $route_match->getParameter('taxonomy_term');
        $breadcrumb->addCacheableDependency($term);
        $parents = $this->termStorage->loadAllParents($term->id());
        array_shift($parents);
        foreach (array_reverse($parents) as $term) {
            $term = \Drupal::service('entity.repository')->getTranslationFromContext($term);
            $my_field = $term->get('field_most_common_name');
            $term_name = $term->getName() . (!empty($my_field->getValue()[0]['value']) ? ' (' . $my_field->getValue()[0]['value'] . ')' : '');
            $breadcrumb->addCacheableDependency($term);
            $breadcrumb->addLink(Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
        }
        $breadcrumb->addCacheContexts(['route']);
        return $breadcrumb;
    }
}

```
> 0 votes

---
Tags: 8, taxonomy-terms, breadcrumbs
---


# Question
Title: How can I provide my own replacement patterns to be used in config form?
I want to give a configuration form where user can configuration text on a widget, like the description and button label, however I want to provide a replacement pattern to be used, like {{count}} so the user can write for instance "{{ count }} images remaining". How can I provide replacement patterns to be used in the configuration form?

# Answer
`{{ count }}` is a Twig variable pattern. Parse the content before you display it as Twig inline template, to replace the variable dynamically:

```
use Drupal\Component\Utility\Xss;

  $build = [
    '#type' => 'inline_template',
    '#template' => $text,
    '#context' => [
      'count' => $dynamic_count_value,
    ],
    '#post_render' => [
      function ($children, $elements) {
        return Xss::filterAdmin($children);
      },
    ],
  ];

```

Xss:filterAdmin() is only safe for admin forms. So don't make the config form accessible to other users.
> 1 votes

---
Tags: forms, 9
---


# Question
Title: How to set default value on Select2 Autocomplete via hook_alter
What's the best way to set a default value to a Select2 autocomplete field widget on form load (I'm using a reference view to populate options). I've tried a ton of different variations from within form\_alter with no success, such as...

```
$form['field_name']['widget']['#select2']['id'] = 12

```

I can set the hidden `<select>` element with...

```
$form['field_name']['widget']['#default_value'] = 12

```

...but this value doesn't populate into the Select2 Widget.

I've combed through docs and issues without finding a solution. What am I missing?

# Answer
> 2 votes
With the select2 widget the ***#default\_value'*** is an array so try with

```
 $form['field_name']['widget']['#default_value'] = [12];

```

It will work!

---
Tags: 8, forms
---


# Question
Title: Sharing articles on Social media loses the images after posting
This seems to have only happened recently. Has anyone found a fix? I'm using D7 with Metatag, Metatag:Facebook & Metatag:Opengraph.

However, I'm not convinced the issue is with any of these modules, and here is why:

When I share an article on facebook (other platforms are doing the same), the image shows correctly in the preview but when it is displayed on a user's profile, either no image or a "safe image" from the platform's CDN is displayed.

When shared on Facebook, the image is replaced with something from FB's CDN:

```
<img height="74" width="74" alt="BBC One releases first look at new thriller Vigil" class="datstx6m pmk7jnqg j9ispegn kr520xx4 k4urcfbm" referrerpolicy="origin-when-cross-origin" src="https://external-lcy1-1.xx.fbcdn.net/safe_image.php?d=AQHbIThpTniFRwWa&w=74&h=74&url=https%3A%2F%2Frts.org.uk%2Fsites%2Fdefault%2Ffiles%2FRTS_logo.png&cfs=1&ext=jpg&ccb=3-5&_nc_hash=AQHydfUnOTwoNOs0">

```

When shared on Linked in, the image is replaced with something from LI's CDN:

```
<img width="308" src="https://media-exp3.licdn.com/dms/image/sync/C4D27AQEfVR4ye-RMcA/articleshare-shrink_480/0/1622988826826?e=1623243600&v=beta&t=8PksYkc4Zp8EI-ENytwmeh4x-hjIQKT1MBLtq_1r2SU" loading="lazy" height="164" alt="" id="ember91" class="ivm-view-attr__img--centered pab-featured-item__image lazy-image ember-view">

```

# Answer
> 0 votes
So, it turned out that it was a combination of a missing OG:image tag due to the metatag module looking at the incorrect image field, but even after I'd fixed that - it's worth noting that Facebook (and other platforms) cache the sample images that are used - it appears that they cahe the image even if a different user has already shared it, so you may need to wait to see the new image

---
Tags: 7, social-network, meta-tags
---


# Question
Title: How do I use variables in links.task.yml?
I have a local **`links.task.yml`** file to display the tab for the node data , But it seems to have a problem passing argument to the path . As you can see I am extending the node's basic fetaures like **edit,delete.revision** with an additional function using tab. I have **`module_name.links.task.yml`**

```
entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title

```

And I have the route in **`module_name.routing.yml`** as follows:

```
module_name.my_route:
  path: '/node/{arg1}/function_name'
  defaults:
    _controller: '\Drupal\module_name\Controller\ControllerName::function_name'
    _title: 'My title'
  requirements:
    _permission: 'access admin tab'

```

But it throws me errors like:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg1") to generate a URL for route "module\_name.my\_route".

How can I pass variables in links.task.yml file ?

# Answer
> 1 votes
The problem is that you are using `{arg1}` in your route and your `links.task.yml` file is registering that as an item that should use base route `entity.node.canonical`. As you can read in this change record, the value for `entity.node.canonical` will become `node/[nid]`.

In your situation, you are providing a variable `arg1`, when the node routing system is expecting a `node` variable.

Just make sure that all sub-pages share the same base path as their parents.

# Answer
> 19 votes
In your module\_name.links.task.yml file you can add a route\_parameters: array that lists the parameters you want to pass, in your case it would end up:

```
entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title
  route_parameters:
    arg1:  'value_for_arg1'

```

You can find this by looking at the code in \Drupal\Core\Menu\LocalTaskManager which parses this file.

# Answer
> 5 votes
You can use a class to generate dynamic tabs, and take example on the core tracker module which supports this.

Let's take a look in the `tracker.links.task.yml` file :

```
tracker.users_recent_tab:
route_name: tracker.users_recent_content
title: 'My recent content'
base_route: tracker.page
class: '\Drupal\tracker\Plugin\Menu\UserTrackerTab'

```

And then the `\Drupal\tracker\Plugin\Menu\UserTrackerTab` class :

```
<?php

namespace Drupal\tracker\Plugin\Menu;

use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Provides route parameters needed to link to the current user tracker tab.
 */
class UserTrackerTab extends LocalTaskDefault {

  /**
   * Current user object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Gets the current active user.
   *
   * @todo: https://www.drupal.org/node/2105123 put this method in
   *   \Drupal\Core\Plugin\PluginBase instead.
   *
   * @return \Drupal\Core\Session\AccountInterface
   */
  protected function currentUser() {
    if (!$this->currentUser) {
      $this->currentUser = \Drupal::currentUser();
    }
    return $this->currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    return ['user' => $this->currentUser()->Id()];
  }

}

```

So you should create your own class like this one and implement the `getRouteParameters` method to return the array with the right parameters to be used. Simple like that :)

Reference to a well written article about this : https://medium.com/@joshirohit100/dynamic-tabs-in-drupal-8-8a76386e212c

# Answer
> 0 votes
You have to use "route\_parameters" key in module\_name.links.task.yml and pass the variables with value. Here is the working code : In `module_name.routing.yml`  file

```
sg_custom.loading_form:
  path: '/form/loading_form/{page}'
  defaults:
    _form: '\Drupal\sg_custom\Form\LoadingForm'
    _title: 'Loading Form'
  requirements:
    _permission: 'access content'

```

And in `module_name.links.task.yml`  file

```
sg_custom.tab_1:
  route_name: sg_custom.loading_form
  title: Loading Start
  base_route: sg_custom.loading_form
  route_parameters:
    page: start_loading

sg_custom.tab_2:
  route_name: sg_custom.loading_form
  title: Loading End
  base_route: sg_custom.loading_form
  route_parameters:
    page: end_loading

```

---
Tags: 8, routes
---


# Question
Title: Class Drupal\dfm\EventSubscriber\DfmSubscriber not found when try to remove the Drupella File Manager
I installed the *Drupella File Manager* module for Drupal 8.8, but I have Drupal 8.7. I received this error.

> Call to undefined method Drupal\Core\File\FileSystem::scanDirectory()

I don't need the module anymore, so I'm trying to remove it. Because of the same error on the uninstall page, I'm trying to manual remove it.

First, I removed *dfm* (which is the module machine name) from the `$module_data` configuration as described in Manually disable a module.

Then, I deleted the *dfm* directory from the /modules directory, but now I receive this error.

> Class 'Drupal\dfm\EventSubscriber\DfmSubscriber' not found in Drupal\Component\DependencyInjection\Container-\>createService() (line 265 of core/lib/Drupal/Component/DependencyInjection/Container.php).

How can I resolve this problem?

Are there other module files that cause problems?

Clearing the cache doesn't help.

# Answer
Ok, I commented the line that causes the first error and then uninstalled the module via the uninstall page
> 0 votes

---
Tags: 8, caching, plugins
---


# Question
Title: How do I set a Boolean config variable to false?
I can't set a boolean config value to FALSE with drush.

```
pk@DC:~/$ lando drush config-set advagg.settings enabled 0 -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': false

pk@DC:~/$ lando drush config-set advagg.settings enabled true -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

pk@DC:~/$ lando drush config-set advagg.settings enabled false -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

```

Why does setting it to `false` make it `true`?

# Answer
See the Drush 10 docs for config:set. With Drush 10, the `format` option is now `input-format`.

> --input-format\[=INPUT-FORMAT\]. Format to parse the object. Recognized values: string, yaml \[default: string\]

For example, to disable core's css aggregation:

```
drush config:set system.performance css.preprocess false --input-format=yaml

```
> 3 votes

# Answer
I would recommend avoiding such an assumption because the functionality might change with the future versions of Drush.

```
$ drush config-set advagg.settings false --format=yaml -y

```

This is explicit and direct, tested with Drush 8.x.
> 2 votes

# Answer
When setting a boolean with Drush 8, you need to use `0`, not `false`.

```
pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

pk@DC:~/$ lando drush config-set advagg.settings enabled 0 -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': false

```

**Unfortunately, this does not work in Drush 10.**
> 0 votes

---
Tags: drush
---


# Question
Title: How do I create a block that shows content related through a second level relationship?
I have three node content types, called 'pathway', 'page' and 'relation'. The relation nodes I use to connect pages to the pathways. The relation nodes have entity reference fields: endpoint A and endpoint B. I want to create a views block of all relation nodes, which use endpoint A reference (pathway) to referene the same patway as the relation that references the currently viewed node using endpoint B.

The purpose of the block is to show all relations of the pathway on every page that is referenced by one of these relations.

# Answer
> 0 votes
If I understand correctly, you want a Views block such that, when I am on the "Node Q" page, the view traverses the relationships all the way up to Pathway "Node X", and then down again to "Relation 1", "Relation 2", and "Relation 3".

Start with a **Contextual Filter "Content: ID"**, configured with a default value to get the Content ID from the URL. This will provide the view with "Node Q" as a starting point.

Next, we need to add a chain of relationships, each one dependent on the last.

* **Add a Relationship "Content using \[Endpoint B field\]".** This connects "Node Q" to "Relation 1". I suggest setting the relationship's administrative title to something more precise, like "Relation from node".
* **Add a Relationship "Content referenced from \[Endpoint A field\]",** configured to use the previous "Relation from node" relationship. This connects "Relation 1" to "Pathway X". Again, set a better administrative title, like "Pathway from relation".
* **Add a Relationship "Content using \[Endpoint A field\]",** configured to use the previous "Pathway from relation" relationship. This connects "Pathway X" to *all* the Relations referencing it in Endpoint A. Set an adminstrative title like "Relations from pathway".

This should get you there. When configuring your View's fields, make sure to use the "Relations from pathway" relationship.

---
Tags: views, 9
---


title: Unable to preview media items

text:
# Question
Title: Unable to preview media items
I have a node page where, in the WYSIWYG, I have embedded about 50 media items. When I edit the node, I can see this error for some of the media items.

> An error occurred while trying to preview the media. Please save your work and reload this page.

In the browser console, the error is the following.

> mysite.com/media/wysiwyg/preview?text=%3Cdrupal-media%20data-entity-type%3D%22media%22%20data-entity-uuid%3D%22b21db71d-3c53-4d46-afed-a3197767fac4%22%20data-href%3D%22%22%20data-size%3D%22original-size%22%3E%3C%2Fdrupal-media%3E&uuid=b21db71d-3c53-4d46-afed-a3197767fac4 429

429 is the status code.

>

Is there any limit for the number of the embedded media?
How do I get rid of these errors?

# Answer
> 0 votes
429 is the HTTP status code for "Too Many Requests". Drupal would not be responsible for serving a 429; something in your server infrastructure would do that, like a load balancer or Apache/nginx. Given that, this might be out of scope for Drupal Answers.

---
Tags: media, wysiwyg, 9
---