Skip to main content

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.