/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); $default_value = isset($items[$delta]->value) ? DrupalDateTime::createFromTimestamp($items[$delta]->value) : ''; $element['value'] = $element + array('#type' => 'datetime', '#default_value' => $default_value, '#date_year_range' => '1902:2037'); $element['value']['#description'] = $this->t('Format: %format. Leave blank to use the time of form submission.', array('%format' => Datetime::formatExample($date_format . ' ' . $time_format))); return $element; }
/** * Callback function to add default time to the input date if needed. * * This will intercept the user input before form validation is processed. */ public static function valueCallback(&$element, $input, FormStateInterface $form_state) { 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'] : ''; // If there is an input date but no time and the date-only option is on // then set the input time to the default specified by scheduler options. $config = \Drupal::config('scheduler.settings'); if (!empty($date_input) && empty($time_input) && $config->get('allow_date_only')) { $input['time'] = $config->get('default_time'); } } // Chain on to the standard valueCallback for Datetime as we do not want to // duplicate that core code here. return Datetime::valueCallback($element, $input, $form_state); }