Reputation: 249
The task is to delete the entities, which satisfies some specified conditions. How can I do it ?
$current_user = \Drupal::currentUser()->id();
$storage = \Drupal::entityManager()->getStorage('context');
$query = $storage->getQuery()->condition('user_id', $current_user);
$query = $storage->getQuery()->delete();
$query->condition('user_id', $current_user);
$query->condition('key_text', $key);
$query->execute();
But the code returns: Fatal error: Call to undefined method Drupal\Core\Config\Entity\Query\Query::delete()
Upvotes: 2
Views: 6414
Reputation: 2886
Use the entity storage's delete()
method to delete multiple entities. There's no need to iterate over all of them.
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', 'tags');
$tids = $query->execute();
$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type);
$entities = $storage_handler->loadMultiple($tids);
$storage_handler->delete($entities);
Taken from https://stackoverflow.com/a/43786945/442022.
Upvotes: 2
Reputation: 29729
The error message is caused from the fact the class you are using for querying your configuration entity doesn't have a delete()
method. This is also true for content entities. The delete()
method is implemented by the entity, so the correct code is similar to the following one.
$storage = \Drupal::entityTypeManager()->getStorage('context');
$query = $storage->getQuery();
$ids = $query->condition('user_id', $current_user)
->condition('key_text', $key)
->execute();
foreach ($storage->loadMultiple($ids) as $entity) {
$entity->delete();
}
See entity.query service deprecated in favor of EntityStorageInterface::getQuery()
.
Upvotes: 0
Reputation: 56
To query entities you can use entityQuery, example below uses this.
// 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();
}
Upvotes: 4
Reputation: 636
You need to get your entities first before you can actually delete them. This method is also required for updating them or getting information from them. Hope the code below helps out :)
$current_user = \Drupal::currentUser()->id();
$ids = \Drupal::entityQuery('context')
->condition('user_id', $current_user)
->execute();
$itemsToDelete = $this->entityTypeManager->getStorage('context')
->loadMultiple($ids);
foreach ($itemsToDelete as $item) {
$item->delete();
}
Upvotes: 0