Skip to content

Commit bba67d8

Browse files
committed
[reference][validation] Adding missing Callback constrain
1 parent 35474b1 commit bba67d8

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

reference/constraints.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Validation Constraints Reference
88
constraints/False
99
constraints/True
1010
constraints/Type
11+
constraints/Callback
1112
constraints/Choice
1213
constraints/Collection
1314
constraints/Date
@@ -38,6 +39,7 @@ The following constraints are natively available in Symfony2:
3839
* :doc:`False <constraints/False>`
3940
* :doc:`True <constraints/True>`
4041
* :doc:`Type <constraints/Type>`
42+
* :doc:`Callback <constraints/Callback>`
4143
* :doc:`Choice <constraints/Choice>`
4244
* :doc:`Collection <constraints/Collection>`
4345
* :doc:`Date <constraints/Date>`

reference/constraints/Callback.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
Callback
2+
========
3+
4+
Calls methods during validation on the object. These methods can then perform
5+
any type of validation and assign errors where needed:
6+
7+
.. code-block:: yaml
8+
9+
Acme\DemoBundle\Entity\Author:
10+
constraints:
11+
- Callback:
12+
methods: [isAuthorValid]
13+
14+
Usage
15+
-----
16+
17+
The callback method is passed a special ``ExecutionContext`` object::
18+
19+
use Symfony\Component\Validator\ExecutionContext;
20+
21+
private $firstName;
22+
23+
public function isAuthorValid(ExecutionContext $context)
24+
{
25+
// somehow you get an array of "fake names"
26+
$fakeNames = array();
27+
28+
// check if the name is actually a fake name
29+
if (in_array($this->getFirstName(), $fakeNames)) {
30+
$property_path = $context->getPropertyPath() . '.firstName';
31+
$context->setPropertyPath($property_path);
32+
$context->addViolation('This name sounds totally fake', array(), null);
33+
}
34+
}
35+
36+
Options
37+
-------
38+
39+
* ``methods``: The method names that should be executed as callbacks.
40+
* ``message``: The error message if the validation fails

0 commit comments

Comments
 (0)