I got php code that is suppouse to remove one role and add a new one to all users in given array. But unfortunatelly it just add new role but doesn't remove one. I tried alphanumeric values as $rid and straightforward numeric $id but still no effect. I tried putting error_logs inside loops and it's executed and printed to error_log.php.

Here's my code

foreach($users as $usr){
            $user = user_load_by_name($usr);
        foreach($users as $usr){
            $user = user_load_by_name($usr);


[0] => client1
[1] => client4

I think it is worth to mention that roleToRemove is assigned to every new user that is registered using registration role module

FIXED check answers


Ok i found an answer. The code is proper and it works. The problem was that I got module installed that assigned a role to new created users. I found out that it not only assign role when someone create new user but also when you was updating any of them. I've patched this bug and i got this hosted on my repo so if anybody needs it. repo


Looking at the Drupal code, it's absolutely clear that removeRole requires not the name but the id of the role:


To test if the error happens in your own code or somewhere else, you could dump $usr->getRoles() immediately before and after executing it.

  • i tried it that way and still no results but i think that i found an error and it is not a code based one. The problem is that module that assigns a registration role assign it again on altering user. – karoluS Jul 6 '17 at 8:31
  • 1
    id of role in drupal 8.x is name of role with all lower case and underscores instead of spaces i.e. Role Name becomes role_name – karoluS Jul 6 '17 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.