Forms API - Modify Form widgets with hook_field_widget_form_alter()
Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites
This documentation needs work. See "Help improve this page" in the sidebar.
Widgets are the parts that make up forms, like textarea widgets, file upload widgets etc.
By altering them you can add, remove or change parts.
You can alter individual form widgets using the following hook:
hook_field_widget_form_alter()
hook_field_widget_WIDGET_TYPE_form_alter
There are at least two ways to find this WIDGET_TYPE;
1. Checking used widgets using hook_field_widget_form_alter
Add the hook_field_widget_form_alter to your module/theme, like this;
function YOUR_THEME_field_widget_form_alter(&$element, &$form_state, $context) {
echo "\n YOUR_THEME_field_widget_form_alter";
echo "\n element: ";
print_r($element);
echo "\n widget type: ";
print_r($context['instance']['widget']['type']);
}
Checking the element you can find the widget you are looking for, then the $context['instance']['widget']['type'] contains the WIDGET_TYPE.
2. Checking hook_field_widget_info in the module
You can locate the hook_field_widget_info in the module which widget you want to alter.
Drupal core's File module file.field.inc file contains the following implementation. You can find the type as the keys of the array it returns.
function file_field_widget_info() {
return array(
'file_generic' => array( // <-- WIDGET_TYPE
'label' => t('File'),
'field types' => array('file'),
'settings' => array(
'progress_indicator' => 'throbber',
),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
'default value' => FIELD_BEHAVIOR_NONE,
),
),
);
}
Then you can add the more specific hook_field_widget_WIDGET_TYPE_form_alter().
The following implementation will move the validation description underneath the description, but only when the field name is "field_design_files"
function YOUR_THEME_field_widget_file_generic_form_alter(&$element, &$form_state, $context) {
if (isset($element['#field_name']) && $element['#field_name'] == 'field_design_files') {
$upload_validators = $element[0]['#upload_validators'];
$element['#description'] .= '<br/>' . theme('file_upload_help', array('description' => '', 'upload_validators' => $upload_validators));
$element['#file_upload_description'] = '';
}
}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion