You are here

public static function SelectOrOtherWidgetBase::validateElement in Select (or other) 8.3

Form validation handler for widget elements.

Parameters

array $element: The form element.

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

File

src/Plugin/Field/FieldWidget/SelectOrOtherWidgetBase.php, line 160
Contains \Drupal\select_or_other\Plugin\Field\FieldWidget\SelectOrOtherWidgetBase.

Class

SelectOrOtherWidgetBase
Base class for the 'select_or_other_*' widgets.

Namespace

Drupal\select_or_other\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);
}