From 0a88191394a7f5710338ce73c94ddae831607918 Mon Sep 17 00:00:00 2001 From: brandonkelly Date: Wed, 15 May 2019 07:06:05 -0700 Subject: [PATCH] Reset Matrix & relation field values after saving a new element --- CHANGELOG-v3.md | 1 + src/fields/BaseRelationField.php | 5 +++++ src/services/Matrix.php | 5 +++++ 3 files changed, 11 insertions(+) diff --git a/CHANGELOG-v3.md b/CHANGELOG-v3.md index 524c22160d3..dbce897468e 100644 --- a/CHANGELOG-v3.md +++ b/CHANGELOG-v3.md @@ -5,6 +5,7 @@ ### Fixed - Fixed a bug where slugs could get double-hyphenated. ([#4266](https://github.com/craftcms/cms/issues/4266)) - Fixed an error that would occur when installing Craft if the `allowAdminChanges` config setting was disabled. ([#4267](https://github.com/craftcms/cms/issues/4267)) +- Fixed a bug where Matrix fields would return the wrong set of Matrix blocks on new or duplicated elements, immediately after they were saved. ## 3.1.27 - 2019-05-14 diff --git a/src/fields/BaseRelationField.php b/src/fields/BaseRelationField.php index 1731794fe86..421abd8de1d 100644 --- a/src/fields/BaseRelationField.php +++ b/src/fields/BaseRelationField.php @@ -543,6 +543,11 @@ public function afterElementSave(ElementInterface $element, bool $isNew) /** @var int|int[]|false|null $targetIds */ Craft::$app->getRelations()->saveRelations($this, $element, $targetIds); + + // Reset the field value if this is a new element + if ($isNew) { + $element->setFieldValue($this->handle, null); + } } parent::afterElementSave($element, $isNew); diff --git a/src/services/Matrix.php b/src/services/Matrix.php index 514e0d5c67c..4a84f82d5ee 100644 --- a/src/services/Matrix.php +++ b/src/services/Matrix.php @@ -814,6 +814,11 @@ public function saveField(MatrixField $field, ElementInterface $owner) throw $e; } + // Reset the field value if this is a new element + if ($owner->duplicateOf || !$query->ownerId) { + $owner->setFieldValue($field->handle, null); + } + // Tell the browser to collapse any new block IDs if (!Craft::$app->getRequest()->getIsConsoleRequest() && !Craft::$app->getResponse()->isSent && !empty($collapsedBlockIds)) { Craft::$app->getSession()->addAssetBundleFlash(MatrixAsset::class);