Symfony2:表单的UniqueValidator

时间:2012-01-13 16:46:58

标签: dependency-injection symfony validation

我有一个RegistrationFormType,其中包含以下验证限制:

public function getDefaultOptions(array $options)
    {
        $collectionConstraint = new Collection(array(
            'email' => array(
                new NotBlank(),
                new Email(array('message' => 'Ungültige E-Mail Adresse')),
                ),
            'username' => new Unique(),
            'code' => new MaxLength(array('limit'=>20)),
            'plainPassword' => new MaxLength(array('limit'=>20)),
        ));

        return array(
            'csrf_protection' => false,
            'validation_constraint' => $collectionConstraint,
        );
    }

为了确保唯一性,我创建了一个Unique Class(扩展Contraint)和一个UniqueValidator(扩展ConstraintValidator),如下所述:http://www.michelsalib.com/2011/04/create-your-own-constraint-validator-in-symfony2-a-doctrine-unique-validator/

问题是,我在提交表单时遇到以下错误:

Catchable Fatal Error: Argument 1 passed to ...\Validation\Constraint\UniqueValidator::__construct() must be an instance of Doctrine\ORM\EntityManager, none given

似乎EntityManager没有注入ConstraintValidator,我在config.yml中创建了一个服务定义:

services:
    eventiply.validator.unique:
        class: Ajado\EventHubBundle\Validation\UniqueValidator
        arguments: 
            entityManager: "@doctrine.orm.entity_manager"
        tags:
            - { name: validator.constraint_validator, alias: validator.unique }

我有什么想法可以在这里取得进展?

2 个答案:

答案 0 :(得分:1)

发现问题:

我在Unique Constraint中有以下代码:

/**
 * @Annotation
 */
class Unique extends Constraint{
    public $message = 'Dieser Wert muss eindeutig sein, ist leider aber schon vergeben';
    public $propertyName;
    public $property;
    public $entityName;

    public function __construct($options = null) {

        parent::__construct($options);
    }

    public function validatedBy()
    { 
        // copied that from http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
        return get_class($this).'Validator';
    }
}

这是纠正的:

/**
 * @Annotation
 */
class Unique extends Constraint{
    public $message = 'Dieser Wert muss eindeutig sein, ist leider aber schon vergeben';

    public function __construct($options = null) {

        parent::__construct($options);
    }

    public function validatedBy()
    {
        return 'validator.unique';
    }

}

答案 1 :(得分:0)

你的YAML看起来很棒。 arguments值应该是数组,而不是哈希:

arguments:
    - "@doctrine.orm.entity_manager"