You are here

public static function TimestampDatetimeNoDefaultWidget::valueCallback in Scheduler 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Field/FieldWidget/TimestampDatetimeNoDefaultWidget.php \Drupal\scheduler\Plugin\Field\FieldWidget\TimestampDatetimeNoDefaultWidget::valueCallback()

Callback function to add default time to the input date if needed.

This will intercept the user input before form validation is processed. However, if the field is 'required' then the browser validation may have already failed before this point. The solution is to pre-fill the time using javascript - see js/scheduler_default_time.js. But that cannot be done when the date is not 'required' hence do the processing here too.

File

src/Plugin/Field/FieldWidget/TimestampDatetimeNoDefaultWidget.php, line 67

Class

TimestampDatetimeNoDefaultWidget
Plugin implementation of the 'datetime timestamp' widget.

Namespace

Drupal\scheduler\Plugin\Field\FieldWidget

Code

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');
    }
  }

  // Temporarily set the #date_time_element to 'time' because if it had been
  // hidden in the form by being set to 'none' then the default time set above
  // would not be used and we would get the current hour and minute instead.
  $originalTimeElement = $element['#date_time_element'];
  $element['#date_time_element'] = 'time';

  // Chain on to the standard valueCallback for Datetime as we do not want to
  // duplicate that core code here.
  $value = Datetime::valueCallback($element, $input, $form_state);

  // Restore the #date_time_element.
  $element['#date_time_element'] = $originalTimeElement;
  return $value;
}