diff --git a/src/LiveComponent/doc/index.rst b/src/LiveComponent/doc/index.rst index a473881d50b..346fb9b0382 100644 --- a/src/LiveComponent/doc/index.rst +++ b/src/LiveComponent/doc/index.rst @@ -2651,6 +2651,47 @@ This way you can also use the component multiple times in the same page and avoi +.. versionadded:: 2.25 + + The property name is passed into the modifier function since LiveComponents 2.25. + +The ``modifier`` function can also take the name of the property as a secondary parameter. +It can be used to perform more generic operations inside of the modifier that can be re-used for multiple props:: + + abstract class AbstractSearchModule + { + #[LiveProp(writable: true, url: true, modifier: 'modifyQueryProp')] + public string $query = ''; + + protected string $urlPrefix = ''; + + public function modifyQueryProp(LiveProp $liveProp, string $propName): LiveProp + { + if ($this->urlPrefix) { + return $liveProp->withUrl(new UrlMapping(as: $this->urlPrefix.'-'.$propName)); + } + return $liveProp; + } + } + + #[AsLiveComponent] + class ImportantSearchModule extends AbstractSearchModule + { + } + + #[AsLiveComponent] + class SecondarySearchModule extends AbstractSearchModule + { + protected string $urlPrefix = 'secondary'; + } + +.. code-block:: html+twig + + + + +The ``query`` value will appear in the URL like ``/search?query=my+important+query&secondary-query=my+secondary+query``. + Validating the Query Parameter Values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/LiveComponent/src/Metadata/LivePropMetadata.php b/src/LiveComponent/src/Metadata/LivePropMetadata.php index b6a94b7f163..5fe8c154065 100644 --- a/src/LiveComponent/src/Metadata/LivePropMetadata.php +++ b/src/LiveComponent/src/Metadata/LivePropMetadata.php @@ -135,7 +135,7 @@ public function withModifier(object $component): self throw new \LogicException(\sprintf('Method "%s::%s()" given in LiveProp "modifier" does not exist.', $component::class, $modifier)); } - $modifiedLiveProp = $component->{$modifier}($this->liveProp); + $modifiedLiveProp = $component->{$modifier}($this->liveProp, $this->getName()); if (!$modifiedLiveProp instanceof LiveProp) { throw new \LogicException(\sprintf('Method "%s::%s()" should return an instance of "%s" (given: "%s").', $component::class, $modifier, LiveProp::class, get_debug_type($modifiedLiveProp))); } diff --git a/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php b/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php index bca2d262f74..b3ffd9f1bfa 100644 --- a/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php +++ b/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php @@ -29,7 +29,7 @@ public function testWithModifier() $component ->expects($this->once()) ->method('modifyProp') - ->with($liveProp) + ->with($liveProp, 'propWithModifier') ->willReturn($liveProp->withFieldName('customField')); $livePropMetadata = $livePropMetadata->withModifier($component);