I have a script that sets up a specific url for a user when they register on a site,

There are no real issues at the moment, but I need to cater for those 'unlikely things to happen that happen 20 times when not prepared for'

Part of this is deleting certain user data when a user deleted (or requests to delete) their account.

I have set up a trigger which at the moment compares the list of uid's with those in the table I wish to delete but this is laborious because every time a user is deleted it has to loop through them all,

What I need is the uid of the user being deleted passed to the trigger so that the trigger than then go directly to the table and delete all user data belonging to uid x.

Is there a method or a way pf programmatically discovering at run time, which uid has been deleted (or being deleted).

The main problem is that the trigger is supposed to be fired after the user is deleted, but it seems to fire beforehand because when I run tests the user data is not removed until the next time, so this is what is happening:

User A is created
User A stores data
User A is deleted 
- trigger fired, nothing happens
User B created
User B stores data
User B deleted 
- trigger fired User A's data removed, User B's data remains until User C is deleted.

so comparing the user table id's with the id's of the table is useless because until after the user has been deleted their uid is still present in the users table.

Any help or pointers on how to get this uid would help me a GREAT deal :)


Sounds like a job for hook_user_delete():

Respond to user deletion.

This hook is invoked from user_delete_multiple() before field_attach_delete() is called and before users are actually removed from the database.

Modules should additionally implement hook_user_cancel() to process stored user data for other account cancellation methods.


function hook_user_delete($account) {
  db_delete('mytable')->condition('uid', $account->uid)->execute();
  • Awesome, thank you for that, I wasnt aware that hook_user_delete() existed, I had to think really laterally to come up with a workaround m but its clunky and ugly, I am glad I can use something like this to slean the functions up. – JimmyBorofan May 12 '15 at 20:56

Drupal 8 uses a different hook, but same syntax: hook_ENTITY_TYPE_delete.

Respond to entity deletion of a particular type.

This hook runs once the entity has been deleted from the storage.


function hook_ENTITY_TYPE_delete(Drupal\Core\Entity\EntityInterface $entity) {
  // Delete the entity's entry from a fictional table of all entities.
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())

Your Answer

