You are here

public static function PersianDateList::valueCallback in Persian Date for Drupal 8 8

Same name and namespace in other branches
  1. 8.4 src/Element/PersianDateList.php \Drupal\persian_date\Element\PersianDateList::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 Datelist::valueCallback

File

src/Element/PersianDateList.php, line 25

Class

PersianDateList
Class PersianDateList

Namespace

Drupal\persian_date\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;
      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) ?: null;
  $date = PersianDrupalDateTime::createFromFormat('Y-m-d H:i:s', $date
    ->format('Y-m-d H:i:s'), $timezone);
  $date = DrupalDateTime::createFromDateTime($date
    ->getDateTime());
  $return['object'] = $date;
  return $return;
}