Direkt zum Inhalt

Devbits

Kleine Code-Schnipsel aus unserem Alltag mit Drupal, PHP und DevOps: Problem, Lösung, Code.

13.11.2026 | Michael Ebert

Replace deprecated .module file in Drupal 11.5 or newer

Starting with Drupal 11.5, the .module file extension is deprecated. It will be no longer autoladed in Drupal 13. This means all functions inside this file have to move to classes and services, otherwise they stop running.

Old Implementation

<?php

/**
 * @file
 * Legacy procedural hooks – deprecated since Drupal 11.5.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_login_form') {
    $form['#attributes']['class'][] = 'my-module-login';
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave() for node entities.
 */
function my_module_node_presave(NodeInterface $node) {
  $node->setTitle(trim($node->getTitle()));
}

New Implementation

<?php

declare(strict_types=1);

namespace Drupal\my_module\Hook;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Hook\Order\Order;
use Drupal\node\NodeInterface;

/**
 * Hook implementations for my_module.
 */
class MyModuleHooks {

  /**
   * Implements hook_form_alter().
   */
  #[Hook('form_alter', order: Order::Last)]
  public function formAlter(array &$form, FormStateInterface $form_state, string $form_id): void {
    if ($form_id === 'user_login_form') {
      $form['#attributes']['class'][] = 'my-module-login';
    }
  }

  /**
   * Implements hook_ENTITY_TYPE_presave() for node entities.
   */
  #[Hook('node_presave')]
  public function nodePresave(NodeInterface $node): void {
    $node->setTitle(trim($node->getTitle()));
  }

}
parameters:
  # All hooks are OOP now – tell core not to scan .module/.inc files.
  my_module.skip_procedural_hook_scan: true

Issue:

Starting with Drupal 11.5, the .module file extension is deprecated. It will be no longer autoladed in Drupal 13. This means all functions inside this file have to move to classes and services, otherwise they stop running. 

As long as Core supports procedual hooks, it scans every .module or .inc files for hooks, which costs performance even when a module has nothing procedual left.

Prerequisites:

  • drupal ≥ 11.5

Solution:

  1. Hook class: Any class in the Drupal\my_module\Hook namespace or its subdirectories is registered automatically as an autowired service, so no services.yml entry is needed. The #[Hook('...')] attribute defines which hook a method implements. One method can carry several #[Hook] attributes and an order parameter. To change hooks of other modules you can use #[RemoveHook] or #[ReorderHook].
  2. Skip the scan: Once no more regular procedual hooks are left in our services.yml, we set my_module.skip_procedural_hook_scan: true so that Core is skipping parsing our modules .module or .inc files. Procedual hooks that are not #[LegacyHook] would not be found anymore.
  3. Move remaining helper functions to services or methods on the hook class. If other projects call your public functions, keep them as deprecated wrappers that call the new service.

To help you upgrading your code for Drupal 13, there is a ddev script listed in the additional links section.

Additional Links:

11.11.2026 | Pascal Crott

Provide content translation language block limited to available translations

Language blocks always show all languages but you only want to show the ones which content translations exist for.

<?php

namespace Drupal\content_translation_language_block\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\language\Plugin\Block\LanguageBlock;
use Drupal\language\Plugin\Derivative\LanguageBlock as LanguageBlockDeriver;

/**
 * Provides a 'Content translation language switcher' block.
 */
#[Block(
  id: "content_translation_language_block",
  admin_label: new TranslatableMarkup("Language switcher"),
  category: new TranslatableMarkup("Content translation"),
  context_definitions: [
    "entity" => new ContextDefinition("entity",
      label: new TranslatableMarkup("Entity"),
      required: TRUE
    ),
  ],
  deriver: LanguageBlockDeriver::class
)]
class ContentTranslationLanguageBlock extends LanguageBlock implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = parent::build();
    if ($entity = $this->getContextValue('entity')) {
      foreach ($build['#links'] as $langcode => $link) {
        if (!$entity->hasTranslation($langcode)) {
          unset($build['#links'][$langcode]);
        }
      }
      if (count($build['#links']) < 2) {
        unset($build['#links']);
      }
    }


    return $build;
  }

}

Issue:

Language blocks always show all languages but you only want to show the ones which content translations exist for.

Prerequisites:

  • You need to be in the context of a translatable content entity.
  • We make use of the Entity Route Context module which needs to be installed.

Solution:

Extend the Core plugin using the provided copy-and-paste snippet.

The snippet checks whether the current entity has translations. If any are found, the language options are reduced to those for which a translation exists.

11.11.2026 | Marc Hitscherich

Git flow hotfix without release tag

By default, git flow hotfix finish creates a release tag. Small fixes, such as config changes or typos, don't always need a new version, but they still need to land in main and develop.

git flow hotfix start fix-short-description
# ... commit changes ...
git flow hotfix finish fix-short-description -n -p

Issue:

By default, git flow hotfix finish creates a release tag. Small fixes, such as config changes or typos, don't always need a new version, but they still need to land in main and develop.

Prerequisites:

git-flow (AVH Edition) is installed and the repository is initialized with git flow init. Ensure that your local main and develop branches are up to date.

Solution:

The -n (--notag) flag finishes the hotfix without creating a tag. The hotfix branch is merged into main and develop and then deleted. The -p (--push) flag then pushes main and develop to origin.

23.10.2026 | Michael Ebert

Translate tab missing on custom config form

You have created a custom Drupal configuration form but no Translate tab appears when you access it.

my_module.my_form_configuration_tab:
  route_name: my_module.my_form_configuration
  title: Configuration
  base_route: my_module.my_form_configuration

Issue:

You have created a custom Drupal configuration form but no Translate tab appears when you access it.

The config_translation module automatically derives the Translate tab from the configuration mapper. However, Drupal only renders the local task (tab) navigation when there are at least two tabs on the same level. Since the Translate tab is the only local task available, Drupal does not display the tab navigation, causing the Translate tab to remain hidden.

Prerequisites:

You have the config_translations module enabled.

Solution:

Drupal Core solves the issue for settings forms by providing a default tab. We apply the same approach in our module by adding a default local task, which allows Drupal to render the tab navigation and display the Translate tab.

23.10.2026 | Lothar Ferreira Neumann

How to fill empty form fields via a custom Drupal AJAX command

In many editor or form workflows fields need to be prefilled (for example based on a selected entity or computed data) without overwriting input the user may have already entered.

<?php

declare(strict_types=1);

namespace Drupal\my_module\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Ajax command: fill empty form elements with a predefined value.
 *
 * This command targets one or more form elements via a CSS selector and sets
 * their value only if the current value is empty (after trimming).
 *
 * The command also triggers `input` and `change` events so Drupal behaviors and
 * other listeners react as if the user entered the value manually.
 */
final class SetValueIfEmptyCommand implements CommandInterface {

  /**
   * The Ajax command name used by Drupal.AjaxCommands.
   */
  public const COMMAND = 'setValueIfEmpty';

  /**
   * Default selector used when none is provided.
   */
  public const DEFAULT_SELECTOR = '[data-my-fill-target]';

  /**
   * Creates a command instance.
   *
   * @param string $fillValue
   *   The value to set when the target element is empty.
   * @param string|null $targetSelector
   *   CSS selector for the target elements. If omitted, DEFAULT_SELECTOR is used.
   */
  public function __construct(
    protected string $fillValue,
    protected ?string $targetSelector = null,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function render(): array {
    return [
      'command' => self::COMMAND,
      'selector' => $this->targetSelector ?? self::DEFAULT_SELECTOR,
      'value' => $this->fillValue,
    ];
  }

}
/**
 * @file Field empty check.
 */
(function (Drupal) {
  'use strict';

  Drupal.AjaxCommands.prototype.setValueIfEmpty = function (ajax, response) {
    const targetSelector = response && response.selector ? response.selector : '';
    const fillValue = response && typeof response.value === 'string' ? response.value : '';

    if (!targetSelector) {
      return;
    }

    const elements = document.querySelectorAll(targetSelector);
    for (const element of elements) {
      let currentValue = '';

      if (typeof element.value === 'string') {
        currentValue = element.value.trim();
      }
      else if (element.isContentEditable) {
        currentValue = (element.textContent || '').trim();
      }

      if (currentValue !== '') {
        continue;
      }

      if (typeof element.value === 'string') {
        element.value = fillValue;
      }
      else if (element.isContentEditable) {
        element.textContent = fillValue;
      }
      else {
        continue;
      }

      element.dispatchEvent(new Event('input', { bubbles: true }));
      element.dispatchEvent(new Event('change', { bubbles: true }));
    }
  };

})(Drupal);
set_value_if_empty:
  js:
    js/set_value_if_empty.js: {}
  dependencies:
    - core/drupal
    - core/drupal.ajax
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\my_module\Ajax\SetValueIfEmptyCommand;

$response = new AjaxResponse();

// Example: fill a media name field if it's empty.
$fill_value = 'foo-bar';

// Selector for a specific element in this use-case.
$target_selector = '[data-drupal-selector$="my_field"]';

$response->addAttachments([
  'library' => [
    'my_module/set_value_if_empty',
  ],
]);

$response->addCommand(new SetValueIfEmptyCommand($fill_value, $target_selector));

return $response;

Issue

In many editor or form workflows fields need to be prefilled (for example based on a selected entity or computed data) without overwriting input the user may have already entered.

Built-in AJAX setters such as InvokeCommand('val') always assign values unconditionally. When an AJAX update happens after the user started typing, this can unintentionally replace user-provided content.

Prerequisites

This approach only works when executed within an AJAX callback returning an AjaxResponse.

Solution

Use a lightweight custom AJAX command that runs in the browser and checks the current value of the target element(s).
The command sets the provided value only if the field is empty (after trimming).

The server supplies the selector and value while the client performs the final emptiness check and applies the update conditionally, preventing accidental overwrites of user input.

14.10.2026 | Nikolas Kopp

Skip migrating row if the value is an empty array

The single_value plugin is necessary since the skip_on_empty plugin doesn't work with an empty array properly. See Issue: https://www.drupal.org/project/drupal/issues/3239410

  skip_on_empty_array:
  -
    plugin: single_value
    source: file_path
  -
    plugin: skip_on_empty
    method: row

Issue:

The single_value plugin is necessary since the skip_on_empty plugin doesn't work with an empty array properly. See Issue: https://www.drupal.org/project/drupal/issues/3239410 

Prerequisites:

The migrate_plus module needs to be enabled.

Solution:

The provided snippet skips the row if the value is an empty array.

14.10.2026 | Lothar Ferreira Neumann

Require a module that is incompatible with your Drupal Core version

Managing dependencies in a Drupal project where certain modules may not be compatible with the Core version you are using.

# Get lenient.
composer require mglaman/composer-drupal-lenient

# Add the module to the allow list. Use escapes for the quote signs. \" ... \"
composer config --merge --json extra.drupal-lenient.allowed-list '[\"drupal/module_with_incompatible_core_version\"]'

# You can check if the merge worked, either just take a look
# into the composer.json or use this command.
composer config --merge --json extra.drupal-lenient.allowed-list
"drupal-lenient": {
  "allowed-list": [
    "drupal/module_with_incompatible_core_version"
  ]
}

Issue:

Managing dependencies in a Drupal project where certain modules may not be compatible with the Core version you are using.

Prerequisites:

Your project needs to be Composer managed.

Solution:

The code uses the mglaman/composer-drupal-lenient package to allow specific Drupal modules that are incompatible with the core version to be installed without causing version conflicts.

Learn more in the Lenient install tutorial.

08.10.2026 | Michael Ebert

Filter user entity reference field options to active users only

In a Drupal entity reference field configured to reference user accounts, the select list currently includes all users, including blocked or deactivated accounts.

Option 1 (recommended): custom entity reference selection handler. Further options down below.

<?php

namespace Drupal\my_module\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\UserSelction;
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[EntityReferenceSelection(
  id: "default:active_user",
  label: new TranslatableMarkup("User selection (only active users)"),
  entity_types: ["user"],
  group: "default",
  weight: 1
)]
class ActiveUserSelection extends UserSelection {

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $query->condition('status', 1);

    return $query;
  }

}

After implementing that plugin, you need to activate it on the entity form display for the field you want it.

Issue:

In a Drupal entity reference field configured to reference user accounts, the select list currently includes all users, including blocked or deactivated accounts.

Expected behavior: only active users should be available for selection by default, or there should be a configurable option to exclude inactive accounts from the reference field results.

Solution:

See the three examples described above.

Option 1 (custom Selection handler, see above)

The best general-purpose solution. It uses the exact extension point Drupal designed for this problem, is scoped precisely to the fields where you assign it, is trivially unit/kernel-testable, and doesn't rely on fragile internals like query tags and metadata that can silently break across core updates.

Option 2: Query tag alter

Avoid this unless you have a very narrow, temporary need and full control over exactly which query is being altered. It's the least robust of the three and the easiest to get wrong (over-broad conditions affecting unrelated queries, or under-broad checks that silently stop working after a core update).

/**
 * Implements hook_entity_query_tag__TAG_alter().
 */
function my_module_entity_query_tag__entity_reference_alter(QueryInterface $query) {
  $handler = $query->getMetadata('entity_reference_selection_handler');

  if (!$handler) {
    return;
  }

  $configuration = $handler->getConfiguration();

  if (($configuration['target_type'] ?? NULL) !== 'user') {
    return;
  }

  // Filter for active users only.
  $query->condition('status', 1);
}

Option 3: entity reference view display

  1. Edit your Entity Reference field and select "Views: Filter by an entity reference view" as the reference method.
  2. Create or select a View that displays only the entities you want to show. Configure filters, sorting, and fields as needed.

The View's filters automatically control which options appear in the dropdown. No custom code required – it's all configured through the UI.

This can be chosen if (sitebuilders/editors need to have permissions to edit the view and maybe there is a config_ignore for that to prevent overrides during deployments):

  • Site builders/editors need to tweak the filtering criteria without a deployment (e.g., "also exclude role X" added later via UI), or
  • You need additional Views features (exposed filters, sorting by last login, relationships to other entities) in the same selection.

08.10.2026 | Pascal Crott

Get default langcode from entity

You want to find the source language of an entity programmatically (e.g. its default language).

// Assume $entity is your translatable entity object.
$default_language_entity = $entity->getUntranslated();
$default_language_code = $default_language_entity->language()->getId();

Issue:

You want to find the source language of an entity programmatically (e.g. its default language).

Solution:

Use the snippet provided. The entity will be loaded "untranslated", then its default language will be loaded.

05.10.2026 | Lothar Ferreira Neumann

Declaring the return parameter with NULLable type as an option.

Handling a situation where a function might return an error since it returns NULL.

/**
 * Retrieves the name of a role based on its ID.
 *
 * @param string $role_id
 *   The ID of the role to retrieve.
 *
 * @return string|null
 *   The name of the role if it exists, or NULL if the role is not found.
 */
public function getRoleName(string $role_id): ?string {
  // Example roles array.
  $roles = [
    'admin' => 'Administrator',
    'editor' => 'Content Editor',
    'viewer' => 'Viewer',
  ];

  // Use the null coalescing operator to return the role name or null.
  return $roles[$role_id] ?? NULL;
}

Issue:

Handling a situation where a function might return an error since it returns NULL.

Solution:

Utilizes the "?" in the definition of the return type.

PHP

05.10.2026 | Michael Ebert

Enable the admin theme for your custom route

You are registering a new route and would like it to be displayed using the administrative theme.

my_module.edit:
  options:
    # Enable the admin theme for this route.
    _admin_route: TRUE

Issue:

You are registering a new route and would like it to be displayed using the administrative theme.

Solution:

To enable the admin theme on your custom route, you can add it as option in your routing.yml file. But keep in mind that this will only work for users that have permission to use the admin theme!

See the Drupal documentation for further information.

05.10.2026 | Lothar Ferreira Neumann

Replace Tagify CDN-loaded contrib library with a local npm asset in Drupal

A contrib module (in this example, Tagify) declares its JavaScript library with type: external, loading it from a third-party CDN such as cdnjs.cloudflare.com. However, for privacy and digital sovereignity reasons we want to reduce the amount of data potentially being exchanged with an external…

composer require npm-asset/yaireo--tagify:4.35.4
/**
 * Implements hook_library_info_alter().
 *
 * The tagify module loads Tagify from cdnjs.cloudflare.com. Serve it from
 * npm-asset/yaireo--tagify in /libraries instead, so no request reaches a
 * third party and the widget keeps working behind restrictive firewalls.
 */
function my_module_library_info_alter(array &$libraries, string $extension): void {
  if ($extension !== 'tagify') {
    return;
  }

  // Assigning replaces the CDN entries. The npm package ships an unminified
  // UMD build and no *.min.css; Drupal aggregates them either way.
  $libraries['tagify']['js'] = [
    '/libraries/yaireo--tagify/dist/tagify.js' => ['minified' => FALSE],
  ];
  $libraries['tagify']['css']['component'] = [
    '/libraries/yaireo--tagify/dist/tagify.css' => ['minified' => FALSE],
  ];
  $libraries['tagify_polyfils']['js'] = [
    '/libraries/yaireo--tagify/dist/tagify.polyfills.min.js' => ['minified' => TRUE],
  ];

  unset($libraries['tagify']['remote'], $libraries['tagify_polyfils']['remote']);
}

Issue

A contrib module (in this example, Tagify) declares its JavaScript library with type: external, loading it from a third-party CDN such as cdnjs.cloudflare.com. However, for privacy and digital sovereignity reasons we want to reduce the amount of data potentially being exchanged with an external provider like Cloudflare.

Prerequisites

  • Composer with the npm-asset repository configured, or composer/installers plus oomphinc/composer-installers-extender for asset packages
  • An affected contrib module (in this example, the Tagify module)

Solution

How to find external libraries? Check out this DevBit!

composer require npm-asset/yaireo--tagify:4.35.4 pulls the library from npm via the npm-asset Composer repository, placing it under /libraries where Drupal's library system expects locally vendored assets.

hook_library_info_alter() is the key mechanism that rewires the library definition without patching the contrib module. Reassigning $libraries['tagify']['js'] and ['css']['component'] replaces the CDN-hosted files with paths into /libraries/yaireo--tagify/dist/. Crucially, unset($libraries['tagify']['remote'], ...) removes the remote key – without this, Drupal still treats the library metadata as pointing to an external library, even though the file paths were changed.

Further information

Use the CDN fetcher module to automatically save external libraries in your Drupal project. This reduces the amount of externally loaded assets.

05.10.2026 | Pascal Crott

How to add an element to an array at the first position in Twig

When using the merge function in Twig, the new element is appended to the array. However, we would like the new element to prepend the existing array.

{# The elements array we want to add a '0' to at the beginning. #}
{% set elements = ['1', '2', '3'] %}
{# Working: Merge elements to a new array and override the variable. The result will be ['0', '1', '2', '3']. #}
{% set elements = ['0']|merge(elements) %}
{# Not working: The result will be ['1', '2', '3', '0']. #}
{% set elements = elements|merge(['0']) %}

Issue:

When using the merge function in Twig, the new element is appended to the array. However, we would like the new element to prepend the existing array.

Solution:

Create a new array and append the original array to it.

10.09.2026 | Mathias Grab

Get "key" from entity type

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.

$entity_type_id = 'node';
$definition = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
$id_key = $definition->getKey('id');

Issue:

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.

Solution:

Load all base field definitions of the given entity type via entityTypeManager() and return the ID with the method getKey().

10.09.2026 | Lothar Ferreira Neumann

How to delete an ECA model that throws PluginNotFoundException for a missing event/action plugin

An ECA (Event-Condition-Action) model's config can end up referencing an event, condition, or action plugin ID that no longer exists on the current site, for example, after a submodule was uninstalled or after importing a config export from an environment with different ECA submodules enabled.…

// web/modules/contrib/eca/src/Entity/Eca.php (simplified excerpt)

protected function isValidationDisabled(): bool {
  return $this->request()->query->get('eca_validation', '') === 'off';
}

public function getPluginCollections(): array {
  if ($this->isValidationDisabled()) {
    return [];
  }
  // Otherwise every referenced event/condition/action plugin is
  // instantiated here, throwing PluginNotFoundException if one
  // of them no longer exists.
  ...
}
# Delete URL — load this directly, don't click through from a listing page
/admin/config/workflow/eca/{eca_id}/delete?eca_validation=off

Issue:

An ECA (Event-Condition-Action) model's config can end up referencing an event, condition, or action plugin ID that no longer exists on the current site, for example, after a submodule was uninstalled or after importing a config export from an environment with different ECA submodules enabled. Opening that model to edit or even delete it in the ECA admin UI (/admin/config/workflow/eca) throws Drupal\Component\Plugin\Exception\PluginNotFoundException: The "..." plugin does not exist. and lands on an error page. This happens because Drupal's entity form eagerly instantiates every plugin referenced in the model as soon as it builds the entity object - even on the delete-confirmation form, before anything is submitted.

Solution:

ECA already ships a way around this: Eca::getPluginCollections() checks Eca::isValidationDisabled() which reads the eca_validation query parameter off the current request. When it's off, plugin collections are skipped entirely, so no plugin gets instantiated and the exception never fires. Load the model's edit or delete URL with ?eca_validation=off appended directly in the address bar. 

Drupal's FormBuilder copies the current request's query string into the form's #action, so the parameter survives the confirm-button POST too. The model can then be viewed, edited, or deleted cleanly, with zero code changes. Info: The parameter has to be on the URL you actually load. Clicking a normal link - e.g. the "Delete" link from the ECA listing page - navigates to a fresh URL without it, so the error still happens. 

Paste the full URL with ?eca_validation=off into the address bar instead.

01.09.2026 | Michael Ebert

Show the status report with Drush in your terminal

You want to show the status report inside your shell or terminal window instead of opening it in the browser, or if access to the status page is not possible for some reason.

drush core:requirements

Issue:

You want to show the status report inside your shell or terminal window instead of opening it in the browser, or if access to the status page is not possible for some reason.

Solution:

The Drush command in the snippet will show you the same output as the status report does (/admin/reports/status).

Read more in the official Drush documentation: https://www.drush.org/13.3.0/commands/core_requirements

01.09.2026 | Dominik Wille

Test PHP database connection without Drupal

You need to debug the database connection.

<?php

include('web/sites/default/settings.php');

$dbHostName = $databases['default']['default']['host'];
$dataBaseName = $databases['default']['default']['database'];
$dbUserName = $databases['default']['default']['username'];
$dbPassword = $databases['default']['default']['password'];
$dbPort = $databases['default']['default']['port'];

$pdo = new PDO('mysql:host='.$dbHostName.';port='.$dbPort.';dbname='.$dataBaseName.'', $dbUserName, $dbPassword, array(
  // PDO::MYSQL_ATTR_SSL_CA    =>'ca.cert',
  PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => TRUE
  )
);

$query = $pdo->query('SHOW TABLES;');
print_r($query->fetchAll());

return $pdo;

Issue:

You need to debug the database connection.

A standalone script – for example a monitoring, backup, or migration helper – needs direct database access without bootstrapping the full Drupal framework. Duplicating database credentials in the script is undesirable since they would need to be kept in sync with settings.php.

Solution:

The snippet provided allows PHP debugging. Use it to check whether your database connection works on PHP level.

The script includes settings.php directly, which populates the $databases array as Drupal itself does during bootstrap. Credentials are then read from $databases['default']['default'], avoiding hardcoded or duplicated connection details.

A PDO connection is built from these values. PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => TRUE enforces SSL certificate verification on the connection – relevant when the database host requires or supports TLS, such as many managed hosting environments.

Since settings.php is plain PHP, including it outside of Drupal's bootstrap process only defines variables and does not require Drupal's autoloader or dependency injection container.

13.08.2026 | Pascal Crott

Can't save Form API autocomplete when referencing too many elements

Sometimes you can't save entity_autocomplete fields when selecting to many items. This comes from the fact that the form element is technically based on the textfield element. This results in inheriting all of the textfield specific properties and behaviors and one of them is a maxlength which…

If this does not work...

$form['nodes'] = [
    '#title' => $this->t('Select articles'),
    '#type' => 'entity_autocomplete',
    '#target_type' => 'node',
    '#tags' => TRUE,
    '#selection_handler' => 'default',
    '#selection_settings' => ['target_bundles' => ['article']],
    '#default_value' => $default_nodes,
];

...try adding an increased maxlength value:

$form['nodes'] = [
    '#title' => $this->t('Select articles'),
    '#type' => 'entity_autocomplete',
    '#target_type' => 'node',
    '#maxlength' => 1024,
    '#tags' => TRUE,
    '#selection_handler' => 'default',
    '#selection_settings' => ['target_bundles' => ['article']],
    '#default_value' => $default_nodes,
];

Issue: 

Sometimes you can't save entity_autocomplete fields when selecting to many items. This comes from the fact that the form element is technically based on the textfield element. This results in inheriting all of the textfield specific properties and behaviors and one of them is a maxlength which limits the text input to 128 characters.

Solution: 

To fix this, increase the maxlength value for your autocomplete field.

06.08.2026 | Michael Ebert

Enable XDebug syntax highlighting in PHP

You want to have a coloured output of a var_dump() or your stack trace when debugging with XDebug.

// Default, only plaintext.
xdebug.cli_color=0
// Coloured if your terminal will support it.
xdebug.cli_color=1
// Forced coloured output.
xdebug.cli_color=2

Prerequisite:

You have a setup runnig with PHP XDebug (>= version 2.2) enabled.

Issue:

You want to have a coloured output of a var_dump() or your stack trace when debugging with XDebug.

Solution:

You can enable coloured output of XDebug in your `php.ini` settings.

In mode 1 it tries to automatically detect if your terminal will support it. In mode 2 it will force coloured output, but if your terminal does not support syntax highlighting it might occur that you see some escaped code.

For more information about the settings of XDebug please consider the official XDebug documentation on xdebug.org.

06.08.2026 | Lothar Ferreira Neumann

Change custom text field sizes in Gin Backend Theme using Asset Injector

A custom text input field might appear too large in Gin. Our example uses an ID field which will usually never be filled with more than ~7 characters.

To alter the node ID field (nid) of our content view we add this to the file:

/* Views exposed filter: appropriate field widths */
.views-exposed-form #edit-nid {
  max-width: 10ch;
}

Issue:

A custom text input field might appear too large in Gin. Our example uses an ID field which will usually never be filled with more than ~7 characters.

Prerequisites:

Our solution uses the Asset Injector module. This module can be useful for small additions to backend theming. However, there may be cleaner solutions to this, e.g. extending Gin for your project with some custom CSS, defining a custom field type, and more. 

Solution:

Adjust the width of specific Views exposed filter fields using CSS through Asset Injection. This keeps short numeric fields like Node ID compact and improves the layout of the exposed filter form. We are using the Gin backend theme in this example. You can access the asset injector for Gin here:
/admin/config/development/asset-injector/css/gin

Please note:

Don't use Asset Injector for altering a frontend theme.

Before:

Screenshot of the content view with long nid field.

After:

Content view with short nid field

Quick note how to get the right ID for the CSS file, in our case #edit-nid:

The ID of the field is shown in the inspector

30.07.2026 | Lothar Ferreira Neumann

Merge multidimensional arrays in Drupal

You want to merge configurations in nested associative arrays without overwriting existing values.

use Drupal\Component\Utility\NestedArray;

// Parent array with default settings.
$parent_array = [
    'config' => [
        'theme' => 'dark',
        'layout' => [
            'width' => 800,
            'height' => 600,
        ],
    ],
];

// Child array adds more nested data but doesn't override existing values.
$child_array = [
    'config' => [
        'layout' => [
            'depth' => 300, // New nested key
        ],
        'features' => [
            'animations' => true, // New section
        ],
    ],
];

// Merge both arrays.
$merged_array = NestedArray::mergeDeep($parent_array, $child_array);
[
    'config' => [
        // Unchanged (not overridden)
        'theme' => 'dark', 
        'layout' => [
            // Keeps parent value
            'width' => 800, 
            // Keeps parent value  
            'height' => 600,
            // New nested key added
            'depth' => 300,   
        ],
        'features' => [
            // New section added
            'animations' => true, 
        ],
    ],
]

Issue:

You want to merge configurations in nested associative arrays without overwriting existing values.

Solution:

The code merges two nested arrays, preserving original values and adding new nested entries where they don't exist.

See the Drupal Nested Array documentation for more on the topic.

30.07.2026 | Michael Ebert

Formatting Dates programmatically with the Drupal date formatter service

You need to format datetime objects before printing them.

Example for a single datetime field

use Drupal\Core\Datetime\DrupalDateTime;

/** @var Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');

// Get DateTime object from stored date from a DateTimeFieldItemList field.
$my_date = $node->field_my_date->date;

// Get unix timestamp.
$my_date_timestamp = $my_date->getTimestamp();

// For formatting your DateTime object all other arguments are optional:
// See DateFormatterInterface for built-in options, or use machine name of a date format in config.
$type = 'medium';
// Custom PHP date format if $type="custom".
$format = '';

$formatted = $date_formatter->format($my_date_timestamp, $type, $format, $timezone = NULL, $langcode = NULL);

Example for a daterange field

use Drupal\Core\Datetime\DrupalDateTime;

/** @var Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');

// Get DateTime objects from stored date from a DateTimeFieldItemList field.
$start_date = $node->field_my_date->start_date;
$end_date = $node->field_my_date->end_date;

// For formatting your DateTime object all other arguments are optional:
// See DateFormatterInterface for built-in options, or use machine name of a date format in config.
$type = 'medium';
// Custom PHP date format if $type="custom".
$format = '';

$start_date_formatted = $date_formatter->format($start_date, $type, $format, $timezone = NULL, $langcode = NULL);
$end_date_formatted = $date_formatter->format($end_date, $type, $format, $timezone = NULL, $langcode = NULL);

Issue:

You need to format datetime objects before printing them.

Solution:

The Drupal date formatter service will be your friend. If you have enabled the datetime and/or datetime_range Core modules, you can set it to a defined date format (/admin/config/regional/date-time) or use a custom one. Details about the parameters you can use can be found on php.net.

We recommend always choosing the Drupal solution instead of a custom solution whenever possible.

16.07.2026 | Dominik Wille

Controller decorator

Sometimes you might want to alter the behavior of a route controller. By default, a controller can only be exchanged once by altering the route and replacing the route controller.

<?php

namespace Drupal\layout_builder_collapse_categories\Routing;

use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
use Drupal\layout_builder_collapse_categories\Controller\ChooseBlockController;

/**
 * Override the controller for layout_builder.move_block.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[RoutingEvents::ALTER] = ['onAlterRoutes', -1000];
    return $events;
  }

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Add a decorator for the choose_block conroller
    if ($route = $collection->get('layout_builder.choose_block')) {
      $defaults = $route->getDefaults();
      $route->setOption('original_controller', substr($defaults['_controller'], 0, strpos($defaults['_controller'], '::')));
      $defaults['_controller'] = ChooseBlockController::class . '::build';
      $route->setDefaults($defaults);
    }

  }
}
<?php

namespace Drupal\layout_builder_collapse_categories\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\layout_builder\SectionStorageInterface;
use Drupal\Core\Controller\ControllerResolverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ChooseBlockController extends ControllerBase {


  /**
   * The original ChooseBlockController
   *
   * @var \Drupal\layout_builder\Controller\ChooseBlockController $originalController
   */
  protected $originalController;

  /**
   * @param \Drupal\Core\Controller\ControllerResolverInterface $controller_resolver
   */
  public function __construct(ControllerResolverInterface $controller_resolver, RouteMatchInterface $route_match) {
    $original_controller_class = $route_match->getRouteObject()->getOption('original_controller');
    $this->originalController = $controller_resolver->getControllerFromDefinition($original_controller_class);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('controller_resolver'),
      $container->get('current_route_match')
    );
  }

  public function build(SectionStorageInterface $section_storage, $delta, $region) {
    $build = $this->originalController->build($section_storage, $delta, $region);

    foreach ($build['block_categories'] as &$category) {
      if (isset($category['#open'])) {
        $category['#open'] = FALSE;
      }
      
    }

    return $build;
  }

}

Issue:

Sometimes you might want to alter the behavior of a route controller. By default, a controller can only be exchanged once by altering the route and replacing the route controller.

Solution:

Use the provided snippet to simulate a decorator pattern for an existing controller like you would do with services. This enables you to alter the outcome multiple times.

09.07.2026 | Holger Weischenberg

Hide HTML comments in Chrome and Firefox browser inspector

Long HTML comments disturb the developer while debugging the HTML structure.

Image showing various settings options in a developer tools interface.

Issue:

Long HTML comments disturb the developer while debugging the HTML structure.

An example:

<main role="main">
    <a id="main-content" tabindex="-1"></a>
    <div class="layout-content">
      

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'region' -->
<!-- FILE NAME SUGGESTIONS:
   ▪️ region--content.html.twig
   ✅ region.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/contrib/classy/templates/layout/region.html.twig' -->
  <div class="region region-content">
    

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   ▪️ block--ef10-messages.html.twig
   ✅ block--system-messages-block.html.twig
   ▪️ block--system.html.twig
   ▪️ block.html.twig
-->

Solution:

Chrome and other Chromium-based browsers 

provide an option to hide comments in the Elements panel. Open the Inspector and click on Settings. Then scroll down to the Elements section. Uncheck the “show HTML comments” option.

1. Open the browser's Developer Tools:

  • Press F12, or
  • Press Ctrl + Shift + I (Windows/Linux), or
  • Right-click an element and select Inspect.

2. Open the DevTools settings:

  • Click the Settings (⚙) icon in the DevTools toolbar.
  • The Settings icon is located near the upper-right corner of DevTools, immediately to the left of the three-dot menu.

3. In the Preferences tab, scroll down to the Elements section. 

4. Clear the Show HTML comments checkbox. (as shown in the screenshot above)

5. Close the Settings panel.

HTML comments (<!-- comment -->) are now hidden in the Elements panel, making the DOM tree easier to navigate and debug. To display comments again, re-enable the Show HTML comments option.

Firefox

Recent Firefox versions provide a similar setting in the Inspector. If the option is not available in your Firefox installation, update to the latest version.

Firefox: „Einstellungen“-Menü im Entwicklerwerkzeug öffnen.

22.06.2026 | Pascal Crott

Gin: Make use of the simple table

Gin per default enhances all tables to use sticky headers and other goodies. But sometimes you just want to have a simple table without the enhancements.

<?php

/**
 * Implements hook_theme_suggestions_HOOK_alter() for table.
 */
function hook_theme_suggestions_table_alter(array &$suggestions, array $variables): void {
  if (empty($variables['attributes']['class'])) {
    return;
  }

  if (is_array($variables['attributes']['class']) && in_array('ief-entity-table', $variables['attributes']['class'])) {
    $suggestions[] = 'table__simple';
  }
}

Issue:

Gin per default enhances all tables to use sticky headers and other goodies. But sometimes you just want to have a simple table without the enhancements.

Solution:

There is a "table--simple" template provided by Gin which you can make use of by defining the theme suggestion for your table. In this example we use simple tables for inline entity form tables, since those are complex tables which don't always work together smoothly with gin tables.

22.06.2026 | Mathias Grab

How to enable Twig debug in Drupal

You work with Twig templates and need to use the debugger.

parameters:
  twig.config:
    debug: true
    auto_reload: null
    cache: false

Issue:

You work with Twig templates and need to use the debugger.

Solution:

Code solution:
Enable Twig debug by copying the snippet provided from root/web/sites/default.services.yml into root/web/sites/development.services.yml

See also: Drupal Docs on Twig

Sitebuilding solution:
Navigate to the administrative area via the admin toolbar to Configuration -> Development -> Development settings or via the path /admin/config/development/settings
 

Enabling twig debug 1


Enable the checkbox Twig development mode, as well as Twig debug mode and Disable Twig cache.
 

Enabling twig debug 3

For further information regarding Drupal and Twig take a look at  https://www.drupal.org/docs/develop/theming-drupal/twig-in-drupal/debugging-twig-templates

Info

This should only be used for local development environments but disabled in production.

11.06.2026 | Michael Ebert

Change the order of local tasks

You are dissatisfied with the order of the local tasks (tabs) and want to rearrange them. If you have a view with multiple displays, it is easy to reorder the tabs by adjusting the order of the view displays. In my case, I have different views that provide the tabs for routes starting with…

function my_module_local_tasks_alter(&$local_tasks) {
  if (isset($local_tasks['entity.section_library_template.collection'])) {
    $local_tasks['entity.section_library_template.collection']['weight'] = 110;
  }
    
  if (isset($local_tasks['feeds.admin'])) {
    $local_tasks['feeds.admin']['weight'] = 120;
  }

}

Issue:

You are dissatisfied with the order of the local tasks (tabs) and want to rearrange them. If you have a view with multiple displays, it is easy to reorder the tabs by adjusting the order of the view displays. In my case, I have different views that provide the tabs for routes starting with "/admin/content".

Solution:

Change the weight of the local tasks. In my example, I have the the Layout Builder Library and the Feeds module installed. I chose these two to explain where you can find the local task you need to adjust the weight.

For the Feeds module, we needed to look up where the route "admin/content/feed" is defined. We will find it inside the routing.yml file of the module. It is defined under feeds.admin.

The Layout Builder Library Module defines the route we are looking for (admin/content/section-library) in the annotation of the entity. The route name can be found in the links.task.yml file. It is defined as entity.[entity_id].[link].

11.06.2026 | Nikolas Kopp

List enabled view modes (view displays) for a bundle of an entity type

A developer needs to find which bundles of a given entity type have a specific view mode enabled – for example, to conditionally apply logic only to bundles where a teaser or custom view mode is configured.

  private function getBundlesWithViewmode(string $entity_type, string $view_mode): array {
    $bundles = [];

    foreach (\Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type) as $bundle => $info) {
      $view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle($entity_type, $bundle);
      if (isset($view_modes[$view_mode])) {
        $bundles[] = $bundle;
      }
    }

    return $bundles;
  }
  

Issue:

A developer needs to find which bundles of a given entity type have a specific view mode enabled – for example, to conditionally apply logic only to bundles where a teaser or custom view mode is configured.

Solution:

This snippet finds all bundles for a certain entity type which have a certain view mode enabled. 

Example: Find all node bundles that have a teaser view display. 
→ php $this->getBundlesWithViewmode('node', 'teaser'); Result: php ['article', 'blog']

21.05.2026 | Lothar Ferreira Neumann

Aggregate heterogeneous media fields for structured Drupal migration

You want to combine multiple image fields from a legacy system into a single media field in a new Drupal system during migration.

  field_media:
    - plugin: merge
      source:
        - field_image
        - field_images
    - plugin: sub_process
      process:
        target_id:
          - plugin: migration_lookup
            source: fid
            migration:
              - my_migration_media_image

Issue:

You want to combine multiple image fields from a legacy system into a single media field in a new Drupal system during migration.

Solution:

The code uses the migration API of Drupal to merge multiple source image fields into a single media field. It employs the merge plugin to combine the fields and a sub-process to transform the references into media entities using a migration lookup.

21.05.2026 | Michael Ebert

Do bulk updates as a batch job

You have to update many entities during development and the server runs out of memory.

<?php

/**
 * Update node title of all nodes.
 */
function custom_module_update_10001(&$sandbox) {
  // Define you entity type.
  $entity_type = 'node';

  // Load the entity type manager service.
  $entity_type_manager = \Drupal::service('entity_type.manager');

  // Get the storage for the entity type.
  $entity_storage = $entity_type_manager->getStorage($entity_type);

  if (!isset($sandbox['total'])) {
    $all_entity_ids = $entity_storage->getQuery()
      ->accessCheck()
      ->execute();
    $sandbox['total'] = count($all_entity_ids);
    $sandbox['current'] = 0;

    if (empty($sandbox['total'])) {
      $sandbox['#finished'] = 1;
      return;
    }
  }

  $entities_per_batch = 25;
  $entity_ids = $entity_storage->getQuery()
    ->accessCheck()
    ->range($sandbox['current'], $entities_per_batch)
    ->execute();
  if (empty($entity_ids)) {
    $sandbox['#finished'] = 1;
    return;
  }

  // Optionally, perform operations with the loaded entities.
  // For example, load and modify each node and set a new title.
  foreach ($entity_ids as $entity_id) {
    $entity = $entity_storage->load($entity_id);

    if ($entity->hasField('title')) {
      $entity->setTitle('New Title');
    }

    $entity->save();
    $sandbox['current']++;
  }

  \Drupal::messenger()
    ->addMessage($sandbox['current'] . ' users processed.');

  if ($sandbox['current'] >= $sandbox['total']) {
    $sandbox['#finished'] = 1;
  }
  else {
    $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  }

}

Issue:

You have to update many entities during development and the server runs out of memory.

Solution:

Update entities in batch mode. Copy-paste the snippet code.

07.05.2026 | Peter Gerken

Run missing entity Schema updates

When you see the "Entity type needs to be updated" message on the Drupal status page, usually it's not possible to solve it without custom code.

⚠️ WARNING: Potential data loss. Use with caution.

/**
 * Run missing database schema updates.
 */
function mymodule_update_10001(&$sandbox) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $entity_type_manager->clearCachedDefinitions();
  $change_summary = \Drupal::service('entity.definition_update_manager')->getChangeSummary();
  foreach ($change_summary as $entity_type_id => $change_list) {
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::entityDefinitionUpdateManager()->installEntityType($entity_type);
  }
}

Issue:

When you see the "Entity type needs to be updated" message on the Drupal status page, usually it's not possible to solve it without custom code.

Solution:

Use this update hook in your custom module to force entity definition updates on next deployment.

Conclusion:

This is basically "drush entup", which was removed because it lead to data deletion in certain instances.

Beware:

Only use with caution and verify if this really yields the result you wanted - especially test for potential data loss.

Docs for the service if you want to know more can be found on drupal.org.

30.04.2026 | Pascal Crott

Prevent empty views blocks from getting rendered even if they are empty.

Sometimes blocks are rendered even when they are empty and even if the setting in views is activated that they should not be rendered when empty. This might be the case in combination i.e. with lazy loading. If an empty block is rendered, this may have impact on the layout because the empty block…

Issue: https://www.drupal.org/project/drupal/issues/953034
<?php

use Drupal\views\Plugin\Block\ViewsBlock;

/**
 * Implements hook_block_alter().
 */
function hook_block_alter(array &$definitions) {
  foreach ($definitions as $block_id => &$block_definition) {
    if ($block_definition['class'] === ViewsBlock::class) {
      $block_definition['class'] = 'Drupal\my_module\Plugin\Block\ViewsBlock';
    }
  }
}
<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\views\Plugin\Block\ViewsBlock as ViewsBlockCore;

/**
 * Replaces the generic Views block.
 */
class ViewsBlock extends ViewsBlockCore {

  /**
   * {@inheritdoc}
   */
  public function build() {
    if (empty($this->view->result) && empty($this->view->empty)) {
      // Without caching.
      // return ['#cache' => ['max-age' => 0]];
      // With hard caching.
      return [];
    }

    return parent::build();
  }

}

Issue:

Sometimes blocks are rendered even when they are empty and even if the setting in views is activated that they should not be rendered when empty. This might be the case in combination i.e. with lazy loading. If an empty block is rendered, this may have impact on  the layout because the empty block might still have margins or paddings

Solution:

This snippet replaces the generic Views block and checks "manually" whether or not the block is empty.

30.04.2026 | Mathias Grab

How to get a list of all available contexts by context providers

You need to load a list with all context providers available in your Drupal system.

<?php

$all_available_contexts = \Drupal::service('context.repository')->getAvailableContexts();

Issue:

You need to load a list with all context providers available in your Drupal system.

Solution:

Load the context.repository service and its getAllAvailableContexts method using the provided snippet.

23.04.2026 | Lothar Ferreira Neumann

Sort render array by custom weight property

You would like to order elements of an array for rendering based on a custom weight value.

// ...

$build['content_1'] = [
    '#markup' => "content 1",
    '#custom_weight_property' => 10,
];

$build['content_2'] = [
    '#markup' => "content 2",
    '#custom_weight_property' => 5,
];

usort($build, function ($a, $b) {
    return SortArray::sortByKeyInt($a, $b, '#custom_weight_property');
});

The output looks like this:

content 2
content 1

Just a hint:

The custom weight system controls the display order of elements, where lower weight values appear earlier, as shown in the example: content_2 (with weight 5) is rendered before content_1 (with weight 10).
 

Issue:

You would like to order elements of an array for rendering based on a custom weight value.

Solution:

The code assigns a custom weight property to each element in an array and then sorts the array using a custom sorting function based on these weights. Here is the link to the documentation of the function: https://www.php.net/manual/en/function.uasort.php

The Drupal SortArray class is documented here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21SortArray.php/class/SortArray/11.x

23.04.2026 | Lothar Ferreira Neumann

Add custom text to gin_login with Form Decorator

First we create a module, lets name it 'gin_login_text'. If you have drush installed, you can generate a module using 'drush generate module'.

We will use the form_decorator module to alter the output of the gin_login module to look something like this:
 

An example what the result looks like when using gin_login_text.

This DevBit provides a step-by-step tutorial how to get there. 

First we create a module, lets name it 'gin_login_text'. If you have drush installed, you can generate a module using 'drush generate module'.

To insert our text into the gin_login we need to find the proper render array. For this we look up the logout screen with the inspector:

A screenshot from the gin_login screen with inspector.

In the picture we can see a FILE NAME SUGGESTION: 'region--pre-content.html.twig', thanks to the enabled Twig debug. If we now look into the templates for gin_login we find this:

...
    <div class="layout-container">
      {{ page.pre_content|without('claro_primary_local_tasks', 'gin_primary_local_tasks') }}
      <main class="page-content clearfix" role="main">
        <div class="visually-hidden"><a id="main-content" tabindex="-1"></a></div>
        {% block title %}
          <h1 class="page-title user-form-page__page-title">{{ 'Log in'|t }}</h1>
        {% endblock %}
        {{ page.highlighted }}
        {% if page.help %}
          <div class="help">
            {{ page.help }}
          </div>
        {% endif %}
        {{ page.content|without('claro_primary_local_tasks', 'gin_primary_local_tasks') }}
      </main>

    </div>
...

We are interested in the line `{{ page.pre_content ..... }}`

So now we need to put our text into the render array for the page with a hook:

<?php

declare(strict_types=1);

/**
 * @file
 * Implements hooks for gin_login_text.
 */

use Drupal\Core\Url;

/**
 * Implements hook_preprocess_page__user__login().
 */
function gin_login_text_preprocess_page__user__login(&$variables) {
  $config = \Drupal::config('gin_login.settings');

  $variables['page']['pre_content']['login_text']['#tree'] = TRUE;
  $variables['page']['pre_content']['login_text']['text'] = [
    '#type' => 'markup',
    '#format' => $config->get('login_text.text')['format'] ?? 'full_html',
    '#markup' => $config->get('login_text.text')['value'] ?? 'Default Heading Text',
  ];
}

$variables['page']['pre_content']['login_text'][''#tree] = TRUE;

This line is used to enable the nested array structure in a form which we will use to alter the form of gin_login to enter a text.

Last but not least add the dependencies to the info.yml:

name: gin_login_text
type: module
description: Provides a login text for gin_login
package: Custom
core_version_requirement: ^10 || ^11
dependencies:
  - form_decorator:form_decorator
  - gin_login:gin_login

As you already see in the info.yml, we have a dependency on the form_decorator. Using this module, we can decorate the form of gin_login which you can find at `/admin/config/system/configuration/gin-login`. The clue is in the title. Follow the example on the module site at https://www.drupal.org/project/form_decorator.

Your file should look like this: 

<?php

declare(strict_types=1);

namespace Drupal\gin_login_text\FormDecorator;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\form_decorator\FormDecoratorBase;
use Drupal\multivalue_form_element\Element\MultiValue;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Decorates the gin login form.
 *
 * @FormDecorator(hook = "form_gin_login_form_alter")
 */
final class GinLoginFormDecorator extends FormDecoratorBase implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;
  use DependencySerializationTrait;

  /**
   * Constructs a GinLoginFormDecorator object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The configuration factory.
   */
  public function __construct(
    array $configuration,
    string $plugin_id,
    mixed $plugin_definition,
    protected ConfigFactoryInterface $configFactory,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $configuration, $plugin_id, $plugin_definition) {
    return new self(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('config.factory'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ...$args): array {
    $form = $this->inner->buildForm($form, $form_state);
    $config = $this->configFactory->get('gin_login.settings');

    $form['login_text'] = [
      '#type' => 'details',
      '#title' => $this->t('Text'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $form['login_text']['text'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text to appear as the login page heading.'),
      '#description' => $this->t('If textfield is left empty no text will be displayed on the login page'),
      '#format' => $config->get('login_text.text')['format'] ?? 'full_html',
      '#default_value' => $config->get('login_text.text')['value'] ?? '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->inner->submitForm($form, $form_state);
    // Get it editable or else its immutable.
    $config = $this->configFactory->getEditable('gin_login.settings');
    $config->set('login_text.text', $form_state->getValue('login_text')['text']);

    $config->save();
  }

}

You should now be able to see this at the gin_login configuration under `/admin/config/system/configuration/gin-login`:

A fancy login_text for gin.

With the text added, even with some bold and italic modifications, let's observe the outcome:

An example what the result looks like when using gin_login_text.

On a site note, there is an issue to tackle that problem, but i wanted to elaborate the form_decorator usage here.
https://www.drupal.org/project/gin_login/issues/3252442 

Hopefully this article helped you alter your login site!

13.04.2026 | Pascal Crott

Restore AJAX functionality when using Slick Slider and Layout Builder

When you are using Layout Builder, AJAX for a Slick Slider may break.

Uses new Drupal "once" Library without using JQuery (see: https://www.drupal.org/node/3158256).

          slick.on('breakpoint', function (e, _) {
            if (settings.isLayoutBuilder) {
              once.remove('ajax', '.use-ajax', _.$slideTrack[0]);
              Drupal.ajax.bindAjaxLinks(_.$slideTrack[0]);
            }
          });

Issue

When you are using Layout Builder, AJAX for a Slick Slider may break.

Prerequisites

Layout Builder with a Slick Slider and Drupal 9.X or newer are in use

Solution

Use the snippet provided to re-bind AJAX events.

02.04.2026 | Lothar Ferreira Neumann

Updating user roles using a module update hook

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

<?php

use Drupal\user\RoleInterface;

/**
 * Remove the old roles and replace them with the new ones.
 */
function MY_MODULE_update_9041(): void {
  $em = \Drupal::entityTypeManager();
  $user_storage = $em->getStorage('user');

  // Ensure the new role exists. If not, create it first.
  $role_storage = $em->getStorage('user_role');
  if ($role_storage->load('new_role') === NULL) {
    /** @var \Drupal\user\RoleInterface $role */
    $role = $role_storage->create([
      'id' => 'new_role',
      'label' => 'New role',
    ]);
    $role->save();
  }

  $uids = \Drupal::entityQuery('user')
    ->accessCheck(FALSE)
    ->execute();

  if (empty($uids)) {
    return;
  }

  /** @var \Drupal\user\UserInterface[] $users */
  $users = $user_storage->loadMultiple($uids);

  foreach ($users as $user) {
    if ($user->hasRole('old_role')) {
      $user->addRole('new_role');
      $user->removeRole('old_role');
    }

    $user->save();
  }
}

Issue:

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

Solution:

This update hook first checks whether the target role (new_role) exists. If it does not, the role is created programmatically.

It then fetches all user IDs using entityQuery with accessCheck(FALSE) to ensure all users are included. The user entities are loaded via user storage, and each user is checked for the presence of the legacy role (old_role). If found, the hook adds new_role, removes old_role, and saves the user entity.

This approach ensures consistency across the user base and allows role migration to be handled safely and repeatably as part of a structured deployment process.

26.03.2026 | Pascal Crott

Clear plugin manager cache

You want to clear a specific plugin cache.

\Drupal::service('plugin_id.manager')->clearCachedDefinitions();
// Clear entity_type plugin cache.
\Drupal::entityTypeManager()->clearCachedDefinitions();

Issue:

You want to clear a specific plugin cache.

Solution:

Use the snippet provided.

26.03.2026 | Dominik Wille

Quick start: module testing on drupal.org

You want to run your automated Drupal module tests on drupal.org

curl https://git.drupalcode.org/project/gitlab_templates/-/raw/main/gitlab-ci/template.gitlab-ci.yml > .gitlab-ci.yml

Issue:

You want to run your automated Drupal module tests on drupal.org

Solution:

Customize the command to fit your module and execute it.

19.03.2026 | Peter Gerken

Block raw network access for a container

You can add this to your docker-compose.yml for any service ('web' is our example here) to prevent it from reaching the internet. This can be useful to isolate a potentially unsafe project for an audit for example.

services:
  web:
    cap_drop:
      - NET_RAW

Issue:

A containerised Drupal service – or any web service – running in an offline or restricted environment should not be able to send raw network packets. By default, Docker grants containers the NET_RAW Linux capability, which allows tools like ping and arping to craft raw IP packets. This is unnecessary for a web container and increases the attack surface.

Solution:

You can add this to your docker-compose.yml for any service ('web' is our example here) to prevent it from reaching the internet. This can be useful to isolate a potentially unsafe project for an audit for example.

19.03.2026 | Michael Ebert

Preview changed config before import/export with drush

You changed config and want to see the changes before it is exported to your config sync directory or you want to see what will be changed if you import changed config.

First, you could check if there are different states of your config between database and local file system.

drush config:status

There is an option `--diff` for the drush command that will print the changes first.

drush config:import --diff

This also works for config export.

drush config:export --diff

Issue:

You changed config and want to see the changes before it is exported to your config sync directory or you want to see what will be changed if you import changed config.

Solution:

There is an option for the drush commands that will print the changes first.

12.03.2026 | Pascal Crott, Michael Böker

Convert MySQL 8 Database Dump to MariaDB

You have a MySQL 8 Database Dump which needs to be converted into MariaDB for use with a Drupal setup.

cat olddump.sql | sed -e s/uca1400_as_ci/utf8mb4_general_ci/ | gzip > newdump.sql.gz

Issue

You have a MySQL 8 Database Dump which needs to be converted into MariaDB for use with a Drupal setup.

Solution

Use the command provided.

12.03.2026 | Peter Gerken

How to build a menu render array programmatically

This is a small but useful snippet for generating menu tree render arrays for any menu from a custom controller.

    $menu_name = 'my_custom_menu_machine_name';
  
    $menu_tree = \Drupal::menuTree();
    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    // Load the tree based on this set of parameters.
    $tree = $menu_tree->load($menu_name, $parameters);
    // Transform the tree using the manipulators you want.
    $manipulators = [
      // Only show links that are accessible for the current user.
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      // Use the default sorting of menu links.
      ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ];
    
    $tree = $menu_tree->transform($tree, $manipulators);

    $menu = $menu_tree->build($tree);

     // Set theme for custom styling.
    $menu['#theme'] = 'my_custom_theme';

Issue:

Sometimes you might need to load and render a custom menu inside a controller – for example on a user dashboard – with access checking, default sorting, and a custom theme hook applied.

Solution:

This is a small but useful snippet for generating menu tree render arrays for any menu from a custom controller.

Just change $menu_name to the machine name of your menu.

Extra: For similar use cases, you might want to use the Drupal Twig Tweak module. You can also use the {{ drupal_menu('my_menu') }} function directly in your template.

05.03.2026 | Lothar Ferreira Neumann

Update a diverged local branch from remote to be on track again

We want to make sure the local 'stage' branch is updated with the latest changes from a specific remote branch before pushing updates back to the 'stage' branch in the repository.

git fetch --all
git checkout stage
# This resets your local stage branch to the version of remote.
# The origin/stage could diverge from the local due to resetting the branch.
git reset --hard origin/stage
git merge origin/BRANCHNAME
git push origin stage
git checkout BRANCHNAME

Issue:

We want to make sure the local 'stage' branch is updated with the latest changes from a specific remote branch before pushing updates back to the 'stage' branch in the repository.

Solution:

The code snippet updates the local 'stage' branch with the latest changes from the remote 'stage' branch, merges updates from another specified branch and pushes these combined updates back to the remote 'stage' branch. Finally, it switches back to the original branch.

05.03.2026 | Michael Ebert

How to output the processed value of a WYSIWYG text field

You need to output the processed value of a WYSIWYG text field to the user.

$raw_value = $entity->my_text_field->value;
echo $raw_value;  // Outputs the raw data
$processed_value = $entity->my_text_field->processed;
echo $processed_value;  // Outputs the processed and safe-to-display data

Issue:

You need to output the processed value of a WYSIWYG text field to the user.

Solution:

For text fields there is a nice property that gives you the processed value directly. Let's have a quick look at the differences:

 unprocessed (raw) outputprocessed output
Field property->value->processed
When to Use
  • when you need the original, unaltered data.
  • when you plan to apply custom processing or formatting.
  • for programmatic manipulation or calculations that require raw data.
  • When displaying the field value directly to users.
  • when you need a value that has been filtered or formatted according to site settings (e.g., text formats, HTML filtering).
  • to ensure consistency in how field data is presented across the site.

CAUTION: The field property 'processed' only exists on WYSIWYG textfields!

26.02.2026 | Holger Weischenberg

Using CSS media queries and CSS variables in JavaScript

You want JavaScript to execute something based on a breakpoint in a CSS media query.

// Retrieve all computed styles from the root HTML element (:root)
const rootStyles = getComputedStyle(document.documentElement);

// Get the value of the CSS variable --Breakpoint.
// Use a fallback (e.g., 768px) if the variable is not defined.
const breakpoint = rootStyles.getPropertyValue('--Breakpoint').trim() || '768px';

// Create a MediaQueryList based on the breakpoint value
const mediaQuery = window.matchMedia(`(min-width: ${breakpoint})`);

// Function that runs when the viewport is at or above the breakpoint
function handleDesktopLayout() {
    console.log("Viewport is at or above the breakpoint.");
}

// Function that runs when the viewport drops below the breakpoint
function handleMobileLayout() {
    console.log("Viewport is below the breakpoint.");
}

// Early return for the initial state:
// If the viewport does NOT meet the breakpoint requirement, run mobile logic and exit
if (!mediaQuery.matches) {
    handleMobileLayout();
    // No desktop logic needed at this point
} else {
    handleDesktopLayout();
}

// Listen for changes in viewport size relative to the breakpoint
mediaQuery.addEventListener('change', (event) => {
    if (event.matches) {
        // The viewport just became equal to or larger than the breakpoint
        handleDesktopLayout();
    } else {
        // The viewport just became smaller than the breakpoint
        handleMobileLayout();
    }
});

Issue:

You want JavaScript to execute something based on a breakpoint in a CSS media query.

Solution:

Read the breakpoint value directly from the --Breakpoint CSS variable, create a matchMedia query from it, and use an event listener to run JavaScript whenever the viewport crosses that breakpoint.

24.02.2026 | Michael Ebert

How to configure mailpit in local dev environment if normal sendmail will fail.

You had problems to receive mails in mailhog in a local setup with sendmail configuration.

// mailsender command for the "Symfony Mailer" module for drupal 10
$settings['mailer_sendmail_commands'] = [
  '/usr/local/bin/mailpit sendmail -t --smtp-addr=mail:1025',
];

Prerequisite:

You have the Drupal Symfony Mailer module enabled and have a local Config Split running.

Issue:

You had problems to receive mails in mailhog in a local setup with sendmail configuration.

Solution:

Add this custom command to the sendmail configuration in your settings.local.php.

After adding go to `/admin/config/system/mailer/transport` and create a transport type 'sendmail'. Chose our newly added command and save the configuration.

Sendmail Transport Command Configuration

Add the `symfony_mailer.mailer_transport.sendmail` config to your partial split configuration for your local split and then export the configuration.

12.02.2026 | Michael Ebert

Get value of an entity field

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

// For single value fields.
$entity->field_name->value;

// If you don`t know the main property.
$main_property_name = $entity->field_name->getMainPropertyName();

// For multiple value fields.
$entity->field_name->getValue();

Issue:

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

Solution:

$entity->field_myfield->value

  • Direct Access: This approach directly accesses the value property of the field item.
  • Single Value: This is typically used when you are certain that the field holds a single value (e.g., a single text value, a single number, etc.). This is common with fields that are configured to store only one value.
  • Simplicity: It provides a simple and straightforward way to get the value if the field only holds one item.
  • Assumptions: It assumes that the field item exists and that the value property is the correct way to access the field data.

$entity->field_myfield->getMainPropertyName()

  • Main Property of the Field: getMainPropertyName() returns the main property of a field. For most fields, this is the value property, but it can also be another property depending on the field type. For example, for a reference field, the main property might be target_id.
  • Field Data Model: Each field in Drupal has a data model that can contains various properties. The main property is considered the primary piece of information for the field.
  • Usage in Entities: This method is useful when you want to use the field in a general context without knowing exactly which specific property represents the main information.

$entity->field_myfield->getValue()

  • Method Access: This approach uses the getValue() method to retrieve the field's value.
  • Array of Values: getValue() returns an array of all the field values. This is useful for fields that can hold multiple values (e.g., multiple text values, multiple references, etc.).
  • Structured Data: The returned array provides more structure and includes potentially other properties of the field items, not just the value property. For example, an image field might return an array with target_id, alt, title, etc.
  • Flexibility: This method is more flexible and can be used for both single and multi-value fields. You will need to handle the array appropriately in your code.

Conclusion:

  • Use $entity->field_myfield->value if you are dealing with a single-value field and want a straightforward, direct access to the field value.
  • Use $entity->field_myfield->getMainPropertyName() if you want to determine the main property of the field in a general way without knowing the specific field type.
  • Use $entity->field_myfield->getValue() if you need to handle multiple values or require the complete array structure of the field data, providing more flexibility and additional information.

12.02.2026 | Pascal Crott

Dynamically remove entity_reference value from views exposed filter via flag

A views filter based on taxonomy terms should not show all terms as filterable options, e.g. because they are internal

<?php

use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;


/**
 * Implements hook_form_FORM_ID_alter() for 'views_exposed_form'.
 */
function hook_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
  // Configure the values to your needs.
  $view_name = 'my_view';
  $display_name = 'my_display';
  $entity_type_id = 'taxonomy_term';
  $reference_field = 'field_category';
  // The field on the referenced entity.
  $flag_on_reference_field = 'field_hide_on_exposed_form';

  if ($form['#id'] == Html::getId("views-exposed-form-{$view_name}-{$display_name}")) {
    $entity_storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
    $options = &$form[$reference_field]['#options'];
    foreach ($entity_storage->loadMultiple(array_keys($options)) as $id => $entity) {
      if ($entity->hasField($flag_on_reference_field) && !$entity->{$flag_on_reference_field}->isEmpty()) {
        unset($options[$id]);
      }
    }
  }
}

Issue:

A views filter based on taxonomy terms should not show all terms as filterable options, e.g. because they are internal

Solution:

Create a field on your taxonomy to determine whether it should be included in filters, then alter your form so it reacts to the field setting. You can copy-paste the code provided into your module.

05.02.2026 | Mathias Grab

How to create a <pubDate> date pattern (RFC822) to be used with Views RSS feeds

RSS feeds require the date pattern to use RFC-822 format ('D, d M Y h:i:s O' | Wed, 02 Oct 2002 08:00:00 EST). The main problem is that CET (Central European Time) is not supported by this RFC standard so we have to switch to GMT (Greenwich Mean Time) + hhmm to have a valid value.

 This snippet is an example config for a date format in Drupal which can be imported.

langcode: en
status: true
dependencies: {  }
id: rss_feed_date_format
label: RFC822
locked: false
pattern: 'D, d M Y h:i:s O'

Change the date format via Sitebuilding
In the administrative menu open Configuration -> Region and language -> Date and time formats or open the path /admin/config/regional/date-time.
Then use the button "+ Add format".

Sitebuilding date format 1
Sitebuilding date format 2
  

Here you can give your new date format a label and enter D, d M Y h:i:s O as a fitting RFC822 <pubDate> format.

Sitebuilding date format 3

For more information about PHP date format options, see the official PHP documentation.

Issue:

RSS feeds require the date pattern to use RFC-822 format ('D, d M Y h:i:s O' | Wed, 02 Oct 2002 08:00:00 EST). The main problem is that CET (Central European Time) is not supported by this RFC standard so we have to switch to GMT (Greenwich Mean Time) + hhmm to have a valid value.

Solution:

Switch to GMT (Greenwich Mean Time) + hhmm to have a valid value.

05.02.2026 | Michael Ebert

Make a database dump including data from an ignored table

You need a dump including the values of a datebase table that is ignored by your drush configuration.

drush sql:dump --structure-tables-list=cache,cachetags,'cache_*',history,'search_*',sessions,webprofiler

Issue:

You need a dump including the values of a datebase table that is ignored by your drush configuration.

Prerequisites:

You use drush in your setup and have a drush config file (e.g.: https://github.com/drush-ops/drush/blob/master/examples/example.drush.yml)  like this:

command:
  sql:
    dump:
      options:
        structure-tables-list:
          - cache
          - cachetags
          - 'cache_*'
          - history
          - 'search_*'
          - 'sessions'
          - 'watchdog'
          - 'webprofiler'

Solution:

This example overrides the settings for the ignored tables in your drush command to also get the data of the watchdog table.

29.01.2026 | Peter Gerken

Manipulate Form Data before Submit

Using the provided solution will enable sharing of a set filter and ensures that whoever opens the link will see all teasers corresponding to the exposed filters. The map will be fully zoomed out so no teasers are 'accidentally' filtered out.

// Modifies form data on submit.
form.addEventListener("formdata", (e) => {
  const formData = e.formData;
  geoLocationFieldNames.forEach((name) => {
    formData.delete(name);
  });
});

Issue:

  • A list of teasers should be filtered by the set "area of detail" (boundaries) on an embedded map and additionaly by exposed filters
  • A filtered version of the view should be shareable by link, ensuring no items are unwantedly filtered out

Solution:

  • use "formdata event" which is supported by recent versions of all major browsers
  • form data is being manipulated on submit
  • map viewport boundaries will be injected into the get request, but not included into exposed filters

Conclusion:

Using the provided solution will enable sharing of a set filter and ensures that whoever opens the link will see all teasers corresponding to the exposed filters. The map will be fully zoomed out so no teasers are 'accidentally' filtered out.

29.01.2026 | Marc Hitscherich

Increasing the length of a basefield with data

You cannot change the specification of an existing field if it already has content. The reason for this is that the content itself may need to be changed as well.

<?php

/**
 * Change my_basefield max_length to 255.
 */
function my_module_update_10001() {
  $entity_type_id = 'my_entity';
  $field_name = 'my_basefield';
  $field_length = 255;

  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $schema_repository */
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  /** @var \Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');
  /** @var Drupal\Core\Field\BaseFieldDefinition[] $base_field_definitions */
  $base_field_definitions = $entity_field_manager->getBaseFieldDefinitions($entity_type_id);
  $schema_repository->setLastInstalledFieldStorageDefinition($base_field_definitions[$field_name]);
  $field_storage_definitions = $schema_repository->getLastInstalledFieldStorageDefinitions($entity_type_id);

  // Update the serialized schema property.
  $rc = new \ReflectionClass($field_storage_definitions[$field_name]);
  $schema_property = $rc->getProperty('schema');
  $schema_property->setAccessible(TRUE);
  $schema = $field_storage_definitions[$field_name]->getSchema();
  $schema['columns']['value']['length'] = $field_length;
  $schema_property->setValue($field_storage_definitions[$field_name], $schema);

  // Update the field definition in the last installed schema repository.
  $schema_repository->setLastInstalledFieldStorageDefinitions($entity_type_id, $field_storage_definitions);

  // Update the storage schema.
  $key_value = \Drupal::keyValue('entity.storage_schema.sql');
  $key_name = $entity_type_id . '.field_schema_data.' . $field_name;
  $storage_schema = $key_value->get($key_name);
  // Update all tables where the field is present.
  foreach ($storage_schema as &$table_schema) {
    $table_schema['fields'][$field_name]['length'] = $field_length;
  }
  $key_value->set($key_name, $storage_schema);

  // Update the database tables where the field is part of.
  $db = Drupal::database();
  foreach ($storage_schema as $table_name => $table_schema) {
    $db->schema()->changeField($table_name, $field_name, $field_name, $table_schema['fields'][$field_name]);
  }

}

Issue:

You cannot change the specification of an existing field if it already has content. The reason for this is that the content itself may need to be changed as well.

Solution:

In case you just want to increase the size of a varchar field, here is an example of an update hook. Don't forget to also update the max_length in the baseFieldDefinitions method of your Entity class.

22.01.2026 | Marc Hitscherich

Fix SSH warning "Remote host identification has changed" after server move.

If you have moved to a new server and want to access it with SSH via domain name, you will get the warning "Remote host identification has changed" due to changed SSH fingerprints in your `~/.ssh/known_host` file.

# Remove all old entries for my.example.com
ssh-keygen -R my.example.com

# Scan all supported fingerprints from the new server and insert them in your known_hosts file
ssh-keyscan my.example.com >> ~/.ssh/known_hosts

Issue:

If you have moved to a new server and want to access it with SSH via domain name, you will get the warning "Remote host identification has changed" due to changed SSH fingerprints in your `~/.ssh/known_host` file.

The code snippet addresses the challenge of updating SSH fingerprints in the known_hosts file for a server, particularly in cases where the server's keys have been changed, or there are discrepancies with the existing entries.

Solution:

Remove all old entries from the `~/.ssh/known_host` file and insert the new fingerprint(s). Hint: Only do this if you are sure that the new server is under your control.

This code snippet provides a solution to update the SSH fingerprints in the known_hosts file. It first removes any old entries related to a specific hostname (my.example.com) using the ssh-keygen command with the -R option. Then, it scans and appends all supported fingerprints from the new server to the known_hosts file using the ssh-keyscan command.

15.01.2026 | Lothar Ferreira Neumann

How to migrate latitude & longitude geodata into a unified geocode field

Migrating geographic coordinate data from the geofield module into a unified geofield requires correct source field mapping.

field_geofield:
  plugin: geofield_latlon
  source:
    - field_latitude
    - field_longitude

Issue:

Migrating geographic coordinate data from the geofield module into a unified geofield requires correct source field mapping.

Solution:

The code uses the geofield_latlon plugin to combine latitude and longitude fields in the specified order for proper geofield migration.

See the Drupal documentation for more info about the topic.

15.01.2026 | Mathias Grab

Show installed module information via composer

When working on a Composer based project, you may need to check the installed version, dependencies, and other details of a specific package.

# Syntax.
composer show vendor/package

# Example.
composer show drupal/eca
name     : drupal/eca
descrip. : Event, Conditions, Actions - powerful, versatile, and user-friendly rules engine for Drupal
keywords : 
versions : * 2.1.0
type     : drupal-module
license  : GNU General Public License v2.0 or later (GPL-2.0-or-later) (OSI approved) https://spdx.org/licenses/GPL-2.0-or-later.html#licenseText
homepage : https://www.drupal.org/project/eca
source   : [git] https://git.drupalcode.org/project/eca.git 2.1.0
dist     : [zip] https://ftp.drupal.org/files/projects/eca-2.1.0.zip 2.1.0
path     : /var/www/html/web/modules/contrib/eca
names    : drupal/eca

support
source : https://drupal.org/project/eca
issues : https://drupal.org/project/issues/eca

requires
dragonmantank/cron-expression ^3.1
drupal/core ^10.3||^11
ext-dom *
ext-json *
mtownsend/xml-to-array ^2.0
php >=8.1

requires (dev)
drupal/eca_ui *
drupal/entity_reference_revisions ^1.12
drupal/inline_entity_form ^3.0
drupal/paragraphs ^1.18
drupal/token ^1.15
drupal/webform dev-3465838-drupal-11-compatibility

Issue:

When working on a Composer based project, you may need to check the installed version, dependencies, and other details of a specific package.

Solution:

Use the command composer show vendor/package to retrieve detailed information about the package, including its version, description, dependencies, license, and more. This helps in debugging, verifying versions, and managing dependencies effectively.

See the Composer documentation for more info.

18.12.2025 | Dominik Wille

How to pass a context to a condition plugin instance

You want to manually create a condition instance (e.g.: "am I on an article?") but it will initially lack a runtime context which would usually be provided by the integrating UI / system, e.g. visibility settings on blocks.

use ConditionAccessResolverTrait;


$conditions = [];
foreach ($conditions as $condition_id => $condition) {
  if ($condition instanceof ContextAwarePluginInterface) {
    try {
      $contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
      $this->contextHandler->applyContextMapping($condition, $contexts);
    }
    catch (MissingValueContextException $e) {
      $missing_value = TRUE;
    }
    catch (ContextException $e) {
      $missing_context = TRUE;
    }
  }
  $conditions[$condition_id] = $condition;
}

$this->resolveConditions($conditions, 'and')

Issue:

You want to manually create a condition instance (e.g.: "am I on an article?") but it will initially lack a runtime context which would usually be provided by the integrating UI / system, e.g. visibility settings on blocks.

Solution:

Use the snippet provided to insert all available runtime contexts. This way, yours will be included.

18.12.2025 | Michael Böker

How to add a password field to an entity as the Field_UI has none to offer

You want to add a password field to an entity via the field_ui. It does not work, and – as a reminder to recurring devs – is not supposed to work. The UI is switched off in the core definition.

/**
 * Defines the 'password' entity field type.
 *
 * @FieldType(
 *   id = "password",
 *   label = @Translation("Password"),
 *   description = @Translation("An entity field containing a password value."),
 *   no_ui = TRUE,
 * )
 */

Issue:

You want to add a password field to an entity via the field_ui. It does not work, and – as a reminder to recurring devs – is not supposed to work. The UI is switched off in the core definition.

Solution:

If you need a password field, first evaluate the necessity to save a password in the database – this might create a serious security risk. 

If your project requires it anyway, you either have to create a custom widget for a textfield or use the module Password field.

12.12.2025 | Michael Ebert

Render field with given formatter type programmatically

You want to print out a field in a given formatter type.

$field_render_array = $entity->{$field_name}->view([
  'type' => 'default_formatter', // Replace with desired formatter type.
  'label' => 'hidden', // If you want to hide the label of the field (optional).
  'settings' => [
    'trim_length' => 100, // Example for textfields: Trim the text to 100 characters.
  ],
]);

Issue:

You want to print out a field in a given formatter type.

Solution:

An easy way would be to use the configuration on the view display of your entity and select the wanted field formatter there. But in some cases (e.g. you don't want to render the field on the node where it is defined) this does not work.

This snippet shows you how to do it programmatically (for example in a preprocess hook). 

As fields themselves do not have a `view()` method, we need to manipulate the render array of a field item list you get when loading an entity.

12.12.2025 | Pascal Crott

Sort blocks inside layout regions by weight.

Blocks inside a layout region are not sorted by weight property per default, even though the weight is used for rendering in the rendering process. But when you work with the blocks in a template directly you can't make sure they appear in the right order.

/**
 * Implements hook_preprocess_HOOK() for layout.html.twig.
 */
function hook_preprocess_layout(&$variables) {
  $layout = $variables['layout'];
  foreach ($layout->getRegionNames() as $region_name) {
    if (array_key_exists($region_name, $variables['content'])) {
      uasort($variables['content'][$region_name], [\Drupal\Component\Utility\SortArray::class, 'sortByWeightProperty']);
    }
  }
}

Issue:

Blocks inside a layout region are not sorted by weight property per default, even though the weight is used for rendering in the rendering process. But when you work with the blocks in a template directly you can't make sure they appear in the right order.

Solution:

Preprocess the regions and use the Drupal Core sortByWeightProperty mechanism to change the order of the blocks in the array before entering the template.

21.11.2025 | Peter Majmesku

PHP 8.5 New Features: Pipe Operator and URI Extension

PHP got updated in version 8.5 with a bunch of new smart features. Especially the new URI extension and the pipe operator are worth a look.

The New URI Extension

<?php

##### URI Extension #####

// PHP 8.4 way

$components = parse_url('https://php.net/releases/8.4/en.php');

var_dump($components['host']);
// string(7) "php.net"

// PHP 8.5 URI Extension

use Uri\Rfc3986\Uri;

$uri = new Uri('https://php.net/releases/8.5/en.php');

var_dump($uri->getHost());
// string(7) "php.net"

The New Pipe Operator

<?php

##### Pipe Operator #####

// PHP 8.4 way

$title = ' PHP 8.5 Released ';

$slug = strtolower(
    str_replace('.', '',
        str_replace(' ', '-',
            trim($title)
        )
    )
);

var_dump($slug);
// string(15) "php-85-released"

// PHP 8.5 Pipe Operator 

$title = ' PHP 8.5 Released ';

$slug = $title
    |> trim(...)
    |> (fn($str) => str_replace(' ', '-', $str))
    |> (fn($str) => str_replace('.', '', $str))
    |> strtolower(...);

var_dump($slug);
// string(15) "php-85-released"

PHP got updated in version 8.5 with a bunch of new smart features. Especially the new URI extension and the pipe operator are worth a look. 

Additional Resources

PHP

13.11.2025 | Lothar Ferreira Neumann

How to place HTML elements into webforms via the Source tab

You want to insert headings or other text elements into a web form, e.g. to subdivide it for better readability and/or understandability.

You can add headlines to a webform using the code below. To get to the source section, navigate to the form you want to alter, click on build and then on the source tab like in the screenshot.

Screenshot of the menu to add code to webform

This is just a short example on how to add a headline.

personal_data:
  '#type': html_tag
  '#tag': h3
  '#value': 'Personal data'

It will look something like this:

Headline within a webform

Issue:

You want to insert headings or other text elements into a web form, e.g. to subdivide it for better readability and/or understandability.

Solution:

Use a structured data format to define HTML elements that add the headline "Personal Data" to a web form.

13.11.2025 | Lothar Ferreira Neumann

Use ternary statements in Twig

You want to conditionally pass values to components in Twig based on variable existence or content.

{# Checks if a URL exists and passes it to the component. Otherwise, sets it to false. Works with primitive data types. #}
{% set link = url ? { url: url } : false %}

{# Checks if the media object is not empty and passes it to the component. Otherwise, sets it to false. Suitable for complex data types like objects. #}
{% set media = media is not empty ? { media: media } : false %}

Issue:

You want to conditionally pass values to components in Twig based on variable existence or content.

Solution:

Uses Twig’s ternary operator to check variable conditions and pass either an object with the variable or false.

If you're working with more complex objects, make sure to handle the empty test according to the Twig documentation on empty, as its behavior may vary depending on the object's implementation.

13.11.2025 | Holger Weischenberg

Check whether there is only one child item using CSS

In breadcrumbs, for example, icons are often assigned for illustrating the following entries. However, under certain circumstances there may only be the initial entry, so the icon points to a blank space.

    .breadcrumb--item:only-child {
      svg {
        display: none;
      }
    }
    

Issue:

In breadcrumbs, for example, icons are often assigned for illustrating the following entries. However, under certain circumstances there may only be the initial entry, so the icon points to a blank space.
 

Breadcrumb <ol> with only one child <li> and icon <svg>
Breadcrumb <ol> with only one child <li> and icon <svg>

Solution:

Make use of the `:only-child` pseudo-class to determine whether there is only one item in the breadcrumb. See more in the Mozilla Dev Documentation

Also check "caniuse" for compatibility information: https://caniuse.com/?search=only-child 

13.11.2025 | Holger Weischenberg

Simple SCSS compiler setup

A simple solution is needed to compile SCSS to CSS in a legacy project.

{
  "name": "Foo project",
  "scripts": {
    "sass-dev": "sass --watch --update --style=expanded src/scss:dist/css",
    "sass-prod": "sass --no-source-map --style=compressed src/scss:dist/css"
  },
  "devDependencies": {
    "sass": "^1.86.0"
  }
}

Issue:

A simple solution is needed to compile SCSS to CSS in a legacy project.

Solution:

Compile SCSS using npm script `npm install sass --save-dev`

13.11.2025 | Holger Weischenberg

Consider the user's preference for dark or light system colors

The theme should take into account whether the user has selected dark or light colors in the OS settings.

/* Default theme */
:root {
  --Background-Color: #fff;
  --Text-Color: #000;
}

/* Dark theme */
@media (prefers-color-scheme: dark) {
  :root {
    --Background-Color: #000;
    --Text-Color: #fff;
  }
}

Issue:

The theme should take into account whether the user has selected dark or light colors in the OS settings.

Solution:

Use the prefers-color-scheme CSS media feature. See also: documentation at developer.mozilla.org.

13.11.2025 | Peter Majmesku

Drush 12+: Simplified Drush commands with PHP 8 attributes

Before Drush version 12 we needed to write a drush.services.yml file for having dependency injection. This leads to errors when we're installing new custom Drupal modules, because the modules *.services.yml file must be instantiated before the drush.services.yml file. That makes a workaround…

<?php

declare(strict_types=1);

namespace Drupal\nice_module\Drush\Commands;

use Drupal\Component\DependencyInjection\ContainerInterface;
use Drupal\nice_module\HelloWorldService;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;

/**
 * A Drush command class for saying "hello" to the world.
 */
final class HelloWorldCommands extends DrushCommands {

  public function __construct(
    private readonly HelloWorldService $helloWorldService,
  ) {
    parent::__construct();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new static($container->get('nice_module.hello_world_service'));
  }

  #[CLI\Command(name: 'nice_module:say-hello', aliases: ['smci'])]
  #[CLI\Argument(name: 'userName', description: 'The name of the user.')]
  public function sayHello(?string $userName = NULL): void {
    $this->helloWorldService->sayHello($userName, $this->output());
    $this->logger()->success('I said "hello" to the user.');
  }

}

Issue:

Before Drush version 12 we needed to write a drush.services.yml file for having dependency injection. This leads to errors when we're installing new custom Drupal modules, because the modules *.services.yml file must be instantiated before the drush.services.yml file. That makes a workaround necessary, where we do rename the drush.services.yml file, before we rebuild the cache for having the services from our modules *.services.yml instantiated. Also the old approach was not leveraging PHP attributes, which are available since PHP 8.

Solution:

The snippet file is meant to be located here: web/modules/custom/nice_module/src/Drush/Commands/HelloWorldCommands.php

By this approach there are no errors on new module installation, where we do have a modules `*.services.yml` and `drush.service.yml`. 

Via PHP attributes our command, argument, and usage descriptions are also validated with PHP. This makes our Drush commands less error prone. 

13.11.2025 | Peter Majmesku

Autowire services with the Autowire attribute in Drupal

If dependencies are injected into a service class, changes must be made in both the `*.services.yml` file and the PHP class itself.

<?php

declare(strict_types=1);

namespace Drupal\my_module;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class Example {

  public function __construct(
    #[Autowire(service: 'current_user')]
    private readonly AccountInterface $currentUser,
  ) {
  }

  public function getCurrentUser(): AccountInterface {
    return $this->currentUser;
  }

}
services:
  my_module.example:
    class: Drupal\my_module\Service\Example
    autowire: true
  Drupal\my_module\Service\Example: '@my_module.example'

Issue: 

If dependencies are injected into a service class, changes must be made in both the `*.services.yml` file and the PHP class itself.

Solution:

If we set autowiring to true in the *.services.yml file, we can use the Autowire attribute in our PHP service class. This allows us to focus on the service class itself without having to switch between the *.services.yml file and the PHP service class.

13.11.2025 | Marc Hitscherich

List MySQL tables by size

You need to sort MySQL tables by size.

SELECT table_name AS `table`, round(((data_length + index_length) / 1024 / 1024), 2) `size in MB`
FROM information_schema.TABLES
WHERE table_schema = "DATABASE_NAME"
ORDER BY `size in MB` DESC
LIMIT 10;

Issue:

You need to sort MySQL tables by size.

Solution:

The snippet shows the size of the 10 biggest tables. DATABASE_NAME needs to be replaced by your database name.

13.11.2025 | Mathias Grab

How to add a Drupal error message and log entry

You would like to create a custom error message shown on the page. Also, if the error occurs, it should be properly logged in the recent log messages backend area (`/admin/reports/dblog`) of your site.

<?php

$error_message = t('There is an error with this.');

\Drupal::messenger()->addError($error_message));
\Drupal::logger('my_module')->log('error', $error_message);

Issue:

You would like to create a custom error message shown on the page. Also, if the error occurs, it should be properly logged in the recent log messages backend area (`/admin/reports/dblog`) of your site.

Solution:

Use the Drupal logger and messenger service to create the errors.

13.11.2025 | Mathias Grab

How to create local task links

You want to create a local task link with a specific custom route.

my_module.my_local_task_link:
  route_name: my_module.custom_route
  title: "Title"
  base_route: route_where.local_task.should_be_placed

Issue:

You want to create a local task link with a specific custom route.

Solution:

To create a local task link, define it in my_module.local.task.yml, optionally accompanied by my_module.routing.yml and MyCustomController.php. Alternatively, you can use existing routes, specifying route_name as the target of the link and base_route as the location where the link should appear.
 

Explanations for the most important properties in yml files

my.module.links.task.yml

yml propertyDescription
my_module.my_local_task_linkMachine name of the link.
route_nameThe route the link leads to.
titleHuman readable title of the link. Is shown on buttons or menu links.
base_routeBase route where the link is placed on.

my_module.routing.yml

yml propertyDescription
my_module.custom_routeMachine name of the registered route.
pathPath in URL.
defaultsDefault values for the upcoming properties.
_controllerNamespace of the controller that handles the logic when the route is accessed.
_titleHuman readable title of the route.
requirementsRequirements that must be met to access the route.
_permissionPermission that must be fulfilled to access the route. 

See the official Drupal documentation for further in-depth information.

13.11.2025 | Nikolas Kopp

Clear APC & Opcache

You need to clear APC and Opcache, e.g. for debugging purposes.

<?php

apcu_clear_cache();
opcache_reset();

Issue:

You need to clear APC and Opcache, e.g. for debugging purposes.

Solution:

drush php:script clear_cache 

This snippet clears APCu and Opcache. Put it into the docroot. Execute from browser, not from CLI.

See the drush documentation for more info.

13.11.2025 | Nikolas Kopp, Pascal Crott

Token Chaining – How to access tokens for nested information

Out of the box there are plenty of tokens available from the group module. In case those don't fit your needs, you can chain the group_relationship's entity tokens to get the desired value from the referenced entity.

/**
 * Implements hook_tokens().
 */
function example_group_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  // Automatically expose related entities to group_relationships.
  if ($type == 'group_relationship' && !empty($data[$type])) {
    $token_service = \Drupal::token();

    /** @var \Drupal\example\GroupRelationshipTypeServiceInterface $group_relationship_type_service */
    $group_relationship_type_service = \Drupal::service('example.group_relationship_type_service');

    $group_relationship = $data['group_relationship'];
    assert($group_relationship instanceof GroupRelationshipInterface);

    foreach ($tokens as $name => $original) {
      /** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
      foreach ($group_relationship_type_service->getConfiguredEntityTypes() as $entity_type_id => $entity_type) {
        if ($name == $entity_type_id) {
          $entity = $group_relationship->getEntity();
          $bubbleable_metadata->addCacheableDependency($entity);
          $replacements[$original] = $entity->label();
        }

        // Actual chaining of tokens handled below.
        if ($entity_tokens = $token_service->findWithPrefix($tokens, $entity_type_id)) {
          $replacements += $token_service->generate($entity_type_id, $entity_tokens, [$entity_type_id => $group_relationship->getEntity()], $options, $bubbleable_metadata);
        }
      }
    }
  }

  return $replacements;
}

Issue:

Out of the box there are plenty of tokens available from the group module. In case those don't fit your needs, you can chain the group_relationship's entity tokens to get the desired value from the referenced entity.

Solution:

Use the snippet to gain access to chained tokens, e.g. users via group relationships.

This snippet has been turned into the group_relationships_tokens module.

13.11.2025 | Nikolas Kopp

Cache Debugging for Render Elements

You need to get to know the caching settings for render elements.

  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []
    debug: true # The debug setting

Issue:

You need to get to know the caching settings for render elements.

Solution:

Drupal 9.5 introduced a debug setting for the renderer configuration to display cache information for each rendered element (see also: https://www.drupal.org/node/3162480).

13.11.2025 | Pascal Crott

Prevent the user profile from being displayed in backend theme using RouteSubscriber

Authenticated users should never see the admin/backend theme in your websystem

<?php

namespace Drupal\scp_base\Routing;

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

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Make sure profile pages are not admin pages, in order to load the right
    // translation.
    if ($route = $collection->get('profile.user_page.single')) {
      $route->setOption('_admin_route', FALSE);
    }
  }

}

Issue:

Authenticated users should never see the admin/backend theme in your websystem

Prerequisites:

You need to have the profile module installed in your project.

Solution:

Paste the provided code snippet into your RouteSubscriber.php file.

13.11.2025 | Pascal Crott

Fix broken media previews

The error log is full of the warning "Warning: copy(public://media-icons/generic/generic.png)" and the media library shows no previews. This can happen when environments are set up based on a database dump and without properly transferring the files. The media icons are usually created during the…

drush php-eval "\Drupal::moduleHandler()->loadInclude('media', 'install');media_install();";

Issue:

The error log is full of the warning "Warning: copy(public://media-icons/generic/generic.png)" and the media library shows no previews. This can happen when environments are set up based on a database dump and without properly transferring the files. The media icons are usually created during the installation of the media module, which will never happen in this scenario.

Devbit broken media preview icons

Solution:

Trigger the install hook of the Core Media module. It will take care of creating those files. Use the provided snippet.

See also https://www.drupal.org/project/drupal/issues/3060509

13.11.2025 | Dominik Wille

Install config from config/install dir in update hook.

You might maintain a Drupal contrib module and want to add some config at a later stage.

/**
 * Save the bulk delete action to config.
 */
function redirect_update_8104() {
  if (!Action::load('redirect_delete_action')) {
    $entity_type_manager = \Drupal::entityTypeManager();
    $module_handler = \Drupal::moduleHandler();

    // Save the bulk delete action to config.
    $config_install_path = $module_handler->getModule('redirect')->getPath() . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY;
    $storage = new FileStorage($config_install_path);
    $entity_type_manager
      ->getStorage('action')
      ->create($storage->read('system.action.redirect_delete_action'))
      ->trustData()
      ->save();
  }
}

Issue:

You might maintain a Drupal contrib module and want to add some config at a later stage.

Solution:

The provided snippet implements a hook to create config.

Further information

Similar results can be achieved using the Configuration Replace module.

13.11.2025 | Dominik Wille

Don't list a widget for a field type.

You want to create a custom widget for a field but it should not be available to all fields of this type.

  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    if (isset($field_definition->getDisplayOptions('form')['type'])) {
      return $field_definition->getDisplayOptions('form')['type'] == 'slot_content_weights';
    }

    return FALSE;
  }

Issue:

You want to create a custom widget for a field but it should not be available to all fields of this type.

Solution:

Use the `isApplicable` method to restrict it to this field only.

13.11.2025 | Michael Ebert

How to alter the langcode of a field for accessibility reasons

You want to assign a language to a certain part of your node which differs from the set content language. That could be the case if you need to make it more readable for disabled persons who use a screenreader.

function my_module_preprocess_field(&$variables): void {
  if ($variables['element']['#bundle'] == 'my_bundle') {
    if (in_array($variables['element']['#field_name'], ['my_field'])) {
      $variables['attributes']['lang'] = 'en';
    }
  }
}

Issue:

You want to assign a language to a certain part of your node which differs from the set content language. That could be the case if you need to make it more readable for disabled persons who use a screenreader.

Solution:

Use a preprocess_field hook and set the lang attribute of that field to e.g. "en" for English. We only want this to work on nodes from the "my_bundle" type.

Similar results may also be achieved using the CKEditor Text part language plugin.