You are here

public static function DateRangeDurationWidget::validateDuration in Datetime Extras 8

If the widget is using duration, update end_value for further validation.

Parameters

array $element: The form element to validate.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

array $complete_form: The complete form structure.

File

src/Plugin/Field/FieldWidget/DateRangeDurationWidget.php, line 254

Class

DateRangeDurationWidget
Plugin implementation of the 'daterange_duration' widget.

Namespace

Drupal\datetime_extras\Plugin\Field\FieldWidget

Code

public static function validateDuration(array &$element, FormStateInterface $form_state, array &$complete_form) {
  if ($element['end_type']['#value'] === 'duration') {
    if (!empty($element['value']['#value']['object']) && $element['value']['#value']['object'] instanceof DrupalDateTime && !empty($element['duration']['#value'])) {

      // Get a DrupalDateTime for the start time plus the duration offset.
      $date = clone $element['value']['#value']['object'];
      $date
        ->add($element['duration']['#value']);

      // Set the end_value via form_state so it persists to submit handlers.
      $end_element['#parents'] = array_merge($element['#parents'], [
        'end_value',
      ]);
      $form_state
        ->setValueForElement($end_element, $date);

      // Also set the end_value's #value so that the new end_value is
      // available as other #validate callbacks happen, especially
      // DateRangeWidgetBase::validateStartEnd().
      $element['end_value']['#value'] = [
        'date' => $date
          ->format(DateFormat::load('html_date')
          ->getPattern()),
        'time' => $date
          ->format(DateFormat::load('html_time')
          ->getPattern()),
        'object' => $date,
      ];
    }
  }
  elseif (!empty($element['#required']) && empty($element['end_value']['#value']['object'])) {
    $form_state
      ->setError($element, t('You must define either a duration or an end date.'));
  }
}