5

How do I execute code before updating nodes?

I am looking for a hook to use in a custom module.

I have created a content type. What I need to do is execute a hook before updating any content. I want to keep the history of every content, so I want to execute some code before updating, which will compare previous and currently update record. If there is any change, I want to insert it in another table.

I also want to show that history on the content detail page.

  • Both of the current answers are correct. However, there are some nuanced differences between the different hooks because they get called at different parts in the node_save() process. You really need to read the docs (and the code for node_save()) to understand this. – mpdonadio Jul 16 '16 at 14:11
5

I use the Hook Post Action module because it's execute after the action. So you know that the node is really updated.

So this module introduces several new Drupal hooks to overcome this limitation

  • hook_entity_postsave
  • hook_entity_postinsert
  • hook_entity_postupdate
  • hook_entity_postdelete
  • hook_node_postsave
  • hook_node_postinsert
  • hook_node_postupdate
  • hook_node_postdelete

But, if you want you can use the hook_node_update.

To show info in the node page you can use the EVA module.

"Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

5

I think, hook_node_presave would help for your requirement. Act on a node being inserted or updated. This hook is invoked from node_save() before the node is saved to the database.

2

The hooks that are called before Drupal saves the node in the database are the following ones (in the order from the first to the last one):

They are all equivalent, since they get the object being saved.

Keep in mind that, since node_save() is using a database transaction, you cannot be sure the data is rolled back, or effectively saved in the database, until the last database operation is not completed.

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.