You are here

public function DatetimeRangeAllDayWidget::massageFormValues in Date all day 8

Massages the form values into the format expected for field values.

Parameters

array $values: The submitted form values produced by the widget.

  • If the widget does not manage multiple values itself, the array holds the values generated by the multiple copies of the $element generated by the formElement() method, keyed by delta.
  • If the widget manages multiple values, the array holds the values of the form element generated by the formElement() method.

array $form: The form structure where field elements are attached to. This might be a full form structure, or a sub-element of a larger form.

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

Return value

array An array of field values, keyed by delta.

Overrides DateRangeWidgetBase::massageFormValues

File

src/Plugin/Field/FieldWidget/DatetimeRangeAllDayWidget.php, line 84

Class

DatetimeRangeAllDayWidget
Plugin implementation of the 'daterange_all_day' widget.

Namespace

Drupal\date_all_day\Plugin\Field\FieldWidget

Code

public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
  if (!empty($values)) {
    $timezone = timezone_open(date_default_timezone_get());
  }
  foreach ($values as &$item) {
    if (!empty($item['value']) && $item['value'] instanceof DrupalDateTime) {
      $is_all_day = DateRangeAllDayHelper::isAllDay($item);

      /** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
      $start_date = $item['value'];

      // All day fields start at midnight on the starting date, but are
      // stored like datetime fields, so we need to adjust the time.
      // This function is called twice, so to prevent a double conversion
      // we need to explicitly set the timezone.
      $start_date
        ->setTimeZone($timezone);
      if ($is_all_day) {
        $start_date
          ->setTime(0, 0, 0);
      }
      $item['value'] = $start_date
        ->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
        'timezone' => DateTimeItemInterface::STORAGE_TIMEZONE,
      ]);
      if (!empty($item['end_value']) && $item['end_value'] instanceof DrupalDateTime) {

        /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
        $end_date = $item['end_value'];

        // All day fields end at midnight on the end date, but are
        // stored like datetime fields, so we need to adjust the time.
        // This function is called twice, so to prevent a double conversion
        // we need to explicitly set the timezone.
        $end_date
          ->setTimeZone($timezone);
        if ($is_all_day) {
          $end_date
            ->setTime(23, 59, 59);
        }
        $item['end_value'] = $end_date
          ->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
          'timezone' => DateTimeItemInterface::STORAGE_TIMEZONE,
        ]);
      }
    }
  }
  return $values;
}