You are here

public static function WebformOtherBase::validateWebformOther in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Element/WebformOtherBase.php \Drupal\webform\Element\WebformOtherBase::validateWebformOther()

Validates an other element.

File

src/Element/WebformOtherBase.php, line 219

Class

WebformOtherBase
Base class for webform other element.

Namespace

Drupal\webform\Element

Code

public static function validateWebformOther(&$element, FormStateInterface $form_state, &$complete_form) {
  $type = static::getElementType();

  // Determine if the element has multiple values.
  $is_multiple = static::isMultiple($element);

  // Get value.
  $value = NestedArray::getValue($form_state
    ->getValues(), $element['#parents']);

  // Get return value.
  $return_value = static::processValue($element, $value);

  // Determine if the return value is empty.
  if ($is_multiple) {
    $is_empty = empty($return_value) ? TRUE : FALSE;
  }
  else {
    $is_empty = $return_value === '' || $return_value === NULL ? TRUE : FALSE;
  }

  // Determine if there is an other value and is the other value empty.
  $element_value = (array) $value[$type];
  $other_value = $value['other'];
  if ($element_value) {
    $element_value = array_filter($element_value);
    $element_value = array_combine($element_value, $element_value);
  }
  $other_is_empty = isset($element_value[static::OTHER_OPTION]) && $other_value === '';

  // Display missing other or missing value error.
  if (Element::isVisibleElement($element)) {
    $required_error_title = isset($element['#title']) ? $element['#title'] : NULL;
    if ($other_is_empty) {
      WebformElementHelper::setRequiredError($element['other'], $form_state, $required_error_title);
    }
    elseif ($element['#required'] && $is_empty) {
      WebformElementHelper::setRequiredError($element, $form_state, $required_error_title);
      $element['other']['#error_no_message'] = TRUE;
    }
  }
  $form_state
    ->setValueForElement($element[$type], NULL);
  $form_state
    ->setValueForElement($element['other'], NULL);
  $element['#value'] = $return_value;
  $form_state
    ->setValueForElement($element, $return_value);
}