From 9e1dfce088e3c8724910c9518e0122e510583976 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 30 Apr 2024 16:33:46 +0200 Subject: [PATCH] FieldsetElement: Correctly handle elements with multiple values fixes #136 --- src/FormElement/FieldsetElement.php | 11 ++++- tests/FormElement/FieldsetElementTest.php | 50 +++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/FormElement/FieldsetElement.php b/src/FormElement/FieldsetElement.php index 0d70ea4c..c18d4726 100644 --- a/src/FormElement/FieldsetElement.php +++ b/src/FormElement/FieldsetElement.php @@ -3,6 +3,7 @@ namespace ipl\Html\FormElement; use InvalidArgumentException; +use ipl\Html\Common\MultipleAttribute; use ipl\Html\Contract\FormElement; use ipl\Html\Contract\FormElementDecorator; use ipl\Html\Contract\Wrappable; @@ -107,15 +108,21 @@ public function setWrapper(Wrappable $wrapper) protected function onElementRegistered(FormElement $element) { $element->getAttributes()->registerAttributeCallback('name', function () use ($element) { + $multiple = false; + if (in_array(MultipleAttribute::class, class_uses($element), true)) { + $multiple = $element->isMultiple(); + } + /** * We don't change the {@see BaseFormElement::$name} property of the element, * otherwise methods like {@see FormElements::populate() and {@see FormElements::getElement()} would fail, * but only change the name attribute to nest the names. */ return sprintf( - '%s[%s]', + '%s[%s]%s', $this->getValueOfNameAttribute(), - $element->getName() + $element->getName(), + $multiple ? '[]' : '' ); }); } diff --git a/tests/FormElement/FieldsetElementTest.php b/tests/FormElement/FieldsetElementTest.php index 4d5227d4..feed37e2 100644 --- a/tests/FormElement/FieldsetElementTest.php +++ b/tests/FormElement/FieldsetElementTest.php @@ -270,4 +270,54 @@ public function testNestedFieldsetsAlsoOnlyHaveAValueIfOneOfTheirElementsHaveOne 'Nested fieldsets with non-empty elements are not non-empty themselves' ); } + + public function testMultiSelectionFieldInFieldset(): void + { + $fieldset = (new FieldsetElement('test_fieldset')) + ->addElement('select', 'test_select', [ + 'multiple' => true, + 'options' => [ + 'one' => 'One', + 'two' => 'Two' + ] + ]); + + $expected = <<<'HTML' +
+ +
+HTML; + + $this->assertHtml($expected, $fieldset); + } + + public function testMultiSelectionFieldInNestedFieldset(): void + { + $inner = (new FieldsetElement('inner')) + ->addElement('select', 'test_select', [ + 'multiple' => true, + 'options' => [ + 'one' => 'One', + 'two' => 'Two' + ] + ]); + $outer = (new FieldsetElement('outer')) + ->addElement($inner); + + $expected = <<<'HTML' +
+
+ +
+
+HTML; + + $this->assertHtml($expected, $outer); + } }