13.11.2026 | Michael Ebert
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:
Solution:
- 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]. - 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. - 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
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
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
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
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
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
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
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
- Edit your Entity Reference field and select "Views: Filter by an entity reference view" as the reference method.
- 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
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
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.
05.10.2026 | Michael Ebert
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
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']);
}
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.
- 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)
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
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
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
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
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
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
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.
13.08.2026 | Henjo Völker
Clients may tend to understand and use issue workflows differently than the person who defined them intended. A specific issue we encountered was this:
06.08.2026 | Michael Ebert
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
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:
After:
Quick note how to get the right ID for the CSS file, in our case #edit-nid:
30.07.2026 | Lothar Ferreira Neumann
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
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
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.
16.07.2026 | Lothar Ferreira Neumann
When enabling the soft or hard character limit for a field using the Maxlength module, the module writes a default label into the field widget configuration. Because the label string is written directly into configuration, the fallback string logic is never used. As a result, the label cannot be…
Example configuration created by enabling Maxlength:
# ...
content:
field_copyright:
type: text_textarea
weight: 3
region: content
settings:
rows: 2
placeholder: ''
third_party_settings:
allowed_formats:
hide_help: '1'
hide_guidelines: '1'
maxlength:
maxlength_js: null
maxlength_js_label: 'Content limited to @limit characters, remaining: <strong>@remaining</strong>'
maxlength_js_enforce: false
# ...
However, the module already contains fallback logic for this label in maxlength.module:
$maxlength_js_label = !empty($thirdPartySettings['maxlength']['maxlength_js_label']) ? $thirdPartySettings['maxlength']['maxlength_js_label'] : t('Content limited to @limit characters, remaining: <strong>@remaining</strong>');
$maxlength_js = $thirdPartySettings['maxlength']['maxlength_js'];
Working configuration: empty the label
# ...
content:
field_copyright:
type: text_textarea
weight: 3
region: content
settings:
rows: 2
placeholder: ''
third_party_settings:
allowed_formats:
hide_help: '1'
hide_guidelines: '1'
maxlength:
maxlength_js: null
maxlength_js_label: ''
maxlength_js_enforce: false
# ...
With the label empty, the module falls back to its internal t() string, which can then be translated normally via the interface translation system.
Issue:
When enabling the soft or hard character limit for a field using the Maxlength module, the module writes a default label into the field widget configuration. Because the label string is written directly into configuration, the fallback string logic is never used. As a result, the label cannot be translated through the Interface Translation system, since Drupal treats it as configuration rather than a translatable interface string.
Solution:
To allow translating the countdown string via the Drupal interface translation, the label must be removed from the configuration so the module fallback is used instead.
- There is alrady a fix for this problem for the maxlength module on drupal.org.
09.07.2026 | Michael Ebert
You want to get informed about updates on nodes like forum topics and need an easy solution to subscribe to it.
Installation with composer:
composer require 'drupal/comment_notify'
Enable with drush:
drush pm:install comment_notify
Configure it under ../admin/config/people/comment_notify.
Select the Bundle on that you want to enable it. Chose "All Comments" under availible subscription modes and set it as default state.
Issue:
You want to get informed about updates on nodes like forum topics and need an easy solution to subscribe to it.
Solution:
During research we found the comment_notify module.
Conclusion:
Install the module, enable it, configure it. Thats it.
09.07.2026 | Holger Weischenberg
Long HTML comments disturb the developer while debugging the HTML structure.
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.
22.06.2026 | Pascal Crott
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
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
Enable the checkbox Twig development mode, as well as Twig debug mode and Disable Twig cache.
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
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
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
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
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
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.
07.05.2026 | Dominik Wille
A page contains multiple Views blocks showing entities of the same type – for example teasers, lists, or cards. Without coordination between them, the same entity can appear in more than one block on the same page.
30.04.2026 | Pascal Crott
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.