Commit 5406adb3 authored by Josh Fabean's avatar Josh Fabean Committed by Josh Fabean
Browse files

Issue #3325454 by josh.fabean: When Deleting a Opening Instance Directly...

Issue #3325454 by josh.fabean: When Deleting a Opening Instance Directly resaving the Opening Will Recreate it
parent 96b933a0
Loading
Loading
Loading
Loading
+49 −0
Original line number Diff line number Diff line
@@ -9,6 +9,7 @@ use Drupal\bookable_calendar\BookableCalendarOpeningInstanceInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\bookable_calendar\DateFormatter;
use Drupal\Core\Database\Connection;

/**
 * Defines the bookable calendar opening instance entity class.
@@ -189,6 +190,54 @@ class BookableCalendarOpeningInstance extends ContentEntityBase implements Booka
    parent::postSave($storage, $update);
  }

  /**
   * When an Instance is deleted remove it from the repeat rule on the parent opening
   *
   * {@inheritdoc}
   */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    foreach ($entities as $entity) {
      $start_date = $entity->date->value;
      $end_date = $entity->date->end_value;
      $opening = $entity->booking_opening->entity;
      $database = \Drupal::database();

      // Find rrule instance we need to remove.
      $instance_to_delete = $database->select('bookable_calendar_opening__date', 'date')
      ->condition('date.entity_id', $opening->id())
      ->condition('date.date_value', $start_date)
      ->condition('date.date_end_value', $end_date)
      ->fields('date', [
        'entity_id',
        'date_value',
        'date_end_value',
        'date_rrule',
        'date_rrule_index'
      ])
      ->execute()->fetch();

      if (!is_null($instance_to_delete)) {
        // If we found an instance to delete, delete it.
        $database->delete('bookable_calendar_opening__date')
          ->condition('entity_id', $opening->id())
          ->condition('date_value', $start_date)
          ->condition('date_end_value', $end_date)
          ->execute();

        // Also add override so it doesn't come back.
        $smart_date_override_storage = \Drupal::entityTypeManager()->getStorage('smart_date_override');
        $new_smart_date = $smart_date_override_storage->create([
          'rrule' => $instance_to_delete->date_rrule,
          'rrule_index' => $instance_to_delete->date_rrule_index,
          'value' => null,
          'end_value' => null,
          'duration' => null
        ]);
        $new_smart_date->save();
      }
    }
  }

  /**
   * How many remaining slots are there.
   *