You are here

public static function MultiselectWidget::validateElement in Multiselect 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Field/FieldWidget/MultiselectWidget.php \Drupal\multiselect\Plugin\Field\FieldWidget\MultiselectWidget::validateElement()

Form validation handler for widget elements.

Parameters

array $element: The form element.

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

Overrides OptionsWidgetBase::validateElement

File

src/Plugin/Field/FieldWidget/MultiselectWidget.php, line 59

Class

MultiselectWidget
Plugin implementation of the 'multiselect' widget.

Namespace

Drupal\multiselect\Plugin\Field\FieldWidget

Code

public static function validateElement(array $element, FormStateInterface $form_state) {

  // @todo fix multiselect validation.
  parent::validateElement($element, $form_state);

  // 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);
}