Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Forms API - Modify Form widgets with hook_field_widget_form_alter()

Last updated on
October 14, 2016 - 20:46

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'] .= '
' . theme('file_upload_help', array('description' => '', 'upload_validators' => $upload_validators)); $element['#file_upload_description'] = ''; } }