You are here

class DateRecurFieldItemList in Recurring Dates Field 3.1.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldType/DateRecurFieldItemList.php \Drupal\date_recur\Plugin\Field\FieldType\DateRecurFieldItemList
  2. 8 src/Plugin/Field/FieldType/DateRecurFieldItemList.php \Drupal\date_recur\Plugin\Field\FieldType\DateRecurFieldItemList
  3. 3.x src/Plugin/Field/FieldType/DateRecurFieldItemList.php \Drupal\date_recur\Plugin\Field\FieldType\DateRecurFieldItemList
  4. 3.0.x src/Plugin/Field/FieldType/DateRecurFieldItemList.php \Drupal\date_recur\Plugin\Field\FieldType\DateRecurFieldItemList

Recurring date field item list.

Hierarchy

Expanded class hierarchy of DateRecurFieldItemList

1 file declares its use of DateRecurFieldItemList
DateRecurValueEvent.php in src/Event/DateRecurValueEvent.php

File

src/Plugin/Field/FieldType/DateRecurFieldItemList.php, line 22

Namespace

Drupal\date_recur\Plugin\Field\FieldType
View source
class DateRecurFieldItemList extends DateRangeFieldItemList {

  /**
   * An event dispatcher, primarily for unit testing purposes.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|null
   */
  protected $eventDispatcher = NULL;

  /**
   * {@inheritdoc}
   */
  public function postSave($update) : bool {
    parent::postSave($update);
    $event = new DateRecurValueEvent($this, !$update);
    $this
      ->getDispatcher()
      ->dispatch(DateRecurEvents::FIELD_VALUE_SAVE, $event);
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function delete() : void {
    parent::delete();
    $event = new DateRecurValueEvent($this, FALSE);
    $this
      ->getDispatcher()
      ->dispatch(DateRecurEvents::FIELD_ENTITY_DELETE, $event);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteRevision() : void {
    parent::deleteRevision();
    $event = new DateRecurValueEvent($this, FALSE);
    $this
      ->getDispatcher()
      ->dispatch(DateRecurEvents::FIELD_REVISION_DELETE, $event);
  }

  /**
   * Get the event dispatcher.
   *
   * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
   *   The event dispatcher.
   */
  protected function getDispatcher() : EventDispatcherInterface {
    if (isset($this->eventDispatcher)) {
      return $this->eventDispatcher;
    }
    return \Drupal::service('event_dispatcher');
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) : array {
    $element = parent::defaultValuesForm($form, $form_state);
    $defaultValue = $this
      ->getFieldDefinition()
      ->getDefaultValueLiteral();
    $element['default_date_time_zone'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Start and end date time zone'),
      '#description' => $this
        ->t('Time zone is required if a default start date or end date is provided.'),
      '#options' => $this
        ->getTimeZoneOptions(),
      '#default_value' => $defaultValue[0]['default_date_time_zone'] ?? '',
      '#states' => [
        // Show the field if either start or end is set.
        'invisible' => [
          [
            ':input[name="default_value_input[default_date_type]"]' => [
              'value' => '',
            ],
            ':input[name="default_value_input[default_end_date_type]"]' => [
              'value' => '',
            ],
          ],
        ],
      ],
    ];
    $element['default_time_zone'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Time zone'),
      '#description' => $this
        ->t('Default time zone.'),
      '#options' => $this
        ->getTimeZoneOptions(),
      '#default_value' => $defaultValue[0]['default_time_zone'] ?? '',
      '#empty_option' => $this
        ->t('- Current user time zone -'),
    ];
    $element['default_rrule'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('RRULE'),
      '#default_value' => $defaultValue[0]['default_rrule'] ?? '',
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) : void {
    $defaultDateTimeZone = $form_state
      ->getValue([
      'default_value_input',
      'default_date_time_zone',
    ]);
    if (empty($defaultDateTimeZone)) {
      $defaultStartType = $form_state
        ->getValue([
        'default_value_input',
        'default_date_type',
      ]);
      if (!empty($defaultStartType)) {
        $form_state
          ->setErrorByName('default_value_input][default_date_time_zone', (string) $this
          ->t('Time zone must be provided if a default start date is provided.'));
      }
      $defaultEndType = $form_state
        ->getValue([
        'default_value_input',
        'default_end_date_type',
      ]);
      if (!empty($defaultEndType)) {
        $form_state
          ->setErrorByName('default_value_input][default_date_time_zone', (string) $this
          ->t('Time zone must be provided if a default end date is provided.'));
      }
    }
    parent::defaultValuesFormValidate($element, $form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) : array {
    $values = parent::defaultValuesFormSubmit($element, $form, $form_state);
    $rrule = $form_state
      ->getValue([
      'default_value_input',
      'default_rrule',
    ]);
    if ($rrule) {
      $values[0]['default_rrule'] = $rrule;
    }
    $defaultDateTimeZone = $form_state
      ->getValue([
      'default_value_input',
      'default_date_time_zone',
    ]);
    if ($defaultDateTimeZone) {
      $values[0]['default_date_time_zone'] = $defaultDateTimeZone;
    }
    $defaultTimeZone = $form_state
      ->getValue([
      'default_value_input',
      'default_time_zone',
    ]);
    if ($defaultTimeZone) {
      $values[0]['default_time_zone'] = $defaultTimeZone;
    }
    return $values;
  }

  /**
   * {@inheritdoc}
   */
  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) : array {
    assert(is_array($default_value));
    $defaultDateTimeZone = $default_value[0]['default_date_time_zone'] ?? NULL;
    $defaultValue = FieldItemList::processDefaultValue($default_value, $entity, $definition);
    $defaultValues = [
      [],
    ];
    $hasDefaultStartDateType = !empty($defaultValue[0]['default_date_type']);
    $hasDefaultEndDateType = !empty($defaultValue[0]['default_end_date_type']);
    if (!empty($defaultDateTimeZone) && ($hasDefaultStartDateType || $hasDefaultEndDateType)) {
      $storageFormat = $definition
        ->getSetting('datetime_type') == DateRecurItem::DATETIME_TYPE_DATE ? DateRecurItem::DATE_STORAGE_FORMAT : DateRecurItem::DATETIME_STORAGE_FORMAT;

      // Instruct 'value' and 'end_value' to convert from the localised time
      // zone to UTC.
      $formatSettings = [
        'timezone' => DateTimeItemInterface::STORAGE_TIMEZONE,
      ];
      if ($hasDefaultStartDateType) {
        $start_date = new DrupalDateTime($defaultValue[0]['default_date'], $defaultDateTimeZone);
        $start_value = $start_date
          ->format($storageFormat, $formatSettings);
        $defaultValues[0]['value'] = $start_value;
        $defaultValues[0]['start_date'] = $start_date;
      }
      if ($hasDefaultEndDateType) {
        $end_date = new DrupalDateTime($defaultValue[0]['default_end_date'], $defaultDateTimeZone);
        $end_value = $end_date
          ->format($storageFormat, $formatSettings);
        $defaultValues[0]['end_value'] = $end_value;
        $defaultValues[0]['end_date'] = $end_date;
      }
      $defaultValue = $defaultValues;
    }
    $rrule = $default_value[0]['default_rrule'] ?? NULL;
    if (!empty($rrule)) {
      $defaultValue[0]['rrule'] = $rrule;
    }
    $defaultTimeZone = $default_value[0]['default_time_zone'] ?? NULL;
    if (!empty($defaultTimeZone)) {
      $defaultValue[0]['timezone'] = $defaultTimeZone;
    }
    else {
      $timeZone = \date_default_timezone_get();
      if (empty($timeZone)) {
        throw new \Exception('Something went wrong. User has no time zone.');
      }
      $defaultValue[0]['timezone'] = $timeZone;
    }
    unset($defaultValue[0]['default_time_zone']);
    unset($defaultValue[0]['default_rrule']);
    return $defaultValue;
  }

  /**
   * 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() {
    return \system_time_zones(TRUE, TRUE);
  }

  /**
   * Set the event dispatcher.
   *
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
   *   The event dispatcher.
   */
  public function setEventDispatcher(EventDispatcherInterface $eventDispatcher) : void {
    $this->eventDispatcher = $eventDispatcher;
  }

  /**
   * Get the parts grid for this field.
   *
   * @return \Drupal\date_recur\DateRecurPartGrid
   *   The parts grid for this field.
   */
  public function getPartGrid() : DateRecurPartGrid {
    $partSettings = $this
      ->getFieldDefinition()
      ->getSetting('parts');

    // Existing field configs may not have a parts setting yet.
    $partSettings = $partSettings ?? [];
    return DateRecurPartGrid::configSettingsToGrid($partSettings);
  }

  /**
   * {@inheritdoc}
   */
  public function onChange($delta) {
    foreach ($this->list as $item) {
      assert($item instanceof DateRecurItem);
      $item
        ->resetHelper();
    }
    parent::onChange($delta);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateRecurFieldItemList::$eventDispatcher protected property An event dispatcher, primarily for unit testing purposes.
DateRecurFieldItemList::defaultValuesForm public function Returns a form for the default value input. Overrides DateRangeFieldItemList::defaultValuesForm
DateRecurFieldItemList::defaultValuesFormSubmit public function Processes the submitted default value. Overrides DateRangeFieldItemList::defaultValuesFormSubmit
DateRecurFieldItemList::defaultValuesFormValidate public function Validates the submitted default value. Overrides DateRangeFieldItemList::defaultValuesFormValidate
DateRecurFieldItemList::delete public function Defines custom delete behavior for field values. Overrides FieldItemList::delete
DateRecurFieldItemList::deleteRevision public function Defines custom revision delete behavior for field values. Overrides FieldItemList::deleteRevision
DateRecurFieldItemList::getDispatcher protected function Get the event dispatcher.
DateRecurFieldItemList::getPartGrid public function Get the parts grid for this field.
DateRecurFieldItemList::getTimeZoneOptions protected function Get a list of time zones suitable for a select field.
DateRecurFieldItemList::onChange public function React to changes to a child property or item. Overrides ItemList::onChange
DateRecurFieldItemList::postSave public function Defines custom post-save behavior for field values. Overrides FieldItemList::postSave
DateRecurFieldItemList::processDefaultValue public static function Processes the default value before being applied. Overrides DateRangeFieldItemList::processDefaultValue
DateRecurFieldItemList::setEventDispatcher public function Set the event dispatcher.
DateTimeFieldItemList::DEFAULT_VALUE_CUSTOM constant Defines the default value as relative.
DateTimeFieldItemList::DEFAULT_VALUE_NOW constant Defines the default value as now.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FieldItemList::$langcode protected property The langcode of the field values held in the object.
FieldItemList::$list protected property Numerically indexed array of field items. Overrides ItemList::$list 1
FieldItemList::access public function Checks data value access. Overrides AccessibleInterface::access 1
FieldItemList::applyDefaultValue public function Applies the default value. Overrides TypedData::applyDefaultValue
FieldItemList::createItem protected function Helper for creating a list item object. Overrides ItemList::createItem
FieldItemList::defaultAccess public function Contains the default access logic of this field. Overrides FieldItemListInterface::defaultAccess 3
FieldItemList::defaultValueWidget protected function Returns the widget object used in default value form.
FieldItemList::delegateMethod protected function Calls a method on each FieldItem.
FieldItemList::equals public function Determines equality to another object implementing FieldItemListInterface. Overrides FieldItemListInterface::equals 2
FieldItemList::filterEmptyItems public function Filters out empty field items and re-numbers the item deltas. Overrides FieldItemListInterface::filterEmptyItems
FieldItemList::generateSampleItems public function Populates a specified number of field items with valid sample data. Overrides FieldItemListInterface::generateSampleItems 1
FieldItemList::getConstraints public function Gets a list of validation constraints. Overrides TypedData::getConstraints 1
FieldItemList::getEntity public function Gets the entity that field belongs to. Overrides FieldItemListInterface::getEntity 1
FieldItemList::getFieldDefinition public function Gets the field definition. Overrides FieldItemListInterface::getFieldDefinition
FieldItemList::getLangcode public function Gets the langcode of the field values held in the object. Overrides FieldItemListInterface::getLangcode
FieldItemList::getSetting public function Returns the value of a given field setting. Overrides FieldItemListInterface::getSetting
FieldItemList::getSettings public function Returns the array of field settings. Overrides FieldItemListInterface::getSettings
FieldItemList::hasAffectingChanges public function Determines whether the field has relevant changes. Overrides FieldItemListInterface::hasAffectingChanges 1
FieldItemList::preSave public function Defines custom presave behavior for field values. Overrides FieldItemListInterface::preSave 1
FieldItemList::setLangcode public function Sets the langcode of the field values held in the object. Overrides FieldItemListInterface::setLangcode
FieldItemList::setValue public function Sets the data value. Overrides ItemList::setValue
FieldItemList::view public function Returns a renderable array for the field items. Overrides FieldItemListInterface::view
FieldItemList::__get public function Magic method: Gets a property value of to the first field item. Overrides FieldItemListInterface::__get
FieldItemList::__isset public function Magic method: Determines whether a property of the first field item is set. Overrides FieldItemListInterface::__isset
FieldItemList::__set public function Magic method: Sets a property value of the first field item. Overrides FieldItemListInterface::__set
FieldItemList::__unset public function Magic method: Unsets a property of the first field item. Overrides FieldItemListInterface::__unset
ItemList::appendItem public function Appends a new item to the list. Overrides ListInterface::appendItem
ItemList::count public function
ItemList::filter public function Filters the items in the list using a custom callback. Overrides ListInterface::filter
ItemList::first public function Returns the first item in this list. Overrides ListInterface::first
ItemList::get public function Returns the item at the specified position in this list. Overrides ListInterface::get 2
ItemList::getItemDefinition public function Gets the definition of a contained item. Overrides ListInterface::getItemDefinition
ItemList::getIterator public function
ItemList::getString public function Returns a string representation of the data. Overrides TypedData::getString
ItemList::getValue public function Gets the data value. Overrides TypedData::getValue
ItemList::isEmpty public function Determines whether the list contains any non-empty items. Overrides ListInterface::isEmpty
ItemList::offsetExists public function 1
ItemList::offsetGet public function
ItemList::offsetSet public function
ItemList::offsetUnset public function
ItemList::rekey protected function Renumbers the items in the list.
ItemList::removeItem public function Removes the item at the specified position. Overrides ListInterface::removeItem
ItemList::set public function Sets the value of the item at a given position in the list. Overrides ListInterface::set
ItemList::__clone public function Magic method: Implements a deep clone.
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.
TypedData::$definition protected property The data definition. 1
TypedData::$name protected property The property name.
TypedData::$parent protected property The parent typed data object.
TypedData::createInstance public static function Constructs a TypedData object given its definition and context. Overrides TypedDataInterface::createInstance
TypedData::getDataDefinition public function Gets the data definition. Overrides TypedDataInterface::getDataDefinition
TypedData::getName public function Returns the name of a property or item. Overrides TypedDataInterface::getName
TypedData::getParent public function Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface::getParent
TypedData::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
TypedData::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
TypedData::getPropertyPath public function Returns the property path of the data. Overrides TypedDataInterface::getPropertyPath
TypedData::getRoot public function Returns the root of the typed data tree. Overrides TypedDataInterface::getRoot
TypedData::setContext public function Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface::setContext
TypedData::validate public function Validates the currently set data value. Overrides TypedDataInterface::validate
TypedData::__construct public function Constructs a TypedData object given its definition and context. 3
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2