You are here

public static function SelectOtherWidget::validateElement in CCK Select Other 8

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/SelectOtherWidget.php, line 117

Class

SelectOtherWidget
Plugin implementation of the 'cck_select_other' widget.

Namespace

Drupal\cck_select_other\Plugin\Field\FieldWidget

Code

public static function validateElement(array $element, FormStateInterface $form_state) {
  $form_state_values = $form_state
    ->getValues();
  $values = NestedArray::getValue($form_state_values, $element['#parents']);
  if (!$element['select_other_list']['#required'] && $values['select_other_list'] == '_none') {

    // Empty select list option.
    $form_state
      ->setValueForElement($element, [
      'value' => NULL,
    ]);
  }
  elseif ($element['select_other_list']['#required'] && $values['select_other_list'] == '') {

    // Empty select list option for required field.
    $form_state
      ->setValueForElement($element, [
      'value' => '',
    ])
      ->setError($element, t('You must select an option.'));
  }
  elseif ($element['select_other_list']['#required'] && $values['select_other_list'] == 'other' && !$values['select_other_text_input']) {

    // Empty text input for required field.
    $form_state
      ->setValueForElement($element, [
      'value' => NULL,
    ])
      ->setError($element['select_other_text_input'], t('You must provide a value for this option.'));
  }
  elseif ($values['select_other_list'] == 'other' && $values['select_other_text_input']) {

    // Non-empty text input value.
    $form_state
      ->setValueForElement($element, [
      'value' => $values['select_other_text_input'],
    ]);
  }
  elseif ($values['select_other_list'] == 'other' && !$values['select_other_text_input']) {

    // Empty text for non-required field.
    $form_state
      ->setValueForELement($element, [
      'value' => NULL,
    ]);
  }
  elseif (!isset($element['select_other_list']['#options'][$values['select_other_list']])) {

    // Non-empty select list value is not in #options. Fail validation before
    // Field constraint can get to it as we MUST override that completely
    // because DrupalWTF.
    $form_state
      ->setError($element['select_other_list'], t('The value you selected is not a valid choice.'));
  }
  else {

    // Non-empty select list value.
    $form_state
      ->setValueForElement($element, [
      'value' => $values['select_other_list'],
    ]);
  }
}