1 nodeapi_example.module nodeapi_example_form_alter(&$form, $form_state, $form_id)

Implements 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 radios in the node's content type configuration page.

Changes made by this hook will be shown when editing the settings of any content type.

Optionally, hook_form_FORM_ID_alter() could be used with the function name nodeapi_example_form_node_type_form_alter

Related topics

File

modules/examples/nodeapi_example/nodeapi_example.module, line 40
Module implementation for nodeapi_example module.

Code

function nodeapi_example_form_alter(&$form, $form_state, $form_id) {
  // We will be saving this setting to a configuration file.
  $config = config('nodeapi_example.settings');

  // First, check for the node type configuration form.
  if ($form_id == 'node_type_form') {
    // Alter the node type's configuration form to add our setting. 
    $form['rating'] = array(
      '#type' => 'fieldset',
      '#title' => t('Rating settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#weight' => -1,
    );

    $form['rating']['nodeapi_example_node_type'] = array(
      '#type' => 'radios',
      '#title' => t('NodeAPI Example Rating'),
      '#default_value' => $config->get('nodeapi_example_node_type_' . $form['#node_type']->type),
      '#options' => array(
        FALSE => t('Disabled'),
        TRUE => t('Enabled'),
      ),
      '#description' => t('Should this node have a rating attached to it?'),
    );
    // Here we add our custom submit function (handler) to save the added
    // settings.
    $form['#submit'][] = 'nodeapi_example_node_type_form_submit';
  }
  // Here we check to see if the type and node field are set. If so, it could
  // be a node edit form.
  elseif (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 ($config->get('nodeapi_example_node_type_' . $form['type']['#value'])) {
      $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,
      );
    }
  }
}