/Drupal 8

public static function Datelist::validateDatelist

public static Datelist::validateDatelist(&$element, FormStateInterface $form_state, &$complete_form)

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.


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.


core/lib/Drupal/Core/Datetime/Element/Datelist.php, line 302


Provides a datelist element.




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);
    // If there's empty input and the field is required, set an error.
    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);
      // If the input is invalid and an error doesn't exist, set one.
      elseif ($form_state->getError($element) === NULL) {
        $form_state->setError($element, t('The %field date is invalid.', array('%field' => !empty($element['#title']) ? $element['#title'] : '')));

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.