@@ -268,6 +268,43 @@ semantic configuration described in the cookbook.
268
268
If you are defining services, they should also be prefixed with the bundle
269
269
alias.
270
270
271
+ Custom Validation Constraints
272
+ -----------------------------
273
+
274
+ Starting with Symfony 2.5, a new Validation API was introduced. In fact,
275
+ there are 3 modes, which the user can configure in their project:
276
+
277
+ * 2.4: the original 2.4 and earlier validation API;
278
+ * 2.5: the new 2.5 and later validation API;
279
+ * 2.5-BC: the new 2.5 API with a backwards-compatible layer so that the
280
+ 2.4 API still works. This is only available in PHP 5.3.9+.
281
+
282
+ As a bundle author, you'll want to support *both * API's, since some users
283
+ may still be using the 2.4 API. Specifically, if your bundle adds a violation
284
+ directly to the :class: `Symfony\C omponent\V alidator\C ontext\E xecutionContext `
285
+ (e.g. like in a custom validation constraint), you'll need to check for which
286
+ API is being used. The following code, would work for *all * users::
287
+
288
+ class ContainsAlphanumericValidator extends ConstraintValidator
289
+ {
290
+ public function validate($value, Constraint $constraint)
291
+ {
292
+ if ($this->context instanceof ExecutionContextInterface) {
293
+ // the 2.5 API
294
+ $this->context->buildViolation($constraint->message)
295
+ ->setParameter('%string%', $value)
296
+ ->addViolation();
297
+ );
298
+ } else {
299
+ // the 2.4 API
300
+ $this->context->addViolation(
301
+ $constraint->message,
302
+ array('%string%' => $value)
303
+ );
304
+ }
305
+ }
306
+ }
307
+
271
308
Learn more from the Cookbook
272
309
----------------------------
273
310
0 commit comments