从未检查过自定义约束


Custom constraint never checked against

我正在尝试用他的约束做一个简单的验证器。

约束

namespace Me'MyBundle'Validator'Constraint;
use Symfony'Component'Validator'Constraint;
class MyConstraint extends Constraint
{
    public $message = 'Grossière erreur';
}

验证器

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;
    }
}

验证

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

正如您所看到的,myField有2个约束,Length被选中,但MyConstraint从未被选中。

可能出了什么问题?我如何调试它?

(Symfony 2.5.9)

调试提示:

在控制器中,使用以下命令获取属性的所有约束。

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

(受此答案启发)

如果在$propertyMetadata中看到这两个约束,那么Length可能会干扰自定义约束,所以请尝试在没有Length约束的情况下运行代码。

通过添加在我的formType 中定义的group修复

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

[Default]不起作用,我不明白为什么