You are here

protected function WebformSubmissionConditionsValidator::validateFormElement in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/WebformSubmissionConditionsValidator.php \Drupal\webform\WebformSubmissionConditionsValidator::validateFormElement()

Validate a form element.

Parameters

array $element: A form element.

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

1 call to WebformSubmissionConditionsValidator::validateFormElement()
WebformSubmissionConditionsValidator::validateFormRecursive in src/WebformSubmissionConditionsValidator.php
Recurse through a form and validate visible elements.

File

src/WebformSubmissionConditionsValidator.php, line 333

Class

WebformSubmissionConditionsValidator
Webform submission conditions (#states) validator.

Namespace

Drupal\webform

Code

protected function validateFormElement(array $element, FormStateInterface $form_state) {
  $states = WebformElementHelper::getStates($element);
  if (empty($states)) {
    return;
  }

  /** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
  $webform_submission = $form_state
    ->getFormObject()
    ->getEntity();
  foreach ($states as $state => $conditions) {

    // Only required/optional validation is supported.
    if (!in_array($state, [
      'required',
      'optional',
    ])) {
      continue;
    }

    // Element must be an input to be required or optional.
    $element_plugin = $this->elementManager
      ->getElementInstance($element);
    if (!$element_plugin
      ->isInput($element)) {
      continue;
    }

    // Determine if the element is required.
    $is_required = $this
      ->validateConditions($conditions, $webform_submission);
    $is_required = $state === 'optional' ? !$is_required : $is_required;
    if (!$is_required) {
      continue;
    }

    // Determine if the element is empty (but not zero).
    if (isset($element['#webform_key'])) {
      $value = $webform_submission
        ->getElementData($element['#webform_key']);
    }
    else {
      $value = $element['#value'];
    }

    // Perform required validation. Use element's method if available.
    $element_definition = $element_plugin
      ->getFormElementClassDefinition();
    if (method_exists($element_definition, 'setRequiredError')) {
      $element_definition::setRequiredError($element, $form_state);
    }
    else {
      $is_empty = empty($value) && $value !== '0';
      $is_default_input_mask = TextBase::isDefaultInputMask($element, $value);

      // If required and empty then set required error.
      if ($is_empty || $is_default_input_mask) {
        WebformElementHelper::setRequiredError($element, $form_state);
      }
    }
  }
}