nodeapi_example.module

Tracking 6.x-1.x branch
  1. drupal
    1. 4.6 documentation/developer/examples/nodeapi_example.module
    2. 4.7 documentation/developer/examples/nodeapi_example.module
    3. 5 documentation/developer/examples/nodeapi_example.module
    4. 6 contributions/examples/nodeapi_example/nodeapi_example.module
    5. 7 contributions/examples/nodeapi_example/nodeapi_example.module
    6. 8 contributions/examples/nodeapi_example/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().
nodeapi_example_themeImplementation of hook_theme().
theme_nodeapi_example_ratingA custom theme function.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * This is an example outlining how a module can be used to extend existing
  5. * content types.
  6. *
  7. * We will add the ability for each node to have a "rating," which will be a
  8. * number from one to five.
  9. */
  10. /**
  11. * @defgroup nodeapi_example Example: NodeAPI
  12. * @ingroup examples
  13. * @{
  14. * Modifying a node during its life-cycle. (drupal 6)
  15. *
  16. * This example demostrates 'piggy-backing' some data on the
  17. * node in another database table.
  18. *
  19. * This example is part of the Examples for Developers Project which you can download
  20. * and experiment with here: http://drupal.org/project/examples
  21. */
  22. /**
  23. * Implementation of hook_form_alter().
  24. *
  25. * By implementing this hook, we're able to modify any form. We'll only make
  26. * changes to two types: a node's content type configuration and edit forms.
  27. *
  28. * We need to have a way for administrators to indicate which content types
  29. * should have our rating field added. This is done by inserting a checkbox in
  30. * the node's content type configuration page, in the 'Workflow' group.
  31. */
  32. function nodeapi_example_form_alter(&$form, $form_state, $form_id) {
  33. if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
  34. // Alter the node type's configuration form to add our setting. We don't
  35. // need to worry about saving this value back to the variable, the form
  36. // we're altering will do it for us.
  37. $form['workflow']['nodeapi_example'] = array(
  38. '#type' => 'radios',
  39. '#title' => t('NodeAPI Example Rating'),
  40. '#default_value' => variable_get('nodeapi_example_'. $form['#node_type']->type, 0),
  41. '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
  42. '#description' => t('Should this node have a rating attached to it?'),
  43. );
  44. }
  45. // If the type and node field are set this may be a node edit form.
  46. elseif (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
  47. // If the rating is enabled for this node type, we insert our control
  48. // into the form.
  49. $node = $form['#node'];
  50. if (variable_get('nodeapi_example_'. $form['type']['#value'], 0)) {
  51. // Note that $form['nodeapi_example_rating'] will become
  52. // $node->nodeapi_example_rating in hook_nodeapi validate op
  53. // This also means that if there is a fieldgroup defined,
  54. // $form['group']['field'], that it will become $node->field.
  55. $form['nodeapi_example_rating'] = array(
  56. '#type' => 'select',
  57. '#title' => t('Rating'),
  58. '#default_value' => isset($node->nodeapi_example_rating) ? $node->nodeapi_example_rating : '',
  59. '#options' => array(0 => t('Unrated'), 1, 2, 3, 4, 5),
  60. '#required' => TRUE,
  61. '#weight' => 0,
  62. );
  63. }
  64. }
  65. }
  66. /**
  67. * Implementation of hook_nodeapi().
  68. *
  69. * We will implement several node API operations here. This hook allows us to
  70. * act on all major node operations, so we can manage our additional data
  71. * appropriately.
  72. */
  73. function nodeapi_example_nodeapi(&$node, $op, $teaser, $page) {
  74. switch ($op) {
  75. // When the content editing form is submitted, we need to validate the input
  76. // to make sure the user made a selection, since we are requiring the rating
  77. // field. We have to check that the value has been set to avoid showing an
  78. // error message when a new blank form is presented. Calling form_set_error()
  79. // when the field is set but zero ensures not only that an error message is
  80. // presented, but also that the user must correct the error before being able
  81. // to submit the node.
  82. case 'validate':
  83. if (variable_get('nodeapi_example_'. $node->type, TRUE)) {
  84. if (isset($node->nodeapi_example_rating) && !$node->nodeapi_example_rating) {
  85. form_set_error('nodeapi_example_rating', t('You must rate this content.'));
  86. }
  87. }
  88. break;
  89. // Now we need to take care of loading one of the extended nodes from the
  90. // database. An array containing our extra field needs to be returned.
  91. case 'load':
  92. // we match against vid in order to keep up with the current revision
  93. $rating = db_result(db_query('SELECT rating FROM {nodeapi_example} WHERE vid = %d', $node->vid));
  94. return array('nodeapi_example_rating' => $rating);
  95. break;
  96. // Insert is called after the node has been validated and saved to the
  97. // database. It gives us a chance to create our own record in the database.
  98. case 'insert':
  99. if (variable_get('nodeapi_example_'. $node->type, 0)) {
  100. db_query('INSERT INTO {nodeapi_example} (nid, vid, rating) VALUES (%d, %d, %d)', $node->nid, $node->vid, $node->nodeapi_example_rating);
  101. }
  102. break;
  103. // Update is called when an existing node has been changed. Here, we use a
  104. // DELETE then an INSERT rather than an UPDATE. The reason is that a node
  105. // created before this module was installed won't already have a rating
  106. // saved so there would be nothing to update.
  107. case 'update':
  108. if (variable_get('nodeapi_example_'. $node->type, 0)) {
  109. db_query('DELETE FROM {nodeapi_example} WHERE vid = %d', $node->vid);
  110. db_query('INSERT INTO {nodeapi_example} (nid, vid, rating) VALUES (%d, %d, %d)', $node->nid, $node->vid, $node->nodeapi_example_rating);
  111. }
  112. break;
  113. // Delete is called when the node is being deleted, it gives us a chance
  114. // to delete the rating too.
  115. // This will delete all revisions as well.
  116. case 'delete':
  117. db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
  118. break;
  119. // When a node revision is deleted, we need to remove the corresponding
  120. // record from our table. The only way to handle revision deletion is by
  121. // implementing hook_nodeapi().
  122. case 'delete revision':
  123. // Notice that we're matching a single revision based on the node's vid.
  124. db_query('DELETE FROM {nodeapi_example} WHERE vid = %d', $node->vid);
  125. break;
  126. // Finally, we need to take care of displaying our rating when the node is
  127. // viewed. This operation is called after the node has already been prepared
  128. // into HTML and filtered as necessary, so we know we are dealing with an
  129. // HTML teaser and body. We will inject our additional information at the front
  130. // of the node copy.
  131. //
  132. // Using nodeapi('view') is more appropriate than using a filter here, because
  133. // filters transform user-supplied content, whereas we are extending it with
  134. // additional information.
  135. case 'view':
  136. if (variable_get('nodeapi_example_'. $node->type, 0)) {
  137. $node->content['nodeapi_example'] = array(
  138. '#value' => theme('nodeapi_example_rating', $node->nodeapi_example_rating),
  139. '#weight' => -1,
  140. );
  141. }
  142. break;
  143. }
  144. }
  145. /**
  146. * Implementation of hook_theme().
  147. *
  148. * This lets us tell Drupal about our theme functions and their arguments.
  149. */
  150. function nodeapi_example_theme() {
  151. return array(
  152. 'nodeapi_example_rating' => array(
  153. 'arguments' => array('rating'),
  154. ),
  155. );
  156. }
  157. /**
  158. * A custom theme function.
  159. *
  160. * By using this function to format our rating, themes can override this presentation
  161. * if they wish; for example, they could provide a star graphic for the rating. We
  162. * also wrap the default presentation in a CSS class that is prefixed by the module
  163. * name. This way, style sheets can modify the output without requiring theme code.
  164. */
  165. function theme_nodeapi_example_rating($rating) {
  166. $options = array(
  167. 0 => t('Unrated'),
  168. 1 => t('Poor'),
  169. 2 => t('Needs improvement'),
  170. 3 => t('Acceptable'),
  171. 4 => t('Good'),
  172. 5 => t('Excellent'));
  173. $output = '<div class="nodeapi_example_rating">';
  174. $output .= t('Rating: %rating', array('%rating' => $options[(int) $rating]));
  175. $output .= '</div>';
  176. return $output;
  177. }
  178. /**
  179. * @} End of "defgroup nodeapi_example".
  180. */