entity API

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

my_module_with_presave_hook.module
<?php

/**
 * @file
 * Primary module hooks for my module.
 */

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function my_module_node_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() === 'article') {
    // Do something here with the article.
  }
}

/**
 * Implements hook_entity_presave().
 */
function my_module_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity instanceof \Drupal\node\NodeInterface || $entity instanceof \Drupal\paragraphs\Entity\Paragraph) {
    // Do something here with the node and paragraph.
  }
}

10.07.2025 | Lothar Ferreira Neumann

Presave hook on one or multiple entities