You are here

class DateRangeDurationWidget in Datetime Extras 8

Plugin implementation of the 'daterange_duration' widget.

Plugin annotation


@FieldWidget(
  id = "daterange_duration",
  label = @Translation("Date and time range with duration"),
  field_types = {
    "daterange"
  }
)

Hierarchy

Expanded class hierarchy of DateRangeDurationWidget

File

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

Namespace

Drupal\datetime_extras\Plugin\Field\FieldWidget
View source
class DateRangeDurationWidget extends DateRangeDefaultWidget {

  /**
   * The duration service.
   *
   * @var \Drupal\duration_field\Service\DurationServiceInterface
   */
  protected $durationService;

  /**
   * The duration service.
   *
   * @var \Drupal\duration_field\Service\GranularityServiceInterface
   */
  protected $granularityService;

  /**
   * Sets the duration service.
   */
  public function setDurationService(DurationServiceInterface $duration_service) {
    $this->durationService = $duration_service;
  }

  /**
   * Sets the granularity service.
   */
  public function setGranularityService(GranularityServiceInterface $granularity_service) {
    $this->granularityService = $granularity_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);

    // Use setter injection to be immune from changes to the parent constructor.
    // @see https://www.previousnext.com.au/blog/safely-extending-drupal-8-plugin-classes-without-fear-of-constructor-changes
    $instance
      ->setDurationService($container
      ->get('duration_field.service'));
    $instance
      ->setGranularityService($container
      ->get('duration_field.granularity.service'));
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'default_duration' => [],
      'duration_granularity' => 'd:h:i',
      'time_increment' => '1',
    ] + parent::defaultSettings();
  }

  /**
   * Return the possible options for time increments.
   *
   * @return array
   *   Valid options for time increments, keyed by seconds, values are labels.
   */
  protected function getTimeIncrementOptions() {
    return [
      1 => $this
        ->t('1 second'),
      30 => $this
        ->t('30 seconds'),
      60 => $this
        ->t('1 minute'),
      300 => $this
        ->t('5 minutes'),
      600 => $this
        ->t('10 minutes'),
      900 => $this
        ->t('15 minutes'),
      1800 => $this
        ->t('30 minutes'),
      3600 => $this
        ->t('1 hour'),
      86400 => $this
        ->t('1 day'),
    ];
  }

  /**
   * Returns the current value of the default duration setting as an interval.
   *
   * @return \DateInterval
   *   The current value of the default duration setting.
   */
  protected function getDefaultDurationInterval() {
    $default_duration = $this
      ->getSetting('default_duration');
    return $this->durationService
      ->convertDateArrayToDateInterval($default_duration);
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = [];
    $element['duration_granularity'] = [
      '#type' => 'granularity',
      '#title' => t('Duration granularity'),
      '#default_value' => $this
        ->getSetting('duration_granularity'),
    ];
    $element['default_duration'] = [
      '#type' => 'duration',
      '#title' => t('Default duration'),
      '#default_value' => $this
        ->getDefaultDurationInterval(),
      '#granularity' => $this
        ->getSetting('duration_granularity'),
      '#cardinality' => $this->fieldDefinition
        ->getFieldStorageDefinition()
        ->getCardinality(),
      // Blast the default #element_validate callback to leave this duration
      // as an array (and don't convert it into a DateInterval object), so we
      // can save it to config storage.
      // @see https://www.drupal.org/project/duration_field/issues/3020681
      '#element_validate' => [],
    ];
    $element['time_increment'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Time increment'),
      '#default_value' => $this
        ->getSetting('time_increment'),
      '#options' => $this
        ->getTimeIncrementOptions(),
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $default_duration_interval = $this
      ->getDefaultDurationInterval();
    $duration_granularity = $this
      ->getSetting('duration_granularity');
    $time_increment = $this
      ->getSetting('time_increment');
    $increment_options = $this
      ->getTimeIncrementOptions();
    $summary = [];

    // Annoyingly, GranularityService::getHumanReadableStringFromDateInterval()
    // expects the granularity as an array, but everything else stores/expects
    // it as a string. So, we have to invoke the granularity service to convert
    // the string into the granularity array.
    $granularity_array = $this->granularityService
      ->convertGranularityStringToGranularityArray($duration_granularity);
    $default_duration = $this->durationService
      ->getHumanReadableStringFromDateInterval($default_duration_interval, $granularity_array, ' ', 'short');
    $summary['default_duration'] = $this
      ->t('Default duration: @duration', [
      '@duration' => $default_duration,
    ]);
    $summary['duration_granularity'] = $this
      ->t('Duration granularity: @granularity', [
      '@granularity' => $duration_granularity,
    ]);
    $summary['time_increment'] = $this
      ->t('Time increment : @increment', [
      '@increment' => $increment_options[$time_increment],
    ]);
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $form_element = parent::formElement($items, $delta, $element, $form, $form_state);
    $increment = $this
      ->getSetting('time_increment');
    foreach ([
      'value',
      'end_value',
    ] as $sub_element) {
      $form_element[$sub_element]['#date_increment'] = $increment;

      // If the increment is in days, don't collect time at all.
      if ($increment >= 86400) {
        $form_element[$sub_element]['#date_time_format'] = '';
        $form_element[$sub_element]['#date_time_element'] = 'none';
        $form_element[$sub_element]['#date_time_callbacks'] = [];
      }
    }

    // Since the user will probably define a duration, not an end time, mark the
    // element unrequired. We'll force a value during our custom validation.
    $form_element['end_value']['#required'] = FALSE;
    $item = $items[$delta];
    if ($item->start_date) {

      /** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
      $start_date = $item->start_date;
    }
    if ($item->end_date) {

      /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
      $end_date = $item->end_date;
    }
    if (!empty($start_date) && !empty($end_date)) {
      $interval = $start_date
        ->diff($end_date);
    }
    $form_element['end_type'] = [
      '#type' => 'radios',
      '#options' => [
        'duration' => $this
          ->t('Duration'),
        'end_date' => $this
          ->t('End date'),
      ],
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
      '#default_value' => 'duration',
      '#weight' => '-5',
    ];
    $form_element['value']['#weight'] = '-10';
    $form_element['end_value']['#weight'] = '0';
    $end_type_name = $this->fieldDefinition
      ->getName() . '[' . $delta . '][end_type]';

    // Use #states to hide the end_value if we're using a duration.
    // Sadly [#2419131] means #states doesn't work directly on a datetime.
    // @todo This hack breaks the label for end_value.
    // @see https://www.drupal.org/node/3026456
    $form_element['end_value']['#theme_wrappers'] = [
      'container',
    ];
    $form_element['end_value']['#states']['visible'][] = [
      ':input[name="' . $end_type_name . '"]' => [
        'value' => 'end_date',
      ],
    ];
    $form_element['duration'] = [
      '#type' => 'duration',
      '#cardinality' => $this->fieldDefinition
        ->getFieldStorageDefinition()
        ->getCardinality(),
      '#granularity' => $this
        ->getSetting('duration_granularity'),
      '#date_increment' => $increment,
      '#weight' => '10',
      '#states' => [
        'visible' => [
          ':input[name="' . $end_type_name . '"]' => [
            'value' => 'duration',
          ],
        ],
      ],
    ];

    // Set the default duration. If we already have an end_date value, use that.
    // Otherwise, use the default duration from the widget settings.
    if (empty($interval)) {
      $interval = $this
        ->getDefaultDurationInterval();
    }
    $form_element['duration']['#default_value'] = $interval;

    // Add #validate callback to set the end_value from duration. We want our
    // #element_validate to run first, so put it at the front of the array.
    array_unshift($form_element['#element_validate'], [
      get_class($this),
      'validateDuration',
    ]);
    return $form_element;
  }

  /**
   * If the widget is using duration, update end_value for further validation.
   *
   * @param array $element
   *   The form element to validate.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   */
  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.'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
DateRangeDefaultWidget::$dateStorage protected property The date format storage.
DateRangeDefaultWidget::__construct public function Constructs a WidgetBase object. Overrides WidgetBase::__construct
DateRangeDurationWidget::$durationService protected property The duration service.
DateRangeDurationWidget::$granularityService protected property The duration service.
DateRangeDurationWidget::create public static function Creates an instance of the plugin. Overrides DateRangeDefaultWidget::create
DateRangeDurationWidget::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
DateRangeDurationWidget::formElement public function Returns the form for a single field widget. Overrides DateRangeDefaultWidget::formElement
DateRangeDurationWidget::getDefaultDurationInterval protected function Returns the current value of the default duration setting as an interval.
DateRangeDurationWidget::getTimeIncrementOptions protected function Return the possible options for time increments.
DateRangeDurationWidget::setDurationService public function Sets the duration service.
DateRangeDurationWidget::setGranularityService public function Sets the granularity service.
DateRangeDurationWidget::settingsForm public function Returns a form to configure settings for the widget. Overrides WidgetBase::settingsForm
DateRangeDurationWidget::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetBase::settingsSummary
DateRangeDurationWidget::validateDuration public static function If the widget is using duration, update end_value for further validation.
DateRangeWidgetBase::massageFormValues public function Massages the form values into the format expected for field values. Overrides DateTimeWidgetBase::massageFormValues
DateRangeWidgetBase::validateStartEnd public function #element_validate callback to ensure that the start date <= the end date.
DateTimeWidgetBase::createDefaultValue protected function Creates a date object for use as a default value.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBaseInterface::extractFormValues 2
WidgetBase::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface::flagErrors 2
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formMultipleElements protected function Special handling to create form elements for multiple values. 1
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState