You are here

public static function OptionsWidgetBase::validateElement in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 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.

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/OptionsWidgetBase.php, line 74
Contains \Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase.

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.', array(
      '@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 = array(
      $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 = array();
  foreach ($values as $value) {
    $items[] = array(
      $element['#key_column'] => $value,
    );
  }
  $form_state
    ->setValueForElement($element, $items);
}