function nodeapi_example_form_alter

Same name in other branches
  1. 7.x-1.x nodeapi_example/nodeapi_example.module \nodeapi_example_form_alter()

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, in the 'Workflow' group.

Related topics

File

nodeapi_example/nodeapi_example.module, line 35

Code

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?'),
        );
    }
    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 (variable_get('nodeapi_example_' . $form['type']['#value'], 0)) {
            // Note that $form['nodeapi_example_rating'] will become
            // $node->nodeapi_example_rating in hook_nodeapi validate op
            // This also means that if there is a fieldgroup defined,
            // $form['group']['field'], that it will become $node->field.
            $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,
            );
        }
    }
}