Contributions API

nodeapi_example_form_alter

Definition

nodeapi_example_form_alter(&$form, $form_state, $form_id)
documentation/examples/nodeapi_example.module, line 22

Description

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.

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.

Code

<?php
function nodeapi_example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
    // Alter the node type's configuration form to add our setting. We don't
    // need to worry about saving this value back to the variable, the form
    // we're altering will do it for us.
    $form['workflow']['nodeapi_example'] = array(
      '#type' => 'radios',
      '#title' => t('NodeAPI Example Rating'),
      '#default_value' => variable_get('nodeapi_example_'. $form['#node_type']->type, 0),
      '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
      '#description' => t('Should this node have a rating attached to it?'),
    );
  }
  // If the type and node field are set this may be a node edit form.
  else if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
    // If the rating is enabled for this node type, we insert our control
    // into the form.
    $node = $form['#node'];
    if (variable_get('nodeapi_example_'. $form['type']['#value'], 0)) {
      $form['nodeapi_example_rating'] = array(
        '#type' => 'select',
        '#title' => t('Rating'),
        '#default_value' => isset($node->nodeapi_example_rating) ? $node->nodeapi_example_rating : '',
        '#options' => array(0 => t('Unrated'), 1, 2, 3, 4, 5),
        '#required' => TRUE,
        '#weight' => 0,
      );
    }
  }
}
?>