You are here

class DateRecurBasicWidget in Recurring Dates Field 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldWidget/DateRecurBasicWidget.php \Drupal\date_recur\Plugin\Field\FieldWidget\DateRecurBasicWidget
  2. 3.0.x src/Plugin/Field/FieldWidget/DateRecurBasicWidget.php \Drupal\date_recur\Plugin\Field\FieldWidget\DateRecurBasicWidget
  3. 3.1.x src/Plugin/Field/FieldWidget/DateRecurBasicWidget.php \Drupal\date_recur\Plugin\Field\FieldWidget\DateRecurBasicWidget

Basic RRULE widget.

Displays an input textarea accepting RRULE strings.

Plugin annotation


@FieldWidget(
  id = "date_recur_basic_widget",
  label = @Translation("Simple Recurring Date Widget"),
  field_types = {
    "date_recur"
  }
)

Hierarchy

Expanded class hierarchy of DateRecurBasicWidget

1 file declares its use of DateRecurBasicWidget
date_recur.install in ./date_recur.install

File

src/Plugin/Field/FieldWidget/DateRecurBasicWidget.php, line 30

Namespace

Drupal\date_recur\Plugin\Field\FieldWidget
View source
class DateRecurBasicWidget extends DateRangeDefaultWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) : array {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    $element['#theme'] = 'date_recur_basic_widget';
    $element['#element_validate'][] = [
      $this,
      'validateRrule',
    ];

    // ::createDefaultValue isnt given enough context about the field item, so
    // override its functions here.
    $element['value']['#default_value'] = $element['end_value']['#default_value'] = NULL;
    $element['value']['#date_timezone'] = $element['end_value']['#date_timezone'] = NULL;
    $this
      ->createDateRecurDefaultValue($element, $items[$delta]);

    // Move fields into a first occurrence container as 'End date' can be
    // confused with 'End date' RRULE concept.
    $element['first_occurrence'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('First occurrence'),
      // Needs a weight otherwise children do not show up within single
      // cardinality widgets.
      '#weight' => 0,
    ];
    $firstOccurrenceParents = array_merge($element['#field_parents'], [
      $this->fieldDefinition
        ->getName(),
      $delta,
      'first_occurrence',
    ]);
    $element['value']['#title'] = $this
      ->t('Start');
    $element['end_value']['#title'] = $this
      ->t('End');
    $element['end_value']['#description'] = $this
      ->t('Leave end empty to copy start date; the occurrence will therefore not have any duration.');

    // The end date is never required. Start date is copied over if end date is
    // empty.
    $element['end_value']['#required'] = FALSE;
    $element['value']['#group'] = $element['end_value']['#group'] = implode('][', $firstOccurrenceParents);

    // Add custom value callbacks to correctly form a date from time zone field.
    $element['value']['#value_callback'] = $element['end_value']['#value_callback'] = [
      $this,
      'dateValueCallback',
    ];

    // Saved values (should) always have a time zone.
    $timeZone = $items[$delta]->timezone ?? NULL;
    $zones = $this
      ->getTimeZoneOptions();
    $element['timezone'] = [
      '#type' => 'select',
      '#title' => t('Time zone'),
      '#default_value' => $timeZone,
      '#options' => $zones,
    ];
    $element['rrule'] = [
      '#type' => 'textarea',
      '#default_value' => $items[$delta]->rrule ?? NULL,
      '#title' => $this
        ->t('Repeat rule'),
      '#description' => $this
        ->t('Repeat rule in <a href=":link">iCalendar Recurrence Rule</a> (RRULE) format.', [
        ':link' => 'https://icalendar.org/iCalendar-RFC-5545/3-8-5-3-recurrence-rule.html',
      ]),
    ];
    return $element;
  }

  /**
   * Validator for start and end elements.
   *
   * Sets the time zone before datetime element processes values.
   *
   * @param array $element
   *   An associative array containing the properties and children of the
   *   generic form element.
   * @param array|false $input
   *   Input, if any.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The value to assign to the element.
   */
  public function dateValueCallback(array $element, $input, FormStateInterface $form_state) : array {
    if ($input !== FALSE) {
      $timeZonePath = array_slice($element['#parents'], 0, -1);
      $timeZonePath[] = 'timezone';

      // Warning: The time zone is not yet validated, make sure it is valid
      // before using.
      $submittedTimeZone = NestedArray::getValue($form_state
        ->getUserInput(), $timeZonePath);
      if (!isset($submittedTimeZone)) {

        // If no time zone was submitted, such as when the 'timezone' field is
        // set to #access => FALSE, its necessary to fall back to the fields
        // default value.
        $timeZoneFieldPath = array_slice($element['#array_parents'], 0, -1);
        $timeZoneFieldPath[] = 'timezone';
        $timeZoneField = NestedArray::getValue($form_state
          ->getCompleteForm(), $timeZoneFieldPath);
        $submittedTimeZone = isset($timeZoneField['#value']) ? $timeZoneField['#value'] : $timeZoneField['#default_value'] ?? NULL;
      }
      $allTimeZones = \DateTimeZone::listIdentifiers();

      // @todo Add test for invalid submitted time zone.
      if (!in_array($submittedTimeZone, $allTimeZones)) {

        // A date is invalid if the time zone is invalid.
        // Need to kill inputs otherwise
        // \Drupal\Core\Datetime\Element\Datetime::validateDatetime thinks there
        // is valid input.
        return [
          'date' => '',
          'time' => '',
          'object' => NULL,
        ];
      }
      $element['#date_timezone'] = $submittedTimeZone;
    }

    // Setting a callback overrides default value callback in the element,
    // call original now.
    return Datetime::valueCallback($element, $input, $form_state);
  }

  /**
   * Validates RRULE and first occurrence dates.
   *
   * @param array $element
   *   An associative array containing the properties and children of the
   *   generic form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   */
  public function validateRrule(array &$element, FormStateInterface $form_state, array &$complete_form) : void {
    $input = NestedArray::getValue($form_state
      ->getValues(), $element['#parents']);

    /** @var \Drupal\Core\Datetime\DrupalDateTime|array|null $startDate */
    $startDate = $input['value'];

    /** @var \Drupal\Core\Datetime\DrupalDateTime|array|null $startDateEnd */
    $startDateEnd = $input['end_value'];
    if (is_array($startDate) || is_array($startDateEnd)) {

      // Dates are an array if invalid input was submitted (e.g date:
      // 80616-02-01).
      return;
    }

    /** @var string $rrule */
    $rrule = $input['rrule'];
    if ($startDateEnd && !isset($startDate)) {
      $form_state
        ->setError($element['value'], (string) $this
        ->t('Start date must be set if end date is set.'));
    }

    // If end was empty, copy start date over.
    if (!isset($startDateEnd) && $startDate) {
      $form_state
        ->setValueForElement($element['end_value'], $startDate);
      $startDateEnd = $startDate;
    }

    // Validate RRULE.
    // Only ensure start date is set, as end date is optional.
    if (strlen($rrule) > 0 && $startDate) {
      try {
        DateRecurHelper::create($rrule, $startDate
          ->getPhpDateTime(), $startDateEnd ? $startDateEnd
          ->getPhpDateTime() : NULL);
      } catch (\Exception $e) {
        $form_state
          ->setError($element['rrule'], (string) $this
          ->t('Repeat rule is formatted incorrectly.'));
      }
    }
  }

  /**
   * Get a list of time zones suitable for a select field.
   *
   * @return array
   *   A list of time zones where keys are PHP time zone codes, and values are
   *   human readable and translatable labels.
   */
  protected function getTimeZoneOptions() : array {
    return \system_time_zones(TRUE, TRUE);
  }

  /**
   * Get the current users time zone.
   *
   * @return string
   *   A PHP time zone string.
   */
  protected function getCurrentUserTimeZone() : string {
    return \date_default_timezone_get();
  }

  /**
   * {@inheritdoc}
   */
  protected function createDefaultValue($date, $timezone) : DrupalDateTime {
    assert($date instanceof DrupalDateTime);
    assert(is_string($timezone));

    // Cannot set time zone here as field item contains time zone.
    if ($this
      ->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE) {
      $date
        ->setDefaultDateTime();
    }
    return $date;
  }

  /**
   * Set element default value and time zone.
   *
   * @param array $element
   *   The element.
   * @param \Drupal\date_recur\Plugin\Field\FieldType\DateRecurItem $item
   *   The date recur field item.
   */
  protected function createDateRecurDefaultValue(array &$element, DateRecurItem $item) : void {
    $startDate = $item->start_date;
    $startDateEnd = $item->end_date;
    $timeZone = isset($item->timezone) ? new \DateTimeZone($item->timezone) : NULL;
    if ($timeZone) {
      $element['value']['#date_timezone'] = $element['end_value']['#date_timezone'] = $timeZone
        ->getName();
      if ($startDate) {
        $startDate
          ->setTimezone($timeZone);
        $element['value']['#default_value'] = $this
          ->createDefaultValue($startDate, $timeZone
          ->getName());
      }
      if ($startDateEnd) {
        $startDateEnd
          ->setTimezone($timeZone);
        $element['end_value']['#default_value'] = $this
          ->createDefaultValue($startDateEnd, $timeZone
          ->getName());
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateRangeDefaultWidget::$dateStorage protected property The date format storage.
DateRangeDefaultWidget::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
DateRangeDefaultWidget::__construct public function Constructs a WidgetBase object. Overrides WidgetBase::__construct
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.
DateRecurBasicWidget::createDateRecurDefaultValue protected function Set element default value and time zone.
DateRecurBasicWidget::createDefaultValue protected function Creates a date object for use as a default value. Overrides DateTimeWidgetBase::createDefaultValue
DateRecurBasicWidget::dateValueCallback public function Validator for start and end elements.
DateRecurBasicWidget::formElement public function Returns the form for a single field widget. Overrides DateRangeDefaultWidget::formElement
DateRecurBasicWidget::getCurrentUserTimeZone protected function Get the current users time zone.
DateRecurBasicWidget::getTimeZoneOptions protected function Get a list of time zones suitable for a select field.
DateRecurBasicWidget::validateRrule public function Validates RRULE and first occurrence dates.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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 2
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::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsInterface::defaultSettings 42
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. 4
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::settingsForm public function Returns a form to configure settings for the widget. Overrides WidgetInterface::settingsForm 16
WidgetBase::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetInterface::settingsSummary 15
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState