You are here

public static function Datelist::validateDatelist in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Datetime/Element/Datelist.php \Drupal\Core\Datetime\Element\Datelist::validateDatelist()

Validation callback for a datelist element.

If the date is valid, the date object created from the user input is set in the form for use by the caller. The work of compiling the user input back into a date object is handled by the value callback, so we can use it here. We also have the raw input available for validation testing.

Parameters

array $element: The element being processed.

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

array $complete_form: The complete form structure.

File

core/lib/Drupal/Core/Datetime/Element/Datelist.php, line 301
Contains \Drupal\Core\Datetime\Element\Datelist.

Class

Datelist
Provides a datelist element.

Namespace

Drupal\Core\Datetime\Element

Code

public static function validateDatelist(&$element, FormStateInterface $form_state, &$complete_form) {
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state
    ->getValues(), $element['#parents'], $input_exists);
  if ($input_exists) {
    $all_empty = static::checkEmptyInputs($input, $element['#date_part_order']);

    // If there's empty input and the field is not required, set it to empty.
    if (empty($input['year']) && empty($input['month']) && empty($input['day']) && !$element['#required']) {
      $form_state
        ->setValueForElement($element, NULL);
    }
    elseif (empty($input['year']) && empty($input['month']) && empty($input['day']) && $element['#required']) {
      $form_state
        ->setError($element, t('The %field date is required.'));
    }
    elseif (!empty($all_empty)) {
      foreach ($all_empty as $value) {
        $form_state
          ->setError($element[$value], t('A value must be selected for %part.', array(
          '%part' => $value,
        )));
      }
    }
    else {

      // If the input is valid, set it.
      $date = $input['object'];
      if ($date instanceof DrupalDateTime && !$date
        ->hasErrors()) {
        $form_state
          ->setValueForElement($element, $date);
      }
      else {
        $form_state
          ->setError($element, t('The %field date is invalid.', array(
          '%field' => !empty($element['#title']) ? $element['#title'] : '',
        )));
      }
    }
  }
}