Symfony2 Validation Against the Whole Essence

I need to be able to do complex custom checks of an entire object in Symfony2.

For example: my entity has many subentities , and all subentities must add up to 100.

As far as I can tell, Symfony2 validators only validate specific fields?

+4
source share
1 answer

The answer is yes. You need to specify your restriction on the object, not the parameter, and specify the restriction on the restriction of the class level. Somewhat true example:

config.yml

 validator.my.uniquename: class: FQCN\To\My\ConstraintValidator arguments: [@service_container] tags: - { name: validator.constraint_validator, alias: ConstraintValidator } 

validation.yml

 FQCN\To\My\Entity: constraints: - FQCN\To\MyConstraint: ~ 

(no arguments to limit in this example)

My limitation

 namespace FQCN\To; use Symfony\Component\Validator\Constraint ; /** * @Annotation */ class MyConstraint extends Constraint { public $message = 'Constraint not valid'; public function validatedBy() { return 'ConstraintValidator'; } public function getTargets() { # This is the important bit. return self::CLASS_CONSTRAINT; } } 

My constraint validator

 class MyConstraintValidator extends ConstraintValidator { protected $container; function __construct($container) { $this -> container = $container; } function isValid($object, Constraint $constraint) { # validation here. return true; } } 
+6
source

Source: https://habr.com/ru/post/1401075/


All Articles