Skip to content

How to Handle Different Error Levels

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

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

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

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

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;
}

2. Customize the Error Message Template

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
{%- block form_errors -%}
    {%- if errors|length > 0 -%}
    <ul>
        {%- for error in errors -%}
            <li class="{{ error.cause.constraint.payload.severity ?? '' }}">{{ 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