function Datetime::valueCallback

Same name in other branches
  1. 9 core/lib/Drupal/Core/Datetime/Element/Datetime.php \Drupal\Core\Datetime\Element\Datetime::valueCallback()
  2. 10 core/lib/Drupal/Core/Datetime/Element/Datetime.php \Drupal\Core\Datetime\Element\Datetime::valueCallback()
  3. 11.x core/lib/Drupal/Core/Datetime/Element/Datetime.php \Drupal\Core\Datetime\Element\Datetime::valueCallback()

Overrides FormElement::valueCallback

File

core/lib/Drupal/Core/Datetime/Element/Datetime.php, line 73

Class

Datetime
Provides a datetime element.

Namespace

Drupal\Core\Datetime\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    $element += [
        '#date_timezone' => date_default_timezone_get(),
    ];
    if ($input !== FALSE) {
        $date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
        $time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
        $date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
        $time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
        // Seconds will be omitted in a post in case there's no entry.
        if (!empty($time_input) && strlen($time_input) == 5) {
            $time_input .= ':00';
        }
        try {
            $date_time_format = trim($date_format . ' ' . $time_format);
            $date_time_input = trim($date_input . ' ' . $time_input);
            $date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $element['#date_timezone']);
        } catch (\Exception $e) {
            $date = NULL;
        }
        $input = [
            'date' => $date_input,
            'time' => $time_input,
            'object' => $date,
        ];
    }
    else {
        $date = isset($element['#default_value']) ? $element['#default_value'] : NULL;
        if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
            $date->setTimezone(new \DateTimeZone($element['#date_timezone']));
            $input = [
                'date' => $date->format($element['#date_date_format']),
                'time' => $date->format($element['#date_time_format']),
                'object' => $date,
            ];
        }
        else {
            $input = [
                'date' => '',
                'time' => '',
                'object' => NULL,
            ];
        }
    }
    return $input;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.