nerdfisch: DevBits

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

13.11.2025 | Pascal Crott

Fix broken media previews

media-install.sh
drush php-eval "\Drupal::moduleHandler()->loadInclude('media', 'install');media_install();";
sh
media
media library
debugging
error handling
13.11.2025 | Dominik Wille

Install config from config/install dir in update hook.

redirect.install
/**
 * 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();
  }
}
modules
php
config
configuration management
13.11.2025 | Dominik Wille

Don't list a widget for a field type.

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

    return FALSE;
  }

php
widgets
fields
13.11.2025 | Michael Ebert

Warm your Drupal caches after a cache clear

my_module.services.yml
tags:
  - { name: cache_prewarmable }

MyPlugin.php
/**
  * Implements \Drupal\Core\PreWarm\PreWarmableInterface.
  */
public function preWarm(): void {
  $this->getDefinitions();
}

services
drush
caching
API
13.11.2025 | Michael Ebert

How to alter the langcode of a field for accessibility reasons

my_module.module
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';
    }
  }
}

module
accessibility
multi-language
field management