Symfony2获得对实体的验证约束

You*_*sef 13 symfony symfony-2.1

我正在研究获取实体的所有验证约束的方法(我想要实现的是使用JQuery Validation Plugin在JSON中返回此数据并在客户端应用相同的约束),但是我在获取约束时遇到一些麻烦,这是我目前的代码:

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

我在$ metadata中得到的是一个用于constraints属性的空数组,其余的($ properties和$ members只有错误消息......但不是实际的约束(例如:required,integer ...)).

我做错了什么?

Tho*_*ire 18

我可能会使用验证器服务而不是实例化新的类元数据.您永远不知道是否通过该服务初始化了某些类.

$metadata = $this->container
                 ->get('validator')
                 ->getMetadataFactory()
                 ->getClassMetadata("Name??space\JobBundle\Entity\Job");
Run Code Online (Sandbox Code Playgroud)

并且$metadata应该有您正在寻找的数据

Symfony 2.3及以上

$metadata = $this->container
                 ->get('validator')
                 ->getMetadataFor("Name??space\JobBundle\Entity\Job");
Run Code Online (Sandbox Code Playgroud)


Rob*_*zvi 7

private function getValidations()
    {
        $validator=$this->get("validator");
        $metadata=$validator->getMetadataFor(new yourentity());
        $constrainedProperties=$metadata->getConstrainedProperties();
        foreach($constrainedProperties as $constrainedProperty)
        {
            $propertyMetadata=$metadata->getPropertyMetadata($constrainedProperty);
            $constraints=$propertyMetadata[0]->constraints;
            foreach($constraints as $constraint)
            {
                //here you can use $constraint to get the constraint, messages etc that apply to a particular property of your entity
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

$验证= $这个- > GET( "验证");
$ metadata = $ validator-> getMetadataFor(new yourentity());

对象$ metadata现在包含有关您的特定实体的验证的所有元数据.