function nodeapi_example_form_alter in Examples for Developers 7
Same name and namespace in other branches
- 6 nodeapi_example/nodeapi_example.module \nodeapi_example_form_alter()
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
- nodeapi_example/
nodeapi_example.module, line 44 - Module implementation for nodeapi_example module.
Code
function nodeapi_example_form_alter(&$form, $form_state, $form_id) {
// 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. 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['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' => variable_get('nodeapi_example_node_type_' . $form['#node_type']->type, FALSE),
'#options' => array(
FALSE => t('Disabled'),
TRUE => 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_node_type_' . $form['type']['#value'], FALSE)) {
$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,
);
}
}
}