Drupal - Is there a node hook that runs AFTER a node is fully inserted into the database?

There isn't a hook that is called after the transaction is completed, as the code node_save() executes is executed during the transaction.

function node_save($node) {
  $transaction = db_transaction();

  try {

    // ...

  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }
}

If node_save() is called from node_form_submit() (the form submission handler for the node form), you can add a form submission handler that is called after that. It would be executed after the node is saved in the database.

What the documentation for hook_node_insert() means is that, since the data are not still saved in the database table, you cannot query a table making a join with the "node" table, as that table still contains the old data; in the same way, you should not call a function that queries the "node" table.


There is another way this can be achievable by adding your custom callback submit function in hook_form_alter which will execute after insert/update node.

E.g:
Check the following code which is for article.


/**
 * Implement hook_form_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    // Checking form_id
    if ($form_id == 'article_node_form') {
        // Adding custom callback function.
        $form['actions']['submit']['#submit'][] = '_callback_on_postsave';
    }
}

Now you can do your post save functionality in _callback_on_postsave function. E.g:


/**
 * General Callback for form_alter
 * 
 * @param type $form
 * @param type $form_state
 */
function _callback_on_postsave($form, &$form_state) {
    $nid = $form_state['values']['nid'];
    $node = node_load($nid);
    // Do your stuff here 
}


Easiest solution is to use this module:

Hook Post Action

It allows you to use new hooks:

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

Tags:

7

Hooks