我有以下验证类OneAnswerValidator.php
:
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
class OneQuestionOneAnswerValidator extends ConstraintValidator {
// is this necessary? In the docs doesn't appear this property
//public $groups = [];
public function validate($answers, Constraint $constraint) {
if (empty($answers)) {
return;
}
$questions = [];
foreach ($answers as $answer) {
$questionId = $answer->getQuestion()->getId();
if (isset($questions[$questionId])) {
$this->context
->buildViolation($constraint->message)
->setParameter('{{ questionId }}', $value)
->addViolation();
break;
}
}
}
}
使用相关约束OneAnswer.php
:
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class OneQuestionOneAnswer extends Constraint
{
public $message = 'La pregunta {{ questionId }} tiene varias respuestas';
}
但是当提交表单时,我收到以下错误:
[2018-09-14 13:59:38] request.CRITICAL: Uncaught PHP Exception PHPUnit\Framework\Error\Notice: "Undefined property: App\Validator\Constraints\OneQuestionOneAnswerValidator::$groups" at /Applications/MAMP/htdocs/team-analytics/vendor/symfony/form/Extension/Validator/Constraints/FormValidator.php line 84 {"exception":"[object] (PHPUnit\\Framework\\Error\\Notice(code: 8): Undefined property: App\\Validator\\Constraints\\OneQuestionOneAnswerValidator::$groups at /Applications/MAMP/htdocs/team-analytics/vendor/symfony/form/Extension/Validator/Constraints/FormValidator.php:84)"} []
在文档中没有任何关于属性$groups
(但是当我将该属性添加到OneAnswerValidator
类时错误得到解决)。知道为什么会这样吗?
顺便说一下,我在Form Type类中添加了约束:
->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => new OneAnswerValidator(['message' => 'fooo'])
]);
谢谢!
在您的表单类型中,您必须提供约束(此处为OneQuestionOneAnswer)而不是ConstraintValidator。
尝试这样的事情
->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => [new OneQuestionOneAnswer()]
]);