ford
ford

Reputation: 1887

How do I execute an action in drupal after each time a node is saved?

I'm developing an Action in Drupal which is supposed to activate after saving a node, exporting content to XML (which includes data from the node that was just saved), using the "Trigger: After saving an updated post" trigger.

Unfortunately this action actually happens right before the information from the recently saved post is saved to the database. ie. when looking at the XML later, I find that the most recent change I made was not included. Saving after editing a different node will restore the previously missing data.

How can I get my action to fire after the saving process is complete?

Upvotes: 6

Views: 3919

Answers (2)

Henrik Opel
Henrik Opel

Reputation: 19441

There is a common pitfall in this context, regardless of whether you use a trigger or Mike Munroes suggestion via hook_nodeapi() (+1):

As long as your export logic runs on the same page cycle that processed the update, and it uses node_load() to get the nodes data, node_load()might return a statically cached version of the node from before the update that does not contain the changes yet. If this is the problem in your case, you can work around it in two ways:

  1. Force a reset of the static node cache by passing TRUE as the third parameter to node_load(). This would ensure that the node gets populated freshly from the database (at the price of some additional db queries, so be aware of a potential performance impact).
  2. If you are going the hook_nodeapi() route, you could avoid the need to call node_load() altogether if you pass the $node object available there directly to your export function, as it will be a representation of the updated state.

Upvotes: 6

Mike Munroe
Mike Munroe

Reputation: 846

You should use hook_nodeapi and invoke your action on insert and update. Look over the documenation for hook_nodeapi for other instances where you could call your export logic.

example where module name = 'export_to_xml':

 /**
 * Implementation of hook_nodeapi().
 */
function export_to_xml_nodeapi(&$node, $op, $a3, $a4) {
  if ($op == 'update' || $op == 'insert') {
    export_logic_function();
  }
}

Upvotes: 5

Related Questions