How to get error message after entity validation
Asked Answered
P

1

8

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 ?

Palmapalmaceous answered 28/5, 2017 at 16:48 Comment(0)
N
17

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.

Nexus answered 28/5, 2017 at 17:2 Comment(2)
Glad to help you! :DNexus
Thanks man - really helpful. Only thing I can add is to remove the json_encode - here you will get a double json_encode leaving a non-usable response. return new JsonResponse( $messages );Egypt

© 2022 - 2024 — McMap. All rights reserved.