my_module.deploy.php
/**
* Reassign content from specific users to anonymous and delete them.
*/
function my_module_deploy_reassign_and_delete_users(&$sandbox) {
$uids = [111, 123, 222, 234, 333, 345];
$user_storage = \Drupal::entityTypeManager()->getStorage('user');
$users = $user_storage->loadMultiple($uids);
foreach ($uids as $uid) {
if (!isset($users[$uid])) {
continue;
}
// Handle all entities (including nodes, comments, etc.).
$entity_type_manager = \Drupal::entityTypeManager();
foreach ($entity_type_manager->getDefinitions() as $entity_type_id => $definition) {
if (!$definition->entityClassImplements(ContentEntityInterface::class)) {
continue;
}
$storage = $entity_type_manager->getStorage($entity_type_id);
$uid_key = $definition->getKey('uid') ?: ($definition->getKey('owner') ?: NULL);
if ($uid_key) {
$ids = $storage->getQuery()
->condition($uid_key, $uid)
->accessCheck(FALSE)
->execute();
if (!empty($ids)) {
foreach ($storage->loadMultiple($ids) as $entity) {
if ($entity instanceof EntityOwnerInterface) {
$entity->setOwnerId(0);
} else {
$entity->set($uid_key, 0);
}
try {
$entity->save();
} catch (\Exception $e) {
\Drupal::logger('sn_base')->error('Failed to reassign entity @type @id: @message', [
'@type' => $entity_type_id,
'@id' => $entity->id(),
'@message' => $e->getMessage(),
]);
}
}
}
}
}
// Finally delete the user.
$users[$uid]->delete();
}
}
24.04.2026 | Michael Ebert