You are here

public static function Datetime::validateDatetime in Zircon Profile 8.0

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

Validation callback for a datetime 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 form element whose value is being validated.

\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/Datetime.php, line 334
Contains \Drupal\Core\Datetime\Element\Datetime.

Class

Datetime
Provides a datetime element.

Namespace

Drupal\Core\Datetime\Element

Code

public static function validateDatetime(&$element, FormStateInterface $form_state, &$complete_form) {
  $input_exists = FALSE;
  $input = NestedArray::getValue($form_state
    ->getValues(), $element['#parents'], $input_exists);
  if ($input_exists) {
    $title = !empty($element['#title']) ? $element['#title'] : '';
    $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
    $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
    $format = trim($date_format . ' ' . $time_format);

    // If there's empty input and the field is not required, set it to empty.
    if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
      $form_state
        ->setValueForElement($element, NULL);
    }
    elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
      $form_state
        ->setError($element, t('The %field date is required. Please enter a date in the format %format.', array(
        '%field' => $title,
        '%format' => static::formatExample($format),
      )));
    }
    else {

      // If the date 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. Please enter a date in the format %format.', array(
          '%field' => $title,
          '%format' => static::formatExample($format),
        )));
      }
    }
  }
}