Community Documentation

nodeapi_example.module

  1. examples
    1. 6 nodeapi_example.module
    2. 7 nodeapi_example.module
    3. 8 nodeapi_example.module
  2. drupal
    1. 4.6 nodeapi_example.module
    2. 4.7 nodeapi_example.module
    3. 5 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.

Functions & methods

NameDescription
nodeapi_example_form_alterImplementation of hook_form_alter().
nodeapi_example_nodeapiImplementation of hook_nodeapi().
theme_nodeapi_example_ratingA custom theme function.
View source
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
<?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.
 */

/**
 * Implementation of hook_form_alter().
 *
 * By implementing this hook, we're able to modify any form. We'll only make
 * changes to two types: a node's content type configuration and edit forms.
 */
function nodeapi_example_form_alter($form_id, &$form) {
  // We're only modifying node forms, if the type field isn't set we don't need
  // to bother; otherwise, store it for later retrieval.
  if (isset($form['type'])) {
    $type = $form['type']['#value'];
  }
  elseif (isset($form['orig_type'])) {
    $type = $form['orig_type']['#value'];
  }
  else {
    return;
  }

  // The rating is enabled on a per node type basis. The variable used to store
  // this information is named named using both the name of this module, to
  // avoid namespace conflicts, and the node type, because we support multiple node
  // types.
  $enabled = variable_get('nodeapi_example_'. $type, 0);

  switch ($form_id) {
    // We need to have a way for administrators to indicate which content
    // types should have our rating field added. This is done by inserting a
    // checkbox in the node's content type configuration page. The variable will
    // be automatically saved by the settings form.
    case 'node_type_form':
      $form['workflow']['nodeapi_example_'. $type] = array(
        '#type' => 'radios',
        '#title' => t('NodeAPI Example Rating'),
        '#default_value' => $enabled,
        '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
        '#description' => t('Should this node have a rating attached to it?'),
      );
    break;
    case $type .'_node_form':
      // If the rating is enabled for this node type, we insert our control
      // into the form.
      if ($enabled) {
        $options = array(0 => t('Unrated'), 1, 2, 3, 4, 5);
        $form['nodeapi_example_rating'] = array(
          '#type' => 'select',
          '#title' => t('Rating'),
          '#default_value' => $form['#node']->nodeapi_example_rating,
          '#options' => $options,
          '#required' => TRUE,
          '#weight' => 0,
        );
      }
    break;
  }
}

/**
 * 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) {
    // 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 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':
      $object = db_fetch_object(db_query('SELECT rating FROM {nodeapi_example} WHERE nid = %d', $node->nid));
      return array('nodeapi_example_rating' => $object->rating);
      break;

    // Insert is called after the node has been validated and saved to the
    // database. It gives us a chance to create our own record in the database.
    case 'insert':
      db_query('INSERT INTO {nodeapi_example} (nid, rating) VALUES (%d, %d)', $node->nid, $node->nodeapi_example_rating);
      break;

    // Update is called when an existing node has been changed. Here, we use a
    // DELETE then an INSERT rather than an UPDATE. The reason is that a node
    // created before this module was installed won't already have a rating
    // saved so there would be nothing to update.
    case 'update':
      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;

    // Delete is called whn the node is being deleted, it gives us a chance
    // to delete the rating too.
    case 'delete':
      db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
      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':
      $node->content['nodeapi_example'] = array(
        '#value' => theme('nodeapi_example_rating', $node->nodeapi_example_rating),
        '#weight' => -1,
      );
      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;
}
Login or register to post comments