public static function DatexDateList::valueCallback in Datex 8
Validates the date type to adjust 12 hour time and prevent invalid dates. If the date is valid, the date is set in the form.
Overrides Datelist::valueCallback
File
- src/
Element/ DatexDateList.php, line 17
Class
- DatexDateList
- Plugin annotation @FormElement("datelist");
Namespace
Drupal\datex\ElementCode
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$parts = $element['#date_part_order'];
$increment = $element['#date_increment'];
$date = NULL;
if ($input !== FALSE) {
$return = $input;
if (empty(static::checkEmptyInputs($input, $parts))) {
if (isset($input['ampm'])) {
if ($input['ampm'] == 'pm' && $input['hour'] < 12) {
$input['hour'] += 12;
}
elseif ($input['ampm'] == 'am' && $input['hour'] == 12) {
$input['hour'] -= 12;
}
unset($input['ampm']);
}
$timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
try {
$date = DrupalDateTime::createFromArray($input, $timezone);
} catch (\Exception $e) {
$form_state
->setError($element, t('Selected combination of day and month is not valid.'));
}
if ($date instanceof DrupalDateTime && !$date
->hasErrors()) {
static::incrementRound($date, $increment);
}
}
}
else {
$return = array_fill_keys($parts, '');
if (!empty($element['#default_value'])) {
$date = $element['#default_value'];
if ($date instanceof DrupalDateTime && !$date
->hasErrors()) {
static::incrementRound($date, $increment);
foreach ($parts as $part) {
switch ($part) {
case 'day':
$format = 'j';
break;
case 'month':
$format = 'n';
break;
case 'year':
$format = 'Y';
break;
case 'hour':
$format = in_array('ampm', $element['#date_part_order']) ? 'g' : 'G';
break;
case 'minute':
$format = 'i';
break;
case 'second':
$format = 's';
break;
case 'ampm':
$format = 'a';
break;
default:
$format = '';
}
$return[$part] = $date
->format($format);
}
}
}
}
$timezone = isset($timezone) ? $timezone : NULL;
$calendar = datex_factory($timezone, 'en');
if ($calendar && $date && $date
->format('Y') < 1600) {
$ok = $calendar
->parse($date
->format('Y m d H i s'), 'Y m d H i s');
if (!$ok) {
$form_state
->setError($element, t('Selected combination of day and month is invalid.'));
}
else {
$date = DrupalDateTime::createFromTimestamp($calendar
->getTimestamp(), $timezone);
}
}
$return['object'] = $date;
return $return;
}