Search code examples
drupaldrupal-7nodesupdatesinsertion

Drupal 7 : difference between node insertion / node update


I've created a module to get server informations. So i've created a specific content type.To collect all the data one field is required the hostname.

I use the function hook_node_presave() to add information such as CPU, RAM, etc in my node. So when I create a new node, I specify manually the name and drupal call the function hook_node_presave() which automatically insert the other information in my node.

I have also setted a cron to update every node informations periodically. To do this I use hook_cron(). I manage to load every node thanks to node_load(), to update them, but when I want to save them using node_save() Drupal call logically hook_node_presave()... But don't want this to happen : because this function update once more the information !

How can I differenciate new node and updated node in hook_node_presave()? Otherwhise which function can I call to avoid this problem ?

Thanks for your help


Solution

  • Just check the is_new member on the node object or for the existence of a nid:

    function MYMODULE_node_presave($node) {
      if ($node->is_new) {
        // ...
      }
     
      // Equivalent to
      if (empty($node->nid)) {
        // ...
      }
    }
    

    Per the user_save() docs:

    Parameters

    $node: The $node object to be saved. If $node->nid is omitted (or $node->is_new is TRUE), a new node will be added.