Symfony2 get validation constraints on an entity

后端 未结 2 677
猫巷女王i
猫巷女王i 2020-12-31 08:40

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 si

相关标签:
2条回答
  • 2020-12-31 08:45

    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");
    
    0 讨论(0)
  • 2020-12-31 08:53
    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
                }
            }
        }
    

    $validator=$this->get("validator");
    $metadata=$validator->getMetadataFor(new yourentity());

    The object $metadata now contains all the metadata about validations that concerns your specific entity.

    0 讨论(0)
提交回复
热议问题