I have tried the following code, but something doesn't work, could you please help. I need to deactivate several accounts at once, if they satisfy the conditions:

$ids = \Drupal::entityQuery('user')
  ->condition('roles', 'student')
  ->condition('field_school_id', $node_id)
$users = User::loadMultiple($ids);

$storage_handler = \Drupal::entityTypeManager()->getStorage("user");

foreach($users as $user){
  $entity = $storage_handler->load($user->id());
  $entity->set("status", 0);
  $storage_handler->save($entity); // THE PROBLEM IS IN THIS LINE

The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in $user.

Change your foreach loop to look like this and it should work:

foreach ($users as $user) {
  $user->set("status", 0);

You can also remove the $storageHandler since you don't use that any more.

| improve this answer | |

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.