本文介绍了我自己的约束验证器即服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a custom validator running as a service (mainly for getting the entity manager).

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

I followed the doc and some blog posts but can't make it working. I have this error

    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

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

推荐答案

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

The service tag name should be validator.constraint_validator instead of validator.selectType

这篇关于我自己的约束验证器即服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:13