Direkt zum Inhalt

Devbits

Kleine Code-Schnipsel aus unserem Alltag mit Drupal, PHP und DevOps: Problem, Lösung, Code.

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.

02.04.2026 | Lothar Ferreira Neumann

Updating user roles using a module update hook

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

<?php

use Drupal\user\RoleInterface;

/**
 * Remove the old roles and replace them with the new ones.
 */
function MY_MODULE_update_9041(): void {
  $em = \Drupal::entityTypeManager();
  $user_storage = $em->getStorage('user');

  // Ensure the new role exists. If not, create it first.
  $role_storage = $em->getStorage('user_role');
  if ($role_storage->load('new_role') === NULL) {
    /** @var \Drupal\user\RoleInterface $role */
    $role = $role_storage->create([
      'id' => 'new_role',
      'label' => 'New role',
    ]);
    $role->save();
  }

  $uids = \Drupal::entityQuery('user')
    ->accessCheck(FALSE)
    ->execute();

  if (empty($uids)) {
    return;
  }

  /** @var \Drupal\user\UserInterface[] $users */
  $users = $user_storage->loadMultiple($uids);

  foreach ($users as $user) {
    if ($user->hasRole('old_role')) {
      $user->addRole('new_role');
      $user->removeRole('old_role');
    }

    $user->save();
  }
}

Issue:

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

Solution:

This update hook first checks whether the target role (new_role) exists. If it does not, the role is created programmatically.

It then fetches all user IDs using entityQuery with accessCheck(FALSE) to ensure all users are included. The user entities are loaded via user storage, and each user is checked for the presence of the legacy role (old_role). If found, the hook adds new_role, removes old_role, and saves the user entity.

This approach ensures consistency across the user base and allows role migration to be handled safely and repeatably as part of a structured deployment process.

13.11.2025 | Pascal Crott

Prevent the user profile from being displayed in backend theme using RouteSubscriber

Authenticated users should never see the admin/backend theme in your websystem

<?php

namespace Drupal\scp_base\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Make sure profile pages are not admin pages, in order to load the right
    // translation.
    if ($route = $collection->get('profile.user_page.single')) {
      $route->setOption('_admin_route', FALSE);
    }
  }

}

Issue:

Authenticated users should never see the admin/backend theme in your websystem

Prerequisites:

You need to have the profile module installed in your project.

Solution:

Paste the provided code snippet into your RouteSubscriber.php file.