function UserRoleAdd::doExecute
Assign role to a user.
Parameters
\Drupal\user\UserInterface $user: User object.
\Drupal\user\RoleInterface[] $roles: Array of UserRoles to assign.
Throws
\Drupal\rules\Exception\InvalidArgumentException
File
-
src/
Plugin/ RulesAction/ UserRoleAdd.php, line 52
Class
- UserRoleAdd
- Provides a 'Add user role' action.
Namespace
Drupal\rules\Plugin\RulesActionCode
protected function doExecute(UserInterface $user, array $roles) {
foreach ($roles as $role) {
// Skip adding the role to the user if they already have it.
if (!$user->hasRole($role->id())) {
// If you try to add anonymous or authenticated role to user, Drupal
// will throw an \InvalidArgumentException. Anonymous or authenticated
// role ID must not be assigned manually.
try {
$user->addRole($role->id());
} catch (\InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage());
}
// Set flag that indicates if the entity should be auto-saved later.
$this->saveLater = TRUE;
}
}
}