File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -177,3 +177,41 @@ in your controller::
177
177
->add('firstName', TextType::class)
178
178
->add('lastName', TextType::class)
179
179
->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
+ ;
You can’t perform that action at this time.
0 commit comments