No Mind

It's the mind that makes you miss the shot

Archive for the ‘Drupal’ Category

November 15th, 2010 by Vivek Khurana

Revisioning in custom drupal module

Today I was faced a problem with revision handling in Drupal. I was developing a custom module which had some data stored in separate DB table.  The second requirement was to be able to do revisioning on the additional data.  All was fine till I got stuck in one place. When you revert to an older revision, Drupal invokes ‘update’ op for nodeapi. In both cases, revision revert as well as ‘update’, ‘presave’ op is also called. My requirement was to be able to pull the data for the previous version and store it as new version. But the question is how do I come to know if the ‘presave’ is called for new node, a node being edited or a revision being reverted ?

After some debugging I found, that when ‘presave’ op for nodeapi is called for node revert,  the $node object has vid for the version to be reverted to and when the node is being updated, the vid is the latest vid. So, fetching the current vid of the $node in ‘presave’ op and comparing it with the vid of the $node passed to presave operation, solved the problem. If the vid of the$node passed is same as the vid in the node table, then it is an update, else it is a node revert.

What about new node creation ? Well in case of new node creation the vid for $node is not set. :)

Here is the code snippet explaining the above logic

function mymodule_nodeapi(&$node, $op, $arg = 0){
   case 'presave':
      //node vid is set, means a this is edit or revision revert.
      $sql = 'select vid from {node} where nid=%d';
      $vid_db = db_fetch_array(db_query($sql,$node->vid));
      if($node->vid == $vid_db['vid']){
        //Execute edit logic.
        //Execute revision revert logic.