Search code examples
phphtmlsymfonyentitysymfony-forms

How to Add message to the @Assert?


I am trying to customize Symfony validator messages!

 * @UniqueEntity(fields={"email"}, message="The Email is already used.")

The unique entity error message works perfectly fine and shows up like this enter image description here

I tried to add a message to * @Assert\NotBlank() for example and do @Assert\NotBlank(message="The password can't be blank ") but it shows like this ..

enter image description here

I want the error message to be The password can't be blank instead of Veuillez compléter ce champ.

Also, I want it to appear like UniqueEntity message! how?

Code of my entity :

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(
 *     fields={"username"},
 *     message="The username is already used."
 * )
 * @UniqueEntity(
 *     fields={"email"},
 *     message="The Email is already used."
 * )
 */
class User
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255 ,  unique=true)
     * @Assert\NotBlank()
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255 , unique=true)
     * @Assert\NotBlank()
     * @Assert\Email(message="This Email is not valid ")
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255 ,  unique=true)
     * @Assert\NotBlank()
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     * @Assert\Regex(
     * pattern="/[0-9]{8}/"
     * )
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $picture;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $braclet_id;

    /**
     * @ORM\Column(type="boolean")
     */
    private $is_doctor;

    /**
     * @Assert\Length(min=5, max=100)
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    private $Full_Name;
}

Code of View

{{ form_start(form) }}


<div class="col-sm-3">
    <div class="form-group">
        <div class="form-line">
            {{ form_widget(form.password, {'attr': {'class': 'form-control', 'placeholder': 'Password','type': 'Password'} }) }}        
        </div>
    </div>
</div>
<div class="col-sm-3">
    <div class="form-group">
        <div class="error">{{ form_errors(form.password) }} </div>
    </div>
</div> 

{{ form_rest(form) }}
{{ form_end(form) }}

Solution

  • Solved thanks to msg comment!

    In case anyone faced this error u can use novalidate attribute to disable browser validation!

    instead of

    {{ form_start(form) }}
    

    use

    {{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}