nodeapi_example_form_alter

5 nodeapi_example.module nodeapi_example_form_alter($form_id, &$form)
6 nodeapi_example.module nodeapi_example_form_alter(&$form, $form_state, $form_id)
7 nodeapi_example.module nodeapi_example_form_alter(&$form, $form_state, $form_id)
8 nodeapi_example.module nodeapi_example_form_alter(&$form, $form_state, $form_id)

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.

File

developer/examples/nodeapi_example.module, line 18
This is an example outlining how a module can be used to extend existing content types.

Code

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;
  }
}
Login or register to post comments