diff --git a/CHANGELOG/CHANGELOG-DATA-STUDIO.md b/CHANGELOG/CHANGELOG-DATA-STUDIO.md index 89168063..b058edea 100644 --- a/CHANGELOG/CHANGELOG-DATA-STUDIO.md +++ b/CHANGELOG/CHANGELOG-DATA-STUDIO.md @@ -1,5 +1,13 @@ # Changelog +## 4.2.5 - UNRELEASED + +### Fixed + +- Fixed assignment of preset Date Range values in Date Source settings ([#320]) + +[#320]: https://github.com/barrelstrength/sprout/issues/320 + ## 4.2.4 - 2024-05-18 ### Fixed diff --git a/src/datastudio/components/elements/DataSetElement.php b/src/datastudio/components/elements/DataSetElement.php index 395788c1..1d5c5899 100644 --- a/src/datastudio/components/elements/DataSetElement.php +++ b/src/datastudio/components/elements/DataSetElement.php @@ -8,6 +8,7 @@ use BarrelStrength\Sprout\datastudio\components\elements\fieldlayoutelements\NameField; use BarrelStrength\Sprout\datastudio\datasets\DataSetRecord; use BarrelStrength\Sprout\datastudio\datasources\DataSource; +use BarrelStrength\Sprout\datastudio\datasources\DateRangeHelper; use BarrelStrength\Sprout\datastudio\DataStudioModule; use BarrelStrength\Sprout\datastudio\visualizations\Visualization; use Craft; @@ -298,6 +299,8 @@ public function beforeSave(bool $isNew): bool $this->name .= ' 1'; } + DateRangeHelper::handleBeforeSaveElement($this); + return parent::beforeSave($isNew); } diff --git a/src/datastudio/datasources/DateRangeHelper.php b/src/datastudio/datasources/DateRangeHelper.php index 39a9e29d..4d3a53df 100644 --- a/src/datastudio/datasources/DateRangeHelper.php +++ b/src/datastudio/datasources/DateRangeHelper.php @@ -2,6 +2,7 @@ namespace BarrelStrength\Sprout\datastudio\datasources; +use BarrelStrength\Sprout\datastudio\components\elements\DataSetElement; use Craft; use craft\helpers\DateTimeHelper; use DateTimeInterface; @@ -34,6 +35,30 @@ public static function getUtcDateTime(mixed $dateSetting): ?DateTimeInterface return $dateTime->setTimezone($timeZone); } + /** + * We need to null out these date values when not in use or the date returns as a boolean + * and throws an error when assigned to the startDate and endDate properties + */ + public static function handleBeforeSaveElement(DataSetElement $element): void + { + // If the Data Source uses the DateRangeTrait, set the start and end date to null + if (!in_array(DateRangeTrait::class, class_uses($element->type), true)) { + return; + } + + if (!isset($element->settings['dateRange'])) { + return; + } + + if ($element->settings['dateRange'] === self::RANGE_CUSTOM) { + return; + } + + // If we're not using a custom date range, set the start and end date to null + $element->settings['startDate'] = null; + $element->settings['endDate'] = null; + } + public static function getStartEndDateRange($value): array { // The date function still return date based on the cpPanel timezone settings