5

I was looking for a way to act on entity fields before they are saved, and I have noticed the following about hook_field_attach_presave(), and hook_entity_presave():

  • They take the same parameters, but in a different order.
  • They are both called when an entity is saved. For example, taxonomy_term_save() contains the following code.

    // Invoke hook_field_attach_presave().
    field_attach_presave('taxonomy_term', $term);
    
    module_invoke_all('taxonomy_term_presave', $term);
    module_invoke_all('entity_presave', $term, 'taxonomy_term');
    

    Similar code is present in comment_save().

    field_attach_presave('comment', $comment);
    
    // Allow modules to alter the comment before saving.
    module_invoke_all('comment_presave', $comment);
    module_invoke_all('entity_presave', $comment, 'comment');
    

As they get the same parameters, the code I should write to access the entity's fields is the same for both the hooks. This means that, apparently, there isn't any reason to choose one instead of the other hook.

When should I then implement one hook instead of the other? Are there cases where I would implement hook_field_attach_presave()?

8

It depends on what type of data you are trying to modify. Some entities are not fieldable. Those entities would never call hook_field_attach_presave() where as they would call hook_entity_presave().

If you are modifying an entity's base properties such as 'title', you should use hook_entity_presave(). If you are modifying the fields attached to an entity, you should use hook_field_attach_presave().

Keep in mind that other modules might be using these hooks as well. They would expect you to be making your modifications to the type of data in its respective hooks.

4

Personally, I would recommend to use the entity hooks. The reason is simple: The field attach hooks no longer existing in Drupal 8.

That both exist has mostly historical reasons. The field system and the field attach functions and hooks have been added to Drupal 7 before the entity concept even existed. Then the entity system has been gradually introduced but it was no longer possible to unify those hooks.

Drupal 8 no longer has a separate field storage API, this has been completely unified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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