2

I am trying to assign multiple role while creating a user programatically. I am successfully creating a user and assigning one role using below code

$user = \Drupal\user\Entity\User::create();
// Mandatory.
$user->setPassword('111');
$user->enforceIsNew();
$user->setEmail('abcd@gmail.com');
$user->setUsername('abcd');
$user->addRole('lecturer');
$user->save();

I want to assign two roles during this code execution and tried the below code but it did not work

$user->addRole(['lecturer','program coodinator']);

How do I assign this?

3

If you look at User::addRole it says

User::addRole($rid)

string $rid: The role ID to add.

Therefore, this cannot be an array. Thus, you must do this separate

$user->addRole('lecturer');
$user->addRole('program coodinator');
$user->save();

If you look at class User, there is no such thing as "addRoles" or any method that allows multiple way of doing it with an array.

1

If you are sure the roles you are adding aren't already added to the user account, you can use the following code.

$roles = $user->getRoles(TRUE);
$user->set('roles', $roles + ['lecturer','program coodinator'])->save();

Since you are creating a user account, this code is probably sufficient. The more generic code would be the following one.

$roles = $user->getRoles(TRUE);
$user->set('roles', array_unique($roles + ['lecturer','program coodinator']))->save();

That code is similar to the code used by User::addRole(), with the exception it doesn't check the role being added is the anonymous user or the authenticated role.

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.