@@ -163,6 +163,72 @@ the above example, the ``allowMissingFields`` option was set to true, meaning
163
163
that if either of the ``personal_email `` or ``short_bio `` elements were missing
164
164
from the ``$personalData `` property, no validation error would occur.
165
165
166
+ .. versionadded :: 2.1
167
+ The ``Required `` and ``Optional `` constraints are new to Symfony 2.1.
168
+
169
+ Required and Optional Field Constraints
170
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
171
+
172
+ Constraints for fields within a collection can be wrapped in the ``Required `` or
173
+ ``Optional `` constraint to control whether they should always be applied (``Required ``)
174
+ or only applied when the field is present (``Optional ``).
175
+
176
+ For instance, if you want to require that the ``personal_email `` field of the
177
+ ``profileData `` array is not blank and is a valid email but the ``alternate_email ``
178
+ field is optional but must be a valid email if supplied, you can do the following:
179
+
180
+ .. configuration-block ::
181
+
182
+ .. code-block :: php-annotations
183
+
184
+ // src/Acme/BlogBundle/Entity/Author.php
185
+ namespace Acme\BlogBundle\Entity;
186
+
187
+ use Symfony\Component\Validator\Constraints as Assert;
188
+
189
+ class Author
190
+ {
191
+ /**
192
+ * @Assert\Collection(
193
+ * fields={
194
+ * "personal_email" = @Assert\Collection\Required({@Assert\NotBlank, @Assert\Email}),
195
+ * "alternate_email" = @Assert\Collection\Optional({@Assert\Email}),
196
+ * }
197
+ * )
198
+ */
199
+ protected $profileData = array(
200
+ 'personal_email',
201
+ );
202
+ }
203
+
204
+ .. code-block :: php
205
+
206
+ // src/Acme/BlogBundle/Entity/Author.php
207
+ namespace Acme\BlogBundle\Entity;
208
+
209
+ use Symfony\Component\Validator\Mapping\ClassMetadata;
210
+ use Symfony\Component\Validator\Constraints as Assert;
211
+
212
+ class Author
213
+ {
214
+ protected $profileData = array('personal_email');
215
+
216
+ public static function loadValidatorMetadata(ClassMetadata $metadata)
217
+ {
218
+ $metadata->addPropertyConstraint('profileData', new Assert\Collection(array(
219
+ 'fields' => array(
220
+ 'personal_email' => new Assert\Collection\Required(array(new Assert\NotBlank(), new Assert\Email())),
221
+ 'alternate_email' => new Assert\Collection\Optional(array(new Assert\Email())),
222
+ ),
223
+ )));
224
+ }
225
+ }
226
+
227
+ Even without ``allowMissingFields `` set to true, you can now omit the ``alternate_email `` property
228
+ completely from the ``profileData `` array, since it is ``Optional ``. However, if the the ``personal_email ``
229
+ field does not exist in the array there will be a constraint violation that the field is missing,
230
+ since it is ``Required ``.
231
+
166
232
Options
167
233
-------
168
234
0 commit comments