# Question
Title: limit_validation_errors resetting form values in submit handler
I have a custom button in my **`form_alter`** and a submit handler for that . I **`don't need validation`** for this button submit . I tried by giving **`limit_validation_errors`** to exclude all validation for the custom submission . When giving like this am **`not receiving any form values`** in submit handler . Any idea on how to resolve this issue ?

**TRY**

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
 //Additional button for the Save as Draft feature
  $form['actions']['draftsubmit'] = array(
      '#type' => 'submit',
      '#value' => t('Save as Draft'),
      '#weight' => 1000,
      '#submit' => array('draft_form_submit'),
      '#limit_validation_errors' => array(),
     );
}

/**
 * Handles the save as draft button submit
 */
function draft_form_submit($form, &$form_state) {
    echo '<pre>';print_r($form_state->getValues());exit;echo '</pre>'; //Not getting values here
    $name = $form_state->getValue('field_p_name')[0]['value'];
    $dc = $form_state->getValue('field_p_dc')[0]['value'];
    $sec_type = $form_state->getValue('field_p_sec_type')[0]['value'];
}

```

**UPDATE**

---

I have other validations in other modules form\_alter like

```
 function othermodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
    $form['field_fwd_acl']['#element_validate'] = array('validate_IpAndNetworks');
    $form['field_fwd_dest_acl']['#element_validate'] = array('field_fqdn_validate');
    $form['field_amount_of_proxies']['#element_validate'] = array('field_instance_validate');
}

```

I mean these validations should not be worked when clicked on **`Save as Draft`** button is clicked

# Answer
> 2 votes
#limit\_validation\_errors prevents values from being passed to the submit handler, since they have not been validated. You can whitelist values by passing the form element key to #limit\_validation\_errors:

```
'#limit_validation_errors' => [
  // format follows the same as in the form state values. Elements
  // that are not #tree will be a string. Nested elements will be
  // an array.
  'element1',
  ['wrapper','element2'],
];

```

If you want to limit validation, but need all the values in the submit handler, then it's better to not use #limit\_validation\_errors. Instead, you can wrap any validation in a conditional to check if the 'next' button was clicked:

```
if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
}

```

Note that if you use #required, validation will still happen even with the above code, since #required is handled separately. In this case, I don't use #required, instead I'll add custom validation to the above code:

```
if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
  if (!strlen($form_state->getValue('some_element')) {
    $form_state->setError('some_element', $this->t('Please fill in a value for some field'));
  }
}

```

# Answer
> 0 votes
You can add a custom validation handler to the button which I think will override the normal form validations (rather than an if statement in each normal validation handler) If this is an entity for, I think the entity validates itself later so there might still be some validation there.

```
$form['actions']['draftsubmit'] = array(
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#weight' => 1000,
  '#submit' => array('draft_form_submit'),
  '#validate' = ['_draftsubmit_validate_callback'];  // this callback just does nothing. so everything is considered valid.
);

```

---
Tags: 8, forms
---


# Question
Title: Use a different template file for front end and submission view
I have defined a custom template file referenced via #theme for my custom webform element.

```
public function getInfo() {
  $class = get_class($this);
  return [
    '#input' => TRUE,
    '#process' => [
      [$class, 'processWebformElementSeatbooking'],
      [$class, 'processAjaxForm'],
    ],
    '#element_validate' => [
      [$class, 'validateWebformSeatbookingElement'],
    ],
    '#pre_render' => [
      [$class, 'preRenderWebformSeatbookingElement'],
    ],
    '#theme' => 'input__my_webform_seatbooking_element',
    '#theme_wrappers' => ['form_element'],
  ];
}

```

This input\__my\_webform\_seatbooking\_element is rendered fine in the front end, but I get an error when it is rendered in the back end when looking at a submission cause the icons used in the custom front end theme are missing.

> Twig\Error\LoaderError: Template "core/themes/seven/assets/icons/icon\_minus.svg" is not defined. in Twig\Loader\ChainLoader-\>getSourceContext() (line 30 of themes/custom/radix\_standard/templates/form/input--number.html.twig).

The template file includes a custom *input--number.twig* template which contains a reference to two SVG files.

```
<div class="col-12 col-md-6">
  {% include '@hw_radix_standard/form/input--number.html.twig' with {
    attributes: attributes.addClass('form-number')
      .setAttribute('step', element['#step'])
      .setAttribute('min', element['#min'])
      .setAttribute('max', element['#max'])
      .setAttribute('max', element['#max'])
      .setAttribute('oninput', "this.value = this.value.replace(/[^0-9]+/g, '');"),
  } %}
</div>

```

I am using a customized radix-theme in the frontend and default seven-theme in the backend.
I would like to render it as plain input field in the backend.
If I put `'#theme' => 'input__number'`, I get the plain input field in the back end, but I need a way to use my custom template file in the front end.
I am stuck here. I checked other render elements and webform code.

How is this normally designed to work?
Maybe I am doing it the wrong way round?
Do I have to put a simple twig inside my custom element module and put the fully featured in the radix?

# Answer
Last thougt was correct. Put a simplified version of input--my-webform-seatbooking-element.html.twig inside the module and the full featured version in the frontend.
> 0 votes

---
Tags: webforms, theming
---


# Question
Title: While upgrading from D6, update.php appears to expect the Drupal 7 version of the database array and it throws errors
Leaving settings.php in place (but writeable), per instructions 13 + 14 of major upgrade section of https://api.drupal.org/api/drupal/UPGRADE.txt/7.x , with the new D7 codebase but the old D6 DB, i get the following errors:

> Notice: Undefined offset: 0 in Database::parseConnectionInfo() (line 1529 of \[...\]includes/database/database.inc).
> Notice: Undefined index: driver in Database::openConnection() (line 1681 of \[...\]includes/database/database.inc).
> Notice: Undefined index: driver in Database::openConnection() (line 1681 of \[...\]/includes/database/database.inc).
> DatabaseDriverNotSpecifiedException: Driver not specified for this database connection: default in Database::openConnection() (line 1682 of \[...\]includes/database/database.inc).
> Notice: Undefined index: driver in Database::openConnection() (line 1681 of \[...\]includes/database/database.inc).
> The website encountered an unexpected error. Please try again later.

Here is the core of the question -- according to the instructions, and normal upgrades, update.php should note that settings.php is D6-style, and change it to D7-style, including db-connection format.

It is not doing so. What could be going wrong? Reading through the script, it determines the DB schema... but it's not obvious to me where it determines the settings.php version and updates it. Help? Thanks!

The installed Drupal 6 release is 6.38, the latest release for Drupal 6.

I first tried to upgrade to Drupal 7.95; then I tried to upgrade to Drupal 7.34, and then again with Drupal 7.0, but I had the same issue.

\[\[Note: the below is not part of the core of this question, but responds to "why don't you just hardcode D7-style DB connection? I can hard-code the database settings using the Drupal 7 array structure, but that leads to other problems (expecting things that don't exist yet):

```
Error
Error message
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal_7_test.main_system' doesn't exist: SELECT name, schema_version FROM {system} WHERE type = :type; Array ( [:type] => module ) in drupal_get_installed_schema_version() (line 151 of [...]/includes/install.inc).
The website encountered an unexpected error. Please try again later.

```

Per this report, my assumption is that this means the code is expecting the new D7 codebase because the database connection was D7 style: https://www.drupal.org/node/1308308 \]\]

# Answer
> 1 votes
The script update.php ascertains whether settings.php is D6 or D7 based on whether the `$databases` array is set. If that array is set in any form, it will skip all code designed to work with Drupal 6 settings file, and will skip upgrading the database to Drupal 7.

In my case, integration with CiviCRM required a bit of a kludgy addition to the settings.php creating aliases for databases, and used the `$databases` variable to do it. This confused update.php.

---
Tags: 7, database, upgrading
---


# Question
Title: Update entityManager()->getViewBuilder from 5 year old site?
I have a Drupal 8 module which hasn't been updated for 5 years. I m trying to update to current version of Drupal.

The error I get is

```
Error: Call to undefined method Drupal::entityManager()

```

The code causing the error is below.

```
      $viewbuilder = \Drupal::entityManager()->getViewBuilder('paragraph');
      $data = $viewbuilder->view($paragraph);
      $array['#cache']['tags'][] = 'node:' . $node->id();

```

When I search one suggestions is to load through drupal service like below

```
\Drupal::service('entity_field.manager')->getViewBuilder('paragraph');

```

This gives a similar error, as does using EntityTypeManager

```
\Drupal::EntityTypeManager()->getViewBuilder('paragraph');

```

How do I update this code?

Thanks for any help

# Answer
View builders are now retrieved from the service `entity_type.manager`, which can be retrieved globally using `\Drupal::entityTypeManager()`:

```
\Drupal::service('entity_type.manager')->getViewBuilder('paragraph');

```

Or:

```
\Drupal::entityTypeManager()->getViewBuilder('paragraph');

```
> 3 votes

# Answer
In Drupal 10, the code to get an entity view builder is used, for example, in `BlockViewBuilderTest::testBasicRendering()`.

```
$builder = \Drupal::entityTypeManager()->getViewBuilder('block');
$output = $builder->view($entity, 'block');

```

The same code is used in Drupal 9 and Drupal 8.9.

Older code used `Drupal::entityManager()`, but as the documentation page says, that method has been deprecated and removed in Drupal 9. `\Drupal::entityTypeManager()` should be instead used in most cases.

If you get an error about `\Drupal::entityTypeManager()` being a non existing method, then the core/lib/Drupal.php file is probably corrupted.

The *entity\_field.manager* is a completely different service and it is not the service you need to use. The class implementing it (`EntityFieldManager`) does not define any `getViewBuilder()` method.
> 1 votes

---
Tags: theming, 9
---


# Question
Title: What is the correct procedure for creating multi-instances and websites?
I have installed Drupal 10 and it is working with no issues. I can create my first multi-instance with a single website with no issues.

The problem I have is when I create my second website in the default instance; all of the links in the second website point back to the first website by default. I am assuming the method I am using to create Drupal 8 websites is not the same as it is now in Drupal 10.

Can anyone give me some insight on how to create websites in Drupal 10? I am sure the way I create them is what is causing the issue, so I am wondering if someone can tell me how to create two sites under the same instance.

This is of how I am doing it now.

1. Copy the default folder in Drupal 10 and rename to your new site
2. On the database server and copy the Drupal 10 database for the site and create a user for it
3. Give permissions to user
4. Go back to web environment
5. Change the current directory to */www/webservices/drupal10/sites/newsite*
6. Edit the *settings.php* file to change the connection information
7. Edit the */www/webservices/drupal10/sites.php* to add a new line for `$sites`
8. Create a symbolic link in */www/webservices* that goes to *drupal10*
9. Check the browser

# Answer
> 0 votes
Follow the documented procedures for installing multisites.

---
Tags: multi-sites, 10
---


title: How to get Paragraph Changed Time?

text:
# Question
Title: How to get Paragraph Changed Time?
I know how get User entity changed time (`$user->getChangedTime()`).
Node has the same value (`$node->changed`), but I need to get this changed time from a `Paragraph`.

When I try this method `$paragraph->getChangedTime()` (the value `changed` do not exists) i got this:

*Error: Call to undefined method Drupal\paragraphs\Entity\Paragraph::getChangedTime() ...*

I have this field in my *User* entity, and I need to know when this field is changed. Is there any way to achieve that?

# Answer
You can add a date/time field to the paragraph type and fill in the current time if the paragraph is changed:

*mymodule.module*

```
<?php

use Drupal\paragraphs\ParagraphInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for paragraph entities.
 */
function mymodule_paragraph_presave(ParagraphInterface $paragraph) {
  if ($paragraph->getType() == 'my_paragraph_type') {
    if ($paragraph->isChanged()) {
      $paragraph->field_date->value = (new DrupalDateTime('now', DateTimeItemInterface::STORAGE_TIMEZONE))
        ->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    }
  }
}

```
> 1 votes

---
Tags: hooks
---


title: Change operator in a query?

text:
# Question
Title: Change operator in a query?
I'm working in a Drupal 9 website.

I need to change operator in my view query from != to \<. In a view i got two contextuals filters:

* The first to retrieve id from an entity reference field.
* The second to retrieve current node id.

In the second contextual filter, exclude is selected to be != in my query.

The result i need is to transform this != to \< for show all nodes who got the same reference field ID AND an ID lower than current node id. It's like a previous Articles by the same reference field!

My view query is :

```
SELECT "field_entreprises_marque_node_field_data"."created" AS "field_entreprises_marque_node_field_data_created", "node_field_data"."nid" AS "nid", "field_entreprises_marque_node_field_data"."nid" AS "field_entreprises_marque_node_field_data_nid"
FROM
{node_field_data} "node_field_data"
LEFT JOIN {node__field_entreprises_marque} "node__field_entreprises_marque" ON node_field_data.nid = node__field_entreprises_marque.field_entreprises_marque_target_id AND node__field_entreprises_marque.deleted = '0'
LEFT JOIN {node_field_data} "field_entreprises_marque_node_field_data" ON node__field_entreprises_marque.entity_id = field_entreprises_marque_node_field_data.nid
WHERE (("node_field_data"."status" = '1') AND ("node_field_data"."type" IN ('entreprise_marque'))) AND ((node_field_data.nid = '3259' )) AND ((field_entreprises_marque_node_field_data.nid != '22561' OR field_entreprises_marque_node_field_data.nid IS NULL))
ORDER BY "field_entreprises_marque_node_field_data_created" DESC
LIMIT 20 OFFSET 0

```

What i need is : field\_entreprises\_marque\_node\_field\_data.nid \< '22561'

I try like this:

```
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;

/**
* Implements hook_views_query_alter().
*/
function mymodule_custom_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->current_display === '20_articles_precedents') {
    $view->query->where[4]["conditions"][0]["operator"] = '>';
  }
}

```

But nothing appens...

# Answer
> 0 votes
I do it like that:

```
/**
 * Implements hook_views_query_alter().
 * modifier la requete d'une vue
 */
function injector_views_query_alter(&$view, &$query) {

  if ($view->id() == '20_articles_precedents' && $view->current_display == 'block_1') {
    $field_name = 'field_entreprises_marque_node_field_data.nid != :nid2 OR field_entreprises_marque_node_field_data.nid IS NULL';
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] === $field_name) {
          $condition['field'] = 'field_entreprises_marque_node_field_data.nid < :nid2 OR field_entreprises_marque_node_field_data.nid IS NULL';
        }
      }
    }
  }

```

# Answer
> -1 votes
I'm not sure, but i think you need to implement the `hook_views_api()`:

```
/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'YOUR_MODULE_NAME'),
  );
}

```

Besides that on your hook I think it's not necessary pass the operator selector, like this:

```
if ($view->current_display === '20_articles_precedents') {
  $view->query->where[4]["conditions"] = '>';
}

```

But I dont't run any test of this.

---
Tags: views, 9
---


# Question
Title: Preventing one site from redirecting to www. prefix in multisite
I am using Drupal 9, multi-site. Generally, for all sites except one, i want to redirect from non-www to www prefix and i'm using the root `.htacces` file for it by uncommenting redirect rules. But the one site is 3rd level domain such as `noha.ruka.cz` and i dont want this particular site to redirect to the `www` prefix. Any idea?

# Answer
Use the regular expression features of mod\_rewrite—specifically `RewriteCond %{HTTP_HOST}`—to match or exclude that domain. The official documentation has a close example.
> 0 votes

---
Tags: 9, redirection, multi-sites
---


# Question
Title: When adding new nodes how can I pre-populate the body field with the body of another node?
I have a Drupal 9 website with number of nodes that I use as templates, I clone them to create nodes with the same body text.

However, I want to make this process simpler by prepopulating the body field using a token that fetches the node ID from the URL parameter.

I checked the modules:

but as far as I can see, they don't support fetching a field from another node? *Entity Prepopulate* comes close I'm not sure how the URL parameter can be used by a token to pre-populate the body field.

# Answer
> 3 votes
The Field clone module can do this without custom code: Example usage: `node/add/page?fieldclone=node:17:body`

> This module adds an option to clone fields to entity create/edit pages via get parameters. After installation you can use links like this (should be self-explanatory): `node/add/page?fieldclone=node:17:field_common|node:23:field_source:field_target`

# Answer
> 5 votes
If you add the template node ID as URL query parameter

```
/node/add/product?template=123

```

this code adds the body content of the template:

*mymodule.module:*

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

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(Node $node) {
  if ($node->getType() == 'product') {
    if (\Drupal::routeMatch()->getRouteName() == 'node.add') {
      $nid = \Drupal::request()->query->get('template');
      if ($template = Node::load($nid)) {
        # add access check for $template if necessary
        $node->body->value = $template->body->value;
        $node->body->format = $template->body->format;
      }
    }
  }
}

```

If the node add form is accessible to untrusted users, you need to add an access check to identify the node as a template. Without a hacker could use the node add form to read unpublished content simply by guessing node IDs.

---
Tags: nodes, forms
---


# Question
Title: Best practice for user specific data related to specific nodes
I have a content type travel\_locations wich contains multiple fields (such as title, body, geolocation, etcetera). Now I would like the user to reference nodes of this content type when for example he has visited this location, together with specific data about this visit (traveldate, rating, textfield for travelnotes etcetera). The specific travel data will probably be collected trough paragraphs module. But I’m unsure which approach is best. Do I: a) Add the paragraphs reference field to the content type travel\_locations? But is seems that in this usecase other users can edit/tamper other users data because every other (privileged) user is able to add his own travel data to the same node (via the node edit form)?

b) Add the paragraphs reference field to the user account to make the relation between the user and the travel\_locations for that specific user. If this is the best approach, what will happen when the user adds for example 200 different travel locations? Will they all be loaded on every page request when the user is logged in (and thus consuming unnecessary large resources)

Or is there a different and better approach? Any suggestions and help will be appreciated! Thanks. (Use Case for Drupal 9/10).

# Answer
You are using content types, which will work and is fine, but this can be done with custom entity types as well. For the case of this explanation, I'll move forward with the assumption that the data types are all nodes (content types).

You can do the following:

1. Create two content types:
    * Travel Location
    * Trip
2. Create an entity reference field in the Trip content type, titled 'Travel Location(s)', referencing the Travel Location content type.
3. Add fields to the Trip content type for the various trip fields; date, rating, notes
4. Create an entity reference on the user to the Trip content type, allowing for unlimited values

This will set up the back-end information architecture for the system whereby a user can have multiple trips assigned to them, and each trip can have a travel location assigned to it.

As for how to structure the front-end with good UX for entering trips, that's more of an opinion-based question, better addressed on Drupal.org than Drupal Answers, as Drupal Answers does not allow for opinion-based questions.
> 0 votes

# Answer
What @berliner said:

> You create a new entity type/node type (depends on your needs) that relates users and locations. This also allows you to easily store additional data for that location visit (think travel time, pictures, recommendations, ...) without bloating your base entities.
> -1 votes

---
Tags: 10
---


# Question
Title: How do I make a block that pulls the current node content?
Ok, so I know blocks in Drupal 8 have these things called "contexts" which allow Core to clear cache on a fine-grained basis. I can't find any decent explanation of how they work, or how to get page variables from them or whatever.

My goal is to have a block type that renders fields or a display mode of the current node into the block content. I have seen elsewhere how one would get the current node, but I don't entirely understand how it's supposed to feed back into cache contexts. I know #cache on render arrays exist, but there's also a bunch of methods from ContextAwarePluginInterface that I'm not sure what they do. Is there some documentation I'm missing?

# Answer
> 9 votes
There are two completely different kinds of contexts.

Cache contexts, which have nothing to do with this. They're not used to invalidate something, but vary by something (e.g. cache differently for different user permissions). Cache tags are for invalidation.

What you mean are plugin contexts. And yes, blocks are able to use them since a short while (They always could, but the block.module didn't support it properly). As @larowlan said, core uses them mostly for visibility conditions but it works the same for blocks.

One such example that you can look at is the NodeType condition. What you need to do is add the context annotation and then you can use it as `$this->getContextValue('node')`. The advantage of this is that your block is more flexible and doesn't need to know where the node is coming from exactly, that's up to the user configuring it.

Note that this is not visible in the UI currently unless there is actually more than one node to chose from.

# Answer
> 9 votes
For using node in block, i use context. For example: this block display links for edition and deleting current node:

```
<?php

    /**
     * @file
     * Contains \Drupal\my_module\Plugin\Block\NodeMenuBlock.
     */

    namespace Drupal\my_module\Plugin\Block;

    use Drupal\Core\Block\BlockBase;
    use Drupal\Core\Link;
    use Drupal\Core\Url;

    /**
     * @Block(
     *   id = "node_menu_block",
     *   admin_label = @Translation("Node Menu Block"),
     *   category = @Translation("My Group"),
     *   context_definitions = {
     *     "node" = @ContextDefinition(
     *       "entity:node",
     *       label = @Translation("Current Node")
     *     )
     *   }
     * )
     */
    class NodeMenuBlock extends BlockBase {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $node = $this->getContextValue('node');
        $nid_fld = $node->nid->getValue();
        $nid = $nid_fld[0]['value'];

        $markup = '';
        $links = ['entity.node.edit_form' => 'Edit', 'entity.node.delete_form' => 'Delete', ];
        foreach($links as $rout=>$text) {
          $url = Url::fromRoute($rout, array('node' => $nid));
          $link = Link::fromTextAndUrl(t($text), $url)->toRenderable();
          $link['#attributes'] = array('class' => array('button', 'button-action'));
          $markup .= render($link).' ';
        }

        $block = [
          '#type' => 'markup',
          '#markup' => $markup,
        ];
        return $block;
      }

    }

```

More information on drupal.org

# Answer
> 1 votes
The context aware plugin stuff is mainly used by block visibility conditions. E.g see the node condition which takes the current node. I'm not sure if blocks per-se can hook into this. I can say for certain that you can use the route match service and get the current node, should it exist, from that.

# Answer
> 0 votes
Check out the Block node contrib module: https://www.drupal.org/project/block\_node

> # Introduction
>
> This module provides a block which can display either the current node or a specified node in a given view mode.
>
> # Possible uses
>
> I want to display a specific node in a sidebar region using a teaser view mode. I want to display a list of teaser nodes referenced by an entity reference field on the current node.
>
> # Installation
>
> Install as usual, ideally with composer. Enable the module.
>
> # Configuration
>
> Place the block using the block layout page as you normally would to place any block.
>
> ## Configuration options:
>
> **Use current node**
>
> * When checked the current node will be displayed in the block if the block is placed on a node page.
>
> **Node to display**
>
> * Search for a node to display. When selected this node will be displayed in the block.
>
> **View mode**
>
> * Choose the view mode from the available options. The node displayed in the block will be displayed in this view mode.
> * Other settings are the standard block settings.

# Answer
> 0 votes
For showing a specific field from the current node in a block, https://www.drupal.org/project/fieldblock

---
Tags: nodes, blocks, 8
---


# Question
Title: Why do I get an error about the extension.list.module service non existing?
I installed Drupal 8.5.6 and Drupal Commerce with Composer. They installed fine, but after I cleared the cache, I got this exception in a WSOD.

> Uncaught PHP Exception Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: "You have requested a non-existent service "extension.list.module"." at C:\wamp\www\drupal-8.5.6\core\lib\Drupal\Component\DependencyInjection\Container.php line 151

I searched for *extension.list.module* and I found this.

```
function system_rebuild_module_data() {
  return \Drupal::service('extension.list.module')->reset()->getList();
}

```

What did I do wrong to cause this problem?
What is my next step to solve this dilemma?

# Answer
> 0 votes
When Drupal loads some 'foo.bar' service (e.g. `\Drupal::service('extension.list.module')`), it expects this service to be defined in one of the `somemodule/somemodule.services.yml` files. For example:

```
services:
  extension.list.module:
    class: Drupal\somewhere\SomeService

```

This particular service (`extension.list.module`) is defined in `core/core.services.yml`

```
  extension.list.module:
    class: Drupal\Core\Extension\ModuleExtensionList

```

This should be available by default, so either the Drupal core files are missing or your lost some integrity of your data in your database. Try rebuilding cache (e.g. `drush cache:rebuild`), if it fails, manually clear all `cache_*` tables (especially `cache_bootstrap`). Otherwise restore your database from the backup.

---
Tags: 8, commerce
---


# Question
Title: Migration entity_lookup not picking up repeating taxonomy terms
**Background**: I am creating new articles in Drupal 9.5 from a source database using the Migrate API. The articles optionally have references to one or more taxonomy terms. I have already created the taxonomy terms in Drupal manually, they look good. I then use the **entity\_lookup** process plugin to lookup the taxonomy IDs as part of the article migration. But when the taxonomy terms repeat, they don't seem to be getting picked up right.

**Problem**:

Minimal migration YAML snippet is below.

Somehow only 'term1' in data row '1' keeps getting set in Drupal correctly when the migration is run. Nothing is set for row '2' (which is correct behavior) and nothing for row '3' either (incorrect behavior). I narrowed down the issue to repeating taxonomy terms, but cannot figure out what is going wrong. I have used the same construct with the explode plugin along with entity\_generate and they worked well (but I don't want to go the route of entity\_generate).

These links (this and this) referred to in past threads don't help much as the examples and explanations appear incomplete. If anyone can throw better light on this and where I am going wrong in the YAML, would be grateful. Thank you!

```
source:
  plugin: embedded_data
  data_rows:
    -
      unique_id: 1
      title: 'xxx'
      description: "xxxxx"
      taxoterms: 'term1'
    -
      unique_id: 2
      title: 'xxxx'
      description: "xxxxxxx"
      taxoterms: ''
    -
      unique_id: 3
      title: 'xxxx'
      description: "xxxxxxxxxxxx"
      taxoterms: 'term2,term3'
  ids:
    unique_id:
      type: integer
process:
  title: title
  body/value: description
  body/format:
    plugin: default_value
    default_value: restricted_html
  taxoterms:
    -
      plugin: skip_on_empty
      source: taxoterms
      method: process
      message: 'Article does not contain taxomony terms'
    -
      plugin: explode
      delimiter: ','
      strict: FALSE
      source: taxoterms
    -
      plugin: callback
      callable: trim
    -
      plugin: entity_lookup
      entity_type: taxonomy_term
      value_key: name
      bundle_key: vid
      bundle: my_taxo_vocab
destination:
  plugin: 'entity:node'
  default_bundle: my_article

```

# Answer
> 0 votes
UPDATE:

The yaml I posted in the question is actually perfectly fine, and it just works! Let me explain what happened.

The problem was an extraneous 'source' property I had set for the 'entity\_lookup' plugin. Specifying a source is not necessary because the source for the plugin is of course the output of the previous plugin in the pipeline. Curiously, however, in my question, I posted ***a*** version of the YAML file that I was tinkering with, and as part of which tinkering I removed the 'source' property but never actually tested it. As it turns out, the extraneous 'source' property is THE mistake.

Sidenote: I would imagine a plugin in the pipeline would ignore the 'source' since it is not required, but it appears the entity\_lookup seems to read it and behave differently. A minor bug? Maybe.

# Answer
> 0 votes
`entity_lookup` does not create new taxonomy terms, it only checks for existing terms and returns null if they don't exist yet.

You need to replace entity\_lookup with entity\_generate instead. It will do a lookup first, and generates the entity if it doesn't exist yet. On subsequent rows it will return the entity it just generated itself.

---
Tags: taxonomy-terms, migrations
---


# Question
Title: I cannot get the Autoban module to work from "Access Denied" or "Page Not Found"
I must be doing something stupid because there are several thousand users of this module! I need this module badly because just about every night the site gets a hundred or more "page not founds". At present I'm entering them manually in the banned ip address list.

I've searched for documentation on this module without success. What I assume should happen is that, once the threshold level is reached, any watchdog entry matched with a rule will result in an automatically generated ip address ban entry.

Here are the settings I'm using...

**Rule** *Message pattern :* LIKE page not found *Referrer pattern :* no entry *Threshhold:* 1 *User Type:* Anonymous *IP Ban Provider:* Core Ban

Drupal version 9.4.6 Log Analysis shows no entries but there **are** entries in the log... e.g. *page not found 10/25/2022 - 16:09 /taxonomy/term/rss.xml Anonymous (not verified)* (? The not verified couldn't be causing the problem, could it? )

**Settings:** *Exclude dblog types:* autoban cron php system user

*Analyses Form Threshold:* 5 *Whitelist:* blank

*Query mode:* LIKE *Use wildcard :* unchecked

I hope this helps pinpoint what I'm doing wrong. Thanks.

# Answer
You should use Message pattern: "page not found" and that's all. (Use message patterns under the Message pattern field). No need to add "LIKE" to the Message patters.

The module will do request "LIKE %page not found%" and when you add "LIKE" to a pattern the module does "LIKE %LIKE page not found%" query and it returns empty data.

**I'm a creator of the Autoban module and I believe I know how my module works.** You may be free to ask questions about my module on the module issues. I added this question to the FAQ question also.

My previous right answer was deleted by apaderno and I want to know why.
> 1 votes

---
Tags: 9
---


# Question
Title: Can't get real field value from paragraph
I need to get value from exact paragraph type in paragraph reference field in node, so I can use it in Twig.

Here's my current code:

```
function my_theme_preprocess_field(array &$variables, $hook) {
  if ($node = \Drupal::request()->attributes->get('node')) {
    if ($node->getType() == 'page'){
      foreach ($node->get('field_sections') as $paragraph) {
        if ($paragraph->entity->getType() == 'targeted_paragraph_type') {
          $targeted_paragraph = $paragraph->entity;
          $variables['check'] = $targeted_paragraph->field_is_main->value;
        }
      }
    }
  }
}

```

The issue is that I'm always getting 0 for this field (it's boolean), and that's not a real situation I have. I also tried to get value from some other fields in this paragraph, and I'm always getting same values for each item (it's wrong value).

In this way (like code above), the variable check will always have latest value from list of paragraphs in foreach.

How I can store data for each paragraph separately and have it in Twig for exact paragraph?

The idea is to wrap title in H1 if the field\_is\_main field is checked, so maybe there's some other approach to do this?

# Answer
I think the problem starts with how you get the node reference, which you probably shouldn't get from the request.

If this field template preprocess hook is in a paragraph you get it via:

```
$paragraph = $variables['element']['#object'];

```

Every paragraph has a parent, which is probably the node you are looking for:

```
$node = $paragraph->getParentEntity();

```

You can then get field values from different levels, starting with the paragraph or the node.

The advantage is by following the references of the nested field and entity objects you get the right field deltas on the way up. If the targeted field is a sibling of the template field you can simply use the referenced paragraph to get the field value of the same paragraph field delta:

```
$value = $paragraph->field_is_main->value;

```
> 1 votes

# Answer
It's because you are overwriting the value of `$variables['check']`. You need to create an array and then populate it, like this:

```
function my_theme_preprocess_field(array &$variables, $hook) {
  if ($node = \Drupal::request()->attributes->get('node')) {
    if ($node->getType() == 'page'){
      $checks = [];
      foreach ($node->get('field_sections') as $paragraph) {
        if ($paragraph->entity->getType() == 'targeted_paragraph_type') {
          $targeted_paragraph = $paragraph->entity;
          $checks[] = $targeted_paragraph->field_is_main->value;
        }
      }
      $variables['check'] = $checks;
    }
  }
}

```

**Edit:**
But, if you want only one value (the checked one) in this var, you need to verify and push only the last selected, like this:

```
function my_theme_preprocess_field(array &$variables, $hook) {
  if ($node = \Drupal::request()->attributes->get('node')) {
    if ($node->getType() == 'page'){
      $checks = [];
      foreach ($node->get('field_sections') as $paragraph) {
        if ($paragraph->entity->getType() == 'targeted_paragraph_type') {
          $targeted_paragraph = $paragraph->entity;
          if ($targeted_paragraph->field_is_main->value) {
            $checks[] = $targeted_paragraph->[FIELD_STRING]->value;
          }
        }
      }
      $variables['checks'] = $checks;
    }
  }
}

```

Now on your twig template:

```
<h1>
{%- for title in checks -%}
  {{ title }}
{%- endfor -%}
</h1>

```
> 0 votes

---
Tags: theming, paragraphs, 10
---


# Question
Title: Set value in a choices.js dropdown after it's been created
Using Drupal 9.4 and choices.js 10.2 (design required a highly styled dropdown that I couldn't do with a standard element). The choices dropdown is created by a view.

When I had the plain select item in place, I could use javascript to set an optional default value for one of the two dropdowns. However, with the choices.js dropdown, I haven't found a simple way to make that happen despite scouring the github and stack overflow.

in my JS, I have tried:

```
var $org = '{{ org_id }}';
$id = "#fcs-{{ paragraph.id() }} #edit-field-audience-target-id";
const dropdown = new Choices(document.querySelector($id));
dropdown.setChoiceByValue($org);

```

However, the console tells me: "choices.min.js?rqlz1t:2 Trying to initialise Choices on element already initialised". I was hoping there was another method where I can tap into an existing Choices instance and call setChoiceByValue('x').

I might be able to do everything manually, but I want to make sure I'm not missing something.

# Answer
You can set a `selected: true` property on the item you want to be auto-selected.

```
[{ value: "red", label: "Red"}, { value: "blue", label: "Blue", selected: true }]

```

See https://github.com/Choices-js/Choices#choices

Also see https://github.com/Choices-js/Choices#setchoiceschoices-value-label-replacechoices which details multiple ways to define the input data.
> 0 votes

---
Tags: 9
---


# Question
Title: How can I run the inbuilt Drush 10.x commands as user #1?
I have a Drupal Queue worker class that fetches the Entity objects from Drupal to index to Elasticsearch.

The following command is causing the lesser documents to show up in Elasticsearch since by Access system unpublished; some entities couldn't be retrieved by anonymous users.

```
drush queue:run category_index_worker --debug

```

The `--user` argument seems removed from Drush. I'm trying to use the `EventSubscriber` to execute any Drush command as user #1 using `AccountSwitcher`, but I'm not sure what's the right event to use.

```
$accountSwitcher = \Drupal::service('account_switcher');
$accountSwitcher->switchTo(new \Drupal\Core\Session\UserSession(['uid' => 1]));

```

`KernelEvents::REQUEST` works in the web browser but not from the command line, like `ConsoleEvents::COMMAND` and `StackMiddleware`.

# Answer
> 5 votes
You could use the pre-command and post-command hooks to achieve this.

By using these hooks you can target a specific drush command such as `queue:run`. Here is an example implementation:

```
<?php

namespace Drupal\drush_queue_run_super_user\Commands;

use Consolidation\AnnotatedCommand\CommandData;
use Drupal\Core\Session\AccountSwitcherInterface;
use Drupal\Core\Session\UserSession;
use Drush\Commands\DrushCommands;

/**
 * A Drush commandfile.
 */
class DrushQueueRunSuperUserCommands extends DrushCommands {

  /**
   * The account switcher service.
   *
   * @var \Drupal\Core\Session\AccountSwitcherInterface
   */
  protected $accountSwitcher;

  /**
   * @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher
   *   The account switching service.
   */
  public function __construct(AccountSwitcherInterface $account_switcher) {
    $this->accountSwitcher = $account_switcher;
  }

  /**
   * @hook pre-command queue:run
   */
  public function preCommand(CommandData $commandData) {
    $this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));
  }

  /**
   * @hook post-command queue:run
   */
  public function postCommand($result, CommandData $commandData) {
    $this->accountSwitcher->switchBack();
  }

}

```

Good luck!

# Answer
> 1 votes
In continuation to @rémy's comment here

> // Switching back not possible

It is possible to switch back the user account. As per discussion here

`drush.services.yml`

```
services:
  my_demo.commands:
    class: \Drupal\my_demo\Commands\DemoCommands
    arguments: ['@account_switcher']
    tags:
      - { name: drush.command }

```

`DemoCommands.php`

```
<?php

namespace Drupal\my_demo\Commands;

use Drupal\Core\Session\UserSession;
use Drush\Commands\DrushCommands;
use Drupal\Core\Session\AccountSwitcherInterface;

/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 *
 * See these files for an example of injecting Drupal services:
 *   - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
 *   - http://cgit.drupalcode.org/devel/tree/drush.services.yml
 */
class DemoCommands extends DrushCommands {

  /**
   * The account switcher service.
   *
   * @var \Drupal\Core\Session\AccountSwitcherInterface
   */
  protected $accountSwitcher;

  /**
   * SimplesitemapCommands constructor.
   *
   * @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher
   *   The account switching service.
   */
  public function __construct(AccountSwitcherInterface $account_switcher) {
    $this->accountSwitcher = $account_switcher;
  }

  /**
   * Some demo drush command.
   *
   * @usage drush run-demo
   *   Run demo command.
   *
   * @command run:demo
   * @aliases run-demo
   */
  public function demo() {
    // Switch to root user (--user option was removed from drush 9).
    $this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));
    // Do here logic related to command.
    // ...
    // Switch account back.
    $this->accountSwitcher->switchBack();
  }

}

```

# Answer
> 0 votes
It's meant to be used in a custom drush command.

If you really want to set it in an event I haven't found one neither ...

But - you could hook a drush command in your own custom command. See https://www.drush.org/latest/hooks/#core-hooks

So you could create a drush command, that does nothing but implements of a hook, for your desired one(s), fe.

```
<?php

namespace Drupal\my_demo\Commands;

use Drupal\Core\Session\UserSession;
use Drush\Commands\DrushCommands;
use Drupal\Core\Session\AccountSwitcherInterface;

/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 *
 * See these files for an example of injecting Drupal services:
 *   - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
 *   - http://cgit.drupalcode.org/devel/tree/drush.services.yml
 */
class DemoCommands extends DrushCommands {

  /**
   * The account switcher service.
   *
   * @var \Drupal\Core\Session\AccountSwitcherInterface
   */
  protected $accountSwitcher;

  /**
   * SimplesitemapCommands constructor.
   *
   * @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher
   *   The account switching service.
   */
  public function __construct(AccountSwitcherInterface $account_switcher) {
    $this->accountSwitcher = $account_switcher;
  }

     /**
     * @hook script
     */
    public function runEveryScriptAsUserOne(CommandData $commandData): void {
      // Switch to root user (--user option was removed from drush 9).
      $this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));

      // Switching back not possible ..
    }

}

```

but - I would not really recommend this, as you cannot switch back, so the account switch is not targeted.

> I would really suggest you implement a full custom command!

---
Tags: 8, drush, queue
---


# Question
Title: Troubleshooting issue forks to make core version compatibility fixes
During the Drupal 8-\>9 upgrade, we noticed an issue where module maintainers had abandoned a project or were not responding to merge requests in a timely manner. As you know, composer doesn't care about patches when it comes to compatibility with major versions of Drupal, so you need an actual release which is compatible with the next major version before you can update drupal core in composer. This problem was easily solved by using issue forks to make core version compatibility fixes as per the article on Drupal.org.

Now, for the 9-\>10 upgrade, I have yet to get this to work for some reason. I am wondering if anything has changed for the syntax we need to use, perhaps with gitlab or something.

For example, I have set my drupal repositories to ignore drupal/views\_ef\_fieldset and use the issue branch:

```
"repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8",
            "exclude": [
                "drupal/views_ef_fieldset"
            ]
        },
        "drupal/views_ef_fieldset": {
            "type": "git",
            "url": "https://git.drupalcode.org/issue/views_ef_fieldset-3290466.git"
        },

```

Require line:

```
"drupal/views_ef_fieldset": "dev-3290466-automated-drupal-10",

```

I am fairly certail all of this is correct. Here is the issue branch:

https://git.drupalcode.org/issue/views\_ef\_fieldset-3290466/-/tree/3290466-automated-drupal-10?ref\_type=heads

But I get this:

> Your requirements could not be resolved to an installable set of packages. Problem 1
>
> * Root composer.json requires drupal/views\_ef\_fieldset dev-3290466-automated-drupal-10, found drupal/views\_ef\_fieldset\[dev-1.x, 1.x-dev (alias of dev-1.x)\] but it does not match the constraint.

Has the methodology for doing this changed since 9th?

# Answer
As @Hudri mentioned, the lenient composer package is the right answer here. It is, actually, the new suggested method for dealing with these situations rather than pinning to a feature branch.

### Documentation:
> 0 votes

---
Tags: composer
---


# Question
Title: Install Drush Launcher on MacOS Ventura on a Apple Silicon (M2) machine
I know this is not really a Drupal question but rather Drush. Maybe a Mac user can help me.

I installed drush launcher under MacOs Ventura on a Mac M2 by following the procedure.

Running `drush st` (for example) after `sudo mv drush.phar /usr/local/bin/drush` gives me this error.

> zsh:permission denied:drush

I changed the permissions but I still get the error. Can you give me any advice?

Should we put it somewhere else?

I managed to install it on my previous Intel Mac but I don't remember how I did it. Perhaps the procedure has since changed.

# Answer
> 1 votes
Please read the README thoroughly. You are missing one step:

```
chmod +x drush.phar

```

---
Tags: drush
---


# Question
Title: Multiple Custom Module Event Subscribers Override Each Other
I've been working on custom modules that alter `RequestEvent`s based on the entity type provided by the route.

The functionality from one entity to another doesn't change, but the data does, hence I split the module. The working example extends a class provided by a base module that holds the core functionality.

I'm not sure if it matters, be it run order precedence or what have you, but the names are akin to `my_module_nodes` and `my_module_taxonomy_terms`.

When I have **just** `my_module_nodes` installed, it works perfectly. When I install `my_module_taxonomy_terms` alongside it, `my_module_taxonomy_terms` appears to override the functionality of `my_module_nodes`.

I've debugged by logging to Watchdog the routes I'm checking against with both modules enabled, and it checks for the route defined in `my_module_taxonomy_terms` twice, rather than checking for the routes defined in each individual module. E.g. I would expect to see `entity.node.canonical` logged as well as `entity.taxonomy_term.canonical`, but I see `entity.taxonomy_term.canonical` logged twice per page load.

Note that I have attempted this with static strings in the `__construct` method as opposed to using arguments from the services file, but nothing changing. Also note that installation order does not change the result - `my_module_taxonomy_terms` *always overrides* `my_module_nodes`.

**One of the two submodule event subscribers in question - identical to the other besides the `data` method.**

`/custom/my_module_base/src/MyModuleBaseSubscriberBase.php`

```
namespace Drupal\my_module_base;

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * @package Drupal\my_module_base\JsonEntitySubscriberBase
 */
class MyModuleBaseSubscriberBase implements EventSubscriberInterface {

  /** @var \Drupal\Core\Cache\CacheBackendInterface */
  protected $cacheBackend;

  /** @var \Drupal\Core\Routing\CurrentRouteMatch */
  protected $routeMatch;

  /** @var string */
  protected $routeName;

  /** @var string */
  protected $routeParameter;

  /**
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The "cache.render" cache backend service.
   * @param \Drupal\Core\Routing\CurrentRouteMatch $route_match
   *   The "current_route_match" route match interface service.
   * @param string $route_name
   *   The Name of the route to check against.
   * @param string $route_parameter
   *   The Name of the route parameter to get.
   */
  public function __construct(CacheBackendInterface $cache_backend, CurrentRouteMatch $route_match, string $route_name, string $route_parameter) {
    $this->cacheBackend = $cache_backend;
    $this->routeMatch = $route_match;
    $this->routeName = $route_name;
    $this->routeParameter = $route_parameter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cache.render'),
      $container->get('current_route_match'),
      $container->get('route.name'),
      $container->get('route.parameter'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest', 29];
    return $events;
  }

  /**
   * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
   *   The current RequestEvent object.
   */
  public function onRequest(RequestEvent $event) {
    $request = $event->getRequest();
    $route_match = $this->routeMatch->getRouteMatchFromRequest($request);

    if ($route_match->getRouteName() !== $this->routeName) {
      return;
    }

    $event->setResponse($this->getResponse(
      $route_match->getParameter($this->routeParameter)
    ));
  }

  // Other functionality...

  /**
   * @param mixed $entity
   * @return array
   */
  protected function getData(mixed $entity): array {
    return [
      'type' => $entity->getEntityTypeId(),
      'id' => $entity->id(),
    ];
  }

}

```

**One of the two submodule event subscribers in question - identical to the other besides the `data` method.**

`/custom/my_module_base/modules/my_module_nodes/src/EventSubscriber/MyModuleNodesSubscriber.php`

```
namespace Drupal\my_module_nodes\EventSubscriber;

use Drupal\my_module_base\MyModuleBaseSubscriberBase;

/**
 * @package Drupal\my_module_nodes\EventSubscriber
 */
class MyModuleNodesSubscriber extends MyModuleBaseSubscriberBase {
  /**
   * {@inheritdoc}
   */
  protected function getData(mixed $entity): array {
    return [
      'type' => $entity->getEntityTypeId(),
      'id' => $entity->id(),
      // Other values...
    ];
  }
}

```

**One of the two submodule service files in question - identical to the other besides the `parameters` values.**

`/custom/my_module_base/modules/my_module_nodes/my_module_nodes.services.yml`

```
parameters:
  route.name: entity.node.canonical
  route.parameter: node

services:
  my_module_nodes.subscriber:
    class: \Drupal\my_module_nodes\EventSubscriber\MyModuleNodesSubscriber
    arguments: ['@cache.render', '@current_route_match', '%route.name%', '%route.parameter%']
    tags:
    - { name: event_subscriber }

```

I've been tinkering on this project over the past week after work and I'm at a bit of a loss. Is there any other relevant information I should include? Thanks!

# Answer
If you have the same container parameter name in different modules the module last in alphabetic order will overwrite previous values. The solution would be to prefix the parameter name with the module name if it is specific to this module.

But why use parameters when you can use string literals?

*my\_module\_nodes.services.yml*

```
services:
  my_module_nodes.subscriber:
    class: \Drupal\my_module_nodes\EventSubscriber\MyModuleNodesSubscriber
    arguments: ['@cache.render', '@current_route_match', 'entity.node.canonical', 'node']
    tags:
    - { name: event_subscriber }

```
> 1 votes

---
Tags: 9, event-subscribers, 10
---


# Question
Title: Option to export path alias not showing in view (pathauto is installed)
On my new D 9.5.x site, I have pathauto installed, and it is working well. That is, neat alias URLs get generated for my articles as expected. I am now trying to export articles from the site. I have the views data export module installed, but when I create the export, I don't see the alias path available as a field to choose (as 'Content: Path' or anything else. The other article fields are available for selection and everything works with the export. Its just that the path is simply not available. Am I missing a setting somewhere? I have looked around, but unable to find any pointers.

I use the same modules on another old D8 site. Everything works perfectly there. I am able to export URL alias paths along with other article information. Makes me wonder if there is some setting from the other D8 site missing in my D9.5 site (note: the 2 sites are unrelated to each other).

# Answer
> 0 votes
Answering my own query after spending some time looking around:

"Content: Path" was deprecated in 8.5 and removed in 9.

The alternative is to use "Content: Link to Content" and massage it. Described in this drupal.org link here.

NOTE: As the link suggests, this alternative may have issues with multilingual sites, which my site is not.

---
Tags: path-aliases, importing-exporting
---


# Question
Title: How to programatically update a field for a revision?
What is wrong with this approach for updating a field value in a specific revision:

```
public function myTest() {

  $test = 'mytest33';

  $node_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  $node_revision->set('field_my_field', $test);
  $node_revision->save();

  return [
    '#markup' => 'Test page.',
  ];
}

```

When I load this simple test page and look at revision 10364 for the node, field\_my\_field doesn't update.

# Answer
I needed to use the setSyncing method, like so:

```
public function myTest() {

  $test = 'mytest33';

  $node_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  // See https://www.drupal.org/project/drupal/issues/2859042#comment-13083066
  $node_revision->original = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  // See https://www.drupal.org/project/drupal/issues/3335119
  $node_revision->setSyncing(TRUE);

  $node_revision->set('field_my_field', $test);
  $node_revision->save();

  return [
    '#markup' => 'Test page.',
  ];
}

```
> 1 votes

---
Tags: 9
---


# Question
Title: Rendering a nested Paragraph's field using Twig
We are using the Drupal 8 Paragraphs module and are have a Paragraph which contains a Paragraph type field, called "Steps" (machine name fs\_steps), allowing editors to add a number of "Step" Paragraphs (machine name fss\_steps) to the parent paragraph for rendering.

Within the twig file, we loop through the entities of the parent's Steps fields, but when we try to render a field of the nested Step paragraph field "Heading" using either (this code is within the context of a for loop):

```
{{ content.field_fs_step[key]['#paragraph'].field_fss_heading }}

```

or

```
{% set step = content.field_fs_steps[key]['#paragraph'] %}
{{ step.field_fss_heading }}

```

It fails with the following error:

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. in Drupal\Core\Template\TwigExtension-\>escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

Here is our current code that successfully retrieving the "values" of the bested paragraphs' fields, but does not end up using the renderer (which would respect the field's formatting types) as we need (this is a rudimentary example retrieving text values, but in other cases we want to render more complex data such as links and images):

```
        {% for key, item in content.field_fs_steps if key|first != '#'%}
                    {% set step = content.field_fs_steps[key]['#paragraph'] %}
                    <div class="step step{{ loop.index }}">
                        <div class="step-number">{{ step.field_fss_step_marker.0.value|raw }}</div>
                        <div class="step-info">
                            <h3>{{ step.field_fss_heading.0.value|raw }}</h3>
                            {{ step.field_fss_description.0.value|raw }}
                        </div>
                    </div>
                {% endfor %}

```

We're looking for help in understanding the following:

1. Why is it that the renderer triggers when calling a top level field against our parent Paragraph, such as {{ content.field\_fs\_heading }}, but attempting to render a subproperty of the "content" object or rendering a field of a referenced entity, generates an error?
2. If we are taking the wrong approach to "nested paragraphs", and/or how to render sub-entity fields properly from within the context of a Twig file? Do we need to (as a guess) create a separate template for the nested paragraph template? If so, how would we then pass in the contextual content data to that "partial" and have it properly render there?

# Answer
For nested / referenced paragraph rendering, it's probably best to use a separate template as you theorized above by stating *"Do we need to (as a guess) create a separate template for the nested paragraph template?"*

A general rule of thumb for Twig rendering is, if you are starting to dig that far down in a render array in a given template, best to use the next template inline in the chain.

in addition, In Drupal 8 Paragraphs, there is a nice API function for referenced paragraphs called getParentEntity().

```
/**
 * Gets the parent entity of the paragraph.
 *
 * Preserves language context with translated entities.
 *
 * @return ContentEntityInterface
 *   The parent entity.
 */
public function getParentEntity();

```

I wrote a blog post dedicated to that here: https://www.dannyenglander.com/blog/drupal-8-architecture-how-to-get-a-value-from-a-paragraphs-parent-entity/

The bottom line is, you will look at Twig template debugging and see the referenced paragraph template suggestion in the output. Then you can use that template with some preprocessing to pull any data you need from the parent paragraph entity. A common use case for this might be some kind of setting like a boolean in the parent entity that you need to pass to the referenced paragraph entity / template.
> 2 votes

# Answer
You can use the twig\_tweak module, which provides the drupal\_field() fucntion in twig to do this.

```
{% block content %}
  {% for key, field_fs_steps_item in content.field_fs_steps %}
    {% if key|first != '#' %}
      {% set paragraph_id = content.field_fs_steps[key]['#paragraph'].id.value %}
      {% set field_fs_steps = drupal_field('field_fs_steps', 'paragraph', paragraph_id) %}

```
> 1 votes

---
Tags: theming, paragraphs
---


# Question
Title: How to programmatically grant access to view unpublished content with a special query string?
In my application, I want anonymous users to be able to view an unpublished node but only if they append a special code to the URL. For example:

```
www.mysite.com/node/123?code=Hx23ufG38

```

I figure I can do something in a preprocess function to check if the code is appended to the URL and, if so, allow the user to view the unpublished node. (This clearly is not for a use case where the content is sensitive, because anyone visiting the page at the URL with the code appended will be able to see the page.)

How can I programmatically grant the current (anonymous) user permission to view unpublished content, provided the condition is met in the URL?

This is for a Drupal 9 website.

# Answer
> 2 votes
You can use https://www.drupal.org/project/access\_unpublished or look at its code.

---
Tags: 9
---


title: Set variable for drupal 9 website

text:
# Question
Title: Set variable for drupal 9 website
I need to get the hostname and then define a variable which is going to be used in all controllers of the website. I am able to call the code in controller as follows:

```
$host = \Drupal::request()->getHost();
\Drupal::logger('host')->notice($host);

switch($host)
{
  case 'A';
    $var = "A";
    break;
  case 'B';
    $var = "B";
    break;
  case 'C';
    $var = "C";
    break;
  case 'D';
    $var = "D";
    break;
  default;
    $var = "";
    break;
}

```

But instead of defining it in all Controllers, I want to define it at a very beginning, then create a global variable(eg. $var) which I would be able to call in all controllers. I need to know which hook or event would help me in this scenario.

# Answer
> 0 votes
> I want to define it at a very beginning, then create a global variable(eg. $var) which I would be able to call in all controllers.

Defining a global variable for this use case is bad practice, and should be avoided.

Instead, you should create a custom service which injects the `request_stack` service, and provides a method to get your host variable based on that.

Then inject your custom service into each of your controllers, and make use of that method to get the variable.

---
Tags: hooks, 9, event-subscribers
---


# Question
Title: Drush won't run, 'status' shows web directory twice
I have a multi-site Drupal 8 install and Drush has stopped working. All Drush commands fail with a "Bootstrap failed" error.

"Drush status" shows the /web dir twice as the root. Manually adding the root (--root:path) results in the same 'Bootstrap Failed" error

Any idea why the web directory would show twice in the root?

```
SITE@mi3-sr25 [~/public_html/web]# drush status
 PHP binary    : /opt/alt/php73/usr/bin/php
 PHP config    : /opt/alt/php73/etc/php.ini
 PHP OS        : Linux
 Drush script  : /home/SITE/.composer/vendor/drush/drush/drush
 Drush version : 9.7.3
 Drush temp    : /tmp
 Drush configs : /home/SITE/.composer/vendor/drush/drush/drush.yml
 Drupal root   : /home/SITE/public_html/web/web

```

I've tried Drush 9 and 10. Checked for any duplicate directories, temporarily removed .htaccess No change.

# Answer
> 0 votes
The problem was that there were copies of the composer.json and composer.lock files in the /web directory. I removed those and now everything is working.

# Answer
> 0 votes
For me this was happening because I was calling an 'external' drush on the system. While at the same time, a 'local' drush was inside the vendor/ folder via composer requirements.

Same effect: webroot shows twice. Some drush commands running twice.

I simply moved on and started calling the drush inside vendor/, using a symlink for convenience.

---
Tags: drush
---


# Question
Title: Authentication provider for specific REST resource only
I would like to use my own auth provider for my REST services. While there's no fundamental problem with creating it, adding to my `services.yml` and referencing it in the `.yml` of the resource, it is called for each route, not just my resources, as logging reveals. Yes, I can inject a `RouteMatchInterface` into my auth provider and use the `applies()` function to check whether the provider should be consulted on a specific route but why is this required?

Can't I limit my provider to only the resource I plan to use it with? Using `applies()` not only means extra overhead on each call, it makes it awkward to maintain, needing to modify usage in both places, the config files *and* the auth provider source code.

# Answer
> 0 votes
I'm running into a related issue. In my case, using the `applies()` method in my custom provider makes sense.

What's bothering me is it's behaviour. When `applies()` returns `FALSE`, it goes directly to the **REST resource plugin** and (for example) will execute my **PATCH request**. After what it goes to the `authenticate()` method of the provider.

I don't understand this logic, as it seems to me that the authenticate should be validated before executing the **REST request**. So we don't process a request for nothing in case of failed authentication.

Any thoughts ?

---
Tags: 9, authentication-authorization
---


# Question
Title: Get path of uploaded file inside a Twig template
I've created a teaser template like this `node--type--teaser.html.twig`. Within that template I want to conditionally create a link to a file that was uploaded via the field `field_pdf`.

How do you extract JUST the path to the pdf in the template.

I've tried `{{ file_url(node.field_pdf.entity.url.value) }}` but that just brings back an empty path.

If thats not possible, is there a way to get a file path from the `fid` in twig?

# Answer
> 5 votes
1. Manage teaser Display : Change Format of your file field to `Generic File` From `admin/structure/types/manage/YouRContentType/display/teaser` .
2. In your twig `node--type--teaser.html.twig` just print `{{
file_url(node.field_pdf.entity.uri.value) }}` you will get the path to your file.
**Note** : As mentioned in comment it's `uri` Not `url`.

# Answer
> 1 votes
In my case I had a paragraph type with a file field. I wanted to get a url of file-field inside paragraph's template. Not sure why but above solution of @berramou did not work for me.

So what I did is, in manage display I changed the file field's format to "URL to file". Then I rendered the file field, stripped its tags, trimmed and passed it to file\_url like follows:

```
{% set url = file_url(content.field_pdf_file|render|striptags|trim) %}

```

# Answer
> 0 votes
In a field template file (for example, */themes/custom/y\_subtheme/templates/field/field--node--field-brochure--course.html.twig*), it will be `{{ file_url(item.content['#file'].getFileUri()) }}`.

---
Tags: 8, theming
---


# Question
Title: How do I migrate paragraph translations?
So I am trying to migrate paragraphs from Drupal 7 to Drupal 8. I have created 3 yaml for the same and execute them in below order:

* Paragraph YAML (migrate\_plus.migration.paragraph\_latest\_story.yml)
* Node YAML (migrate\_plus.migration.pp.yml)
* Node Translation YAML (migrate\_plus.migration.pp\_translation.yml)

Migrations for paragraphs works fine until I run *Node Translation YAML*. When I run translation for node it overrides existing paragraph values with the translated one. Below is my code:

**Latest Story Paragraph YAML:**

```
id: paragraph_latest_story
label: 'Paragraph Migration - Latest Story'
migration_group: custom
migration_tags:
  - Drupal 7
  - Paragraph
  - Field Collection
source:
  plugin: d7_paragraphs_item
  bundle: latest_story
  field_name: field_latest_story
  new_revisions: true
process:
  langcode: langcode
  # default_langcode: default_langcode
  # revision_translation_affected: revision_translation_affected
  # content_translation_source: content_translation_source
  field_card_title:
    plugin: sub_process
    source: field_card_title
    process:
      value: value
    revision_id: revision_id
  field_story_template_selector:
    plugin: sub_process
    source: field_story_template_selector
    process:
      value: value
    revision_id: revision_id
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: latest_story
migration_dependencies:
  required: {}
  optional: {}

```

**Node YAML**

```
id: ct_pp
label: 'Migration Content Type: PP'
audit: true
migration_group: custom
migration_tags:
  - Drupal 7
  - Content
  - Domain
  - Workbench
  - Base
deriver: Drupal\node\Plugin\migrate\D7NodeDeriver
source:
  plugin: d7_node
  node_type: ct_pp
  constants:
      field_collection_list:
        - 'field_latest_story'
process:
  nid: tnid
  type: type
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_banner_sub_title:
    -
      plugin: get
      source: field_banner_sub_title
  field_latest_story:
    -
      plugin: skip_on_empty
      method: process
      source: field_latest_story
    -
      plugin: migration_lookup
      migration: paragraph_latest_story
      no_stub: true
    -
      plugin: sub_process
      process:
        target_id: '0'
        target_revision_id: '1'
destination:
  plugin: entity:node
migration_dependencies:
  required: {}

```

**Node Translation YAML**

```
id: ct_pp_translation
label: 'Migration Content Type: PP - Translation'
audit: true
migration_group: custom
migration_tags:
  - Drupal 7
  - Content
  - Domain
  - Workbench
  - translation
  - Multilingual
class: Drupal\node\Plugin\migrate\D7NodeTranslation
deriver: Drupal\node\Plugin\migrate\D7NodeDeriver
source:
  plugin: d7_node
  node_type: ct_pp
  translations: true
  constants:
      field_collection_list:
        - 'field_latest_story'
process:
  content_translation_source: source_langcode
  nid:
    plugin: migration
    source: tnid
    migration: ct_pp
  type: type
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_banner_sub_title:
    -
      plugin: get
      source: field_banner_sub_title
  field_latest_story:
    -
      plugin: skip_on_empty
      method: process
      source: field_latest_story
    -
      plugin: migration_lookup
      migration: paragraph_latest_story
      no_stub: true
    -
      plugin: sub_process
      process:
        target_id: '0'
        target_revision_id: '1'
destination:
  plugin: entity:node
  translations: true
migration_dependencies:
  required: {}

```

# Answer
> 0 votes
Well, I don't know how it was in 2020. But it is possible with latest paragraph module and patches from https://www.drupal.org/project/paragraphs/issues/3160679. All steps I've just described in this issue. Note: I show example in a context of d7 -\> d9 migration.

But shortly.

The main problem is that paragraph translations imported with different ids. Paragraph translation record should have same id but different langcode. Let's look into **paragraphs\_item\_field\_data** table.

Good exampe:

```
id      revision_id
84448   86919   contact_fc  de  1   1682686892  157062  node    field_contact_fc    a:0:{}  0   1   en  0   1682686958
84448   86919   contact_fc  en  1   1682686892  157062  node    field_contact_fc    a:0:{}  1   1   und 0   1682686958

```

Bad exampe:

```
id      revision_id
84450   86923   contact_fc  de  1   1682686892  157062  node    field_contact_fc    a:0:{}  0   1   en  0   1682686958
84448   86919   contact_fc  en  1   1682686892  157062  node    field_contact_fc    a:0:{}  1   1   und 0   1682686958

```

You need:

* paragraph source tanslation config
* paragraph translations config
* node source translation config
* node translations config

Note: import them in right order.

Nowadays we use **paragraphs\_lookup** plugin in node migrations to find correct paragraph. Field mapping example:

```
  field_contact_fc:
    -
      plugin: sub_process
      source: field_contact_fc
      process:
        target_id:
          -
            plugin: paragraphs_lookup
            tags: 'Field Collection Content'
            source: value
            no_stub: true
          -
            plugin: extract
            index:
              - id
        target_revision_id:
          -
            plugin: paragraphs_lookup
            no_stub: true
            tags:
              - 'Field Collection Revisions Content'
              - 'Field Collection Content'
            tag_ids:
              'Field Collection Revisions Content':
                - revision_id
              'Field Collection Content':
                - value
          -
            plugin: extract
            index:
              - revision_id

```

---
Tags: 8, migrations
---


# Question
Title: Using Webform Submission, update a custom field attached to a user
*EDIT: After working more on this, the user cannot be blocked and must be active / authenticated.*

Using webforms, I have a form that has a field that a new user (blocked) needs to fill out to tell the admin what area they belong to. Is there a way that I can add the field value to the user (blocked, but currently filling out the form) account?

I have tried:

```
function helper_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if (in_array($form_id, ['webform_submission_request_account_node_123_add_form'])) {
    $form['actions']['submit']['#submit'][] = '_helper_additional_insert';
  }
}
function _helper_additional_insert($form, &$form_state)
{
  ksm($form);
}

```

However, I can never see the ksm output, even having the form show modal or message for example. I tried outputting the value to the log also with no love.

I thought of using RULES, but I do not see how I can capture the field value and then update the current user field with it...

Suggestions? Thoughts? Thanks!

# Answer
> 0 votes
Here is a working solution as long as the user is "active" and authenticated without any permissions that works for my usecase:

```
/**
 * Implements hook_form_alter().
 * This function is called whenever a form is altered.
 * Here, we are targeting the webform_submission_request_account_node_100_add_form form.
 */
function submission_helper_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['webform_submission_request_account_node_100_add_form'])) {
    // Add a custom submit handler to the form.
    // When the form is submitted, submission_helper_set_user_field() will be called.
    $form['actions']['submit']['#submit'][] = 'submission_helper_set_user_field';
  }
}

/**
 * Custom submission handler to set user field.
 * This function is called when the webform_submission_request_account_node_100_add_form is submitted.
 */
function submission_helper_set_user_field(&$form, &$form_state) {
  // Load the current user object.
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

  // Get the value of the field_name field from the form.
  $selected_field_tid = $form_state->getValue('field_name');

  // Set the value of the field_user_field_machine_name field on the user object.
  $user->set('field_user_field_machine_name', $selected_field_tid);

  // Save the user object to the database.
  $user->save();

  // Load the taxonomy term object for the selected field.
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($selected_field_tid);

  // If the taxonomy term object exists, log the term name to the Drupal logger.
  if ($term) {
    $term_name = $term->getName();
    \Drupal::logger('submission_helper')->notice('User account requested and user field set to: @field.', ['@field' => $term_name]);
  }
}

```

---
Tags: users, webforms, 9
---


# Question
Title: User form twig overwrite breaks after the submission doesn't have the current password
I am overwriting the user edit form using this code.

```
function demetra_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['field_first_name']['widget'][0]['value']['#title'] = t('');
    $form['field_first_name']['widget'][0]['value']['#placeholder'] = t('Enter your name...');
  }
}

```

This works fine except when the user doesn't enter his password. The reason for this is that the user\_form ID changes after the save to something like this `user-form--hWMonV_OXao`, therefore any overwriting is not working.

How do I handle this?

# Answer
> 1 votes
check if the beginning of the $form\_id string matches the string user\_form

```
function demetra_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (strpos($form_id, 'user_form') === 0) {
    $form['field_first_name']['widget'][0]['value']['#title'] = t('');
    $form['field_first_name']['widget'][0]['value']['#placeholder'] = t('Enter your name...');
  }
}

```

# Answer
> 0 votes
A form ID does not change when the form is submitted. It does not contains hyphens too; therefore, *user-form--hWMonV\_OXao* is not a form ID.

The Contact module alters the user profile form using the following code. (See `contact_form_user_form_alter()`.) It works whenever users enter their current password or not.

```
function contact_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $form['contact'] = [
    '#type' => 'details',
    '#title' => t('Contact settings'),
    '#open' => TRUE,
    '#weight' => 5,
  ];
  $account = $form_state->getFormObject()->getEntity();
  if (!\Drupal::currentUser()->isAnonymous() && $account->id()) {
    $account_data = \Drupal::service('user.data')->get('contact', $account->id(), 'enabled');
  }
  $form['contact']['contact'] = [
    '#type' => 'checkbox',
    '#title' => t('Personal contact form'),
    '#default_value' => $account_data ?? \Drupal::config('contact.settings')
      ->get('user_default_enabled'),
    '#description' => t('Allow other users to contact you via a personal contact form which keeps your email address hidden. Note that some privileged users such as site administrators are still able to contact you even if you choose to disable this feature.'),
  ];
  $form['actions']['submit']['#submit'][] = 'contact_user_profile_form_submit';
}

```

As a side note, the current password is only required when users change their own email or the password. The description for the *Current password* field says that.

> Required if you want to change the *Email address* or *Password* below.

The following hook implementation is sufficient.

```
function demetra_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_first_name']['widget'][0]['value']['#title'] = '';
  $form['field_first_name']['widget'][0]['value']['#placeholder'] = t('Enter your name...');
}

```

As a further side note, an empty string is not translatable: It is still an empty string (`''`) in every language.

---
Tags: forms, 9
---


# Question
Title: Need to pass $variable from validateForm back to form even if validation fails
It is a multipage Ajax form and I need to alter elements in a page based on form validation . This means, even if validation fails and the form stays on the same page, I need to visually alter that form page. Setting a field error with `$form_state->setErrorByName` is not sufficient for me so I'm exploring other options that I can't seem to find :)

I've tried using `$form_state->set()` and `$form_state->setTemporary()` but it seems the values set this way are only set if the validations passes. If validation fails, I get NULLs back in buildForm.

I've also tried storing to Drupal session, which works, but not as expected since my form is an Ajax form and the session variable would only be available on a second submit and would persist one step further than needed.

And I'm out of options.

Any suggestions?

PS I'm on Drupal 10.

# Answer
You can set values in $form\_state, the problem is the timeline when buildForm() is executed.

For a multistep form the form is only rebuilt if it is error-free. So the solution would be to not set an error but rebuild a different version of the form including your custom error messages by setting:

```
$form_state->setRebuild();

```
> 1 votes

---
Tags: forms, 10
---


# Question
Title: Drupal 8 theme showing Uncaught TypeError: $(…).find(…).once is not a function in console
New to Drupal 8.

I've created a demo theme. The `.libraries.yml` file is below:

```
global-styling-and-scripts:
 version: VERSION
 css:
  base:
   assets/css/font-awesome.css: {}
   assets/css/bootstrap.css: {}
   assets/css/slick.css: {}
   assets/css/bootstrap-datepicker.css: {}
   assets/css/jquery.fancybox.css: {}
   assets/css/theme-color/default-theme.css: {}
   assets/css/style.css: {}
  theme:
   '//fonts.googleapis.com/css?family=Tangerine': { type: external, minified: true }
   '//fonts.googleapis.com/css?family=Open+Sans': { type: external, minified: true }
   '//fonts.googleapis.com/css?family=Prata': { type: external, minified: true }
 js:
  assets/js/jquery.min.js: {}
  assets/js/bootstrap.js: {}
  assets/js/slick.js: {}
  assets/js/waypoints.js: {}
  assets/js/jquery.counterup.js: {}
  assets/js/bootstrap-datepicker.js: {}
  assets/js/jquery.mixitup.js: {}
  assets/js/jquery.fancybox.pack.js: {}
  assets/js/custom.js: {}
  dependencies:
   - core/drupalSettings
   - core/jquery
   - core/jquery.once

```

If I deleted all the `.js` from this file, I see no errors in the console however, the images, and slideshows etc are not properly rendering.

# Answer
Perhaps your bootstrap requires an older version of jquery, see if you can override it with a version lower than 3 following the instructions from

How do I use a jQuery version different from the default one used by core?
> 3 votes

# Answer
You're loading 2 versions of jquery: assets/js/jquery.min.js: {} \- core/jquery

That's most likely your issue. Try removing the assets/js/jquery.min.js entry and flushing your cache. That will mean you're just using Drupal's core jquery which hopefully your plugin should work fine with
> 3 votes

# Answer
This shouldn't be an issue in newer versions of Drupal but just in case anyone stumbles upon this like me: After @GiorgosK's answer I changed my

```
  once('drop-render', '.form-item-field-myfield-value-min', context).each(function () {
  });

```

to

```
  $(once('drop-render', '.form-item-field-myfield-value-min', context)).each(function () {
  });

```

and it worked beautifully.
> 0 votes

---
Tags: theming
---


# Question
Title: How do I use a jQuery version different from the default one used by core?
I need to use a different jQuery version. Currently, Drupal is using jQuery 3.2.1, but I need a previous version.

In Drupal 7 you could easily change jQuery version with the *jQuery Update* module. How can I achieve the same with Drupal 8?

# Answer
Add your custom jQuery library in your mytheme.libraries.yml:

```
jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

```

Then override the core jQuery library in your mytheme.info.yml:

```
libraries-override:
  # Replace an entire library.
  core/jquery: mytheme/jquery-custom

```
> 19 votes

# Answer
Re from: Drupal 8 theme showing Uncaught TypeError: $(…).find(…).once is not a function in console \>

This shouldn't be an issue in newer versions of Drupal but just in case anyone stumbles upon this like me: After @GiorgosK's answer I changed my

```
  once('drop-render', '.form-item-field-myfield-value-min', context).each(function () {
  });

```

to

```
  $(once('drop-render', '.form-item-field-myfield-value-min', context)).each(function () {
  });

```

and it worked beautifully.
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Prevent last updated property from changing when updating node in code?
I have this code that updates a node in a queue worker:

```
      $changed = $entity->getChangedTime();
      // Don't update the changed time by
      $entity->setChangedTime($changed);
      $entity->set('my_field', "my_data");
      $entity->setNewRevision(FALSE);
      $entity->save();

```

Here is a screenshot of xdebug showing `changed` and `after_save` value with the relevant code:

But no matter what I do, the changed property keeps getting updated to the time of the update.

I tested the functionality in a different contenxt like:

```
  $node = Node::load($nid);
  $changed_time = new DrupalDateTime('2022-01-01 12:00:00');
  $timestamp = $changed_time->getTimestamp();
  $node->setChangedTime($timestamp);
  $node->save();

```

and this seem to work.

Why does my code in the queue worker fail to do the same thing? is it because it's updating a field value?

# Answer
> 0 votes
There's a module that could help with your request. It's a bit hackish but it works.

---
Tags: nodes, 9
---


# Question
Title: Is there a simpler way to sum selected options in Webform computed_twig
I want to sum up all values of selected radios (all `q_` keys checked values) in a Drupal Webform form. Now I am doing it like this `{% set answersTotal = (data.q_1 + data.q_2 + data.q_3 + data.q_4 + data.q_5 )|number_format %} {{ answersTotal }}` and it's working fine but I want a more efficient/simpler way to avoid having to type all the `data.q_#` as there are many `q_` in each group. I tried this (in a `computed_twig` element in Webform) with the reduce filter:

```
{% set questions = elements.qp1.ps1|filter((v,k) => k starts with 'q_') %} {# this is working fine #}
{{ questions | reduce((carry, v) => carry + v) }} {# this is triggering the error #}

```

The above is giving me an `Unsupported operand types` error.

I also tried this:

```
{{ questions.value | reduce((carry, v) => carry + v) }}

```

but it's giving me error:

```
The "reduce" filter only works with arrays or "Traversable", got "NULL" as first argument in "__string_template__33be2e0acc2d52a6558e04668185b54eb92d8ec87a21403496ffb5af73d8c9d1" at line 5.

```

The relevant line 5 in the twig template mentioned in the above error is:

```
echo $this->extensions['Drupal\Core\Template\TwigExtension']->escapeFilter($this->env, twig_array_reduce($this->env, $this->sandbox->ensureToStringAllowed(twig_get_attribute($this->env, $this->source, ($context["questions"] ?? null), "value", [], "any", false, false, true, 5), 5, $this->source), function ($__carry__, $__v__) use ($context, $macros) { $context["carry"] = $__carry__; $context["v"] = $__v__; return (($context["carry"] ?? null) + ($context["v"] ?? null)); }), "html", null, true);

```

I feel stuck and have no idea in what direction I should move and/or what materials for a newbie I should read to know what I am doing in a better and more organized/structured way.

Here is a minimal sample of my yaml code:

```
qp1:
  '#type': wizard_page
  '#title': 'Part I'
  '#open': true
  ps1:
    '#type': details
    '#title': title...
    '#required': true
    '#attributes':
      class:
        - qp1_1
    q_1:
      '#type': radios
      '#title': q1.....
      '#options':
        - 'option 1 with value 0'
        - 'option 2 with value 1'
        - 'option 3 with value 2'
        - 'option 4 with value 3'
      '#required': true
    q_2:
      '#type': radios
      '#title': q2....
      '#options':
        - 'option 1 with value 0'
        - 'option 2 with value 1'
        - 'option 3 with value 2'
        - 'option 4 with value 3'
      '#required': true
    q_3:
      '#type': radios
      '#title': q3.....
      '#options':
        - 'option 1 with value 0'
        - 'option 2 with value 1'
        - 'option 3 with value 2'
        - 'option 4 with value 3'
      '#required': true
    q_4:
      '#type': radios
      '#title': q4.......
      '#options':
        - 'option 1 with value 0'
        - 'option 2 with value 1'
        - 'option 3 with value 2'
        - 'option 4 with value 3'
      '#required': true
    q_5:
      '#type': radios
      '#title': q5........
      '#options':
        - 'option 1 with value 0'
        - 'option 2 with value 1'
        - 'option 3 with value 2'
        - 'option 4 with value 3'
      '#required': true

```

# Answer
> 1 votes
I finally found a great clean solution and I hope it can save someone the frustration and hours of search and trials and reading to no avail like I did. I simply used this in my `computed_twig` template. Using a `for` loop to iterate through the `data` array and sum up the values of only the keys that start with `q_`:

```
    {% set sum = 0 %}
     {% for key, value in data %}
      {% if key matches '/^q_\\d+$/' %}
       {% set sum = sum + value %}
      {% endif %}
     {% endfor %} {{ sum }}

```

This is working perfectly as expected for my case and saves me having to type too many `data.q#` as per the number of the tens of questions I have.

---
Tags: webforms
---


# Question
Title: How to run cron more often than every hour?
I'd like to run cron every 5 minutes, but the UI doesn't offer any increment of time smaller than an hour. I'm assuming the solution is as simple as

* creating a feature module for the setting, and changing the integer to `300` (60 seconds × 5), ***OR***
* cracking open the database and changing the value to `300`.

Are there any hidden 'gotchas' with either of those approaches (or any reason they'll fail)? Is there a better way?

# Answer
> 10 votes
You can get really fine-grained control over your cron runs with these modules:

* Elyisa cron
> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.
* Ultimate Cron

> The Ultimate Cron handling for Drupal. Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

(In no particular order) I've only used Elysia cron before, and only recently at that, but it works well.

Either module will let you use a standard cron rule to define it's frequency, which I think means you can get the granularity down as far as seconds if you need it.

I think the only gotcha is that the more often you run cron (if it has expensive tasks to perform), the more load there will be on your server. Testing and benchmarking are the only real way to solve that one :)

# Answer
> 5 votes
You can also just run a cron job from the server. If Cpanel is in use, it's simple to run cron.php on any schedule.

# Answer
> 0 votes
I have another option, if you are ok using the stock "automated cron" (aka poor man's cron) module that comes with drupal, which I'm assuming based on the question, you are.

You can set the interval for cron using settings.php.

In drupal 7

```
$conf['cron_safe_threshold'] = 300;

```

In drupal 8+

```
$config['automated_cron.settings']['interval'] = 300;

```

Obviously, do to the nature of the way the Drupal automated cron works, this wouldn't garentee the cron to be run every 5 minutes, but instead would be run on the next visit to any page that hit Drupal after 5 minutes have pasted since the last run. This is also true with the standard settings but at larger intervals obviously. This does mean if you do have edge caching like varnish in front or simply little traffic to the site, this may not be ideal.

Also, given the setting is set via settings.php, the drop down will no longer show the correct value and may be misleading to another developer or administrator.

---
Tags: 7, features, cron
---


# Question
Title: Add default_value to a name field in a .yml file
I am using the migrate source CSV module. I have a few records that do not have the *Contact* field set or its value is null; the migration fails for this reason. I tried using the default\_value plugin that ships with core, but I keep getting the following error.

> A colon cannot be used in an unquoted mapping value at line 42 (near `default_value: 'Full Name'`).

```
process:
  uid: EIN
  field_contractor_name: CONTACT
  name: CONTACT
  -
  plugin: default_value
  default_value: 'Full Name'

```

How do I get a default value added to that field when a value is not present in the record?

# Answer
> 0 votes
The correct YAML to use is the following one.

```
process:
  uid: EIN
  field_contractor_name:
    -
      plugin: get
      source: CONTACT
    -
      plugin: default_value
      default_value: 'Full Name'

```

---
Tags: 8, migrations
---


# Question
Title: Single product with multiple variation types: set-up for a product (book) that's available as hardcopy and as downloadable file
I'm searching for an approach for selling printed books as well as e-books in different file formats with Drupal Commerce:

1. Hardcopy (variation type 1)
2. PDF file (variation type 2)
3. ePUB file (variation type 2)

While variation type 1 works fine as a regular product variation, variation type 2 is working with commerce\_license and commerce\_file: Product option 1 (hardcopy) will be shipped and will NOT include a file or license, options 2 and 3 will NOT be shipped, but will include a downloadable file and a license.

It would be great if I could use different variation types for the same product, then they can be used as different options for the same product, instead of splitting the different options into two different products (when they are the same product for 95% of the fields – same title, description, images, etc.).

To my knowledge, a single product with multiple variation types isn't possible with Drupal Commerce. This shortcoming is discussed in https://www.drupal.org/comment/reply/3089040, but unfortunately that thread is not easily understandable for me, deals with backward-compatibility and dates back to 2019.

**So what's a good approach for selling printed and digital versions of books with Drupal Commerce in 2023 when starting with a clean Drupal 10?** No need for backward compatibility, instead, the approach should focus on future-proofness and should be as little hacky as possible.

# Answer
> It would be great if I could use different variation types for the same product, then they can be used as different options for the same product, instead of splitting the different options into two different products (when they are the same product for 95% of the fields – same title, description, images, etc.).

Speaking as someone who has built a Commerce store that sells ebooks and print books, there are many cases in which you may want to treat physical and digital products separately.

For example, you may want to charge shipping for the print copy, but you would not charge shipping for a digital copy.

I would create two different products, physical and digital.

And if you want to offer them together at a discount, you could create a third product that contains both.

If you have a lot of information that you want to share between them-- for example, the book title, description, and so on are the same-- then create a custom content type (for "Books I sell") and input all the information there, and then add an entity reference to that content type on the product.

The trick with Drupal Commerce is to figure out what things should be shared and what things should be different, and then create new entities/bundles (content types, product types, etc.) until you have a sensible setup.
> 1 votes

---
Tags: commerce
---