0

I have a user_territories field which can have multiple values. I need to run a certain action when this field value is changed from the user entity, not when other fields are changed.

How can I write a condition for that?

I need to perform an action when taxonomy field is deleted and another action when a taxonomy field is added. How can I achieve this?
Is hook_user_presave() the best hook to fulfill this?

2
  • We cannot say which hook is the best hook to achieve what you described: It depends on what action you need to perform and on which entity. In any case, there isn't a best hook. Do you then need to perform an action when a taxonomy field is added/removed to the User entity, or when a value is added/removed from a taxonomy field for the User entity?
    – apaderno
    Aug 3, 2022 at 7:24
  • when a value is added/removed from a taxonomy field for the User entity
    – Rifas Ali
    Aug 3, 2022 at 10:57

1 Answer 1

1

Yes, hook_user_presave() is the way to go.

Here's an example for a standard field. You'll need to tweak this a bit for a taxonomy entity reference.

function MYMODULE_user_presave(UserBundle $user): void {
  // If the user is new, then the value hasn't changed.
  if (!$user->isNew()) {
    $field_value_current = $user->get('my_field_name')->value;
    $field_value_previous = $user->original->get('my_field_name')->value;
    if ($field_value_current !== $field_value_previous) {
      // Do something
    }
  }
}
7
  • Thanks I will check that. But how can I know the taxonomy term is deleted or added? @patrick-kenny
    – Rifas Ali
    Aug 3, 2022 at 7:13
  • The value of the field changes. If $previous is NULL or '' and $current is set, value was added. If $previous is set and $current is NULL or '', value was deleted. Aug 3, 2022 at 7:24
  • That's cool. Thanks for the help.
    – Rifas Ali
    Aug 3, 2022 at 7:27
  • 1
    When a taxonomy term is removed from a taxonomy reference field, the taxonomy term isn't necessarily deleted. It will be deleted when the taxonomy term is not used from any taxonomy reference field. If @RifasAli needs to know when a taxonomy term is deleted, the code needs to be different.
    – apaderno
    Aug 3, 2022 at 7:27
  • @apaderno Good point. In my comment, I said "deleted" when I should have said "the value of the field was unset." Aug 3, 2022 at 7:28

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