Brought to you by molecularsciences.org.
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
This publication may not be redistributed without this notice.

nodeapi explained

Nodeapi is a very useful hook which allows modules to react to actions affecting all kinds of nodes regardless of the module defining the node. Like most things in drupal, nodeapi is very powerful but difficult to understand. Here I present some examples to reduce the learning curve.

For our examples we would work on a custom node type called "theory".

Administer > Content Management > Content types > Add Content Type

Type "theory" in the first two fields, fill out the remainder of the form as you wish and click on "Save content type". A "theory" menu should appear under the Create content menu. Click on it and create a node of type theory.

Display a line of text with nodeapi

Inside the modules directory create a directory called "nodi". Create a nodi.info file, paste the following text and save it.

name = nodi
description = nodi
package = Core - optional
core = 6.x
version = "6.3"
project = "nodi"

Create a nodi.module file, paste the following text and save it.

function nodi_perm() { 
  return array('use nodi'); 
} 

function nodi_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    // when in view mode as opposed to edit, delete, etc.
    case 'view':
      // if the node type is theory. we don't want to modify all nodes.
      if($node->type == 'theory') {
        // append the following text to the body
        $node->content['body']['#value'] .= 'body added by nodi module using nodeapi!';
      }
      break;
  }
}

Enable the nodi module and set permissions.

Administer > Site Building > Modules
Administer > User Management > Permissions

Now go to view the theory node you created in the beginning. You should see "body added by nodi module using nodeapi!" at the end of body text.

Using nodeapi when deleting a node

function nodi_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)
{
  switch ($op) {
    case 'delete':
      if($node->type == 'theory') {
        drupal_set_message('You just deleted theory node.');
      }
    break;
  }
}

This would display a message when a node is deleted.

Other options include insert, load, prepare, print, presave, update and validate.