Get the user id for triggers when deleting a user

by JimmyBorofan   Last Updated January 07, 2018 19:07 PM

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 :)



Answers 2


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.

e.g.

function hook_user_delete($account) {
  db_delete('mytable')->condition('uid', $account->uid)->execute();
}
Clive
Clive
May 11, 2015 19:03 PM

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.

Example:

function hook_ENTITY_TYPE_delete(Drupal\Core\Entity\EntityInterface $entity) {
  // Delete the entity's entry from a fictional table of all entities.
  db_delete('example_entity')
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}
Chris Happy
Chris Happy
January 07, 2018 18:17 PM

Related Questions






How to change a field value with a Rules Action?

Updated August 25, 2016 08:04 AM