Skip to content

Commit e060e98

Browse files
committed
minor #21043 [Form] Document conditional constraints in forms without classes (javiereguiluz)
This PR was merged into the 6.4 branch. Discussion ---------- [Form] Document conditional constraints in forms without classes Fixes #19720. Commits ------- 1740bb6 [Form] Document conditional constraints in forms without classes
2 parents 56accda + 1740bb6 commit e060e98

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

form/without_class.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,3 +177,41 @@ in your controller::
177177
->add('firstName', TextType::class)
178178
->add('lastName', TextType::class)
179179
->getForm();
180+
181+
Conditional Constraints
182+
~~~~~~~~~~~~~~~~~~~~~~~
183+
184+
It's possible to define field constraints that depend on the value of other
185+
fields (e.g. a field must not be blank when another field has a certain value).
186+
To achieve this, use the ``expression`` option of the
187+
:doc:`When constraint </reference/constraints/When>` to reference the other field::
188+
189+
$builder
190+
->add('how_did_you_hear', ChoiceType::class, [
191+
'required' => true,
192+
'label' => 'How did you hear about us?',
193+
'choices' => [
194+
'Search engine' => 'search_engine',
195+
'Friends' => 'friends',
196+
'Other' => 'other',
197+
],
198+
'expanded' => true,
199+
'constraints' => [
200+
new Assert\NotBlank(),
201+
]
202+
])
203+
204+
// this field is only required if the value of the 'how_did_you_hear' field is 'other'
205+
->add('other_text', TextType::class, [
206+
'required' => false,
207+
'label' => 'Please specify',
208+
'constraints' => [
209+
new Assert\When(
210+
expression: 'this.getParent().get("how_did_you_hear").getData() == "other"',
211+
constraints: [
212+
new Assert\NotBlank(),
213+
],
214+
)
215+
],
216+
])
217+
;

0 commit comments

Comments
 (0)