Search code examples
phpsymfonysymfony-2.1symfony-3.2

How to get error message after entity validation


I'm trying to get a clean error message after validating my Subscribe Entity :

/**
 * Subscribe
 * @UniqueEntity("email")
 * @ORM\Table(name="subscribe")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\SubscribeRepository")
 */
class Subscribe
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank()
     * @Assert\Email()
     * @ORM\Column(name="email", type="string", length=255, nullable=true, unique=true)
     */
    private $email;

After calling the validator service and test it with blank email:

$validator = $this->get('validator');
$errors    = $validator->validate($email);
if (count($errors) > 0) {
    return new JsonResponse((string)$errors);
}

I got this validation message :

Object(AppBundle\Entity\Subscribe).email: This value must not be empty. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3).

Any idea how to clean it ?


Solution

  • Try this:

    $validator = $this->get('validator');
    $errors    = $validator->validate($email);
    if (count($errors) > 0) {
        $messages = [];
        foreach ($errors as $violation) {
            $messages[$violation->getPropertyPath()][] = $violation->getMessage();
        }
        return new JsonResponse($messages);
    }
    

    In this way I have create an array of errors, where the key is the not valid field, you can change this logic and add only the name of the field in front of the error and return a simple string.

    This code can works with all fields in the form.