0

I'm doing a headless drupal cms.

I need to check the entities before they are deleted. I need to do it globally as the deletion of entities can take place via api (already written) or by using the cms as an administrator.

How can I overwrite the "delete" core operation? I've tried using hooks (hook_entity_predelete / hook_entity_delete) but they don't block delete operation. I need something like this:

if ($condition == true) 
  core_delete()
else
  disable_core_delete()

Thank you

  • I might be wrong, but I think you'll have to do this on a type-by-type basis. It would be something similar to drupal.stackexchange.com/questions/281940/… but overriding the delete method instead. You'd need a class per entity type for that solution – Clive Jun 6 '19 at 18:20
  • You can block deletion in an entity hook by throwing an exception. To avoid a generic 500 error catch this exception in an exception subscriber and return a json response containing a more specific error message. – 4k4 Jun 6 '19 at 18:31
1

The only way I can think to do this is to override the entity's storage handler in hook_entity_type_alter() with a storage handler that provides the delete functionality you want.

Something like

// You're going to want to be sure you're extending the entity's original
// storage handler.
class CustomStorageHandler extends EntityStorageBase {

  /*
   * {@inheritdoc}
   */
  public function delete(array $entities) {
    array_filter($entities, function ($entity) {
      // Do your logic to determine if the entity should be deleted here.
      // This example only allows entities with odd ids to be deleted.
      return (bool) $entity_id % 2;
    }
    parent::delete($entities)
  } 
}

It is probably a better idea, however, to use the entity's access system to prevent users from deleting entities as it will be confusing to try to delete an entity, then for that to not happen.

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.