In Drupal 8/9 this is pretty straightforward as UserInterface
provides two methods for doing this: block()
and activate()
.
The only catch is that the user entity must be saved after doing this.
Code for blocking a user programmatically:
/** @var \Drupal\user\UserInterface $user */ $user = \Drupal\user\Entity\User::load(USER_ID_HERE); $user->block(); $user->save();
Code for activating a user programmatically:
/** @var \Drupal\user\UserInterface $user */ $user = \Drupal\user\Entity\User::load(USER_ID_HERE); $user->activate(); $user->save();