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 message Object(AppBundle\Entity\Subscribe).email: This value must not be empty. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)
.
Any idea how to clean it ?
EntityValidationErrors is a collection which represents the entities which couldn't be validated successfully, and the inner collection ValidationErrors per entity is a list of errors on property level. These validation messages are usually helpful enough to find the source of the problem.
Validation errors typically occur when a request is malformed -- usually because a field has not been given the correct value type, or the JSON is misformatted.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With