@@ -80,7 +80,10 @@ But if the form is not mapped to an object and you instead want to retrieve an
80
80
array of your submitted data, how can you add constraints to the data of
81
81
your form?
82
82
83
- The answer is to set up the constraints yourself, and attach them to the individual
83
+ Constraints At Field Level
84
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
85
+
86
+ One possibility is to set up the constraints yourself, and attach them to the individual
84
87
fields. The overall approach is covered a bit more in :doc: `this validation article </validation/raw_values >`,
85
88
but here's a short example::
86
89
@@ -123,3 +126,55 @@ but here's a short example::
123
126
When a form is only partially submitted (for example, in an HTTP PATCH
124
127
request), only the constraints from the submitted form fields will be
125
128
evaluated.
129
+
130
+ Constraints At Class Level
131
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
132
+
133
+ Another possibility is to add the constraints at the class level.
134
+ This can be done by setting the ``constraints `` option in the
135
+ ``configureOptions() `` method::
136
+
137
+ use Symfony\Component\Form\Extension\Core\Type\TextType;
138
+ use Symfony\Component\Form\FormBuilderInterface;
139
+ use Symfony\Component\OptionsResolver\OptionsResolver;
140
+ use Symfony\Component\Validator\Constraints\Length;
141
+ use Symfony\Component\Validator\Constraints\NotBlank;
142
+
143
+ public function buildForm(FormBuilderInterface $builder, array $options): void
144
+ {
145
+ $builder
146
+ ->add('firstName', TextType::class)
147
+ ->add('lastName', TextType::class);
148
+ }
149
+
150
+ public function configureOptions(OptionsResolver $resolver): void
151
+ {
152
+ $constraints = [
153
+ 'firstName' => new Length(['min' => 3]),
154
+ 'lastName' => [
155
+ new NotBlank(),
156
+ new Length(['min' => 3]),
157
+ ],
158
+ ];
159
+
160
+ $resolver->setDefaults([
161
+ 'data_class' => null,
162
+ 'constraints' => $constraints,
163
+ ]);
164
+ }
165
+
166
+ This means you can also do this when using the ``createFormBuilder() `` method
167
+ in your controller::
168
+
169
+ $form = $this->createFormBuilder($defaultData, [
170
+ 'constraints' => [
171
+ 'firstName' => new Length(['min' => 3]),
172
+ 'lastName' => [
173
+ new NotBlank(),
174
+ new Length(['min' => 3]),
175
+ ],
176
+ ],
177
+ ])
178
+ ->add('firstName', TextType::class)
179
+ ->add('lastName', TextType::class)
180
+ ->getForm();
0 commit comments