1 node_hooks_example.module node_hooks_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 content type's 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.

Related topics

File

modules/examples/node_hooks_example/node_hooks_example.module, line 35
Hook implementations for the Node Hooks Example module.

Code

function node_hooks_example_form_alter(&$form, $form_state, $form_id) {
  $config = config('node_hooks_example.settings');

  if ($form_id == 'node_type_form') {
    // Alter the content type's configuration form to add our settings.
    $form['rating'] = array(
      '#type' => 'fieldset',
      '#title' => t('Rating settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#weight' => -1,
    );
    $form['rating']['node_hooks_example_node_type'] = array(
      '#type' => 'radios',
      '#title' => t('Node Hooks Example rating'),
      '#default_value' => $config->get('node_hooks_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?'),
    );
    // We add our custom submission handler to save the settings.
    $form['#submit'][] = 'node_hooks_example_node_type_form_submit';
  }
  elseif (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    // If rating is enabled for this content type, we insert our control into
    // the node edit form.
    $node = $form['#node'];
    if ($config->get('node_hooks_example_node_type_' . $form['type']['#value'])) {
      $form['node_hooks_example_rating'] = array(
        '#type' => 'select',
        '#title' => t('Rating'),
        '#default_value' => isset($node->node_hooks_example_rating) ? $node->node_hooks_example_rating : '',
        '#options' => array(0 => t('Unrated'), 1, 2, 3, 4, 5),
        '#required' => TRUE,
        '#weight' => 0,
      );
    }
  }
}