# Question
Title: Take over display of a content type node route
I have a *discussion* content type. I would like the primary viewing experience (at "discussion/discussion-name") to be a cacheable form using a form mode.

Basically, I'm trying to create something like a web app experience where anyone who can view it, can edit it, so there is no point to separating view and edit, a more integrated experience is desired.

It feels like it should be easy, but I haven't found anything about how to override the routing for just one content type.

How can I override the route for a content type?

# Answer
> 9 votes
You'll need to alter the `entity.node.canonical` route to do this. You can do this via a `RouteSubscriber::alterRoutes()` in a custom module to have the route driven by your custom logic. In src/Routing/RouteSubscriber.php:

```
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

```

Then build the logic in your custom controller to redirect based on your node type, in src/Controller/NodeRedirectController.php:

```
namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Redirect to the edit path on the discussion type
    if ($node->bundle() === 'discussion') {
      return new RedirectResponse('/node/' . $node->id() . '/edit');
    }
    // Otherwise, fall back to the parent route controller.
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

```

Lastly, register your routeSubscriber service in mymodules.services.yml:

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

Documentation is on drupal.org: Altering existing routes and adding new routes based on dynamic ones.

# Answer
> 1 votes
Here is the other answer that was here but for some reason was deleted today.

The answer provided by Shawn works great, but if you would prefer to have separate controllers per content type eg. PageController, ArticleController etc. This is achievable by the Kernel Subscriber.

```
services:
  app.node_view_subscriber:
    class: Drupal\app\EventSubscriber\NodeViewSubscriber
    arguments: ['@controller_resolver']
    tags:
      - { name: event_subscriber }

```

The subscriber listens for the KernelEvents::CONTROLLER event, whereupon you can query the Request and check which node type you have - keeping this logic off the controller.

```
<?php

namespace Drupal\app\EventSubscriber;

use Drupal\node\NodeInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class NodeViewSubscriber implements EventSubscriberInterface {

  /**
   * The controller resolver.
   *
   * @var \Symfony\Component\HttpKernel\Controller\ControllerResolverInterface
   */
  protected $controllerResolver;

  /**
   * Constructs a new PathSubscriber instance.
   */
  public function __construct(ControllerResolverInterface $controllerResolver) {
    $this->controllerResolver = $controllerResolver;
  }

  /**
   * Returns subscribed events.
   *
   * @return string[]
   *   Subscribed events.
   */
  public static function getSubscribedEvents(): array {
    return [
      KernelEvents::CONTROLLER => 'onController'
    ];
  }

  /**
   * Sets custom controller for a content type.
   *
   * @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event
   *   The event.
   */
  public function onController(ControllerEvent $event): void {
    $request = $event->getRequest();
    $attributes = $request->attributes;

    if ($attributes->has('_route') === FALSE) {
      return;
    }

    $route = $attributes->get('_route');

    if ($route === 'entity.node.canonical') {
      $node = $attributes->get('node');
      if ($node instanceof NodeInterface) {
        switch ($node->bundle()) {
          case 'article': // Node type
            $controller = $this->controllerResolver->getControllerFromDefinition('\Drupal\app\Controller\ArticlesController::collection');
            break;

          default:
            $controller = $this->controllerResolver->getControllerFromDefinition('\Drupal\node\Controller\NodeViewController::view');
            break;
        }
        $event->setController($controller);
      }
    }
  }

```

---
Tags: nodes, forms, 8, routes, page-controller
---


# Question
Title: How to pass variable value from html.html.twig to page-title.html.twig
Adding a dump '`dd()`' to parent **html.html.twig** template file when rendering a 'page type' page I get, among others, the following pair: `"node_type" => "page"` that I can render within this very template file. When rendering an 'article type' page I get "node\_type" =\> "article". So far so good.

Now I'd need to make use of that variable (node\_type) in child template **page-title.html.twig**. Same dump function retrieves some other variable-value pairs but not the node\_type one. I guess they're 'local variables' that are not available out of their own scope. However there may be **some way to pass it from parent template** but I couldn't find a straightforward simple solution to it. Any clue?

I'm using latest Drupal 9 stable release, so Twig 2 is in charge of theming.

T.I.A.

# Answer
> 0 votes
You can't pass variables between the two templates as such, but you can make `node_type` available in page-title.html.twig by copying the code from `node_preprocess_html`, which is responsible for getting it into html.html.twig in the first place:

```
function MODULEorTHEME_preprocess_page_title(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) || ($node = \Drupal::routeMatch()->getParameter('node_preview'))) {
    if ($node instanceof NodeInterface) {
      $variables['node_type'] = $node->getType();
    }
  }
}

```

---
Tags: theming
---


# Question
Title: Is there a way to clone a content type and its fields?
I have a content type named "event\_xyz" that I want to rename to "event". I figure I can clone the content type and then delete the original. But I don't see any tuts or modules on how to do this.

Alternatively, is there a way to rename a bundle's machine name?

I found a closed question related to cloning content types for Drupal 7, but not for Drupal 8.

# Answer
The best way to do this is the entity\_clone contrib module. I downloaded it, installed it, hit the clone button and all of fields and form settings were copied to the new content type. It worked very well.
> 5 votes

# Answer
Here's one solution to rename a content type using Kevin's suggestion.

1) search and replace in the codebase for "event\_xyz"

2) go to /config/sync directory (or where your configs are)

3) run command to search and replace in filenames

4) delete content type "event\_xyz"

5) run config import ("drush cim -y")

This worked and took less than ten minutes, although I didn't have to delete any content.
> 6 votes

# Answer
You can use Content Type Clone designed specifically for this task. It's available for Drupal 7 and Drupal 8: https://www.drupal.org/project/content\_type\_clone
> 0 votes

# Answer
now you can use in drupal 8 Entity Type Clone.

> Entity Type Clone allows Administrator to clone Content types, Paragraphs, and Vocabularies. These will be used in creating an additional entity type with the existing one. You can clone entity type along with the Form and View modes.
> 0 votes

# Answer
Best way to do this in my opinion is through the config import approach.

Here's a step by step guide:

1. Search for your content type's name in your config folder:

2. Copy all these config files to a new folder.
3. Open up your new folder in your favorite IDE and do a search/replace for your old/new content type names:

4. Delete the `uuid` line from every config file, since this `uuid` is already associated with a different, existing config record:

5. Back to your folder (from the OS view), update the config file names by replacing the old content type name with the new one:

6. Import config from this folder using the following command:

`drush cim --partial --source=/path/to/your/new/config/folder`

7. Voilà! You should now have your content type perfectly duplicated!
> 0 votes

# Answer
For D7, you can use Node Convert. Build a fresh content type, with fields new/same/similar then use field mapping (field matching) to move/migrate them. Maybe or maybe not with Views Bulk Operations.
> -1 votes

---
Tags: 8, configuration
---


# Question
Title: Exclude taxonomy terms from being choosen in facets
I am working on a search field with a facet which has a list of taxonomy terms.

Some taxonomy terms I want to exclude from being choosen, because it is not relevant for people to know about.

How can I exclude taxonomy terms in a facet so people can't choose them while searching?

# Answer
> 1 votes
I found it.

At this page: `/admin/config/search/facets/(facet name)/edit`, there's something called `Exclude specified items`.

That's the place where I can exclude taxonomy terms.

---
Tags: taxonomy-terms, search
---


# Question
Title: Why would loading nodes by UUID not work in a drush command?
I have a simple bit of test code to load nodes by UUID:

```
$uuids = ['5e331255-adf6-423e-a355-dc02c621ffcd'];
$nids = \Drupal::entityTypeManager()->getStorage('node')
  ->getQuery()
  ->condition('uuid', $uuids, 'IN')
  ->execute();

```

When I execute this code in `hook_page_attachments_alter()`, or anywhere else in a rendered page build, `$nids` is populated as expected with the correct node ID.

When I execute exactly the same code, verbatim, in a drush command, `$nids` is empty.

Loading the node by ID works fine in both contexts:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load(12345);

```

This happens with the same code/database in multiple environments (Lando, ACSF, standard LAMP), and I've confirmed that drush is connecting to the correct database everywhere.

Are there any obvious properties of the node or storage system, or configuration of drush, which could be responsible for this?

Content moderation, revisions, and translations are all enabled for the node's content type, in case it matters.

# Answer
> 3 votes
Disable the query access check

```
  ->accessCheck(FALSE)

```

or use this service

```
$node = \Drupal::service('entity.repository')->loadEntityByUuid('node', $uuid);

```

---
Tags: entities, drush
---


# Question
Title: Call to undefined function flag_get_flag() with Flag 4.x
I'm using the 8.x-4.0-beta3 release of the Flag module in a custom D9 module to flag a newly programmatically created node using a flag I created in the UI.

```
$flag = flag_get_flag('new_call');
$flag->flag('flag', $call_node->nid);
$call_node->save();

```

But this results in this error when it is called:

```
Error: Call to undefined function Drupal\zoom_call\flag_get_flag() in Drupal\zoom_call\ZoomApiWebhookEventSubscriber->clientcall() (line 75 of /var/www/html/modules/zoom_call/src/ZoomApiWebhookEventSubscriber.php)

```

Does someone know a solution to this? Is flag\_get\_flag() deprecated in D9 perhaps?

# Answer
You need to use the flag service:

```
$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service->flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service->unflag($flag, $entity);

```

Documentation for Flag 4.x is lacking but I made a list of the basics.
> 2 votes

---
Tags: nodes, flags
---


# Question
Title: How can I use Feeds to import flaggings with Flag 4.x?
I'm trying to set up the Feeds module to import flaggings with the Flag module on Drupal 9. However, I keep getting errors. What is the minimum necessary configuration to import flaggings?

# Answer
> 0 votes
1. Create a feed of flaggings.
2. Add a mapping for **UID** and set the reference to User ID (drupal numeric ID) or UUID.
3. Add a mapping for **Entity Type** and make sure your source data has an entity type set (*node*, *taxonomy\_term*, etc.)
4. Add a mapping for **Entity ID** and then use the numeric Drupal ID in your source data. You cannot use a UUID for this at present.

---
Tags: 9, feeds, flags
---


# Question
Title: How to render language select block in page template?
**Background information**: I used the following script to list all the twig blocks: *drush ev "print\_r(array\_keys(\Drupal::service('plugin.manager.block')-\>getDefinitions()))*" and when I tried the following twig : *{{ drupal\_entity('block', '') }}* and it is not rendering the twig block–

I developed a Twig page in Drupal 8 to allow my website visitors the ability to select the language they want. I downloaded all the multilingual contrib modules.

I am facing two issues:

1. How to render a block in the middle of my twig page to display the language drop-down menu? (I already have a block that displays a drop-down menu language from a contrib module).
2. The CSS background image I had setup is covering one of the Twig field I wanted to test. How can I tweak the CSS in order to display the twig block?

# Answer
Just place this in the your custom twig page where you want your language switcher links. We are using twig tweak module here. So intall this module before adding this line:

`{ # Language switcher # }`

```
{{ drupal_block('language_block:language_interface', wrapper=false) }}

```
> 2 votes

# Answer
`drupal_entity()` is for rendering entities. For rendering block plugins use `drupal_block()` instead. The difference is explained very well in the following guide. https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak
> 0 votes

---
Tags: theming
---


# Question
Title: Core Update 9.4.1->9.4.2 breaks drush command updatedb (throws PHP Fatal error: Cannot declare class Drupal\mysql\…)
I need help at this mysterious issue: Core upgrade 9.4.1 -\> 9.4.2 breaks drush command `updatedb` at some installations:

> Fatal error: Cannot declare class Drupal\mysql\Driver\Database\mysql\Install\Tasks, because the name is already in use in /path/to/site/web/core/modules/mysql/src/Driver/Database/mysql/Install/Tasks.php on line 14

Drush-Version: 10.6.2

The error occures

* not in 9.4.1, but in 9.4.2 and (also 9.4.3).
* only with drush (not with update.php)
* at 2 different installations (but not in 3 other installations)

It has something to do with the changes in location of mysql-driver in 9.4, but Version 9.4.1 makes no problems - this error is introduced with changes in 9.4.2. The error is triggered in update.inc, line 98  `$requirements = \Drupal::moduleHandler()->invokeAll('requirements', ['update']);` \- but only if called via drush.

What can I do to get rid of it? Any ideas welcome.

# Answer
I have found the solution after a long search. It is a weird Mac-specific issue with a case insensitive filesystem.

On my mac development machine the APFS-Filesystem is case-insensitive.

```
/Users/username/Sites/mydrupalapp

```

and

```
/Users/username/sites/mydrupalapp

```

is the same for the system and most of the apps, **but not for drush**.

If I `cd` to my app path with wrong case, drush will sometimes fail. If I `cd` to my app path with correct case, all is fine.

For every Mac-User looking for errors with drush and errors like

```
PHP Fatal error: Cannot declare class…

```

Try to switch to your directory with the correct case spelling. Or better: avoid case insensitive file systems when unix developing…
> 1 votes

---
Tags: drush, 9
---


# Question
Title: How can I use hook_update_N() to update a FieldConfigStorage?
This is the code I am attempting to use to update a content type with a new field. When I run `drush dbup` I get this error.

> PHP Fatal error: Using $this when not in object context in EntityStoageBase.php.

```
function some_config_update_8101() {
  if (!FieldConfig::load('image_byline')) {
    $config_path = drupal_get_path('module', 'some_config') . '/config/install/field.field.node.main_image.field_image_byline.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.field.node.main_image.field_image_byline')->setData($data)->save(TRUE);
    $message .= "FieldConfig installed for module some_config.\n";
  }
  else {
    $message .= "It didn't work!\n";
  }

  if (!FieldConfigStorage::load('image_byline')) {
    $config_path = drupal_get_path('module', 'some_config') . '/config/install/field.storage.node.field_image_byline.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.storage.node.field_image_byline')->setData($data)->save(TRUE);
    $message .= "FieldConfigStorage installed for module some_config.\n";
  }
  else {
    $message .= "That didn't work either!\n";
  }
}

```

How is my code affecting the context of `EntityStorageBase`, if I have not changed code in that file?

# Answer
Updating Entities and Fields in Drupal 8, in particular Updating field storage config items, shows the following example code.

```
if (!$field_storage_configs = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties(array('type' => 'taxonomy_term_reference'))) {
  return;
}

foreach ($field_storage_configs as $field_storage) {
  // Since the usual workflow for field storages do not allow changing the
  // field type, we have to work around it in this case.
  $new_field_storage = $field_storage->toArray();
  $new_field_storage['type'] = 'entity_reference';
  $new_field_storage['module'] = 'core';
  $new_field_storage['settings']['target_type'] = 'taxonomy_term';

  $vocabulary_name = $new_field_storage['settings']['allowed_values'][0]['vocabulary'];
  unset($new_field_storage['settings']['allowed_values']);

  $new_field_storage = FieldStorageConfig::create($new_field_storage);
  $new_field_storage->original = $new_field_storage;
  $new_field_storage->enforceIsNew(FALSE);

  $new_field_storage->save();
}

```

That example code updates an entity field to change its type; it doesn't add an entity field if that doesn't exist. Still, comparing that code with the code you are using, it's clear you are using the wrong class: It's `FieldStorageConfig`, which is a a configuration entity class, not `FieldConfigStorage`, which is a storage handler class.

Being a class that implements an entity, `FieldStorageConfig` has the `create()` static method and the `load()` static method.

The example code is still useful for your case, since it shows how to create a new entity field storage configuration entity. In your case, you will check first the field storage configuration entity doesn't already exist by calling `FieldStorageConfig::load()`.
> 1 votes

# Answer
FieldConfigStorage::load() isn't static, so you can't use it statically.

Get an instance of `FieldConfigStorage` instead, and use that

```
if ($storage->load('image_byline')) {
  // ...
}

```
> 0 votes

---
Tags: 8, entities, updating
---


# Question
Title: How to set default value for entity reference programmatically in a form?
I have a custom form that I created programmatically.

```
    $target_type = 'node';
    $selection_handler = 'default';

    $selection_settings = ['page'];
    $data = serialize($selection_settings) . $target_type . $selection_handler;
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key, $selection_settings);
    }

    $form['terms_default_node'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Terms of Business - default page'),
      '#autocomplete_route_name' => 'system.entity_autocomplete',
      '#autocomplete_route_parameters' => [
        'target_type' => $target_type,
        'selection_handler' => $selection_handler,
        'selection_settings_key' => $selection_settings_key,
      ],
      '#default_value' =>  \Drupal\node\Entity\Node::load(1)->value, // What do I put here?
    ];

```

I don't get how to make the default value of the field be "Terms of Business (1)".

Autocomplete works, saving works, but I don't know how to recall that saved value again and make it as `default_value` when I open this form again.

This field doesn't have any widgets, etc. And I can't find anything in Google

# Answer
This whole approach of entity autocomplete is not okay. Here is the correct way, and also it accepts Node Object as the default value well.

```
    $form['terms_default_node'] = [
      '#title' => $this->t('Terms of Business - default page'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#selection_handler' => 'default',
      '#selection_settings' => [
        'target_bundles' => ['article', 'page'],
      ],
      '#default_value' => $this->entityTypeManager->getStorage('node')->load($id), // Dependency injection.
    ];

```
> 0 votes

---
Tags: forms, 9
---


# Question
Title: How can we use \Drupal class inside Settings.php
How can we use `\Drupal` class inside the *settings.php* file to load configuration ojects, for example?

```
$slogan = \Drupal::config('system.site')->get('slogan');

```

# Answer
> 3 votes
There is no config available when settings.php is executed. This is in very early stages of the Drupal bootstrap process and neither the database connection nor the service container is initialized.

# Answer
> 0 votes
The *settings.php* file is loaded from `DrupalKernel::initializeSettings()`, which is called from `DrupalKernel::handle()` before `DrupalKernel::boot()`.
This means that when the code in *settings.php* is executed, the dependency injection container hasn't yet initialized, the services aren't yet available, and `\Drupal::config()` would throw an exception about `\Drupal::$container` not yet initialized.

The code in the *settings.php* file can use PHP functions or functions/methods already loaded from the autoloader. The latter aren't guaranteed to function properly.

The purpose of the *settings.php* file is (generally speaking) setting configuration values.
It could read some configuration values from its local variables, for example `$settings['hash_salt']` or `$settings['file_public_base_url']`, but code that would work in a module isn't guaranteed to work in the *settings.php* file.

---
Tags: 8
---


# Question
Title: How do you override the add or edit node for a particular content type
I want to format the editing or adding form for the article content type. i.e. `node/add/article` path and editing the same article.
I copied over the `node-edit-form.html.twig` template from `core/modules/node/template` and renamed it `node-edit-form--article.html.twig`.
I also tried `node--article-edit-form.html.twig` and some other flavors.
I can override the `node.html.twig` file by simply copying it to my themes template folder.
But since I couldn't get the edit file to work I also tried overriding the form alter function by adding this in my theme file.

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

function newsass_form_node_form_alter(&$form, FormStateInterface
$form_state) {
  $form['#theme'] = ['node_edit_form'];
}

```

This code is from here- How to override node add template for custom content type?

I added some text on top of the code, but I still can't get the article 'edit' or article 'add' page to display the text.

Drupal 8.6.1, and have debugging enabled. Full explanation of requirement: I have a user entity reference field in the article content type with a list of users that the article can be assigned to. For the most part they have an 'article' role. But if the person leaves, their role will be changed to 'Away'. The article can/will still be assigned to them but I need to indicate that they are no longer with the company or 'Away'. Within views entity reference I am able to re-write the user with the users role but this information doesn't get back to the entity reference field in the editing node. I thought of editing the article node and adding a hook to call the assigned users role..... Which I still need to figure out how to do. With debugging I tried suggested template `page--node--add--article.html.twig` but I still couldn't get the content revealed and yes I cleared cache. Using page level though doesn't allow granularity for each field.

QUESTION: By mytype is that the machine name of the entity reference field in the content type? I am also not quite understanding this function, where is the call to query the roles? I enabled kint and added this to the function.

```
kint($elements); die();

```

but get nothing returned. How do I check if this function is actually being called.
I tried something else also. I have users in the entity reference and in the entity reference views for users I added the roles, made them hidden and rewrote the users to include the roles. I works nicely in the views preview, but the roles detail doesn't get carried back to the content type add/edit pages.

# Answer
> 0 votes
Depending on where exactly you want to indicate that "away" status, I think you should rather alter the entity reference field widget for that specific field to add this "away" status rather than trying to achieve this via templates.

Sounds like you want to try implementing this hook:

```
function hook_field_widget_multivalue_WIDGET_TYPE_form_alter(array &$elements, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $elements['#attributes']['class'][] = 'myclass';
  }
}

```

# Answer
> 0 votes
This line in your code:

```
$form['#theme'] = ['node_edit_form'];

```

Means that it will take "node-edit-form.html.twig" from your theme's templates directory. So, you do not need to rename it. Just copy this file in your theme directory and edit it accordingly.

---
Tags: 8, theming, hooks
---


# Question
Title: Maintenance page being rendered as an entire page load after the main page load
I've noticed that I've got a maintenance page being rendered in its entire HTML markup format after my pages. The site is *not* in maintenance mode, and this is not intentional behaviour. I'm trying to debug, but even as a reasonably experienced Drupal developer I still don't understand all the mechanisms at work here. Guidance on that would be welcomed.

I had been using the module CDN, to experiment with integrating a CDN. That was using that area at the bottom of the page, but when I disabled it, and uninstalled it, it has not stopped the problem.

I then enabled Theme developer 7.x-1.x-dev just to help me see what was going on, and the maintenance page render has stopped appearing. I then disabled Theme developer again and it has returned. Does this help anyone to suggest something?

```
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">

<head>

[...]

</head>
<body class="maintenance-page in-maintenance no-sidebars">
  <div id="page">
    <div id="header">

```

This also displays on my admin theme. Does this mean it is not something to do with my custom theme? Is there anything in particular that I could look or has anyone seen this behaviour before?

# Answer
> 1 votes
I'm still waiting to see an answer to the question of what causes maintenance mode to be displaying messages. So I don't know specifically whether the recoverable fatal error (this issue) being thrown by the buggy 7.x-2.4 version of XML Sitemap module was what caused the avoidance of a general WSOD/ crash and yet a display of an odd maintenance mode message.

I had not noticed they'd released 7.x-2.5 and so I've updated that which has stopped the behaviour altogether. Happy days :)

# Answer
> 0 votes
Chiming in late here, but I came across this yesterday after having the same problem. In my case, there was a stray call to dpm() in hook\_preprocess\_field\_collection\_item(); The Devel module was disabled in production, so when the page hit the dpm() call, everything broke. I don't know why this caused the page to go into maintenance mode, but removing the Devel debugging function fixed the problem.

# Answer
> 0 votes
Did you ever find the reason? I am having the same problem right now and cant find why or how

https://stackoverflow.com/questions/73191467/drupal-7-response-with-two-sets-of-html-a-normal-followed-by-an-in-maintenance

---
Tags: 7, theming, debugging, maintenance-mode
---


# Question
Title: Media with WYSIWYG not converting media tags to markup
I just installed the Media module v 7.x-2.0-alpha3 along with WYSIWYG, CKEditor, and Image Resize Filter. (The site has many other modules active.) The site also uses Display Suite, and its view modes are used for different types of images. My use case is for images embedded in the Filtered HTML text format, not as separate entities in a content type.

When an image is first embedded, its source code is like this:

```
[[{"fid":"161","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"f asdfasdf"},"type":"media","attributes":{"alt":"alt text","class":"media-element file-default"}}]]

```

From my reading, I found that checking "Convert Media tags to markup" at mysite/admin/config/content/formats/filtered\_html is required. I have verified that is active.

Instructions at https://www.drupal.org/node/1599070 include *"Image resize filter" is AFTER "Convert Media tags to markup"* and my filters are in that order.

If I double-click an embedded image in the CKEditor and make it a captioned image, then the Media tags are converted to markup. If a caption isn't added, the Media tags do not get converted.

Based on my configuration, can anyone suggest why the conversion is not occurring?

# Answer
> 4 votes
I was having this same problem and have solved it. My problem was not rendering the text in the correct format in the template. So if you are using a custom theme, .tpl or whatever you need to make sure you render it correctly. I had it like this:

```
<?php print $node->field_main_body['und'][0]['value'] ;?>

```

Changing this to proper rendering using `field_view_field` fixed it for me:

```
<?php print render(field_view_field('node', $node, 'field_main_body', array('label'=>'hidden'))) ;?>

```

Hope that's helpful

# Answer
> 0 votes
Might be worth checking that your "Limit html tags" isnt limiting your img tags

# Answer
> 0 votes
If you updated Media, WYSIWYG and CTools module with latest stable version, then run update.php The embeded image source code will automatically convert to image.

---
Tags: 7, media, wysiwyg
---


# Question
Title: Making field value available in template page-title.html.twig
My page content type contains the field field\_subheading. How can I make this field available in the template page-title.html.twig? Below code doesn't work, probably because $variables\['node'\] isn't set. Also, I don't know, if it's correkt to retrieve the field value by `$variables['node']->field_subheading->value;`. Thanks!

```
/**
 * Implements hook_theme_preprocess_page_title().
 */
function mytheme_preprocess_page_title(&$variables) {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->bundle() == 'page') {
        if (isset($variables['node'])) {
            $variables['subheading'] = $variables['node']->field_subheading->value;
        }
    }
}

```

kk

# Answer
> 1 votes
Try this

```
function mytheme_preprocess_page_title(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if ($node && $node->bundle() == 'page') {
      $variables['subheading'] = $node->field_subheading->value;
  }
}

```

And in your twig file use {{ subheading }}

---
Tags: theming
---


title: Drupal Core errors and logging

text:
# Question
Title: Drupal Core errors and logging
Looking for a way to suppress PHP errors that come from the Drupal core itself. Obviously, if the issue isn't being fixed in the core code base, we generally assume it's okay to ignore it and that it will get fixed in the core before long.

For example, we occasionally see this error in the logs:

Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException: The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned null. Did you forget to add a return statement somewhere in your controller? in () (line 98 of /var/www/html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php).

Which comes from a core library and since we are not familiar with that particular bit of the core, we don't have plans to chase it down. Obviously, issues that originate from our own code is something we would want to see but it there a way to get the Drupal error log to ignore errors that we really can't do anything about?

Just trying to unclutter our logs a bit so we can focus on more important issues (or at least ones we have control over).

# Answer
> 1 votes
If you are referring to database logging, and are comfortable with custom code, decorate the `logger.dblog` service, wrapping the original service with your own implementation. Override the `log` method of `Drupal\dblog\Logger\DbLog`, in which you filter messages before passing them to the wrapped object's `log` method.

---
Tags: log-messages
---


# Question
Title: Class not found for service in custom module
I am trying to create an event subscriber service in a custom module and I keep getting a "Class not found" error. The module directory is modules/custom/avgc The class is in src/EventSubscriber.php This is my avgc.services.yml:

```
services:
  avgc.order_fulfillment_subscriber:
    class: Drupal\avgc\EventSubscriber\OrderFulfillmentSubscriber
    arguments: ['@language_manager', '@plugin.manager.mail']
    tags:
      - { name: event_subscriber }

```

and this is EventSubscriber.php up to the class declaration:

```
<?php

namespace Drupal\avgc\EventSubscriber;

use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sends an email when the order transitions to Fulfillment.
 */
class OrderFulfillmentSubscriber implements EventSubscriberInterface {
....

```

Everything is copypasted from https://docs.drupalcommerce.org/commerce2/developer-guide/orders/workflows/react-to-workflow-transitions All I did was change my\_module to avgc, and reading the answers to previous questions on this topic everything would seem to be in order, but it isn't.

What am I doing wrong?

# Answer
With `namespace Drupal\avgc\EventSubscriber` and a class name of `OrderFulfillmentSubscriber`, the class file should be in `/avgc/src/EventSubscriber/OrderFulfillmentSubscriber.php` to get discovered.
> 1 votes

---
Tags: commerce, event-subscribers, symfony-services
---


# Question
Title: Show the count of the total results when searching with a search api solr view
I am working on a view which uses Search API Solr.

When I search for an article, I want to see how many results Solr has found.

How can I do this in Drupal 9?

# Answer
> 0 votes
Showing result counts in Search API views are the same as for any Drupal View. See How does one add a Total(s) row to Views results? for multiple ways to do so.

---
Tags: search, 9
---


title: How to create a field with hook_update?

text:
# Question
Title: How to create a field with hook_update?
I want to create a field with hook\_update in my module. I have the following code that creates the configuration for a field\_link field:

```
$module_path = drupal_get_path('module', 'my_module');
$configs['field.field.paragraph.image.field_link'] = $module_path . '/config/install/field.field.paragraph.image.field_link.yml';
$configs['field.storage.paragraph.field_link'] = $module_path . '/config/install/field.storage.paragraph.field_link.yml';

foreach ($configs as $name => $config_path) {
  $data = Yaml::parse($config_path);
  $config = \Drupal::configFactory()->getEditable($name);
  $config->setData($data)->save(TRUE);
}

```

As far as configuration it seems to be working correctly. When I try to create a node it all displays as it should. But if you save, you get an error that the table doesn't exist. Perhaps I have to use the ConfigInstaller class. Anyone know how to have the table get created?

# Answer
Thanks @Berdir. I was able to create the field with FieldConfig & FieldStorageConfig classes.

```
$module_path = drupal_get_path('module', 'my_module');

$yml = Yaml::parse(file_get_contents($module_path . '/config/install/field.storage.paragraph.field_link.yml'));
if (!FieldStorageConfig::loadByName($yml['entity_type'], $yml['field_name'])) {
  FieldStorageConfig::create($yml)->save();
}
$yml = Yaml::parse(file_get_contents($module_path . '/config/install/field.field.paragraph.image.field_link.yml'));
if (!FieldConfig::loadByName($yml['entity_type'], $yml['bundle'], $yml['field_name'])) {
  FieldConfig::create($yml)->save();
}

```
> 3 votes

# Answer
Don't use the low-level config, that doesn't trigger the necessary API calls.

Use FieldConfig::create() and FieldStorageConfig::create()
> 1 votes

# Answer
Rather than use the `Yaml` class directly, it's better to use `FieldStorage`. Storage settings may need to be transformed, depending on the field type.

```
$config_path = drupal_get_path('module', 'my_module') . '/config/install';
$storage = new FileStorage($config_path);

// Note: .yml extension not needed.
$data = $source->read('field.storage.paragraph.field_link');

if (!FieldStorageConfig::loadByName($data['entity_type'], $data['field_name'])) {
  // Transform storage settings, if required.
  $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  $class = $field_type_manager->getPluginClass($data['type']);
  $data['settings'] = $class::storageSettingsFromConfigData($data['settings']);

  FieldStorageConfig::create($data)->save();
}

```
> 0 votes

# Answer
In my case I already had the configuration in my sync folder

```
  $config_storage = new FileStorage('../config/sync');
  foreach ([
    'field.storage.paragraph.field_button_style',
    'field.field.paragraph.quick_donate_widget.field_button_style',
  ] as $config_name) {
    $entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($config_name);
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $config_record = $config_storage->read($config_name);

    /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $storage */
    $entity = $storage->createFromStorageRecord($config_record);
    if ($storage->load($entity->id())) {
      continue;
    }
    $entity->save();

```
> 0 votes

---
Tags: 8, configuration, updating
---


# Question
Title: Twig conditional render if specific field in array of referenced entities contains text
In a template, I'm conditionally rendering a sidebar based on whether the *content.field\_body* custom field (a Paragraphs entity reference revisions field type) contains any items.

```
{% if content.field_body['#items'] %}
  <div class="jump-sidebar mb-5">
    <h3 class="text-sans">In this article:</h3>
    <ul class="list-unstyled">
      {% for item in content.field_body['#items'] %}
        {% if item.entity.field_subhead %}
          <li class="text-18">
            <a href="#{{ item.entity.field_subhead.value | clean_class | trim }}">{{ item.entity.field_subhead.value | raw }}</a>
          </li>
        {% endif %}
      {% endfor %}
    </ul>
  </div>
{% endif %}

```

This worked fine until the requirements changed. Now I need to render this entire sidebar `<div>` if and only if one of the `item.entity.field_subhead` fields in the `['#items']` array contains a value.

`{{ dump(content.field_body['#items']|keys) }}` returns the following:

```
^ array:2 [▼
  0 => 0
  1 => 1
]

```

So the `['#items']` are a regular numerically-indexed array.

Is it possible, in a template file, to write a conditional that returns `true` if any key of a multi-value field contains a specific field?

This is further complicated by the fact that there may be different Paragraph types referenced here, and only one of these (the "Section" paragraphs type) will contain `entity.field_subhead`, but there might be any number of Sections.

# Answer
I'd always do data checks on the entity object (in this case `node`), and not on the render array `content`. The second part is the magic `.entity` to get the linked referenced entity from the host's entity reference field:

```
{% set render_something = false %}
{% for field_item in node.field_entity_reference %}
  {% if not field_item.entity.field_to_check.isEmpty %}
    {% set render_something = true %}
  {% endif %}
{% endfor %}

{% if render_something %}
  <div class="my_wrapper">
    ...content...
  </div>
{% endif %}

```

Be warned though data behind `.entity` is usually not cache-safe (but it is cache-safe in this special case with Paragraphs, because their revisioning is directly tied to their host entity)
> 2 votes

# Answer
Thanks @Hudri!

For future reference, the code that worked in my case looked like this:

```
{# Test every Section for non-empty Subhead #}
{% set render_sidebar = false %}
{% for field_item in node.field_body %}
  {% if field_item.entity.field_subhead %}
    {% if not field_item.entity.field_subhead.isEmpty %}
      {% set render_sidebar = true %}
    {% endif %}
  {% endif %}
{% endfor %}
{# If any Section contains non-empty Subhead, render block #}
{% if render_sidebar %}
  <div class="jump-sidebar mb-5">
    {# a bunch of markup #}
  </div>
{% endif %}

```
> 0 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: How can I reference imported content types?
I have imported two content types. One is for a vendor list and the other is for a contact list. The vendor list was imported with a vendor id column. The contact list was also imported with a vendor id column that indicates which vendor a contact is related to. A vendor also has many contacts.

I have added an entity reference field to the vendor list referencing the contact list but I don't see a way to link the vendor id columns together.

I have also tried to use an entity reference view with a relationship and contextual filter.

The result I get is an empty contact list for each vendor.

I have read many articles and watched several videos but I haven't found one that pertains to my situation.

How do I get these two content types to reference each other via the vendor id? Do I need to go about it a different way? Is there something I am missing when setting up the entity reference?

# Answer
You only need to store the vendor ID retrieved from the remote API on the Vendor. Contacts would be linked by an entity reference field, not the remote vendor ID. The logic is as follows:

1. Create an entity for Vendor (Either a new content type, or a new entity type)
2. Create an entity type for Contact (Either a new content type, or a new entity type)
3. Add a field for `remote_vendor_id` to the Vendor entity. This will hold the value retrieved from the remote API
4. Add an entity reference field allowing for unlimited values, to the Vendor, referencing the Contact entity you created
5. Upon import, create the Vendor entity if it does not already exist, and set the value for `remote_vendor_id` to be the value retrieved from the remote API
6. For Contacts retrieved from the remote API, load the Vendor entity that has `remote_vendor_id` set to the vendor ID for the contact, Create a new Contact entity, and add that Contact entity as an entity reference using the field created on the Vendor entity in step 1 above.

This thread can likely help you with the coding for the above: https://www.drupal.org/project/entityreference/issues/1388924
> 0 votes

---
Tags: 7, nodes, importing-exporting
---


# Question
Title: Why does my custom views filter error with 'InvalidArgumentException: The configuration property...'
When I configure the view, it looks proper and works fine until I try to save it, at which point I get this error: `The website encountered an unexpected error. Please try again later.` Checking the drupal logs, the error recorded is

| \___ | \___ |
| --- | --- |
| Type | php |
| Date | Tuesday, August 2, 2022 - 12:19 |
| User | {hidden} |
| Location | {hidden} |
| Referrer | {hidden} |
| Message | InvalidArgumentException: The configuration property display.page\_2.display\_options.filters.newsletter\_edition\_public\_filter.value.edition doesn't exist. in Drupal\Core\Config\Schema\ArrayElement-\>get() (line 76 of /opt/drupal/web/core/lib/Drupal/Core/Config/Schema/ArrayElement.php). |
| Severity | Error |
| Hostname | 10.0.0.2 |
| Operations |  |

I think I have the views.schema.yml file wrong, but for the life of me cannot figure out what I am doing wrong with it. I even tried to uninstall and reinstall the module to force the file to load, but to no avail.

**msul\_newsletter\_helper/config/schema/msul\_newsletter\_helper.views.schema.yml**:

```
views.filter.newsletter_edition_public_filter:
  type: mapping
  label: 'MSUL Newsletter Edition'
  mapping:
    edition:
      type:  sequence
      label: 'Edition(s)'
      sequence:
        type: string
        label: 'Edition'

```

**msul\_newsletter\_helper/msul\_newsletter\_helper.module** (abreviated for brevity...showing only the functions that use `edition`:

```
class NewsletterEditionPublicFilter extends FilterPluginBase {

  /**
   * {@inheritdoc}
   */
   /* Admin summary makes it nice for editors. */
  public function adminSummary() {
    if (!empty($this->value['edition'])) {
      $returnVal = $this->t('(exposed default): ');
    }
    else {
      $returnVal = '';
    }
    if(is_array($this->value['edition'])){
      return $returnVal.implode(', ', array_map(function ($item) {
          return date('F j, Y',$item);
          }
          ,array_slice($this->value['edition'],0,2,TRUE))).
        (count($this->value['edition'])<=2)?'':', ...';
    }
    else{
      return $returnVal.date('F j, Y',(int)$this->value['edition']);
    }
  }

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

    $availableEditions = ['0001'=>'0001']
    //...

    $nextEdition = strtotime('first monday of this month + 2 days');

    $defaultValue = [(string)max(array_keys($availableEditions))];
    $form['value']['#tree'] = TRUE;
    $form['value']['edition'] = [
      '#type' => 'select',
      '#title' => 'Edition(s)',
      '#options' => $availableEditions,
      '#default_value' => $this->value['edition'] ?: $defaultValue,
      '#multiple' => TRUE,
    ];
  }

```

# Answer
> 0 votes
I'll leave the original question up in case it helps someone, it turns out that there was nothing wrong with the code, but the file path was messed up, I had congif instead of config in the path.

---
Tags: views, 9
---


title: Pass one exposed filter onto another?

text:
# Question
Title: Pass one exposed filter onto another?
I have about a dozen string fields that contain objects and their states (for example, let's take 'AC\_on' and 'heater\_off'). And I have a view that shows nodes containing those fields. The task I'm trying to achieve is this. A user should have two sets of options to filter the nodes by the aforementioned fields:

* To pick one of the objects via radio button (AC or heater);
* To pick the states in which the previously picked option should be in the filtered set of nodes (only "on", or only "off", or "on" an "off" - so obviously check boxes).

It's no big deal to create the desired filters cosmetically: we can use combined fields filter for the set of radio buttons (search through all object fields and if the user picks "AC", filter out all "AC\_null" values), and once again - for check boxes (for "On" include those values that contain "on" etc). The problem is, this approach doesn't work :) The second set doesn't care which object with"off" state it filters out.

So, I figured I could somehow pass whatever the user picked in the radio part (AC) into the values of the checkbox filter (so it wouldn't just search for "on", but for "AC\_on"). The problem is, for the life of me I can't find a module that would allow me to do that.

"Views Dependent filters" seems like just the tool for the job, but unfortunately, it's for D7, and I have D9. Is there any way to achieve this? Any help would be highly appreciated.

PS I can't code, apart from the simplest PHP one-liners and CSS, so no-code solution is preferable.

# Answer
> 1 votes
Thank you **misterdidi** for setting me on a right track. The article you've provided helped, but in order to find out the solution, I had to study a few dozens more, and eventually the solution came around.

So, for this task the only certain solution I found is this:

1. Read whatever is in "Radio filter".
2. Alter "checkbox filter", so it would contain the value from "radio filter" in every option.
3. Merge all "state fields" into one multi-value field, so we could...
4. Use contextual filters to read "checkbox filter" value from URL and look for it in our multi-value field.

## 1. Reading value from Radio filter

I achieved this with *views\_pre\_view* hook:

```
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  // Check if it's the right view and display mode
  if ($view->id() == 'MY_VIEW') {
    switch ($display_id) {
      case 'MY_DISPLAY':
        //Get whatever value is in Radio Filter and write it into global variable
        $filter_input = $view->getExposedInput();
        global $arg;
        $arg= $filter_input['RADIO_FILTER'];
    }
  }
}

```

*(Here and forward, everything IN CAPS is the names you have to replace with the ones you use)*

With this code, I read what's in the Radio Filter and put it into a global variable **$arg**.

## 2. Put value from Radio Filter into Checkbox Filter

For this part I used *form\_views\_exposed\_form\_alter* hook:

```
function MY_MODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {

  // Call the global variable with the value of Radio Filter
  global $arg;

  // Convert the raw value of the Radio Filter into something we can use for contextual filter
  if ($arg == '1') {
    $arg= 'AC';
  }
  elseif ($arg == '2') {
    $arg= 'HEATER';
  }
  elseif ($arg == 'All') {
    $arg= '';
  }

  $arg_on = ($arg . '_on');
  $arg_off = ($arg . '_off');

  // Check that it's the right form
  if ($form['#id'] == 'EXPOSED_FILTER_FORM_ID') {

    // We need different filter values, depending on whether value in Radio Filter is chosen, or if it's set to default ("All")
    if ($arg != '') {
    $form['CHECKBOX_FILTER']['#options'] = array(
      $arg_on => $arg_on,
      $arg_off => $arg_off,
      );
    }
    else {
      $form['CHECKBOX_FILTER']['#options'] = array(
      '_on' => '_on',
      '_off' => '_off', );
    }
    // If nothing is chosen, we should consider everything chosen.
    if ($form['CHECKBOX_FILTER']['#value'] == '') {
      $form['CHECKBOX_FILTER']['#value'] = [$arg_on, $arg_off];
    }
  }
}

```

This way I modify values in Checkbox Filter. Doing so makes them pretty much inoperable as exposed filters (I'm not sure why, but the moment the form is modified via hook - it doesn't filter anything anymore), but it provides URL parameters, which we will use for contextual filters.

## 3. Merging all parameter fields into one

This one is something I've expected to find a module for, but failed, so *hook\_entity\_presave* it is.

```
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  // Here we prepare variables for every field we will need to merge ...
  if ($entity->bundle() == 'MY_NODE_TYPE') {
    $par_ac = ($entity->field_AC_CHECK->value);
    $par_heater = ($entity->field_HEATER_CHECK->value);
    $par_all = ($par_ac . ',' . $par_heater);

    // ... and also check out if there's any "on" or "off" among them ...
    if (str_contains($par_all, 'on')) {
      $par_cont_on = '_on';
    }
    if (str_contains($par_all, 'off')) {
      $par_cont_off = '_off';
    }

    // ... to merge them all into one field, and provide the overall "on" and "off" values for the cases when Radio Filter is not filled
    $entity->field_par_comb = [$par_ac, $par_heater, $par_cont_on, $par_cont_off];
  }
}

```

I'm not particularly happy with the fact that the fields are hard-coded and not dynamically gathered, maybe later I'll think of a way of de-hardcoding these.

But for now, we have a multi-value field that contains a state for every parameter, and we can finally...

## 4. Use contextual filter

As we found out in p. 2, the exposed Checkbox Filter doesn't do anything when it's modified. But we can make it check the URL parameter of a Checkbox Filter. This way, if we have "checkbox\_filter=heater\_on", the contextual filter will look in our multi-value field from p. 3 for "heater\_on" value.

Since Checkbox Filter can contain several values, we should choose "OR" conjunction in a filter's settings.

Note that the Radio Filter should be "not required". It's because, when the view is loaded for the first time, default exposed filter values are NOT shown in URL parameters, for some reason. But, since the default Radio Filter value is "Any" (and we should hide it with CSS via **:first-child** selector), in our code there's a part that takes this case into account by replacing "All" Radio Filter value with ''. And, since we have special check and "\_on"/"\_off" values in our multi-value field, it will work fine:

* If the default "Any" value is chosen in Radio Filter, the code will not replace Checkbox Filter values.
* In view settings, default Checkbox Filter values are set to "\_on" and "\_off" and the filter is operable.
* When the user picks "AC", "Heater" or any other option in Radio Filter, it's being put into modified Checkbox Filter values and Contextual Filter kicks in.

### This was a hell of a case for the first Drupal module development experience, but it works flawlessly. The customer is happy, I am happy.

# Answer
> -2 votes
On the twig file

```
<script src="/themes/custom/customtheme/js/block-view.js"></script>

```

The js file

```
const cleanFields = (e) =>{
  document.querySelector('.form-item-field-type>.select-wrapper>select').value = 'All'
  document.querySelector('.form-item-field-1>.select-wrapper>select').value = 'All'
  document.querySelector('.form-item-field-2>.select-wrapper>select').value = 'All'

}
const filterFields = (e) =>{
const deleteOption = document.querySelector('.form-item-type>.select-wrapper>select');
if(deleteOption.options[0].value == 'All'){
  deleteOption.remove(0)
}
if(e.value == '1'){
  document.querySelector('.form-item-field-1').style.display = 'none'
  document.querySelector('.form-item-field-2').style.display = 'none'
  return
}

if(e.value == 2){
  document.querySelector('.form-item-field-1').style.display = 'none'
  document.querySelector('.form-item-field-2').style.display = 'flex'
  return
}
if(e.value == 3){
  document.querySelector('.form-item-field-1').style.display = 'flex'
  document.querySelector('.form-item-field-2').style.display = 'none'
  return
}
}
const newSelect = (elem) => {
filterFields(elem);

elem.addEventListener('input', e =>{
    cleanFields(e.target)
    filterFields(e.target);
})

};

newSelect(document.querySelector('.form-item-type>.select-wrapper>select'));

(function() {
var proxied = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
    //Here is where you can add any code to process the request.
    //If you want to pass the Ajax request object, pass the 'pointer' below
    var pointer = this
    var intervalId = window.setInterval(function(){
            if(pointer.readyState != 4){
                    return;
            }
            //console.log( pointer.responseText );

            //Here is where you can add any code to process the response.
            //If you want to pass the Ajax request object, pass the 'pointer' below
            clearInterval(intervalId);

            nuevoSelect(document.querySelector('.form-item-type>.select-wrapper>select'))

    }, 1);//I found a delay of 1 to be sufficient, modify it as you need.

    return proxied.apply(this, [].slice.call(arguments));
};
})();

```

---
Tags: views, 9
---


# Question
Title: How can I run a certain action when a taxonomy field value is removed or added?
I have a *user\_territories* field which can have multiple values. I need to run a certain action when this field value is changed from the user entity, not when other fields are changed.

How can I write a condition for that?

I need to perform an action when taxonomy field is deleted and another action when a taxonomy field is added. How can I achieve this?
Is `hook_user_presave()` the best hook to fulfill this?

# Answer
Yes, `hook_user_presave()` is the way to go.

Here's an example for a standard field. You'll need to tweak this a bit for a taxonomy entity reference.

```
function MYMODULE_user_presave(UserBundle $user): void {
  // If the user is new, then the value hasn't changed.
  if (!$user->isNew()) {
    $field_value_current = $user->get('my_field_name')->value;
    $field_value_previous = $user->original->get('my_field_name')->value;
    if ($field_value_current !== $field_value_previous) {
      // Do something
    }
  }
}

```
> 1 votes

---
Tags: 8, users, taxonomy-terms, hooks
---


# Question
Title: How to get field value from multiple items? Twig
```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

I need to get some values from fields in item (displayed in screenshot)

# Answer
> 0 votes
Example -

```
{{ item.content['#paragraph'].field_NAME.value }}

```

original source - https://www.drupal.org/forum/support/theme-development/2018-08-01/get-reference-entity-values-in-field-level-twig-template

---
Tags: paragraphs
---


title: Drush isn't connecting to my database

text:
# Question
Title: Drush isn't connecting to my database
I have a Drupal install on a CentOS development server. Running drush from outside my web directory returns as you'd expect (a list of Drush commands).

Running drush from inside my web directory returns nothing at all. Running with debug returns this:

```
Using the Drush script found at /home/***/vendor/drush/drush/drush using pcntl_exec
[preflight] Config paths: /home/***/vendor/drush/drush/drush.yml
[preflight] Alias paths: /home/***/drush/sites,/home/coventry/drush/sites
[preflight] Commandfile search paths: /home/***/vendor/drush/drush/src

```

When using Drush from outside my web directory with --root, I get this:

```
drush uli --root=~/***.com
We could not find an applicable site for that command.

```

My settings.php file exists in that above directory/sites/default, and the database connection info works. The site is accessible in the browser.

Any ideas on this botched Drush install?

# Answer
I had this error and for me I solved it by using a version of drush that is compatible with the version of Drupal that the site is using.

In my scenario I was getting that error when using drush 10 with a Drupal 7 site.

When I used Drush 8 with that same Drupal 7 site, I could then run usual drush commands, without getting that error.
> 2 votes

# Answer
In addition to above, make sure you are running the uli command from the docroot of your project, I had lando setup and I got same error because I was running the command outside the docroot.
> 1 votes

---
Tags: drush
---


# Question
Title: How do I create a configuration schema of type array?
I have a PHP array where an instance may look like this:

```
$mymodule_myarray = [
  'first' => 0,
];

```

I want to have it represented and initialised as part of the configuration for the custom module "mymodule":

I've after gettings some comments i now have the following in `mymodule.schema.yml`

```
mymodule.settings:
  type: config_object
  label: 'My schema'
  mapping:
    mymodule_mystring:
      type: string
      label: 'Some string'
    mymodule_myarray:
      type: sequence
      label: 'Some array'

```

And I now have the following in `mymodule.settings.yml`:

```
mymodule_mystring: 'some string'
mymodule_myarray:
  'first'
  0

```

This produced the following error:

> Schema errors for mymodule.settings with the following errors: mymodule.settings:mymodule\_nodetypes variable type is string but applied schema class is Drupal\Core\Config\Schema\Sequence

Creating a configuration for `mymodule_mystring` and initialising it works.

I guess I use the wrong syntax to create the schema for `mymodule_myarray`, but I unable to find documentation for how to do it right.

The only thing I can find (by looking at the documentation at Drupal.org is that 'array' is not a supported type.

Please: How do I create a configuration schema of type array?

EDIT:

I am not concerned about translations. If creating an array is *not* the right way to go about this, is there an alternative approach?

# Answer
This is an example for a structured array schema:

*/config/schema/mymodule.schema.yml*

```
mymodule.settings:
  type: config_object
  label: 'My schema'
  mapping:
    mymodule_mystring:
      type: string
      label: 'Some string'
    mymodule_myarray:
      type: sequence
      label: 'My array'
      sequence:
        type: mapping
        label: 'My array item'
        mapping:
          label:
            type: label
            label: 'Some string'
          value:
            type: integer
            label: 'Some integer'

```

The YAML syntax to set this array as default setting:

*/config/install/mymodule.settings.yml*

```
mymodule_myarray:
  -
    label: first
    value: 0
  -
    label: second
    value: 1

```

BTW using type label for the string is intentionally so that you can translate "first", "second" and so on in different languages.

---

Edit:

It's hard to tell what the OP wants. The example did contain a translatable string, so I adjusted the schema accordingly. As already mentioned in the first comment, if you are not interested in defining the array as schema, then serialize it and store it in a string schema value.

If you want a simple array, to store untranslatable IDs, see this example from the core book module:

*/config/schema/book.schema.yml*

```
book.settings:
  type: config_object
  label: 'Book settings'
  mapping:
    allowed_types:
      type: sequence
      label: 'Content types allowed in book outlines'
      sequence:
        type: string
        label: 'Content type'

```

*/config/install/book.settings.yml*

```
allowed_types:
  - book

```

This is probably the simplest example for storing an array in a configuration schema.
> 1 votes

# Answer
I've upvoted and accepted the answer by 4uk4, since it answers my question as it was *originally* asked.

And I also agree with the recently added notion: "It's hard to tell what the OP wants." In this case, I didn't realize at the time I asked the question, that translations are a big part of this, and that I should have said up front that I was not into that.

But I've struggled with this problem over the last few days, and have started to realize that creating an array type configuration is not always the right thing to do, because it carries too much baggage.

So, I've found an alternative solution, and I am going to post it below, in case somebody else is struggling with the same thing, and is looking for a *simple* solution. My solution:

1. Create the schema for the array by setting its type to `ignore`.
2. Do *not* use `.settings.yml` to set the initial (default) value. Instead, do it by PHP elsewhere (in my case in the `setUp()` function of a PHPUNit Kernel test class):

So I ended up with:

**mymodule.schema.yml:**

```
mymodule.settings:
  type: config_object
  label: 'My schema'
  mapping:
    mymodule_mystring:
      type: string
      label: 'Some string'
    mymodule_myarray:
      type: ignore
      label: 'Some array'

```

**mymodule.settings.yml:**

```
mymodule_mystring: 'some string'

```

And then use the following PHP to initialise:

```
$this->setMymoduleSettings([
  'mymodule_myarray' => [
    'first' => 0,
  ],
]);

```
> 0 votes

---
Tags: 9, configuration
---


title: Custom handler for custom message

text:
# Question
Title: Custom handler for custom message
I have a Webform (6.x) with style *Cards*, and *Ajax*.

I would like the users to be able to personalize the message shown as confirmation of the form, with paragraphs and the like.

With a regular webform we have implemented a custom handler with a redirect to a node. With the Cards/Ajax it would be interesting to show the content of that node (configured in the handler) as a confirmation message.

Any suggestion on how we could, from a custom handler, I guess that with the `confirmForm` function, "catch and replace" the confirmation message?

# Answer
> 1 votes
I have found the solution myself after debugging. Leaving it here for further reference: based on https://git.drupalcode.org/project/webform/-/blob/6.1.x/src/Plugin/WebformHandlerBase.php#L607

```
public function preprocessConfirmation(array &$variables) {}

```

Implementing this we can easily modify the message as a simple "markup" element in

```
$variables['message']

```

---
Tags: webforms
---


# Question
Title: User error: "attributes" is an invalid render array key when rendering image
I'm seeing the following error on my Drupal 8.4.3 site:

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

It happens when rendering a Paragraph that has a multi-value field in it, which uses the Responsive Image formatter.

The Twig template looks like this:

```
...
{% for item in items %}
  {% set original_image = item.content['#item'].getValue()['original_url'] %}
  <a href="#" target="_blank" rel="nofollow">
    {{ item }}
  </a>
{% endfor %}
....

```

The problem is on that middle line `{{ item }}`. It prints the error message once per item in the "items" array. According to the Twig debug output in the HTML source, the next inner Twig template should be `core/themes/stable/templates/field/responsive-image-formatter.html.twig`. For fun, I went into that template and deleted every line, leaving an empty file. And the error is still there. So it's happening somewhere between the outer template and the inner template.

When I put a step debugger on line 97, I see a variable $elements with the following structure:

```
[
'content' => ... render array stuff in here ...,
'attributes' => Drupal\Core\Template\Attribute[ storage => [] ],  // <-- what's this?
'#printed' => false,
'#cache' => ...,
'#attached' => []
]

```

It seems that the problem is that Drupal wants anything not starting with # to be a valid render array. Which the 'attributes' element isn't. But I can't figure out how that got in there. I don't think any of my custom code could generate something like "**'storage' =\> \[\]**". I've been poring over the stack trace for hours and I can't tell where it's coming from.

Anyone know of a contribibuted or core module that could generate this? I would love to file an issue in the Drupal issue queue, but I can't even figure out which module is causing this.

System specs:

* Drupal 8.4.3
* Paragraphs 8.x-1.2 (the field in question is inside a Paragraph entity)
* Multiversion 8.x-1.0-beta7 (in case that matters; it does change entity structure somewhat)
* Image Lazyloader 8.x-1.0-alpha2 (I've seen this in the stack trace a few times)
* PHP 7.0.26
* Ubuntu 16.04

# Answer
> 17 votes
Yes, it seems like you are not supposed to render `item` in a field template. Render `item.attributes` and `item.content` separately:

```
<div{{ item.attributes }}>{{ item.content }}</div>

```

Or the attributes in a `<span>` if the `<div>` doesn't work with your layout and you need the attributes:

```
<span{{ item.attributes }}>{{ item.content }}</span>

```

BTW `storage' => []` is part of the Attribute object any code can store attributes on its way until it reaches your template. So it's a good idea to print the attributes, even if they are now empty, because you don't know which extension you might want to install in the future and debugging will then be some fun until you'll find out that one of the field templates is not fully working.

# Answer
> 2 votes
In a view template, I had to do something similar:

```
{% for row in rows %}
{#  {{ row }} #}
  <div{{ row.attributes }}>{{ row.content }}</div>
{% endfor %}

```

---
Tags: 8, theming
---


# Question
Title: How do I build Breadcrumbs for a certain node?
In a node preprocess hook I am getting breadcrumbs for the currently viewed node by doing the following:

```
$vars['breadcrumb'] = Drupal::service('breadcrumb')
    ->build(Drupal::routeMatch())->toRenderable();

```

This works fine as it uses `Drupal::routeMatch()` to get the matched route for the current request.

But I also want to get the breadcrumb for each node in a listing of several nodes. In this case I cannot use `Drupal::routeMatch()` since I want to get the breadcrumb for each node in the listing, not the current page. The problem is I cannot find a way of getting a RouteMatchInterface object (needed by the BreadcrumbBuilder) from a node object. I can get the url containing route information via `$node->urlInfo()`but there seems to be no way of getting from there to a route match either.

How can this be done?

**Edit:**

I found a way to get the route match for a certain node. Not sure if it's the ideal way but it gets the job done:

```
$routeName = $node->urlInfo()->getRouteName();
$routeParameters = $node->urlInfo()->getRouteParameters();
$route = Drupal::service('router.route_provider')->getRouteByName($routeName);
$routeMatch = new RouteMatch($routeName, $route, $routeParameters);

```

However passing the `$routeMatch` into `PathBasedBredcrumbBuilder::create` does not generate bredcrumbs for that route!

On closer inspection it seems that the built-in `PathBasedBreadCrumbBuilder` class completely ignores the passed in `$routeMatch` parameter and instead builds the breadcrumbs using the path of the current page, fetched using the injected RequestContext object. I think I would need to swap out this service with my own implementation which uses the passed in parameters somehow. To be continued...

# Answer
I eventually solved it by creating my own subclass of the PathBasedBredcrumbBuilder from core. This class unlike core's version actually uses the passed in route\_match and returns breadcrumbs based on that which makes it possible to get breadcrumbs for a certain node (or any other given route).

I still need to calculate the route match from the current node to pass to the build method (as shown in the question). It feels a bit awkward since the route\_match is converted back into a url object in the build method but it works and it is the cleanest solution i've come up with so far.

Below is the subclass:

```
namespace Drupal\contextual_breadcrumbs;

use Drupal\system\PathBasedBreadcrumbBuilder;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

class ContextualPathBasedBreadcrumbBuilder extends PathBasedBreadcrumbBuilder {

    /**
    * {@inheritdoc}
    */
    public function build(RouteMatchInterface $route_match) {

      /// Set request context from passed in $route_match
      $url = Url::fromRouteMatch($route_match);
      if ($request = $this->getRequestForPath($url->toString(), [])) {
        $context = new RequestContext();
        $context->fromRequest($request);
        $this->context = $context;
      }

      // Build breadcrumbs using new context ($route_match is unused)
      return parent::build($route_match);
    }

}

```
> 2 votes

# Answer
It seems you could use the service\_collector to just add your custom ContextualPathBasedBreadcrumbBuilder.

For that just add in your modules services.yml:

```
  my_custom_module.breadcrumb:
    class: Drupal\ my_custom_module.breadcrumb\CustomBreadcrumbBuilder
    arguments: ['@router.request_context', '@access_manager', '@router', '@path_processor_manager', '@config.factory',  '@title_resolver', '@current_user', '@path.current', '@path.matcher']
    tags:
      - { name: breadcrumb_builder, priority: 1002 }

```
> 0 votes

# Answer
I'm not sure why but I had to amend the ContextualPathBasedBreadcrumbBuilder to following for it to work, it was complaining about missing node parameter before:

```
class ContextualPathBasedBreadcrumbBuilder extends PathBasedBreadcrumbBuilder {

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {

    $url = Url::fromRoute($route_match->getRouteName(), $route_match->getParameters()->all());

    if ($request = $this->getRequestForPath($url->toString(), [])) {
      $context = new RequestContext();
      $context->fromRequest($request);
      $this->context = $context;
    }

    // Build breadcrumbs using new context ($route_match is unused)
    return parent::build($route_match);
  }

}

```
> 0 votes

# Answer
For Drupal 9 you don't need to extend anything. Working code here:

```
$routeName = $entity->toUrl()->getRouteName();
$routeParameters = $entity->toUrl()->getRouteParameters();
$route = Drupal::service('router.route_provider')->getRouteByName($routeName);
$routeMatch = new Drupal\Core\Routing\RouteMatch($routeName, $route, $routeParameters, $routeParameters);
$build['search_breadcrumb'] = Drupal::service('breadcrumb')->build($routeMatch)->toRenderable();

```
> 0 votes

# Answer
**Build Breadcrumbs for a certain node in Drupal-9.**

*Code is running with Drupal-9:*

```
$entity = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

$routeName = $entity->toUrl()->getRouteName();
$routeParameters = $entity->toUrl()->getRouteParameters();
$route = \Drupal::service('router.route_provider')->getRouteByName($routeName);
$routeMatch = new \Drupal\Core\Routing\RouteMatch($routeName, $route, $routeParameters, $routeParameters);
$breadcrumb = \Drupal::service('breadcrumb')->build($routeMatch)->toRenderable();

dump($breadcrumb)

```

Output:

```
^ array:3 [▼
"#cache" => array:3 [▼
    "contexts" => array:3 [▼
      0 => "route"
      1 => "url.path"
      2 => "languages"
    ]
    "tags" => array:1 [▼
      0 => "config:easy_breadcrumb.settings"
    ]
    "max-age" => -1
  ]
  "#theme" => "breadcrumb"
  "#links" => array:1 [▼
    0 => Drupal\Core\Link {#4369 ▼
      #linkGenerator: null
      #text: "Home"
      #url: Drupal\Core\Url {#4752 ▼
        #urlGenerator: null
        #urlAssembler: null
        #accessManager: null
        #routeName: "<front>"
        #routeParameters: []
        #options: []
        #external: false
        #unrouted: false
        #uri: null
        #internalPath: null
        #_serviceIds: []
        #_entityStorages: []
      }
    }
  ]
]

```
> 0 votes

---
Tags: 8, routes, uri, breadcrumbs, symfony-services
---


# Question
Title: Always keep admin UI in English when translating content
How can I prevent the admin UI switching to a foreign language every time I translate a piece of content?

i.e. I'm editing a Menu item and I've clicked the *Translate* tab. I click 'Add' in the German row to add a translation.

However the link always begins /de, which means all the UI labels change as well - to get back to English I have to manually remove it from the address bar and (it seems) do so every single time.

Is there any way to turn this off?

I tried going to *Detection and Selection* (/admin/config/regional/language/detection) and checking 'Account Administation pages', or checking 'User' and promoting it to the top of the list, but this didn't seem to make any difference to the button URL or the form output.

# Answer
> 12 votes
This functionality is partially achievable since Drupal 8.6.4.

1. Navigate to Detection and selection (admin/config/regional/language/detection)
2. Adjust your settings accordingly. Be sure to activate "Account administration pages". Your content language detection methods are optional.

3. Edit your user profile and set your "Administration pages language" to English.

Now your Admin UI will stay in English no matter what the other language detection methods resolve to. That means while creating a translation, the interface will remain in English.

However, the unsupported part is keeping the Admin Toolbar in English when being redirected to the translated page on saving it. But when going back to the Admin UI it's in English again.

These issues are dealing with that: https://www.drupal.org/project/drupal/issues/2313309

And if you use the Admin Toolbar module: https://www.drupal.org/project/admin\_toolbar/issues/3004575

**UPDATE 2022 August**

For a truly single-language admin toolbar, this patch (or the latest version thereof) needs to be applied, in addition to following the above mentioned steps.

# Answer
> 7 votes
This can be done from within the user edit page. I took the following steps from this link: https://www.drupal.org/node/2623206 \[comment #8\]

1- Enabled the Language module, and set-up one additional language.

2- I configure the administration language separate to the content language by below setting:

```
/admin/config/regional/language/detection:
Account administration pages: enabled

```

3-Admin -\> Edit Profile -\> Edit(Tab)

# Answer
> 1 votes
For people unable to edit content in different languages after following the steps suggested on answers here, please take a look at this link: https://www.drupal.org/docs/multilingual-guide/setting-the-language-for-administration-pages#s-translate-content-with-admin-pages-in-user-language

I was having the same issue (after doing the updates in `/admin/config/regional/language/detection` I was only able to see and edit nodes in English, even though I was using `/fr` in the URL for French content), but after checking the options suggested at the link above, the problem was fixed. I'm now able to select a preferred language in my user profile and edit both English and French content on my website.

# Answer
> 0 votes
* Go to /admin/config/regional/language/detection and check "Customize Content language detection to differ from Interface text language detection settings" That way it will distinguish between interface language and content language.

---
Tags: 8, i18n-l10n
---


# Question
Title: JSON:API returns the body field as format, processed, and value: How to get only processed?
When using JSON:API, the body field of a node (article) is returned like this:

```
body: {
  format: "basic_html",
  processed: "<p>blah blah blah</p>",
  value: "blah blah blah"
}

```

However, I just want to return `body: "<p>blah blah blah</p>"` (the value of `processed`).

What hook or class method should I use to override this?

# Answer
> 2 votes
Actually, the JSON:API Extras module includes this feature.

1. Enable JSON:API Extras resource overrides for Articles at `/admin/config/services/jsonapi/resource_types`.
2. On the Article resource override, for the body field, click **Advanced**, then **Single Nested Property**, and enter **processed** as the value.

You can use this technique to drill down into any properties you need, not just the values of text fields.

Warning: Using a Field Enhancer on a field will break POST if you POST to the field alias. Workaround: POST to the actual field name, not the alias.

Many thanks to xaviemirmon in the #decoupled Slack for telling me about this.

---
Tags: 9
---


title: save draggableview weight

text:
# Question
Title: save draggableview weight
I have a question related to draggableview (DV) integrated in Drupal 9. How can I save DV weight field value in other content type field called "field\_priority" ?

I found this info but it's using form submit event to get the field value. not clear about how I can integrate this code into my custom module. save weight field value

DV custom view

Content Types custom field

# Answer
This is what I did to solve the requirement. Installed a module called Sortableview This one is similar to Draggableview module except it can save the position value ( After drag and drop the question ) into custom content type field.

Here are the steps:

* composer installed the Sortableview module
* create a new integer field called field\_priority (content type)
* added that field as a sorting criteria to the custom Drupal view
* added **Sortableviews: Drag and drop** handler as a field to the custom view
* change the format to the Sortable table
* finally added the **Save Sortableviews changes** handler to the footer of the custom view
> 1 votes

---
Tags: views, taxonomy-terms
---


title: Extract order item field data

text:
# Question
Title: Extract order item field data
On a Drupal 9/Commerce 2 installation, I have a Gift Card product through the commerce\_giftcard module. When a customer places a Gift Card order, I need to automatically send an email with the Gift Card code. I wrote a custom module to do that, but the problem is: how do I get the Gift Card code starting from the order? I managed to dig it out with a raw SQL query like so:

```
SELECT code
FROM commerce_giftcard g
JOIN commerce_giftcard_transaction t ON t.giftcard = g.id
JOIN commerce_order_item i ON t.reference_id = i.order_item_id
JOIN commerce_order o ON o.order_id = i.order_id
WHERE o.order_id = $id

```

This works but it's horrible, and when I need to add a custom field (like a message from the donor), it becomes even messier.

How can we drill down to the Gift Card data (or any other order item data) in a more Drupal-like way?

# Answer
In the end I decided that in this case an SQL query is probably the most efficient way after all. Drupal does have a Database API just for that, and I used the Static Queries method.

There is no possible caching involved because this is data to be used only once to send an email inside an event subscriber, so a single hit to the database seems to be the most straightforward and economical solution.
> 0 votes

---
Tags: commerce
---


title: Get the real filename of file entity

text:
# Question
Title: Get the real filename of file entity
I'd like to get the real filename of a file entity.

My code is like this

```
    $filenames = [];
    foreach ($entity->$field->referencedEntities() as $image) {
      // Filename.
      $media = Media::load($image->id());
      $fid = $media->field_media_image->target_id;
      $file = File::load($fid);
      $filenames[] = $file->getFilename();
    };

    return $filenames;
  }

```

But filename returns the label of the file entity like so. `my-image.jpg` and using `getFileUri()` returns `public://images/my-image_0.jpg` I think because the image has been replaced at some point.

What I would like is just `my-image_0.jpg` but I can't seem to find a function to do it.

Thanks

# Answer
The File class itself, in `File::preCreate()` uses the following code.

```
  // Automatically detect filename if not set.
  if (!isset($values['filename']) && isset($values['uri'])) {
    $values['filename'] = \Drupal::service('file_system')
      ->basename($values['uri']);
  }

```

In you case, the following code should be used.

```
$filenames[] = \Drupal::service('file_system')->basename($file->getFileUri());

```

In a context where dependency injection is available, the *file\_system* service should be injected.
> 2 votes

---
Tags: files, 9
---


title: How can I show a custom user edit form?

text:
# Question
Title: How can I show a custom user edit form?
I need to show only a few fields on the user edit form: username, email, and password.

I want to have a user edit form on a different page & URL and not the default form where users shall be able to edit the username, password, and email address of their own account

How do I show only these fields and theme the page?

# Answer
**For the Drupal user form changes:**

Try with `HOOK_form_form_id_alter()` in .module

```

    function MYMODULE_form_user_form_alter(&$form, $form_state, $form_id) {
      // Your code...
    }

```

or you can try `HOOK_form_alter()`

```
    function MYMODULE_form_alter(&$form, $form_state, $form_id) {
      if ($form_id == 'user_form') {
        // Your code...
      }
    }

```

e.g

```
function MODULENAME_form_user_form_alter(&$form, $form_state, $form_id) {

      if (!\Drupal::currentUser()->hasPermission('administer users')) {

        $form['field_organization_name']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
        $form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';

      }

}

```
> 0 votes

---
Tags: forms, 9
---


# Question
Title: How do I set default includes for custom JSON:API Resources?
The JSON:API Extras module includes the **JSON:API Extras Defaults** submodule, which enables you to set default includes for JSON:API. For example, to include an entity reference to the tags vocabulary for articles, I can go to `/admin/config/services/jsonapi/resource_types/node--article` and add "tag" to the **Default include list** under **Collection**.

Now, I want to include some referenced entities by default for a custom resource that I made with the JSON:API Resources module. How can I do that?

# Answer
> 0 votes
Set the `include` parameter of the query directly in the code for your custom resource:

```
  public function process(Request $request): ResourceResponse {
    // Set the default includes.
    $request->query->set('include',  'tags,mediaReference.file');

```

You can include multiple values separated by commas. Note that the above code overwrites the `include` parameter; if you want to allow users to also add their own includes, you can check for `$request->query->has('include')` first.

---
Tags: 9
---


title: Redirect after form submission

text:
# Question
Title: Redirect after form submission
I created a custom form in Drupal 8. I remember we can redirect to custom path in Drupal 7 with `$form_state['redirect'] = 'mycustompath';` in a submission handler.

How can I achieve the same in Drupal 8?

I know I should use `submitForm()`.

```
public function submitForm (array &$form, FormStateInterface $form_state) {
   // Redirect users.
}

```

# Answer
> 36 votes
In your "submitForm" method write below code

```
 $form_state->setRedirect('machine_name');
 return;

```

where `machine_name` is the machine name mentioned in the routing file.

I hope this helps .. :)

# Answer
> 10 votes
If you want to set at buildform you need to use some routing path like.

```
use Drupal\Core\Url;

$url = Url::fromRoute('route.path');
$form_state->setRedirectUrl($url);

```

# Answer
> 3 votes
Theres a lot of answers in here but none that correctly show how to redirect to a specific path.

Firstly, you want to set the redirect in your submit handler. You can add a new one to the form array in your form\_alter;

```
$form['#submit'][] = 'my_form_submit_handler';

```

Sometimes you may need to add the handler to the submit button as well;

```
$form['actions']['submit']['#submit'][]  = 'my_form_submit_handler';

```

Its important to append the item to the submit array so that you don't remove any handlers that already exist.

Then, in your submit handler;

```
function my_form_submit_handler(&$form, FormStateInterface $form_state) {
  $form_state->setRedirect(URL::fromUserInput('/whatever/path/you/want'));
}

```

And thats it. Theres no return as more submit handlers may come after this one.

And dont use any Response returns like RedirectResponse. Their correct usage is in Controllers when returning a response to a request.

# Answer
> 0 votes
```

use Drupal\Core\Url;

// url to redirect
$path = '/my-path';
// query string
$path_param = [
 'abc' => '123',
 'xyz' => '456'
];
// use below if you have to redirect on your known url
$url = Url::fromUserInput($path, ['query' => $path_param]);
$form_state->setRedirectUrl($url);

```

# Answer
> 0 votes
This took me a while to figure out, so I thought I'd share.

I wanted to redirect the user to /admin after a custom admin form submission. I could not find the admin route in Google searches.

I grepped all the routing ymls in core:

```
find -name \*.routing.yml -exec grep -l "path: '/admin'" {} \;

```

...and found it in ./modules/system/system.routing.yml

```
system.admin:
  path: '/admin'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Administration'
  requirements:
    _permission: 'access administration pages'

```

So my form redirect is:

```
$form_state->setRedirect('system.admin');

```

Needed a cache clear before it worked.

# Answer
> -1 votes
```
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\RedirectResponse;

$redirect_to_thankyou = new RedirectResponse(Url::fromUserInput('/thankyou')->toString());
$redirect_to_thankyou->send();

```

Works in Drupal 9 - 9.0.7, if you just want to direct to a URL on your site (haven't tested it on external URLs), rather than ponce about with routing.

Put it at the end of your `submitForm` function in your class that extends `FormBase`.

# Answer
> -2 votes
If you want to redirect user edit form to the home page or other page follow below code.

First, add-hook - hook\_form\_alter\`

```
function yourmodulename_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if ($form_id === 'your form id') {
    $form['actions']['submit']['#submit'][] = 'modulename_user_edit_form_submit';
  }
}

```

after adding hook add below function

```
function modulename_user_edit_form_submit($form,  FormStateInterface &$form_state) {
  global $base_url; //set base path
  $response = new Symfony\Component\HttpFoundation\RedirectResponse($base_url ."/xyz"); //set url
  $response->send();
  return;
}

```

I hope this help.

---
Tags: 8, forms, redirection
---


# Question
Title: User login doesn't work after server migration
We had a Drupal 7 site running on PHP 5.6. We have moved this site to another server running on PHP 7.4.

When I navigate to /user/login, type my username and password, and click on *Submit*, I'm redirected to /users/myusername, but it says *Access Denied* and it doesn't show the top bar to change configuration, content, etc. I had also checked the *sessions* table and it stores the new session with the user ID.

>

No session ID has been stored in cookies after I log in.

>

I had tried so many ways, but nothing helped me.

1. I checked that mod\_rewrite is enabled
2. I tried with and without *Base URL* setting in the *settings.php* file
3. I tried with and without `RewriteBase` setting in the *.htaccess* file
4. I tried with and without `cookie_domain` setting in the *settings.php* file

I am surprised that, when I tried to migrate another website to the same server with another sub-directory, the login worked fine.

They are Drupal 7 sites migrated to the same server but on different sub-directories.

Why doesn't the login work in one of the sites?

# Answer
After a lot of debug I found the issue in settings.php file

```
ini_set('session.cookie_secure', 1);

```

for HTTPS site the session cookie must be secure but as the current site is HTTP, so we need to turn off this feature by

```
ini_set('session.cookie_secure', 0);

```

Now, login is working fine.
> 1 votes

---
Tags: 7
---


title: Webform date field format

text:
# Question
Title: Webform date field format
How do I change the date format of a date field in WEBFORM?

I have enabled popup calendar for this field, and when I select a date from the calendar, the default format is in Y-m-d which I want to change it to d-m-Y.

I do not see any configuration available in date field edit page.

Under configuration -\> Date and time -\> Short date type has the format "d M Y", I have tried updating this to d-m-Y but with no lock!

Help! Screenshots attached:

# Answer
> 3 votes
I was able to find the webform-calendar.tpl.php file that you used Drupal 7 - Change webform date select to textfield with calendar popup.

Basically what it does is adds a text field and hides the drop down date field.

I figuredout that the date field output is controlled in **webform.js**

You'll need to change from

```
  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'yy-mm-dd',
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[0]).trigger('change');
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[2]).trigger('change');
    },
    beforeShow: function (input, inst) {
      // Get the select list values.
      var year = $webformDatepicker.find('select.year, input.year').val();
      var month = $webformDatepicker.find('select.month').val();
      var day = $webformDatepicker.find('select.day').val();

      // If empty, default to the current year/month/day in the popup.
      var today = new Date();
      year = year ? year : today.getFullYear();
      month = month ? month : today.getMonth() + 1;
      day = day ? day : today.getDate();

      // Make sure that the default year fits in the available options.
      year = (year < startYear || year > endYear) ? startYear : year;

      // jQuery UI Datepicker will read the input field and base its date
      // off of that, even though in our case the input field is a button.
      $(input).val(year + '-' + month + '-' + day);
    }
  });

```

to

```
  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'dd-mm-yy', // changed
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[2]).trigger('change'); // changed
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[0]).trigger('change'); // changed
    },
    beforeShow: function (input, inst) {
          // Get the select list values.
          var year = $webformDatepicker.find('select.year, input.year').val();
          var month = $webformDatepicker.find('select.month').val();
          var day = $webformDatepicker.find('select.day').val();

          // If empty, default to the current year/month/day in the popup.
          var today = new Date();
          year = year ? year : today.getFullYear();
          month = month ? month : today.getMonth() + 1;
          day = day ? day : today.getDate();

          // Make sure that the default year fits in the available options.
          year = (year < startYear || year > endYear) ? startYear : year;

          // jQuery UI Datepicker will read the input field and base its date
          // off of that, even though in our case the input field is a button.
          $(input).val(day + '-' + month + '-' + year); // changed
        }
      });

```

4 lines changed, I marked them with `// changed`

Save the new file in */sites/themes/YOURTHEME/js/webform.js*

You can use hook\_js\_alter to replace the JS file.

```
/*
 * Implements hook_js_alter
 */
function YOURTHEME_js_alter(&$javascript) {
  if (!empty($javascript['sites/all/modules/webform/js/webform.js'])) {
    $javascript['sites/all/modules/webform/js/webform.js']['data'] = drupal_get_path('theme', 'YOURTHEME') . '/js/webform.js';
  }
}

```

# Answer
> 0 votes
We can change using MYTHEME\_webform\_date ($variables) hook below reference url is there. You have to write this code in template.php

https://jamesdavidson.io/blog/how-reorder-date-format-webform-date-picker

# Answer
> 0 votes
If you want also update date via input, not only via datepicker. I extended code from above and added onChange function at the end:

```
$calendar.datepicker({
    dateFormat: 'dd.mm.yy', // changed
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('.');
      $webformDatepicker.find('select.year, input.year').val(+date[2]).trigger('change'); // changed
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[0]).trigger('change'); // changed
    },
    beforeShow: function (input, inst) {
          // Get the select list values.
          var year = $webformDatepicker.find('select.year, input.year').val();
          var month = $webformDatepicker.find('select.month').val();
          var day = $webformDatepicker.find('select.day').val();

          // If empty, default to the current year/month/day in the popup.
          var today = new Date();
          year = year ? year : today.getFullYear();
          month = month ? month : today.getMonth() + 1;
          day = day ? day : today.getDate();

          // Make sure that the default year fits in the available options.
          year = (year < startYear || year > endYear) ? startYear : year;

          // jQuery UI Datepicker will read the input field and base its date
          // off of that, even though in our case the input field is a button.
          $(input).val(day + '.' + month + '.' + year); // changed
    }
  }).on('change', function(ev) {  // new
    var date = $(ev.target).val().split('.'); // new
    $webformDatepicker.find('select.year, input.year').val(+date[2]).trigger('change'); // new
    $webformDatepicker.find('select.month').val(+date[1]).trigger('change'); // new
    $webformDatepicker.find('select.day').val(+date[0]).trigger('change'); // new
  });

```

---
Tags: 7, webforms, datetime
---