Drupal - What hook can I use for post-save actions?

The correct way of doing this is to respect Drupal's db transaction. If you want to do any database action in hook_node_insert you must consider that the node is not actually saved yet. which means if it fails and rolled back you end up with orphaned data in your database. So Drupal database API should be used and not direct query execution.

If you want to update the node itself in hook_node_insert, you can't because it's not possible to use node_save since the node is not yet saved in the database and calling it causes exception. One solution is to use register_shutdown_function function and passing nid, you can use node_load to make sure that it's really saved and then do any other action you may want on the new node.

function your_module_node_update($node){
  if($node->type == 'your_node'){
    register_shutdown_function('_your_module_post_insert',$node->nid);
  }
}

function _your_module_post_insert($nid) {
  $node = node_load($nid);
  if ($node) {
      node_save($node);
  }
} 

UPDATE: You can also find an easier alternative here https://stackoverflow.com/a/24035797/1726778


Looking at the comments on the question, it looks like the obvious solution is to use the hooks hook_node_insert() and hook_node_update().

I actually just did something very similar as described in the answer: I wrote a function that does what I want to be done every time a node is created/updated and then call it from each of those hooks. It works just fine.


There is a new drupal module, Hook Post Action, which adds the post save hooks. Let's try it to see if it works.

Tags:

Nodes

7

Hooks