Score:0

How do you remove a user role via a hook update?

id flag

I would like to remove a user role via a hook update in Drupal 9.

I believe I would need to do something like the below but unclear what other code might be needed.

$user->removeRole('administrator');
$user->save();
sonfd avatar
in flag
Are you trying to remove a role from a specific user? Or delete the role so that it no longer exists in the system and can't be assigned to any user?
id flag
First remove the role for all users who have the assigned role. Then delete the role so that it no longer exists in the system and can't be assigned to any user.
leymannx avatar
ne flag
Search for drupal batch process update hook. Because when you want to process a lot of users you may want to prevent timeouts when your update hook runs.
Score:0
de flag

First, load all your users having the role you wish to delete:

$usersHavingRole = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['roles' => 'my_role']);

Then, for each user, remove the role (this is the code you mentioned):

foreach($usersHavingRole as $user) {
  $user->removeRole('my_role');
  $user->save();
}

And finally, delete the role:

$role = \Drupal\user\Entity\Role::load('my_role');
if (!empty($role)) {
  $role->delete();
}
leymannx avatar
ne flag
I guess OP is more in search of actual update hook code implementing a batch process at best.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.