|
19 | 19 | use Symfony\Component\PropertyAccess\PropertyAccessorInterface; |
20 | 20 | use Symfony\UX\LiveComponent\Attribute\LiveAction; |
21 | 21 | use Symfony\UX\LiveComponent\Attribute\LiveArg; |
| 22 | +use Symfony\UX\LiveComponent\Attribute\LiveListener; |
22 | 23 | use Symfony\UX\LiveComponent\Attribute\LiveProp; |
23 | 24 | use Symfony\UX\LiveComponent\ComponentToolsTrait; |
24 | 25 | use Symfony\UX\LiveComponent\ComponentWithFormTrait; |
@@ -76,4 +77,35 @@ protected function instantiateForm(): FormInterface |
76 | 77 | $this->data, |
77 | 78 | ); |
78 | 79 | } |
| 80 | + |
| 81 | + #[LiveListener('media-manager:file-selected')] |
| 82 | + public function mediaManagerFileSelected( |
| 83 | + #[LiveArg] |
| 84 | + string $inputName, |
| 85 | + #[LiveArg] |
| 86 | + string $filePath, |
| 87 | + ): void { |
| 88 | + // Support any depth: e.g. menu_item[linkSettings][thumbnail] or menu_item[foo][bar][baz] |
| 89 | + $inputNameParts = explode('[', str_replace(']', '', $inputName)); |
| 90 | + // Remove the first part (form name, e.g. menu_item) |
| 91 | + array_shift($inputNameParts); |
| 92 | + $this->setFormValueByPath($inputNameParts, $filePath); |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * Set a value in formValues using a path array (e.g. ['linkSettings','thumbnail']). |
| 97 | + * |
| 98 | + * @param array<int, string> $path |
| 99 | + */ |
| 100 | + private function setFormValueByPath(array $path, mixed $value): void |
| 101 | + { |
| 102 | + $ref = &$this->formValues; |
| 103 | + foreach ($path as $segment) { |
| 104 | + if (!isset($ref[$segment]) || !\is_array($ref[$segment])) { |
| 105 | + $ref[$segment] = []; |
| 106 | + } |
| 107 | + $ref = &$ref[$segment]; |
| 108 | + } |
| 109 | + $ref = $value; |
| 110 | + } |
79 | 111 | } |
0 commit comments