node api hooks
Blog

How to use node api hooks in drupal 7

A hook is a PHP function that has a defined set of parameters and a specified result type. When you are implementing a hook in a module you are allowing it to interact with Drupal core. Drupal’s module system is based on the concept of hooks and the Node API in Drupal has a vast collection of hooks to help you work with nodes to add data or custom content. You can also extend node structures to include new fields or even establish new node types.

Underlying Concepts in Drupal API

The concepts in Drupal API are largely interdependent as one ceases to exist without the other. The Entity API is instrumental in creating lightweight and flexible Drupal solutions.

# Entity Type

The field system comes into play in Drupal 7 as you get to add fields to entity types like Nodes(content), Comment, User Profiles & Taxonomy Terms.

# Bundle

A subtype of an entity type, bundles are an implementation of the entity type to which you can attach the fields. But not all entity types have bundles, for instance Taxonomy does not have separate bundles(subtypes). Although many entity types do not allow bundles by default, you can still create bundles and with the help of the Field system add different fields to each bundle.

# Entity

An instance of a particular entity type like a taxonomy term or a bundle , you can load any entity using entity_load. The Entity API module lets you save or delete a function as there are options like entity_create(), entity_save(), entity_delete(), entity_view() and entity_access().

# Fields

A field is a primitive data type that can be added to entity types or bundles to help organize the content. It has custom validators and widgets for editing content and formatters to alter the display.

You can invoke several sets of hooks during the node operations based on the create, update, view and delete options. These hooks allow the modules to modify the base node operation and can be categorized into the following types :

# Node-type specific hooks
# All module hooks
# Field hooks
# Entity hooks

# Creating

  1. Function hook_node_presave
    You can invoke this hook from node_save() before the node is saved in the database. This hook is invoked when a node is being inserted or updated.
    /**
    *
    * Implements hook_node_presave()
    *
    * Create Page @ node/add/page, Page title will be saved with date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being inserted or updated.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_presave($node) {
      dpm($node);
      if ($node->type =='page' && $node->is_new) {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
        }
        // Remove $node->is_new to call at node updation time
    }
    
  2. Function hook_node_insert
    You can invoke this hook from node_save() after the database query meant to insert the node into the node table has been scheduled for execution. Before invoking this hook you will have to invoke type-specific hook_insert and call the field_attach_insert().

    You need to note that the write/update database queries executed from this hook are not committed immediately as you should not be relying on the data in the database when a transaction is still in process. If you want to trigger a mail or create any other event, you can use hook_node_insert for the same.

    /**
    *
    * Implements hook_node_insert()
    *
    * Act on a node being inserted.
    *
    *
    * @param $node
    * The node that is being inserted.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_insert($node) {
      dpm($node);
      if ($node->type =='page' && $node->is_new) {
        // after creating a new node the message is displayed with node id:
        drupal_set_message("Thanks for creating a page, your node id is" . $node->nid);
      }
      // Remove $node->is_new to call at node updation time
    }
    

# Updating

  1. Function hook_node_presave
    This hook acts on a node when it is being inserted or updated.  You can invoke the hook from  node_save() before saving the node to the database.
    /**
    *
    * Implements hook_node_presave()
    *
    * Create Page @ node/add/page, Page title will be saved with date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being inserted or updated.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_presave($node) {
      dpm($node);
      if ($node->type =='page') {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
      }
      // Remove $node->is_new to call at node updation time
    }
    
  2. Function hook_node_update
    You can invoke this node from node_save() after invoking the type-specific hook_update() and calling the field_attach_update().
    /**
    *
    * Implements hook_node_update()
    *
    * Update Page @ node/nid/edit , Page title will be saved with  current date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being updated.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_update($node) {
      dpm($node);
      if ($node->type =='page') {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
      }
      // In this node title with Updated date time extension 
    }
    

# View

  1. Function hook_node_view This hook acts on a node that is being assembled before being rendered.
    /**
    *
    * Implements hook_node_view()
    *
    * When View Page, Image style  will be change.
    *
    * Act on a node being viewed.
    *
    * @param $node
    * The node that is being view.
    *
    * @param $view_mode
    * The view mode of node.
    *
    * @param $langcode
    * The language of node.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_view($node, $view_mode, $langcode) { 
      if($view_mode == 'teaser') {
    	$node->content['field_image'][0]['#image_style'] = 'demo_image';
      }
    
  2. Function hook_node_view_alter
    You can call this hook after assembling the content in a structured array. This hook may be useful to carry out the processing part that requires you to complete building the entire node content structure. You can add a post_render callback using this hook if you want a module to act on the rendered HTML of the node instead of a structured content array.
    /**
    *
    * Implements hook_node_view_alter()
    *
    * when view page altering the weight.
    *
    * Act on a node being viewed.
    *
    * @param &$build
    * The node that is being view.
    * @ingroup node_api_hooks
    */
    function hook_node_view_alter(&$build) { 
      if ($build ['#view_mode'] == 'full' && isset($build ['field_image'])) {
        // Change its weight.
        $build ['field_image']['#weight'] = -10;
      }
    

# Delete

Function hook_node_delete

This hook is invoked from node_delete_multiple() after you have invoked the type specific hook_delete(). You need to invoke this hook prior to calling hook_entity_date and field_attach_delete() and before you remove the node from the node table in the database.

/**
*
* Implements hook_node_delete()
*
* Act on a node being delete.
*
*
* @param $node
* The node that is being delete.
*
* @ingroup node_api_hooks
*/
function hook_node_delete($node) {
  // after deleting a node the message is displayed.
  drupal_set_message(“Node Deleted Successfully”);
}

# Prepare

Function hook_node_prepare

This hook acts on a node object about to be shown on the add/edit form. After you have invoked the type specific hook_prepare() you can follow it up by invoking this hook from the node_object_prepare().

/**
*
* Implements hook_node_prepare()
*
* when view page altering the weight.
*
* Act on a node being insert or update.
*
* @param $node
* The node that is being insert or update.
* @ingroup node_api_hooks
*/

function hook_node_prepare($node) {
  if (!isset($node->comment)) {
    $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
  }
}

# Validate

  1. Function hook_node_validate
    This hook performs node validation before the creation or updation of a node. It is invoked from node validate after you have finished editing the node before previewing or submitting it. The standard validation steps are followed by the invocation of the type specific hook_validate() after which the node_validate is invoked.
    /**
    *
    * Implements hook_node_validate()
    *
    * When node is being inserted.
    *
    * Act on a node being inserted.
    *
    * @param $node
    * The node that is being inserted.
    *
    * @param $form
    * The node form.
    *
    * @param $form_state
    * The node form_state.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_validate($node, $form, &$form_state) {
      if (isset($node->field_date_end) && isset($node->field_date_start)) {
        if ($node->field_date_start > $node->field_date_end) {
          form_set_error('time', t('An event may not end before it starts.'));
        }
      }
    }
    /**
     *  Implements hook_node_load
    */
    function hook_node_load($nodes, $types) {
    global $user
    // check to see if the person viewing the node is the author, if not then hide the
    // annotation
    }
    
  2. Function hook_node_load
    This hook is used to add information that is not in the node/node revisions table. Although it adds information to the node object, it does not replace the information in the node tables which could interfere with the entity cache.
    /**
     *  Implements hook_node_load
    */
    function hook_node_load($nodes, $types) {
    global $user
    // check to see if the person viewing the node is the author, if not then hide the
    // annotation
     foreach ($nodes as $node) {
        if ($user->uid != $node->uid) {
           unset($node->article);
        }
     }
    

P.S.- In the examples above replace “hook’ with your module’s name.

Reference:
https://www.drupal.org/node/1261744
https://api.drupal.org/api/drupal/modules!node!node.api.php/group/node_api_hooks/7

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch