function Datetime::validateDatetime
Same name in other branches
- 9 core/lib/Drupal/Core/Datetime/Element/Datetime.php \Drupal\Core\Datetime\Element\Datetime::validateDatetime()
- 8.9.x core/lib/Drupal/Core/Datetime/Element/Datetime.php \Drupal\Core\Datetime\Element\Datetime::validateDatetime()
- 11.x 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 347
Class
- Datetime
- Provides a datetime element.
Namespace
Drupal\Core\Datetime\ElementCode
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 = static::getElementTitle($element, $complete_form);
// 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.', [
'%field' => $title,
]));
}
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. Enter a date in the correct format.', [
'%field' => $title,
]));
}
}
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.