user

my_module.deploy.php
/**
 * Reassign content from specific users to anonymous and delete them.
 */
function my_module_deploy_reassign_and_delete_users(&$sandbox) {
  $uids = [111, 123, 222, 234, 333, 345];
  $user_storage = \Drupal::entityTypeManager()->getStorage('user');
  $users = $user_storage->loadMultiple($uids);

  foreach ($uids as $uid) {
    if (!isset($users[$uid])) {
      continue;
    }

    // Handle all entities (including nodes, comments, etc.).
    $entity_type_manager = \Drupal::entityTypeManager();
    foreach ($entity_type_manager->getDefinitions() as $entity_type_id => $definition) {
      if (!$definition->entityClassImplements(ContentEntityInterface::class)) {
        continue;
      }

      $storage = $entity_type_manager->getStorage($entity_type_id);
      $uid_key = $definition->getKey('uid') ?: ($definition->getKey('owner') ?: NULL);

      if ($uid_key) {
        $ids = $storage->getQuery()
          ->condition($uid_key, $uid)
          ->accessCheck(FALSE)
          ->execute();

        if (!empty($ids)) {
          foreach ($storage->loadMultiple($ids) as $entity) {
            if ($entity instanceof EntityOwnerInterface) {
              $entity->setOwnerId(0);
            } else {
              $entity->set($uid_key, 0);
            }
            try {
              $entity->save();
            } catch (\Exception $e) {
              \Drupal::logger('sn_base')->error('Failed to reassign entity @type @id: @message', [
                '@type' => $entity_type_id,
                '@id' => $entity->id(),
                '@message' => $e->getMessage(),
              ]);
            }
          }
        }
      }
    }

    // Finally delete the user.
    $users[$uid]->delete();
  }
}

switch_roles.install
<?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();
  }
}
02.04.2026 | Lothar Ferreira Neumann

Updating user roles using a module update hook

get_one_time_login_for_domains.sh
drush uli

https://my-project.dev.erd.fish/user/reset/1/1743658959/GxIzcvUB-Hv7E9WPoxyAIF-_pXD4kTH3GCIXQ2QFZz0/login

get_environment_one_time_login.txt
copy:
/user/reset/1/1743658959/GxIzcvUB-Hv7E9WPoxyAIF-_pXD4kTH3GCIXQ2QFZz0/login

look up your site domains in the .ddev/.ddev-docker-compose-base.yaml:

external_links:
    - "ddev-router:cms.ddev.site"

Add everything after '/' from the drush uli command.

cms.ddev.site/user/reset/1/1743659359/GxIzcvUB-Hv7E9WPoxyAIF-_pXD4kTH3GCIXQ2QFZz0/login
drush_user_information.sh
drush user:information --uid=user_id

 

output.md
 ```
 --------- ----------- ------------------- --------------- -------------
  User ID   User name   User mail           User roles      User status
 --------- ----------- ------------------- --------------- -------------
  1         admin       admin@example.com   authenticated   1
 --------- ----------- ------------------- --------------- -------------
 ```
RouteSubscriber.php
<?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);
    }
  }

}