8.5.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.0.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.1.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.2.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.3.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.4.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
8.6.x field.api.php hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
7.x field.api.php hook_field_widget_form_alter(&$element, &$form_state, $context)

Alter forms for field widgets provided by other modules.

This hook can only modify individual elements within a field widget and cannot alter the top level (parent element) for multi-value fields. In most cases, you should use hook_field_widget_multivalue_form_alter() instead and loop over the elements.

Parameters

$element: The field widget form element as constructed by \Drupal\Core\Field\WidgetBaseInterface::form().

$form_state: The current state of the form.

$context: An associative array containing the following key-value pairs:

  • form: The form structure to which widgets are being attached. This may be a full form structure, or a sub-element of a larger form.
  • widget: The widget plugin instance.
  • items: The field values, as a \Drupal\Core\Field\FieldItemListInterface object.
  • delta: The order of this item in the array of subelements (0, 1, 2, etc).
  • default: A boolean indicating whether the form is being shown as a dummy form to set default values.

See also

\Drupal\Core\Field\WidgetBaseInterface::form()

\Drupal\Core\Field\WidgetBase::formSingleElement()

hook_field_widget_WIDGET_TYPE_form_alter()

hook_field_widget_multivalue_form_alter()

Related topics

1 function implements hook_field_widget_form_alter()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

field_test_field_widget_form_alter in core/modules/field/tests/modules/field_test/field_test.module
Implements hook_field_widget_form_alter().

File

core/modules/field/field.api.php, line 193
Field API documentation.

Code

function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {

  // Add a css class to widget form elements for all fields of type mytype.
  $field_definition = $context['items']
    ->getFieldDefinition();
  if ($field_definition
    ->getType() == 'mytype') {

    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}