Same filename and directory in other branches
  1. 4.7.x developer/examples/nodeapi_example.module
  2. 5.x developer/examples/nodeapi_example.module

This is an example outlining how a module can be used to extend existing content types.

We will add the ability for each node to have a "rating," which will be a number from one to five.

To store this extra information, we need an auxiliary database table.

Database definition:


  CREATE TABLE nodeapi_example (
    nid int(10) unsigned NOT NULL default '0',
    rating int(10) unsigned NOT NULL default '0',
    PRIMARY KEY (nid)
  )

File

developer/examples/nodeapi_example.module
View source
<?php

/**
 * @file
 * This is an example outlining how a module can be used to extend existing
 * content types.
 *
 * We will add the ability for each node to have a "rating," which will be a
 * number from one to five.
 *
 * To store this extra information, we need an auxiliary database table.
 *
 * Database definition:
 * @code
 *   CREATE TABLE nodeapi_example (
 *     nid int(10) unsigned NOT NULL default '0',
 *     rating int(10) unsigned NOT NULL default '0',
 *     PRIMARY KEY (nid)
 *   )
 * @endcode
 */

/**
 * Implementation of hook_help().
 *
 * Throughout Drupal, hook_help() is used to display help text at the top of
 * pages. Some other parts of Drupal pages get explanatory text from these hooks
 * as well. We use it here to provide a description of the module on the
 * module administration page.
 */
function nodeapi_example_help($section) {
  switch ($section) {
    case 'admin/modules#description':

      // This description is shown in the listing at admin/modules.
      return t('An example module showing how to extend existing content types.');
  }
}

/**
 * Implementation of hook_nodeapi().
 *
 * We will implement several node API operations here. This hook allows us to
 * act on all major node operations, so we can manage our additional data
 * appropriately.
 */
function nodeapi_example_nodeapi(&$node, $op, $teaser, $page) {
  switch ($op) {

    // First, we need to have a way for administrators to indicate which content
    // types can have our rating field added. The "settings" operation allows us to
    // place this option on the content type configuration page. Note that the
    // variable we use to store this information needs to be named using both the
    // name of this module (to avoid namespace conflicts) and the name of the node
    // type the setting is for.
    case 'settings':
      $settings = array();
      $settings[t('rateable')] = form_checkbox('', 'nodeapi_example_' . $node->type, 1, variable_get('nodeapi_example_' . $node->type, TRUE));
      return $settings;

    // Next we provide a way for users to enter the information for our new field.
    // The "form pre" operation allows us to insert information in front of the
    // rest of the form; we could instead use "form post" or "form admin" to place
    // the input element elsewhere.
    case 'form pre':
      $form = '';
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        $options = array(
          0 => t('Unrated'),
          1 => t('Poor'),
          2 => t('Needs improvement'),
          3 => t('Acceptable'),
          4 => t('Good'),
          5 => t('Excellent'),
        );
        $form .= form_select(t('Rating'), 'nodeapi_example_rating', $node->nodeapi_example_rating, $options, NULL, 0, FALSE, TRUE);
      }
      return $form;

    // When the content editing form is submitted, we need to validate the input
    // to make sure the user made a selection, since we are requiring the rating
    // field. We have to check that the value has been set to avoid showing an
    // error message when a new blank form is presented. Calling form_set_error()
    // when the field is set but zero ensures not only that an error message is
    // presented, but also that the user must correct the error before being able
    // to submit the node.
    case 'validate':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        if (isset($node->nodeapi_example_rating) && !$node->nodeapi_example_rating) {
          form_set_error('nodeapi_example_rating', t('You must rate this content.'));
        }
      }
      break;

    // Now that the form has been properly completed, it is time to commit the new
    // data to the database.
    case 'insert':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        db_query('INSERT INTO {nodeapi_example} (nid, rating) VALUES (%d, %d)', $node->nid, $node->nodeapi_example_rating);
      }
      break;

    // If the form was called to edit an existing node rather than create a new
    // one, this operation gets called instead. We use a DELETE then INSERT rather
    // than an UPDATE just in case the rating didn't exist for some reason.
    case 'update':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
        db_query('INSERT INTO {nodeapi_example} (nid, rating) VALUES (%d, %d)', $node->nid, $node->nodeapi_example_rating);
      }
      break;

    // If the node is being deleted, we need this opportunity to clean up after
    // ourselves.
    case 'delete':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
      }
      break;

    // Now we need to take care of loading one of the extended nodes from the
    // database. An array containing our extra field needs to be returned.
    case 'load':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        $object = db_fetch_object(db_query('SELECT rating FROM {nodeapi_example} WHERE nid = %d', $node->nid));
        return array(
          'nodeapi_example_rating' => $object->rating,
        );
      }
      break;

    // Finally, we need to take care of displaying our rating when the node is
    // viewed. This operation is called after the node has already been prepared
    // into HTML and filtered as necessary, so we know we are dealing with an
    // HTML teaser and body. We will inject our additional information at the front
    // of the node copy.
    //
    // Using nodeapi('view') is more appropriate than using a filter here, because
    // filters transform user-supplied content, whereas we are extending it with
    // additional information.
    case 'view':
      if (variable_get('nodeapi_example_' . $node->type, TRUE)) {
        $node->body = theme('nodeapi_example_rating', $node->nodeapi_example_rating) . $node->body;
        $node->teaser = theme('nodeapi_example_rating', $node->nodeapi_example_rating) . $node->teaser;
      }
      break;
  }
}

/**
 * A custom theme function.
 *
 * By using this function to format our rating, themes can override this presentation
 * if they wish; for example, they could provide a star graphic for the rating. We
 * also wrap the default presentation in a CSS class that is prefixed by the module
 * name. This way, style sheets can modify the output without requiring theme code.
 */
function theme_nodeapi_example_rating($rating) {
  $output = '<div class="nodeapi_example_rating">';
  $options = array(
    0 => t('Unrated'),
    1 => t('Poor'),
    2 => t('Needs improvement'),
    3 => t('Acceptable'),
    4 => t('Good'),
    5 => t('Excellent'),
  );
  $output .= t('Rating: %rating', array(
    '%rating' => $options[(int) $rating],
  ));
  $output .= '</div>';
  return $output;
}

Functions

Namesort descending Description
nodeapi_example_help Implementation of hook_help().
nodeapi_example_nodeapi Implementation of hook_nodeapi().
theme_nodeapi_example_rating A custom theme function.