nerdfisch: DevBits

Kleine, aber feine Code-Snippets, nützliche Tweaks und elegante Lösungsansätze aus dem Entwickler-Alltag

08.10.2026 | Pascal Crott

Get default langcode from entity

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

05.10.2026 | Lothar Ferreira Neumann

Declaring the return parameter with NULLable type as an option.

null_return.php
/**
 * 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;
}
05.10.2026 | Michael Ebert

Enable the admin theme for your custom route

my_module.routing.yml
my_module.edit:
  options:
    # Enable the admin theme for this route.
    _admin_route: TRUE
05.10.2026 | Lothar Ferreira Neumann

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

install_libraries_locally.sh
composer require npm-asset/yaireo--tagify:4.35.4
my_module.module
/**
 * 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']);
}
05.10.2026 | Pascal Crott

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

add-to-first-position.twig
{# 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']) %}