通过服务名称使用Symfony自定义验证约束

时间:2015-12-10 07:22:12

标签: symfony symfony-forms symfony-2.8

我创建了以下自定义验证约束:

validator.constraint.user.email_unicity:
    class: AppBundle\Validator\Constraints\User\EmailUnicityValidator
    tags:
        - { name: validator.constraint_validator, alias: user_email_unicity_validator }

我将它添加到我的字段中,如下所示:

AppBundle\Security\User\WebserviceUser:
    properties:
        email:
            - AppBundle\Validator\Constraints\User\EmailUnicity: ~

但是我希望通过使用约束的别名来避免使用我的classe的完整路径但是找不到正确的方法。这样的事情:

AppBundle\Security\User\WebserviceUser:
    properties:
        email:
            - user_email_unicity_validator: ~

AppBundle\Security\User\WebserviceUser:
    properties:
        email:
            - @user_email_unicity_validator: ~

在这两种情况下,我都有以下例外:

  

尝试从命名空间“\ Symfony \ Component \ Validator \ Constraints”加载类“[alias name]”。   您是否忘记了另一个命名空间的“use”语句?

有办法吗?

谢谢大家! :)

[编辑2015/12/10]

我尝试使用以下别名,但不是更好(相同的异常消息):

{ name: validator.constraint_validator, alias: User\EmailUnicityValidator }

[编辑2015/12/11]

这里我的代码详细信息:

# AppBundle\Validator\Constraints\User\EmailUnicity.php
namespace AppBundle\Validator\Constraints\User;

use Symfony\Component\Validator\Constraint;

class EmailUnicity extends Constraint
{
    public $messageMatchesFound = '[...]';

    public function validatedBy()
    {
        return 'user_email_unicity_validator';
    }
}

# AppBundle\Validator\Constraints\User\EmailUnicityValidator.php
namespace AppBundle\Validator\Constraints\User;

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

class EmailUnicityValidator extends ConstraintValidator
{
    public function validate($email, Constraint $constraint)
    {
        [...]
    }
}

0 个答案:

没有答案