You are here

public static function Datelist::valueCallback in Zircon Profile 8

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

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 FormElement::valueCallback

File

core/lib/Drupal/Core/Datetime/Element/Datelist.php, line 51
Contains \Drupal\Core\Datetime\Element\Datelist.

Class

Datelist
Provides a datelist element.

Namespace

Drupal\Core\Datetime\Element

Code

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;
      $date = DrupalDateTime::createFromArray($input, $timezone);
      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);
        }
      }
    }
  }
  $return['object'] = $date;
  return $return;
}