user deletion : user_cancel_reassign not working when user has more than 10 associated contents I am attempting to suppress Users with no permissions/roles from our sites.
The user associated contents should be kept on user deletion.
This code below works when the user has a few associated content.
On deletion the content becomes of anonymous author.
It does not work anymore when the user is the author of more than 10 contents.
All associated contents are deleted when the user is deleted.
Another method is invoked , i suppose.
How can i solve this?
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use \Drupal\user\Entity\User;

function hook_preprocess_page(&amp;$variables, $hook) {    
  $route_name = \Drupal::routeMatch()-&gt;getRouteName();
  $user = \Drupal::currentUser();    
  if (count($user-&gt;getRoles()) == 1 &amp;&amp; ($route_name != &quot;system.401&quot; &amp;&amp; $route_name != &quot;user.login&quot;)) {
    $userWithoutRole = User::load($user-&gt;id());
    if ($userWithoutRole !== null){
      $method='user_cancel_reassign';
      user_cancel([], $user-&gt;id(), $method);
      $userWithoutRole-&gt;delete();
    }
    throw new UnauthorizedHttpException('insufficient permissions');
  }
}

NB: The same issue is remaining on the &quot;auto purge users&quot; module
user_cancel() is run in a batch. This means that either it's called in a form, or batch_process() needs to be called after it. For example, this is the code used from UserController::confirmCancel().
$edit = [
  'user_cancel_notify' =&gt; isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this-&gt;config('user.settings')-&gt;get('notify.status_canceled'),
];
user_cancel($edit, $user-&gt;id(), $account_data['cancel_method']);

// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually and should redirect to the front page
// after completion.
return batch_process('&lt;front&gt;');

It's not necessary to delete the account, as that is already done from _user_cancel(), the batch operation callback used from user_cancel().
case 'user_cancel_reassign':
case 'user_cancel_delete':
  // Send account canceled notification if option was checked.
  if (!empty($edit['user_cancel_notify'])) {
    _user_mail_notify('status_canceled', $account);
  }
  $account-&gt;delete();
  // …

It's also probable that hook_preprocess_page() is the wrong place to call user_cancel() as it would be called when the page is being rendered, while the batch operations require to redirect users. See batch_process(), which contains the following code.
if (($function = $batch['redirect_callback']) &amp;&amp; function_exists($function)) {
  $function($batch_url-&gt;toString(), [
    'query' =&gt; $query_options,
  ]);
}
else {
  return new RedirectResponse($batch_url-&gt;setAbsolute()-&gt;toString(TRUE)-&gt;getGeneratedUrl());
}