Skip to content

Commit

Permalink
feature #4724 [Reference][Constraints] document the validation payloa…
Browse files Browse the repository at this point in the history
…d 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
  • Loading branch information
weaverryan committed Mar 13, 2015
2 parents 5e08856 + dca4655 commit dbdb408
Show file tree
Hide file tree
Showing 48 changed files with 315 additions and 1 deletion.
1 change: 1 addition & 0 deletions cookbook/map.rst.inc
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@
* :doc:`/cookbook/validation/index`

* :doc:`/cookbook/validation/custom_constraint`
* :doc:`/cookbook/validation/severity`

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

Expand Down
1 change: 1 addition & 0 deletions cookbook/validation/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Validation
:maxdepth: 2

custom_constraint
severity
165 changes: 165 additions & 0 deletions cookbook/validation/severity.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
.. index::
single: Validation; Error Levels
single: Validation; Payload

How to Handle Different Error Levels
====================================

Sometimes, you may want to display constraint validation error messages differently
based on some rules. For example, you have a registration form for new users
where they enter some personal information and choose their authentication
credentials. They would have to choose a username and a secure password,
but providing bank account information would be optional. Nonetheless, you
want to make sure that these optional data, if entered, are still valid,
but display them differently.

The process to achieve this behavior consists of two steps:

#. Apply different error levels to the validation constraints;
#. Customize your error messages depending on the configured error level.

1. Assigning the Error Level
----------------------------

.. versionadded:: 2.6
The ``payload`` option was introduced in Symfony 2.6.

Use the ``payload`` option to configure the error level for each constraint:

.. configuration-block::

.. code-block:: php-annotations
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class User
{
/**
* @Assert\NotBlank(payload = {severity = "error"})
*/
protected $username;
/**
* @Assert\NotBlank(payload = {severity = "error"})
*/
protected $password;
/**
* @Assert\Iban(payload = {severity = "warning"})
*/
protected $bankAccountNumber;
}
.. code-block:: yaml
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\User:
properties:
username:
- NotBlank:
payload:
severity: error
password:
- NotBlank:
payload:
severity: error
bankAccountNumber:
- Iban:
payload:
severity: warning
.. code-block:: xml
<!-- src/AppBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="AppBundle\Entity\User">
<property name="username">
<constraint name="NotBlank">
<option name="payload">
<value key="severity">error</value>
</option>
</constraint>
</property>
<property name="password">
<constraint name="NotBlank">
<option name="payload">
<value key="severity">error</value>
</option>
</constraint>
</property>
<property name="bankAccountNumber">
<constraint name="Iban">
<option name="payload">
<value key="severity">warning</value>
</option>
</constraint>
</property>
</class>
</constraint-mapping>
.. code-block:: php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
class User
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('username', new Assert\NotBlank(array(
'payload' => array('severity' => 'error'),
)));
$metadata->addPropertyConstraint('password', new Assert\NotBlank(array(
'payload' => array('severity' => 'error'),
)));
$metadata->addPropertyConstraint('bankAccountNumber', new Assert\Iban(array(
'payload' => array('severity' => 'warning'),
)));
}
}
2. Customize the Error Message Template
---------------------------------------

.. versionadded:: 2.6
The ``getConstraint()`` method in the ``ConstraintViolation`` class was
introduced in Symfony 2.6.

When validating the ``User`` object failed, you can retrieve the constraint
that caused a particular failure using the
:method:`Symfony\\Component\\Validator\\ConstraintViolation::getConstraint`
method. Each constraint exposes the attached payload as a public property::

// a constraint validation failure, instance of
// Symfony\Component\Validator\ConstraintViolation
$constraintViolation = ...;
$constraint = $constraintViolation->getConstraint();
$severity = isset($constraint->payload['severity']) ? $constraint->payload['severity'] : null;

For example, you can leverage this to customize the ``form_errors`` block
such that the severity is added as an additional HTML class:

.. code-block:: html+jinja

{%- block form_errors -%}
{%- if errors|length > 0 -%}
<ul>
{%- for error in errors -%}
{% if error.cause.constraint.payload.severity is defined %}
{% set severity = error.cause.constraint.payload.severity %}
{% endif %}
<li{% if severity is defined %} class="{{ severity }}"{% endif %}>{{ error.message }}</li>
{%- endfor -%}
</ul>
{%- endif -%}
{%- endblock form_errors -%}
3 changes: 3 additions & 0 deletions reference/constraints/All.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ you to apply a collection of constraints to each element of the array.
| Applies to | :ref:`property or method <validation-property-target>` |
+----------------+------------------------------------------------------------------------+
| Options | - `constraints`_ |
| | - `payload`_ |
+----------------+------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\All` |
+----------------+------------------------------------------------------------------------+
Expand Down Expand Up @@ -107,3 +108,5 @@ constraints

This required option is the array of validation constraints that you want
to apply to each element of the underlying array.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/Blank.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ blank, see :doc:`/reference/constraints/NotBlank`.
| Applies to | :ref:`property or method <validation-property-target>` |
+----------------+-----------------------------------------------------------------------+
| Options | - `message`_ |
| | - `payload`_ |
+----------------+-----------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Blank` |
+----------------+-----------------------------------------------------------------------+
Expand Down Expand Up @@ -87,3 +88,5 @@ message
**type**: ``string`` **default**: ``This value should be blank.``

This is the message that will be shown if the value is not blank.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/Callback.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ can do anything, including creating and assigning validation errors.
| Applies to | :ref:`class <validation-class-target>` |
+----------------+------------------------------------------------------------------------+
| Options | - :ref:`callback <callback-option>` |
| | - `payload`_ |
+----------------+------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Callback` |
+----------------+------------------------------------------------------------------------+
Expand Down Expand Up @@ -297,3 +298,5 @@ instance as only argument.
Static or closure callbacks receive the validated object as the first argument
and the :class:`Symfony\\Component\\Validator\\ExecutionContextInterface`
instance as the second argument.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/CardScheme.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ through a payment gateway.
+----------------+--------------------------------------------------------------------------+
| Options | - `schemes`_ |
| | - `message`_ |
| | - `payload`_ |
+----------------+--------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\CardScheme` |
+----------------+--------------------------------------------------------------------------+
Expand Down Expand Up @@ -124,4 +125,6 @@ message

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

.. include:: /reference/constraints/_payload-option.rst.inc

.. _`Wikipedia: Issuer identification number (IIN)`: http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29
3 changes: 3 additions & 0 deletions reference/constraints/Choice.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ an array of items is one of those valid choices.
| | - `minMessage`_ |
| | - `maxMessage`_ |
| | - `strict`_ |
| | - `payload`_ |
+----------------+-----------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Choice` |
+----------------+-----------------------------------------------------------------------+
Expand Down Expand Up @@ -349,3 +350,5 @@ strict
If true, the validator will also check the type of the input value. Specifically,
this value is passed to as the third argument to the PHP :phpfunction:`in_array` method
when checking to see if a value is in the valid choices array.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/Collection.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and that extra keys are not present.
| | - `extraFieldsMessage`_ |
| | - `allowMissingFields`_ |
| | - `missingFieldsMessage`_ |
| | - `payload`_ |
+----------------+--------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Collection` |
+----------------+--------------------------------------------------------------------------+
Expand Down Expand Up @@ -328,3 +329,5 @@ missingFieldsMessage

The message shown if `allowMissingFields`_ is false and one or more fields
are missing from the underlying collection.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/Count.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ element count is *between* some minimum and maximum value.
| | - `minMessage`_ |
| | - `maxMessage`_ |
| | - `exactMessage`_ |
| | - `payload`_ |
+----------------+---------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Count` |
+----------------+---------------------------------------------------------------------+
Expand Down Expand Up @@ -139,3 +140,5 @@ exactMessage

The message that will be shown if min and max values are equal and the underlying collection elements
count is not exactly this value.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/Country.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Validates that a value is a valid `ISO 3166-1 alpha-2`_ country code.
| Applies to | :ref:`property or method <validation-property-target>` |
+----------------+------------------------------------------------------------------------+
| Options | - `message`_ |
| | - `payload`_ |
+----------------+------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Country` |
+----------------+------------------------------------------------------------------------+
Expand Down Expand Up @@ -82,4 +83,6 @@ message

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

.. include:: /reference/constraints/_payload-option.rst.inc

.. _`ISO 3166-1 alpha-2`: http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes
3 changes: 3 additions & 0 deletions reference/constraints/Currency.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Validates that a value is a valid `3-letter ISO 4217`_ currency name.
| Applies to | :ref:`property or method<validation-property-target>` |
+----------------+---------------------------------------------------------------------------+
| Options | - `message`_ |
| | - `payload`_ |
+----------------+---------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Currency` |
+----------------+---------------------------------------------------------------------------+
Expand Down Expand Up @@ -88,4 +89,6 @@ message

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

.. include:: /reference/constraints/_payload-option.rst.inc

.. _`3-letter ISO 4217`: http://en.wikipedia.org/wiki/ISO_4217
3 changes: 3 additions & 0 deletions reference/constraints/Date.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ valid YYYY-MM-DD format.
| Applies to | :ref:`property or method <validation-property-target>` |
+----------------+--------------------------------------------------------------------+
| Options | - `message`_ |
| | - `payload`_ |
+----------------+--------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Date` |
+----------------+--------------------------------------------------------------------+
Expand Down Expand Up @@ -83,3 +84,5 @@ message
**type**: ``string`` **default**: ``This value is not a valid date.``

This message is shown if the underlying data is not a valid date.

.. include:: /reference/constraints/_payload-option.rst.inc
3 changes: 3 additions & 0 deletions reference/constraints/DateTime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ a valid YYYY-MM-DD HH:MM:SS format.
| Applies to | :ref:`property or method <validation-property-target>` |
+----------------+------------------------------------------------------------------------+
| Options | - `message`_ |
| | - `payload`_ |
+----------------+------------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\DateTime` |
+----------------+------------------------------------------------------------------------+
Expand Down Expand Up @@ -83,3 +84,5 @@ message
**type**: ``string`` **default**: ``This value is not a valid datetime.``

This message is shown if the underlying data is not a valid datetime.

.. include:: /reference/constraints/_payload-option.rst.inc
5 changes: 4 additions & 1 deletion reference/constraints/Email.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ cast to a string before being validated.
| | - `message`_ |
| | - `checkMX`_ |
| | - `checkHost`_ |
| | - `payload`_ |
+----------------+---------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\Email` |
+----------------+---------------------------------------------------------------------+
Expand Down Expand Up @@ -99,7 +100,7 @@ strict
**type**: ``boolean`` **default**: ``false``

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

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

.. include:: /reference/constraints/_payload-option.rst.inc

.. _egulias/email-validator: https://packagist.org/packages/egulias/email-validator
3 changes: 3 additions & 0 deletions reference/constraints/EqualTo.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ force that a value is *not* equal, see :doc:`/reference/constraints/NotEqualTo`.
+----------------+-----------------------------------------------------------------------+
| Options | - `value`_ |
| | - `message`_ |
| | - `payload`_ |
+----------------+-----------------------------------------------------------------------+
| Class | :class:`Symfony\\Component\\Validator\\Constraints\\EqualTo` |
+----------------+-----------------------------------------------------------------------+
Expand Down Expand Up @@ -104,3 +105,5 @@ message
**type**: ``string`` **default**: ``This value should be equal to {{ compared_value }}.``

This is the message that will be shown if the value is not equal.

.. include:: /reference/constraints/_payload-option.rst.inc
Loading

0 comments on commit dbdb408

Please sign in to comment.