You are here

public static function OptionsWidgetBase::validateElement in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsWidgetBase.php \Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase::validateElement()

Form validation handler for widget elements.

Parameters

array $element: The form element.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

1 method overrides OptionsWidgetBase::validateElement()
ModerationStateWidget::validateElement in core/modules/content_moderation/src/Plugin/Field/FieldWidget/ModerationStateWidget.php
Form validation handler for widget elements.

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsWidgetBase.php, line 69

Class

OptionsWidgetBase
Base class for the 'options_*' widgets.

Namespace

Drupal\Core\Field\Plugin\Field\FieldWidget

Code

public static function validateElement(array $element, FormStateInterface $form_state) {
  if ($element['#required'] && $element['#value'] == '_none') {
    $form_state
      ->setError($element, t('@name field is required.', [
      '@name' => $element['#title'],
    ]));
  }

  // Massage submitted form values.
  // Drupal\Core\Field\WidgetBase::submit() expects values as
  // an array of values keyed by delta first, then by column, while our
  // widgets return the opposite.
  if (is_array($element['#value'])) {
    $values = array_values($element['#value']);
  }
  else {
    $values = [
      $element['#value'],
    ];
  }

  // Filter out the 'none' option. Use a strict comparison, because
  // 0 == 'any string'.
  $index = array_search('_none', $values, TRUE);
  if ($index !== FALSE) {
    unset($values[$index]);
  }

  // Transpose selections from field => delta to delta => field.
  $items = [];
  foreach ($values as $value) {
    $items[] = [
      $element['#key_column'] => $value,
    ];
  }
  $form_state
    ->setValueForElement($element, $items);
}