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:

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

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.

16.07.2026 | Lothar Ferreira Neumann

How to translate the Maxlength Countdown message label globally

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…

A Drupal backend screenshot showing the "Count down message" field

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.

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.

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.

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.

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.

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 | 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 | 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.