nodeapi_example.module

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

Functions & methods

NameDescription
nodeapi_example_form_alterImplementation of hook_form_alter().
nodeapi_example_helpImplementation of hook_help().
nodeapi_example_nodeapiImplementation of hook_nodeapi().
theme_nodeapi_example_ratingA custom theme function.

File

developer/examples/nodeapi_example.module
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. * To store this extra information, we need an auxiliary database table.
  11. *
  12. * Database definition:
  13. * @code
  14. * CREATE TABLE nodeapi_example (
  15. * nid int(10) unsigned NOT NULL default '0',
  16. * rating int(10) unsigned NOT NULL default '0',
  17. * PRIMARY KEY (nid)
  18. * )
  19. * @endcode
  20. */
  21. /**
  22. * Implementation of hook_help().
  23. *
  24. * Throughout Drupal, hook_help() is used to display help text at the top of
  25. * pages. Some other parts of Drupal pages get explanatory text from these hooks
  26. * as well. We use it here to provide a description of the module on the
  27. * module administration page.
  28. */
  29. function nodeapi_example_help($section) {
  30. switch ($section) {
  31. case 'admin/modules#description':
  32. // This description is shown in the listing at admin/modules.
  33. return t('An example module showing how to extend existing content types.');
  34. }
  35. }
  36. /**
  37. * Implementation of hook_form_alter().
  38. *
  39. * By implementing this hook, we're able to modify any form. We'll only make
  40. * changes to two types: a node's content type configuration and edit forms.
  41. */
  42. function nodeapi_example_form_alter($form_id, &$form) {
  43. // We're only modifying node forms, if the type field isn't set we don't need
  44. // to bother.
  45. if (!isset($form['type'])) {
  46. return;
  47. }
  48. // Make a copy of the type to shorten up the code
  49. $type = $form['type']['#value'];
  50. // The rating is enabled on a per node type basis. The variable used to store
  51. // this information is named named using both the name of this module, to
  52. // avoid namespace conflicts, and the node, because we support multiple node
  53. // types.
  54. $enabled = variable_get('nodeapi_example_'. $type, 0);
  55. switch ($form_id) {
  56. // We need to have a way for administrators to indicate which content
  57. // types should have our rating field added. This is done by inserting a
  58. // checkbox in the node's content type configuration page. The variable will
  59. // be automatically saved by the settings form.
  60. case $type .'_node_settings':
  61. $form['workflow']['nodeapi_example_'. $type] = array(
  62. '#type' => 'radios',
  63. '#title' => t('NodeAPI Example Rating'),
  64. '#default_value' => $enabled,
  65. '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
  66. '#description' => t('Should this node have a rating attached to it?'),
  67. );
  68. break;
  69. case $type .'_node_form':
  70. // If the rating is enabled for this node type, we insert our control
  71. // into the form.
  72. if ($enabled) {
  73. $options = array(0 => t('Unrated'), 1, 2, 3, 4, 5);
  74. $form['nodeapi_example_rating'] = array(
  75. '#type' => 'select',
  76. '#title' => t('Rating'),
  77. '#default_value' => $form['#node']->nodeapi_example_rating,
  78. '#options' => $options,
  79. '#required' => TRUE,
  80. '#weight' => 0,
  81. );
  82. }
  83. break;
  84. }
  85. }
  86. /**
  87. * Implementation of hook_nodeapi().
  88. *
  89. * We will implement several node API operations here. This hook allows us to
  90. * act on all major node operations, so we can manage our additional data
  91. * appropriately.
  92. */
  93. function nodeapi_example_nodeapi(&$node, $op, $teaser, $page) {
  94. switch ($op) {
  95. // When the content editing form is submitted, we need to validate the input
  96. // to make sure the user made a selection, since we are requiring the rating
  97. // field. We have to check that the value has been set to avoid showing an
  98. // error message when a new blank form is presented. Calling form_set_error()
  99. // when the field is set but zero ensures not only that an error message is
  100. // presented, but also that the user must correct the error before being able
  101. // to submit the node.
  102. case 'validate':
  103. if (variable_get('nodeapi_example_'. $node->type, TRUE)) {
  104. if (isset($node->nodeapi_example_rating) && !$node->nodeapi_example_rating) {
  105. form_set_error('nodeapi_example_rating', t('You must rate this content.'));
  106. }
  107. }
  108. break;
  109. // Now we need to take care of loading one of the extended nodes from the
  110. // database. An array containing our extra field needs to be returned.
  111. case 'load':
  112. $object = db_fetch_object(db_query('SELECT rating FROM {nodeapi_example} WHERE nid = %d', $node->nid));
  113. return array('nodeapi_example_rating' => $object->rating);
  114. break;
  115. // Insert is called after the node has been validated and saved to the
  116. // database. It gives us a chance to create our own record in the database.
  117. case 'insert':
  118. db_query('INSERT INTO {nodeapi_example} (nid, rating) VALUES (%d, %d)', $node->nid, $node->nodeapi_example_rating);
  119. break;
  120. // Update is called when an existing node has been changed. Here, we use a
  121. // DELETE then an INSERT rather than an UPDATE. The reason is that a node
  122. // created before this module was installed won't already have a rating
  123. // saved so there would be nothing to update.
  124. case 'update':
  125. db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
  126. db_query('INSERT INTO {nodeapi_example} (nid, rating) VALUES (%d, %d)', $node->nid, $node->nodeapi_example_rating);
  127. break;
  128. // Delete is called whn the node is being deleted, it gives us a chance
  129. // to delete the rating too.
  130. case 'delete':
  131. db_query('DELETE FROM {nodeapi_example} WHERE nid = %d', $node->nid);
  132. break;
  133. // Finally, we need to take care of displaying our rating when the node is
  134. // viewed. This operation is called after the node has already been prepared
  135. // into HTML and filtered as necessary, so we know we are dealing with an
  136. // HTML teaser and body. We will inject our additional information at the front
  137. // of the node copy.
  138. //
  139. // Using nodeapi('view') is more appropriate than using a filter here, because
  140. // filters transform user-supplied content, whereas we are extending it with
  141. // additional information.
  142. case 'view':
  143. $node->body = theme('nodeapi_example_rating', $node->nodeapi_example_rating) . $node->body;
  144. $node->teaser = theme('nodeapi_example_rating', $node->nodeapi_example_rating) . $node->teaser;
  145. break;
  146. }
  147. }
  148. /**
  149. * A custom theme function.
  150. *
  151. * By using this function to format our rating, themes can override this presentation
  152. * if they wish; for example, they could provide a star graphic for the rating. We
  153. * also wrap the default presentation in a CSS class that is prefixed by the module
  154. * name. This way, style sheets can modify the output without requiring theme code.
  155. */
  156. function theme_nodeapi_example_rating($rating) {
  157. $output = '<div class="nodeapi_example_rating">';
  158. $options = array(
  159. 0 => t('Unrated'),
  160. 1 => t('Poor'),
  161. 2 => t('Needs improvement'),
  162. 3 => t('Acceptable'),
  163. 4 => t('Good'),
  164. 5 => t('Excellent'));
  165. $output .= t('Rating: %rating', array('%rating' => $options[(int)$rating]));
  166. $output .= '</div>';
  167. return $output;
  168. }
Login or register to post comments