add role to existing user on hook_entity_presave

27/07/2018


I’m trying to add a role to a user but I can’t save the change.

function hook_entity_presave(DrupalCoreEntityEntityInterface $entity){
  $user = DrupaluserEntityUser::load(Drupal::currentUser()->id());
  $user->addRole('foobar');
}

I would like to save the change, but $user->save() causes a fatal error.

What would be the correct way?

قالب وردپرس