Symfony 3.3无法使用Custom Validator

时间:2017-10-30 11:05:02

标签: php symfony validation

您好我有一个自定义验证,检查两个表的唯一值(这意味着我无法使用UniqueEntity验证)

除了更新数据外,我的代码工作正常。验证看实体已经有一个新数据,但实际上它是一个更新

问题是如何修复此错误

这是我的代码

KeywordsUnique.php

class KeywordsUnique extends Constraint
{
    public $message = 'This {{value}} already used';

    /**
    * {@inheritdoc}
    */
    public function validatedBy()
    {
        return 'keyword_unique';
    }
}

KeywordsUniqueValidator.php

class KeywordsUniqueValidator extends ConstraintValidator
{
   /**
    * @var RepositoryInterface
    */
   public $keywordRepository;

   /**
    * @var RepositoryInterface
    */
   public $additionalKeywordRepository;

   public function __construct(
       RepositoryInterface $keywordRepository,
       RepositoryInterface $additionalKeywordRepository
   )
   {
       $this->keywordRepository = $keywordRepository;
       $this->additionalKeywordRepository = $additionalKeywordRepository;
   }

   /**
    * @param mixed $value
    * @param Constraint|KeywordsUnique $constraint
    */
   public function validate($value, Constraint $constraint)
   {
       if (!$value) {
           return;
       }

       /** @var KeywordInterface $keyword */
       $keyword = $this->keywordRepository->findOneBy(['word' => $value]);

       /** @var AdditionalKeywordInterface $additionalKeyword */
       $additionalKeyword = $this->additionalKeywordRepository->findOneBy(['word' => $value]);

       if ($keyword !== null) {
           if ($value === $keyword->getWord()) {
               $builder = $this->context->buildViolation($constraint->message);
               $builder->addViolation();
           }
       }

       if ($additionalKeyword !== null) {
           if ($value === $additionalKeyword->getWord()) {
               $builder = $this->context->buildViolation($constraint->message);
               $builder->addViolation();
           }
       }
   }
}

感谢您的进步。

1 个答案:

答案 0 :(得分:0)

问题解决了!

问题是manager发现该实体为新实体(manage会自动检测

如何解决此问题?

您必须使用object检查传入验证的id,并使用value的{​​{1}}检查context以获取对象

喜欢这段代码

Constraint $constraint

那就是它!!