Skip to content

Instantly share code, notes, and snippets.

@aytee
Last active February 14, 2022 19:07
Show Gist options
  • Save aytee/7d8523234780ba7f7aba7dc53104cdf7 to your computer and use it in GitHub Desktop.
Save aytee/7d8523234780ba7f7aba7dc53104cdf7 to your computer and use it in GitHub Desktop.
Drupal 9 Search and Delete Entities
Generic:
// Get all users with email containing "xyz"
$query = \Drupal::entityQuery('user')
->condition('mail', "XYZ", 'CONTAINS');
$uids = $query->execute();
// Load these entities ($uids) in our case using storage controller.
// We call loadMultiple method and give $uids array as argument.
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('user')
->loadMultiple($uids);
// Loop through our entities and deleting them by calling by delete method.
foreach ($itemsToDelete as $item) {
$item->delete();
}
//Profiles:
// Get all profiles owned by anonymous
$query = \Drupal::entityQuery('profile')
->condition('uid', 0, );
$profiles = $query->execute();
// Load these entities ($profiles) in our case using storage controller.
// We call loadMultiple method and give $profiles array as argument.
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('profile')
->loadMultiple($profiles);
// Loop through our entities and deleting them by calling by delete method.
foreach ($itemsToDelete as $item) {
$item->delete();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment