【问题标题】:My Own Constraint Validator as service我自己的约束验证器即服务
【发布时间】:2012-12-12 14:57:54
【问题描述】:

我正在尝试构建一个作为服务运行的自定义验证器(主要用于获取实体管理器)。

我关注了文档和一些博客文章,但无法使其正常工作。我有这个错误

    Catchable Fatal Error: Argument 1 passed to 
D\AjaxBundle\Validator\Constraints\SelectTypeValidator::__construct() must implement 
interface Doctrine\Common\Persistence\ObjectManager, none given, called in 
/AJAX/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Validator/ConstraintValidatorFactory.php on line 67 and defined in 
/AJAX/src/D/AjaxBundle/Validator/Constraints/SelectTypeValidator.php line 14

services.yml

    validator.selectType:
        class: D\AjaxBundle\Validator\Constraints\SeletTypeValidator
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - { name: validator.selectType, alias: selectType }

选择类型验证器:

namespace D\AjaxBundle\Validator\Constraints;

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

use Doctrine\Common\Persistence\ObjectManager;

class SelectTypeValidator extends ConstraintValidator
{
    private $om;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    public function validate($value, Constraint $constraint)
    {
        $fieldOne = $this->om->getRepository('DAjaxBundle:City')->findOneBy(array('id' =>
                $value->getId()));

        if ($fieldOne == null) {
            $this->context->addViolation($constraint->message, array('%string%' => $value->
                    getId()));
        }
    }
}

选择类型

namespace D\AjaxBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class SelectType extends Constraint
{
    public $message ='jakis text';

    public function validateBy()
    {
        return 'selectType';
    }
}

【问题讨论】:

    标签: validation symfony


    【解决方案1】:

    服务标签名称应为validator.constraint_validator 而不是validator.selectType

    【讨论】:

      【解决方案2】:

      我不确定这是否会有所作为,但值得一试...我从不使用引号括起服务参数:

      arguments: [@doctrine.orm.entity_manager]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-22
        • 1970-01-01
        • 2013-04-09
        • 2015-06-27
        • 1970-01-01
        相关资源
        最近更新 更多