From e125ad559b3925248e541950a881dfe8a13af58c Mon Sep 17 00:00:00 2001 From: Indra Gunawan Date: Wed, 1 Oct 2025 18:15:34 +0800 Subject: [PATCH] support default value for new collection item --- src/LiveComponent/src/LiveCollectionTrait.php | 7 ++++- .../tests/Unit/LiveCollectionTraitTest.php | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/LiveComponent/src/LiveCollectionTrait.php b/src/LiveComponent/src/LiveCollectionTrait.php index 70f11f23b8b..e31b98e061d 100644 --- a/src/LiveComponent/src/LiveCollectionTrait.php +++ b/src/LiveComponent/src/LiveCollectionTrait.php @@ -34,7 +34,7 @@ public function addCollectionItem(PropertyAccessorInterface $propertyAccessor, # } $index = [] !== $data ? max(array_keys($data)) + 1 : 0; - $propertyAccessor->setValue($this->formValues, $propertyPath."[$index]", []); + $propertyAccessor->setValue($this->formValues, $propertyPath."[$index]", $this->setCollectionItemDefaultValue($propertyPath, $index)); } #[LiveAction] @@ -60,4 +60,9 @@ private function fieldNameToPropertyPath(string $collectionFieldName, string $ro return $propertyPath; } + + protected function setCollectionItemDefaultValue(string $propertyPath, int $index): iterable + { + return []; + } } diff --git a/src/LiveComponent/tests/Unit/LiveCollectionTraitTest.php b/src/LiveComponent/tests/Unit/LiveCollectionTraitTest.php index 12e92730e77..2c7876984f1 100644 --- a/src/LiveComponent/tests/Unit/LiveCollectionTraitTest.php +++ b/src/LiveComponent/tests/Unit/LiveCollectionTraitTest.php @@ -73,6 +73,23 @@ public static function provideAddedItems(): iterable ], ], ]; + yield 'named parent, default value' => [ + [ + 'parentName' => [ + 'collectionNameDefault' => null, + ], + ], + 'parentName[collectionNameDefault]', + [ + 'parentName' => [ + 'collectionNameDefault' => [ + 0 => [ + 'property' => 'value', + ], + ], + ], + ], + ]; yield 'named parent, empty array value' => [ [ 'parentName' => [ @@ -221,6 +238,17 @@ protected function instantiateForm(): FormInterface { return $this->theForm; } + + protected function setCollectionItemDefaultValue(string $propertyPath, int $index): iterable + { + if ('[collectionNameDefault]' === $propertyPath) { + return [ + 'property' => 'value', + ]; + } + + return []; + } }; $component->formName = array_key_first($postedFormData); $component->formValues = $postedFormData[$component->formName];