How to validate deletion of custom entity? I'm making decently complex system, where many entities are referencing each other, and I don't want to allow any broken references. That is why I would like to implement validation at entity deletion, but where should I actually put it?

I know hook_form_validate runs on deletion, but it is hard to know if it has been invoked by deleting operation. I guess I can also do proper check in access callback of entity, however it isn't about access but validation, and I think that would be ugly workaround, as those are two different things. What would be a good place to put, a validation mechanism for deletion that would query the database to know if deletion of entity is possible?
There are a few options that may mean you don't have to code anything:


A patch for the entityreference module to add this type of cleanup: https://www.drupal.org/node/1368386
A module to handle cleanup: https://www.drupal.org/project/reference_delete
A sandbox module to handle cleanup: https://www.drupal.org/sandbox/drothstein/1775816


I would go with one of those if possible instead of writing custom code.

Seeing as you do want to run custom code though I would suggest reading up on how those solutions work and implementing something similar, but with your own custom logic.

For example in the issue in that first link they discuss 3 different ways of doing the deletions and some of the pros and cons of certain possible solutions, so I think that information would be useful to you in implementing your own.

Although I don't know your exact requirements I would suggest that doing this at the validation stage is not a good idea because it means it is possible for you to delete referencing entities at validation stage and then something could stop the deletion of the referenced entities after your code runs and you will have deleted the reference when you shouldn't have.

It should be done later than the validation stage.

That patch issue suggests maybe hook_entity_delete(), which I think is a better place for it, however in that issue they also mention possible page timeouts if there are lots of references to delete.

The code in those 2 modules may also be useful to you but I haven't read those.

EDIT: just had a quick look an the reference_delete module also uses the entity delete hook.