Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Cookbook
  4. Validation
  5. How to Handle Different Error Levels
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • 1. Assigning the Error Level
  • 2. Customize the Error Message Template

How to Handle Different Error Levels

Edit this page

Warning: You are browsing the documentation for Symfony 2.6, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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 fields, if entered, are still valid, but display their errors differently.

The process to achieve this behavior consists of two steps:

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

1. Assigning the Error Level

2.6

The payload option was introduced in Symfony 2.6.

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

  • Annotations
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- 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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 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

2.6

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

When validation of the User object fails, you can retrieve the constraint that caused a particular failure using the getConstraint() method. Each constraint exposes the attached payload as a public property:

1
2
3
4
5
// 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 so that the severity is added as an additional HTML class:

1
2
3
4
5
6
7
8
9
10
11
12
{%- 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 -%}

See also

For more information on customizing form rendering, see How to Customize Form Rendering.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Online exam, become Symfony certified today

    Online exam, become Symfony certified today

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Raphael Hardt, a Symfony contributor

    Thanks Raphael Hardt for being a Symfony contributor

    2 commits • 38 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia