Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit c8b48d8

Browse filesBrowse files
committed
feature #40430 [Form] Add "form_attr" FormType option (cristoforocervino)
This PR was squashed before being merged into the 5.3-dev branch. Discussion ---------- [Form] Add "form_attr" FormType option | Q | A | ------------- | --- | Branch? | 5.x | Bug fix? |no | New feature? | yes | Deprecations? | no | Tickets | N/A | License | MIT | Doc PR | [#15108](symfony/symfony-docs#15108) ## What is this about This PR add support for [`form` attribute](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form) to Symfony Form ([browser compatibility](https://caniuse.com/form-attribute)). The `form` attribute allows form elements to override their associated form (which is their nearest ancestor form element by default). This is extremely useful to solve **nested form problem** and allows **form children** to be **rendered outside form tag** while still working as expected. ## New "form_attr" FormType option #### form_attr **type**: `bool` or `string` **default**: `false` If set to `true` on a **root form**, adds [`form` attribute](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form) on every children with their root **form id**. This allows you to render form children outside the form tag and avoid **nested form problem** in some situations while keeping the form working properly. If set to `true` on a **child**, adds [`form` attribute](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form) on it with its **root form id**. This allows you to render **that child** outside the form tag and avoid **nested form problem** in some situations while keeping the form working properly. If root form has no `id` (this may happen by create an *unnamed* form), you can set it to a `string` identifier to be used at `FormView` level to link children and root form anyway. ## Usage on Root Form Example #### Form Type Enable the feature by setting `form_attr` to `true` on the root form. ```php use Symfony\Component\Form\Extension\Core\Type; class ListFilterType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('search', Type\SearchType::class) ->add('orderBy', Type\ChoiceType::class, [ 'choices' => [ // ... ], ]) ->add('perPage', Type\ChoiceType::class, [ 'choices' => [ // ... ], ]) } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('form_attr', true); // <--- Set this to true } } ``` #### Twig The following Twig template **works properly** even if form children are **outside** their form tag ([browser compatibility](https://caniuse.com/form-attribute)). ```twig <div class="header-filters"> {{ form_errors(form) }} {{ form_row(form.search) }} {# has attribute form="list_filter" #} {{ form_row(form.orderBy) }} {# has attribute form="list_filter" #} </div> <!-- --> <!-- Some other HTML content, like a table or even another Symfony form --> <!-- --> <div class="footer-filters"> {{ form_row(form.perPage) }} {# has attribute form="list_filter" #} </div> {{ form_start(form) }} {# id="list_filter" #} {{ form_end(form) }} ``` ✅ Every form elements work properly even outside form tag. ## Usage on Form Child Example Enable the feature by setting `form_attr` to `true` on selected child. ```php use Symfony\Component\Form\Extension\Core\Type; class ListFilterType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('search', Type\SearchType::class) ->add('orderBy', Type\ChoiceType::class, [ 'choices' => [ // ... ], ]) ->add('perPage', Type\ChoiceType::class, [ 'form_attr' => true, // <--- Set this to true 'choices' => [ // ... ], ]) } } ``` #### Twig The following Twig template **works properly** even if `form.perPage` is **outside** form tag ([browser compatibility](https://caniuse.com/form-attribute)). ```twig <div class="header-filters"> {{ form_start(form) }} {# id="list_filter" #} {{ form_errors(form) }} {{ form_row(form.search) }} {{ form_row(form.orderBy) }} {{ form_end(form, {'render_rest': false}) }} </div> <!-- --> <!-- Some other HTML content, like a table or even another Symfony form --> <!-- --> <div class="footer-filters"> {{ form_row(form.perPage) }} {# has attribute form="list_filter" #} </div> ``` ✅ `form.perPage` element work properly even outside form tag. Commits ------- 5f913ce [Form] Add "form_attr" FormType option
2 parents 1c22e6a + 5f913ce commit c8b48d8
Copy full SHA for c8b48d8

File tree

6 files changed

+80
-2
lines changed
Filter options

6 files changed

+80
-2
lines changed

‎src/Symfony/Component/Form/Extension/Core/Type/FormType.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Extension/Core/Type/FormType.php
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ public function buildView(FormView $view, FormInterface $form, array $options)
9696
}
9797

9898
$helpTranslationParameters = array_merge($view->parent->vars['help_translation_parameters'], $helpTranslationParameters);
99+
100+
$rootFormAttrOption = $form->getRoot()->getConfig()->getOption('form_attr');
101+
if ($options['form_attr'] || $rootFormAttrOption) {
102+
$view->vars['attr']['form'] = \is_string($rootFormAttrOption) ? $rootFormAttrOption : $form->getRoot()->getName();
103+
if (empty($view->vars['attr']['form'])) {
104+
throw new LogicException('"form_attr" option must be a string identifier on root form when it has no id.');
105+
}
106+
}
107+
} elseif (\is_string($options['form_attr'])) {
108+
$view->vars['id'] = $options['form_attr'];
99109
}
100110

101111
$formConfig = $form->getConfig();
@@ -210,6 +220,7 @@ public function configureOptions(OptionsResolver $resolver)
210220
'is_empty_callback' => null,
211221
'getter' => null,
212222
'setter' => null,
223+
'form_attr' => false,
213224
]);
214225

215226
$resolver->setAllowedTypes('label_attr', 'array');
@@ -221,6 +232,7 @@ public function configureOptions(OptionsResolver $resolver)
221232
$resolver->setAllowedTypes('is_empty_callback', ['null', 'callable']);
222233
$resolver->setAllowedTypes('getter', ['null', 'callable']);
223234
$resolver->setAllowedTypes('setter', ['null', 'callable']);
235+
$resolver->setAllowedTypes('form_attr', ['bool', 'string']);
224236

225237
$resolver->setInfo('getter', 'A callable that accepts two arguments (the view data and the current form field) and must return a value.');
226238
$resolver->setInfo('setter', 'A callable that accepts three arguments (a reference to the view data, the submitted value and the current form field).');

‎src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.php
+62Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Symfony\Component\Form\CallbackTransformer;
1515
use Symfony\Component\Form\DataMapperInterface;
1616
use Symfony\Component\Form\Exception\InvalidArgumentException;
17+
use Symfony\Component\Form\Exception\LogicException;
1718
use Symfony\Component\Form\Exception\TransformationFailedException;
1819
use Symfony\Component\Form\Extension\Core\Type\CurrencyType;
1920
use Symfony\Component\Form\Extension\Core\Type\FormType;
@@ -774,6 +775,67 @@ public function testErrorBubblingDoesNotSkipCompoundFieldsWithInheritDataConfigu
774775
$this->assertSame($error, $form->get('inherit_data_type')->getErrors()[0]);
775776
$this->assertCount(0, $form->get('inherit_data_type')->get('child')->getErrors());
776777
}
778+
779+
public function testFormAttrOnRoot()
780+
{
781+
$view = $this->factory
782+
->createNamedBuilder('parent', self::TESTED_TYPE, null, [
783+
'form_attr' => true,
784+
])
785+
->add('child1', $this->getTestedType())
786+
->add('child2', $this->getTestedType())
787+
->getForm()
788+
->createView();
789+
$this->assertArrayNotHasKey('form', $view->vars['attr']);
790+
$this->assertSame($view->vars['id'], $view['child1']->vars['attr']['form']);
791+
$this->assertSame($view->vars['id'], $view['child2']->vars['attr']['form']);
792+
}
793+
794+
public function testFormAttrOnChild()
795+
{
796+
$view = $this->factory
797+
->createNamedBuilder('parent', self::TESTED_TYPE)
798+
->add('child1', $this->getTestedType(), [
799+
'form_attr' => true,
800+
])
801+
->add('child2', $this->getTestedType())
802+
->getForm()
803+
->createView();
804+
$this->assertArrayNotHasKey('form', $view->vars['attr']);
805+
$this->assertSame($view->vars['id'], $view['child1']->vars['attr']['form']);
806+
$this->assertArrayNotHasKey('form', $view['child2']->vars['attr']);
807+
}
808+
809+
public function testFormAttrAsBoolWithNoId()
810+
{
811+
$this->expectException(LogicException::class);
812+
$this->expectErrorMessage('form_attr');
813+
$this->factory
814+
->createNamedBuilder('', self::TESTED_TYPE, null, [
815+
'form_attr' => true,
816+
])
817+
->add('child1', $this->getTestedType())
818+
->add('child2', $this->getTestedType())
819+
->getForm()
820+
->createView();
821+
}
822+
823+
public function testFormAttrAsStringWithNoId()
824+
{
825+
$stringId = 'custom-identifier';
826+
$view = $this->factory
827+
->createNamedBuilder('', self::TESTED_TYPE, null, [
828+
'form_attr' => $stringId,
829+
])
830+
->add('child1', $this->getTestedType())
831+
->add('child2', $this->getTestedType())
832+
->getForm()
833+
->createView();
834+
$this->assertArrayNotHasKey('form', $view->vars['attr']);
835+
$this->assertSame($stringId, $view->vars['id']);
836+
$this->assertSame($view->vars['id'], $view['child1']->vars['attr']['form']);
837+
$this->assertSame($view->vars['id'], $view['child2']->vars['attr']['form']);
838+
}
777839
}
778840

779841
class Money

‎src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_1.json

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_1.json
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"by_reference",
4141
"data",
4242
"disabled",
43+
"form_attr",
4344
"getter",
4445
"help",
4546
"help_attr",

‎src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_1.txt

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_1.txt
+3-2Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice")
1717
expanded by_reference
1818
group_by data
1919
multiple disabled
20-
placeholder getter
21-
preferred_choices help
20+
placeholder form_attr
21+
preferred_choices getter
22+
help
2223
help_attr
2324
help_html
2425
help_translation_parameters

‎src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_2.json

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_2.json
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"disabled",
1818
"empty_data",
1919
"error_bubbling",
20+
"form_attr",
2021
"getter",
2122
"help",
2223
"help_attr",

‎src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_2.txt

Copy file name to clipboardExpand all lines: src/Symfony/Component/Form/Tests/Fixtures/Descriptor/resolved_form_type_2.txt
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Symfony\Component\Form\Extension\Core\Type\FormType (Block prefix: "form")
1919
disabled
2020
empty_data
2121
error_bubbling
22+
form_attr
2223
getter
2324
help
2425
help_attr

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.