You are here

public static function OfficeHoursDatelist::valueCallback in Office Hours 8

Callback for office_hours_select element.

Takes #default_value and dissects it in hours, minutes and ampm indicator. Mimics the date_parse() function.

  • g = 12-hour format of an hour without leading zeros 1 through 12
  • G = 24-hour format of an hour without leading zeros 0 through 23
  • h = 12-hour format of an hour with leading zeros 01 through 12
  • H = 24-hour format of an hour with leading zeros 00 through 23

Parameters

array $element:

mixed $input:

\Drupal\Core\Form\FormStateInterface $form_state:

Return value

array|mixed|null

Overrides Datelist::valueCallback

File

src/Element/OfficeHoursDatelist.php, line 62

Class

OfficeHoursDatelist
Provides a one-line text field form element.

Namespace

Drupal\office_hours\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  if ($input == FALSE) {

    // Prepare the numeric value: use a DateTime value.
    $time = $element['#default_value'];
    $date = NULL;
    try {
      if (is_array($time)) {
        $date = OfficeHoursDateHelper::createFromArray($time);
      }
      elseif (is_numeric($time)) {
        $timezone = $element['#date_timezone'];

        // The Date function needs a fixed format, so format $time to '0030'.
        $time = OfficeHoursDatetime::get($time, 'Hi');
        $date = OfficeHoursDateHelper::createFromFormat('Gi', $time, $timezone);
      }
    } catch (\Exception $e) {
      $date = NULL;
    }
    $element['#default_value'] = $date;
  }

  // Set empty minutes field to '00' for better UX.
  if (!empty($input['hour']) && isset($input['minute']) && empty($input['minute'])) {
    $input['minute'] = '00';
  }
  $input = parent::valueCallback($element, $input, $form_state);
  return $input;
}