You are here

public static function WebformCompositeBase::validateWebformComposite in Webform 6.x

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

Validates a composite element.

File

src/Element/WebformCompositeBase.php, line 166

Class

WebformCompositeBase
Provides an base composite webform element.

Namespace

Drupal\webform\Element

Code

public static function validateWebformComposite(&$element, FormStateInterface $form_state, &$complete_form) {

  // 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
  $value = NestedArray::getValue($form_state
    ->getValues(), $element['#parents']);

  // Only validate composite elements that are visible.
  if (Element::isVisibleElement($element)) {

    // Validate required composite elements.
    $composite_elements = static::getCompositeElements($element);
    $composite_elements = WebformElementHelper::getFlattened($composite_elements);
    foreach ($composite_elements as $composite_key => $composite_element) {
      $is_required = !empty($element[$composite_key]['#required']);
      $is_empty = isset($value[$composite_key]) && $value[$composite_key] === '';
      if ($is_required && $is_empty) {
        WebformElementHelper::setRequiredError($element[$composite_key], $form_state);
      }
    }
  }

  // Clear empty composites value.
  if (empty(array_filter($value))) {
    $element['#value'] = NULL;
    $form_state
      ->setValueForElement($element, NULL);
  }
}