Search code examples
symfonyassertsymfony5

Symfony 5 : display of Assert messages


I have an entity with @Assert on 2 variables :

/**
 * @ORM\Column(type="date")
 * @Assert\GreaterThan("today", message ="La dade de début ne devrait pas être antérieure à la date du jour ", class="alert")
 */
private $dateStart;

/**
 * @ORM\Column(type="date")
 * @Assert\Expression(
 *     "this.getDateStart() < this.getDateEnd()",
 *     message="La date de fin ne doit pas être antérieure à la date de début"
 * )
 */
private $dateEnd;

The display is not really good looking and I would like to improve it by adding a CSS class. Is it possible to do that with Symfony 5? How? Thanks for your help !


Solution

  • To add a CSS class, you have to put it in the form rendering. If you use twig, you render the form with the example code below. This code contains a CSS class .my-custom-class-for-errorsyou can use to style your error messages.

    {{ form_start(form) }}
    <div class="my-custom-class-for-errors">
        {{ form_errors(form) }}
    </div>
    
    <div class="row">
        <div class="col">
            {{ form_label(form.dateStart) }}
            <div class="my-custom-class-for-errors">
                {{ form_errors(form.dateStart) }}
            </div>
            {{ form_widget(form.dateStart) }}
        </div>
        <div class="col" id="some-custom-id">
            {{ form_label(form.dateEnd) }}
            <div class="my-custom-class-for-errors">
                {{ form_errors(form.dateEnd) }}
            </div>
            {{ form_widget(form.dateEnd) }}
        </div>
     </div>
    {{ form_rest(form) }}
    {{ form_end(form) }}