You are here

public static function WebformElementBase::validateMultiple in Webform 8.5

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

Form API callback. Validate element #multiple > 1 value.

File

src/Plugin/WebformElementBase.php, line 2146

Class

WebformElementBase
Provides a base class for a webform element.

Namespace

Drupal\webform\Plugin

Code

public static function validateMultiple(array &$element, FormStateInterface $form_state) {
  if (!isset($element['#multiple'])) {
    return;
  }

  // IMPORTANT: Must get values from the $form_states since sub-elements
  // may call $form_state->setValueForElement() via their validation hook.
  // @see \Drupal\webform\Element\WebformEmailConfirm::validateWebformEmailConfirm
  // @see \Drupal\webform\Element\WebformOtherBase::validateWebformOther
  $values = NestedArray::getValue($form_state
    ->getValues(), $element['#parents']);

  // Skip empty values or values that are not an array.
  if (empty($values) || !is_array($values)) {
    return;
  }
  if (count($values) > $element['#multiple']) {
    if (isset($element['#multiple_error'])) {
      $form_state
        ->setError($element, $element['#multiple_error']);
    }
    elseif (isset($element['#title'])) {
      $t_args = [
        '%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title'],
        '@count' => $element['#multiple'],
      ];
      $form_state
        ->setError($element, t('%name: this element cannot hold more than @count values.', $t_args));
    }
    else {
      $form_state
        ->setError($element);
    }
  }
}