Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Reference][Constraints] document the validation payload option #4724

Merged
merged 1 commit into from
Mar 13, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cookbook/map.rst.inc
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

annotations should now be the first

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


// 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::
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one : to much?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The double colon is a shortcut for the default language so that you don't need to add a code-block directive.


// 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 @@ -26,6 +26,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 @@ -302,3 +303,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
15 changes: 9 additions & 6 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 @@ -89,11 +90,11 @@ If your valid choice list is simple, you can pass them in directly via the

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
protected $gender;

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Assert\Choice(array(
Expand Down Expand Up @@ -176,11 +177,11 @@ constraint.

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
protected $gender;

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Assert\Choice(array(
Expand Down Expand Up @@ -244,11 +245,11 @@ you can pass the class name and the method as an array.

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
protected $gender;

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Assert\Choice(array(
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
Loading