Skip to content

Commit dbdb408

Browse files
committed
feature #4724 [Reference][Constraints] document the validation payload option (xabbuh)
This PR was merged into the 2.6 branch. Discussion ---------- [Reference][Constraints] document the validation payload option | Q | A | ------------- | --- | Doc fix? | no | New docs? | yes (symfony/symfony#12005) | Applies to | 2.6+ | Fixed tickets | #4274 Commits ------- dca4655 document the validation payload option
2 parents 5e08856 + dca4655 commit dbdb408

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+315
-1
lines changed

cookbook/map.rst.inc

+1
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@
220220
* :doc:`/cookbook/validation/index`
221221

222222
* :doc:`/cookbook/validation/custom_constraint`
223+
* :doc:`/cookbook/validation/severity`
223224

224225
* :doc:`/cookbook/web_server/index`
225226

cookbook/validation/index.rst

+1
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ Validation
55
:maxdepth: 2
66

77
custom_constraint
8+
severity

cookbook/validation/severity.rst

+165
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
.. index::
2+
single: Validation; Error Levels
3+
single: Validation; Payload
4+
5+
How to Handle Different Error Levels
6+
====================================
7+
8+
Sometimes, you may want to display constraint validation error messages differently
9+
based on some rules. For example, you have a registration form for new users
10+
where they enter some personal information and choose their authentication
11+
credentials. They would have to choose a username and a secure password,
12+
but providing bank account information would be optional. Nonetheless, you
13+
want to make sure that these optional data, if entered, are still valid,
14+
but display them differently.
15+
16+
The process to achieve this behavior consists of two steps:
17+
18+
#. Apply different error levels to the validation constraints;
19+
#. Customize your error messages depending on the configured error level.
20+
21+
1. Assigning the Error Level
22+
----------------------------
23+
24+
.. versionadded:: 2.6
25+
The ``payload`` option was introduced in Symfony 2.6.
26+
27+
Use the ``payload`` option to configure the error level for each constraint:
28+
29+
.. configuration-block::
30+
31+
.. code-block:: php-annotations
32+
33+
// src/AppBundle/Entity/User.php
34+
namespace AppBundle\Entity;
35+
36+
use Symfony\Component\Validator\Constraints as Assert;
37+
38+
class User
39+
{
40+
/**
41+
* @Assert\NotBlank(payload = {severity = "error"})
42+
*/
43+
protected $username;
44+
45+
/**
46+
* @Assert\NotBlank(payload = {severity = "error"})
47+
*/
48+
protected $password;
49+
50+
/**
51+
* @Assert\Iban(payload = {severity = "warning"})
52+
*/
53+
protected $bankAccountNumber;
54+
}
55+
56+
.. code-block:: yaml
57+
58+
# src/AppBundle/Resources/config/validation.yml
59+
AppBundle\Entity\User:
60+
properties:
61+
username:
62+
- NotBlank:
63+
payload:
64+
severity: error
65+
password:
66+
- NotBlank:
67+
payload:
68+
severity: error
69+
bankAccountNumber:
70+
- Iban:
71+
payload:
72+
severity: warning
73+
74+
.. code-block:: xml
75+
76+
<!-- src/AppBundle/Resources/config/validation.xml -->
77+
<?xml version="1.0" encoding="UTF-8" ?>
78+
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
79+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
80+
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
81+
82+
<class name="AppBundle\Entity\User">
83+
<property name="username">
84+
<constraint name="NotBlank">
85+
<option name="payload">
86+
<value key="severity">error</value>
87+
</option>
88+
</constraint>
89+
</property>
90+
<property name="password">
91+
<constraint name="NotBlank">
92+
<option name="payload">
93+
<value key="severity">error</value>
94+
</option>
95+
</constraint>
96+
</property>
97+
<property name="bankAccountNumber">
98+
<constraint name="Iban">
99+
<option name="payload">
100+
<value key="severity">warning</value>
101+
</option>
102+
</constraint>
103+
</property>
104+
</class>
105+
</constraint-mapping>
106+
107+
.. code-block:: php
108+
109+
// src/AppBundle/Entity/User.php
110+
namespace AppBundle\Entity;
111+
112+
use Symfony\Component\Validator\Mapping\ClassMetadata;
113+
use Symfony\Component\Validator\Constraints as Assert;
114+
115+
class User
116+
{
117+
public static function loadValidatorMetadata(ClassMetadata $metadata)
118+
{
119+
$metadata->addPropertyConstraint('username', new Assert\NotBlank(array(
120+
'payload' => array('severity' => 'error'),
121+
)));
122+
$metadata->addPropertyConstraint('password', new Assert\NotBlank(array(
123+
'payload' => array('severity' => 'error'),
124+
)));
125+
$metadata->addPropertyConstraint('bankAccountNumber', new Assert\Iban(array(
126+
'payload' => array('severity' => 'warning'),
127+
)));
128+
}
129+
}
130+
131+
2. Customize the Error Message Template
132+
---------------------------------------
133+
134+
.. versionadded:: 2.6
135+
The ``getConstraint()`` method in the ``ConstraintViolation`` class was
136+
introduced in Symfony 2.6.
137+
138+
When validating the ``User`` object failed, you can retrieve the constraint
139+
that caused a particular failure using the
140+
:method:`Symfony\\Component\\Validator\\ConstraintViolation::getConstraint`
141+
method. Each constraint exposes the attached payload as a public property::
142+
143+
// a constraint validation failure, instance of
144+
// Symfony\Component\Validator\ConstraintViolation
145+
$constraintViolation = ...;
146+
$constraint = $constraintViolation->getConstraint();
147+
$severity = isset($constraint->payload['severity']) ? $constraint->payload['severity'] : null;
148+
149+
For example, you can leverage this to customize the ``form_errors`` block
150+
such that the severity is added as an additional HTML class:
151+
152+
.. code-block:: html+jinja
153+
154+
{%- block form_errors -%}
155+
{%- if errors|length > 0 -%}
156+
<ul>
157+
{%- for error in errors -%}
158+
{% if error.cause.constraint.payload.severity is defined %}
159+
{% set severity = error.cause.constraint.payload.severity %}
160+
{% endif %}
161+
<li{% if severity is defined %} class="{{ severity }}"{% endif %}>{{ error.message }}</li>
162+
{%- endfor -%}
163+
</ul>
164+
{%- endif -%}
165+
{%- endblock form_errors -%}

reference/constraints/All.rst

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ you to apply a collection of constraints to each element of the array.
88
| Applies to | :ref:`property or method <validation-property-target>` |
99
+----------------+------------------------------------------------------------------------+
1010
| Options | - `constraints`_ |
11+
| | - `payload`_ |
1112
+----------------+------------------------------------------------------------------------+
1213
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\All` |
1314
+----------------+------------------------------------------------------------------------+
@@ -107,3 +108,5 @@ constraints
107108

108109
This required option is the array of validation constraints that you want
109110
to apply to each element of the underlying array.
111+
112+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Blank.rst

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ blank, see :doc:`/reference/constraints/NotBlank`.
1010
| Applies to | :ref:`property or method <validation-property-target>` |
1111
+----------------+-----------------------------------------------------------------------+
1212
| Options | - `message`_ |
13+
| | - `payload`_ |
1314
+----------------+-----------------------------------------------------------------------+
1415
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Blank` |
1516
+----------------+-----------------------------------------------------------------------+
@@ -87,3 +88,5 @@ message
8788
**type**: ``string`` **default**: ``This value should be blank.``
8889

8990
This is the message that will be shown if the value is not blank.
91+
92+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Callback.rst

+3
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ can do anything, including creating and assigning validation errors.
2121
| Applies to | :ref:`class <validation-class-target>` |
2222
+----------------+------------------------------------------------------------------------+
2323
| Options | - :ref:`callback <callback-option>` |
24+
| | - `payload`_ |
2425
+----------------+------------------------------------------------------------------------+
2526
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Callback` |
2627
+----------------+------------------------------------------------------------------------+
@@ -297,3 +298,5 @@ instance as only argument.
297298
Static or closure callbacks receive the validated object as the first argument
298299
and the :class:`Symfony\\Component\\Validator\\ExecutionContextInterface`
299300
instance as the second argument.
301+
302+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/CardScheme.rst

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ through a payment gateway.
1010
+----------------+--------------------------------------------------------------------------+
1111
| Options | - `schemes`_ |
1212
| | - `message`_ |
13+
| | - `payload`_ |
1314
+----------------+--------------------------------------------------------------------------+
1415
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\CardScheme` |
1516
+----------------+--------------------------------------------------------------------------+
@@ -124,4 +125,6 @@ message
124125

125126
The message shown when the value does not pass the ``CardScheme`` check.
126127

128+
.. include:: /reference/constraints/_payload-option.rst.inc
129+
127130
.. _`Wikipedia: Issuer identification number (IIN)`: http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29

reference/constraints/Choice.rst

+3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ an array of items is one of those valid choices.
1818
| | - `minMessage`_ |
1919
| | - `maxMessage`_ |
2020
| | - `strict`_ |
21+
| | - `payload`_ |
2122
+----------------+-----------------------------------------------------------------------+
2223
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Choice` |
2324
+----------------+-----------------------------------------------------------------------+
@@ -349,3 +350,5 @@ strict
349350
If true, the validator will also check the type of the input value. Specifically,
350351
this value is passed to as the third argument to the PHP :phpfunction:`in_array` method
351352
when checking to see if a value is in the valid choices array.
353+
354+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Collection.rst

+3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ and that extra keys are not present.
1818
| | - `extraFieldsMessage`_ |
1919
| | - `allowMissingFields`_ |
2020
| | - `missingFieldsMessage`_ |
21+
| | - `payload`_ |
2122
+----------------+--------------------------------------------------------------------------+
2223
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Collection` |
2324
+----------------+--------------------------------------------------------------------------+
@@ -328,3 +329,5 @@ missingFieldsMessage
328329

329330
The message shown if `allowMissingFields`_ is false and one or more fields
330331
are missing from the underlying collection.
332+
333+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Count.rst

+3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ element count is *between* some minimum and maximum value.
1212
| | - `minMessage`_ |
1313
| | - `maxMessage`_ |
1414
| | - `exactMessage`_ |
15+
| | - `payload`_ |
1516
+----------------+---------------------------------------------------------------------+
1617
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Count` |
1718
+----------------+---------------------------------------------------------------------+
@@ -139,3 +140,5 @@ exactMessage
139140

140141
The message that will be shown if min and max values are equal and the underlying collection elements
141142
count is not exactly this value.
143+
144+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Country.rst

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Validates that a value is a valid `ISO 3166-1 alpha-2`_ country code.
77
| Applies to | :ref:`property or method <validation-property-target>` |
88
+----------------+------------------------------------------------------------------------+
99
| Options | - `message`_ |
10+
| | - `payload`_ |
1011
+----------------+------------------------------------------------------------------------+
1112
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Country` |
1213
+----------------+------------------------------------------------------------------------+
@@ -82,4 +83,6 @@ message
8283

8384
This message is shown if the string is not a valid country code.
8485

86+
.. include:: /reference/constraints/_payload-option.rst.inc
87+
8588
.. _`ISO 3166-1 alpha-2`: http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes

reference/constraints/Currency.rst

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Validates that a value is a valid `3-letter ISO 4217`_ currency name.
1010
| Applies to | :ref:`property or method<validation-property-target>` |
1111
+----------------+---------------------------------------------------------------------------+
1212
| Options | - `message`_ |
13+
| | - `payload`_ |
1314
+----------------+---------------------------------------------------------------------------+
1415
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Currency` |
1516
+----------------+---------------------------------------------------------------------------+
@@ -88,4 +89,6 @@ message
8889

8990
This is the message that will be shown if the value is not a valid currency.
9091

92+
.. include:: /reference/constraints/_payload-option.rst.inc
93+
9194
.. _`3-letter ISO 4217`: http://en.wikipedia.org/wiki/ISO_4217

reference/constraints/Date.rst

+3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ valid YYYY-MM-DD format.
99
| Applies to | :ref:`property or method <validation-property-target>` |
1010
+----------------+--------------------------------------------------------------------+
1111
| Options | - `message`_ |
12+
| | - `payload`_ |
1213
+----------------+--------------------------------------------------------------------+
1314
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Date` |
1415
+----------------+--------------------------------------------------------------------+
@@ -83,3 +84,5 @@ message
8384
**type**: ``string`` **default**: ``This value is not a valid date.``
8485

8586
This message is shown if the underlying data is not a valid date.
87+
88+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/DateTime.rst

+3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ a valid YYYY-MM-DD HH:MM:SS format.
99
| Applies to | :ref:`property or method <validation-property-target>` |
1010
+----------------+------------------------------------------------------------------------+
1111
| Options | - `message`_ |
12+
| | - `payload`_ |
1213
+----------------+------------------------------------------------------------------------+
1314
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\DateTime` |
1415
+----------------+------------------------------------------------------------------------+
@@ -83,3 +84,5 @@ message
8384
**type**: ``string`` **default**: ``This value is not a valid datetime.``
8485

8586
This message is shown if the underlying data is not a valid datetime.
87+
88+
.. include:: /reference/constraints/_payload-option.rst.inc

reference/constraints/Email.rst

+4-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ cast to a string before being validated.
1111
| | - `message`_ |
1212
| | - `checkMX`_ |
1313
| | - `checkHost`_ |
14+
| | - `payload`_ |
1415
+----------------+---------------------------------------------------------------------+
1516
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Email` |
1617
+----------------+---------------------------------------------------------------------+
@@ -99,7 +100,7 @@ strict
99100
**type**: ``boolean`` **default**: ``false``
100101

101102
When false, the email will be validated against a simple regular expression.
102-
If true, then the `egulias/email-validator`_ library is required to perform
103+
If true, then the `egulias/email-validator`_ library is required to perform
103104
an RFC compliant validation.
104105

105106
message
@@ -126,4 +127,6 @@ If true, then the :phpfunction:`checkdnsrr` PHP function will be used to
126127
check the validity of the MX *or* the A *or* the AAAA record of the host
127128
of the given email.
128129

130+
.. include:: /reference/constraints/_payload-option.rst.inc
131+
129132
.. _egulias/email-validator: https://packagist.org/packages/egulias/email-validator

reference/constraints/EqualTo.rst

+3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ force that a value is *not* equal, see :doc:`/reference/constraints/NotEqualTo`.
1818
+----------------+-----------------------------------------------------------------------+
1919
| Options | - `value`_ |
2020
| | - `message`_ |
21+
| | - `payload`_ |
2122
+----------------+-----------------------------------------------------------------------+
2223
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\EqualTo` |
2324
+----------------+-----------------------------------------------------------------------+
@@ -104,3 +105,5 @@ message
104105
**type**: ``string`` **default**: ``This value should be equal to {{ compared_value }}.``
105106

106107
This is the message that will be shown if the value is not equal.
108+
109+
.. include:: /reference/constraints/_payload-option.rst.inc

0 commit comments

Comments
 (0)