Symfony2获得对实体的验证约束

时间:2013-03-18 17:09:06

标签: 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);

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

我做错了什么?

2 个答案:

答案 0 :(得分:18)

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

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

$metadata应该包含您要查找的数据

Symfony 2.3及以上

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

答案 1 :(得分: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
            }
        }
    }

<强> $验证= $这 - &GT;获得( “验证”);
$ metadata = $ validator-&gt; getMetadataFor(new yourentity());
对象$ metadata现在包含有关您特定实体的验证的所有元数据。