Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46228

Custom constraint never checked against

I'm trying to do a simple validator with his constraint.

Constraint

namespace Me\MyBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

class MyConstraint extends Constraint
{
    public $message = 'Grossière erreur';
}

Validator

namespace Me\MyBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class MyConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $this->context->buildViolation($constraint->message)
            ->addViolation();
        return false;
    }
}

Validation

Me\MyBundle\Entity\MyEntity:
    properties:
        myField:
            - Length:
                min: 9
            - Me\MyBundle\Validator\Constraint\MyConstraint: ~

As you can see myField has 2 contraints, Length is checked but MyConstraint is never.

What could be wrong ? How can I debug that ?

(Symfony 2.5.9)

Upvotes: 3

Views: 69

Answers (2)

Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46228

Fixed by adding the group that was defined in my formType

- Me\MyBundle\Validator\Constraint\MyConstraint:
    groups: ['the_related_form']

[Default] didn't work, I don't understand why

Upvotes: 0

afilina
afilina

Reputation: 938

Debugging tip:

Inside your controller, use the following to get all the constraints for your property.

$factory          = $this->container->get('validator.mapping.class_metadata_factory');
$classMetadata    = $factory->getMetadataFor('Your\Bundle\Entity\Name');
$propertyMetadata = $classMetadata->getPropertyMetadata('propertyName');

(inspired by this answer)

If you see both constraints in $propertyMetadata, then perhaps Length interferes with the custom one, so try to run the code without the Length constraint.

Upvotes: 1

Related Questions