Symfony2 get validation constraints on an entity

后端 未结 2 680
猫巷女王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: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.

提交回复
热议问题