I am using the user.data service to store additional data for users. I would like to trigger some custom functionality each time the user.data is changed. I can't find any hook or event that I could use. Is there any way to achieve this?

  • 1
    Can you confirm whether you are talking about the user.data service or updating user properties/fields?
    – mpdonadio
    Jun 25, 2018 at 19:25
  • Could you provide a sample use case of what exactly you are trying to do and when?
    – leymannx
    Jun 25, 2018 at 19:34
  • I'm talking about the user.data service. One of the use cases is the following ones: I'm using search api and extended it to also index certain user.data. Now when the user.data changes I need to update the index. Everything works fine, except that I have to take cate by myself to update the index each time I update the user.data. It would be much easier if there would be ahook or event, so that I don't need to take care of updating the index throught my code. I'm using user.data quite a lot throught my code.
    – Peter
    Jun 25, 2018 at 21:54

1 Answer 1


hook_entity_presave (hook_ENTITY_TYPE_presave)

Act on an entity before it is created or updated.

You can get the original entity object from $entity->original when it is an update of the entity.

hook_entity_update (hook_ENTITY_TYPE_update)

Respond to updates to an entity.

This hook runs once the entity storage has been updated. Note that hook implementations may not alter the stored entity data. Get the original entity object from $entity->original.

Here's a sample implemented by system.module:

 * Implements hook_ENTITY_TYPE_presave() for user entities.
function system_user_presave(UserInterface $account) {
  $config = \Drupal::config('system.date');
  if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
    $account->timezone = $config->get('timezone.default');
  • I don't think UserData is an entity. So these won't work.
    – Peter
    Jun 25, 2018 at 16:09
  • If the system module does this, its safe to say it works. It is using hook_user_presave, so it knows the argument being passed implements UserInterface. Try it.
    – Kevin
    Jun 25, 2018 at 16:51
  • UserData is a service that is more or less a a key/value store in the users_data table.
    – mpdonadio
    Jun 25, 2018 at 19:12
  • @mpdonadio - I'm getting confused. Did I misunderstand the question?
    – leymannx
    Jun 25, 2018 at 19:22
  • @leymannx Maybe? My read was it was about the user.data service not updating user properties/fields. Contact form is the only real place (?) it is used in core proper.
    – mpdonadio
    Jun 25, 2018 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.