Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 get validation constraints on an entity

Im working on a method to get all validation constraints of an entity (what i am trying to achieve is to return this data in JSON and apply the same constraints on client side using JQuery Validation Plugin), however im having some trouble getting the constraints, Here is my current code:

    $metadata = new \Symfony\Component\Validator\Mapping\ClassMetadata("Namespace\JobBundle\Entity\Job");
    $annotationloader = new AnnotationLoader(new AnnotationReader());
    $annotationloader->loadClassMetadata($metadata);

what i get in $metadata is an empty array for the constraints attribute, the rest ($properties and $members have only the error messages... but not the actual constraints (eg : required, integer...)).

What im a doing wrong?

like image 283
Youssef Avatar asked Mar 18 '13 17:03

Youssef


1 Answers

I would probably use the validator service instead of instantiating a new class metadata. You never know if some classes are initialized through the service.

$metadata = $this->container
                 ->get('validator')
                 ->getMetadataFactory()
                 ->getClassMetadata("Name‌​space\JobBundle\Entity\Job");

and $metadata should have the data you are looking for

Symfony 2.3 and above

$metadata = $this->container
                 ->get('validator')
                 ->getMetadataFor("Name‌​space\JobBundle\Entity\Job");
like image 146
Thomas Potaire Avatar answered Oct 24 '22 13:10

Thomas Potaire