Reputation: 6140
I need to be able to do complex custom validation of an entire entity in Symfony2.
Eg: my entity
has many subentities
, and all subentities
must sum to 100.
As far as I can fathom, Symfony2 validators only validate singular fields?
Upvotes: 4
Views: 2214
Reputation: 6140
The answer is yes. You need to specify your constraint against the object rather than a parameter, and specify the constraint that its a class level constraint. A somewhat verbose example is this:
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 args for the constraint in this example)
My Constraint
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 ConstraintValidator
class MyConstraintValidator extends ConstraintValidator
{
protected $container;
function __construct($container)
{
$this -> container = $container;
}
function isValid($object, Constraint $constraint)
{
# validation here.
return true;
}
}
Upvotes: 6