Symfony Validation Class:未定义的属性$groups



我有以下验证类OneAnswerValidator.php

<?php
namespace AppValidatorConstraints;
use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;
use SymfonyComponentValidatorExceptionInvalidArgumentException;
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 AppValidatorConstraints;
use SymfonyComponentValidatorConstraint;
/**
* @Annotation
*/
class OneQuestionOneAnswer extends Constraint
{
public $message = 'La pregunta {{ questionId }} tiene varias respuestas';
}

但是当提交表单时,我收到以下错误:

[2018-09-14 13:59:38] request.CRITICAL: Uncaught PHP Exception PHPUnitFrameworkErrorNotice: "Undefined property: AppValidatorConstraintsOneQuestionOneAnswerValidator::$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时,错误得到了解决(。知道为什么会这样吗?

顺便说一下,我在窗体类型类中添加约束:

->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => new OneAnswerValidator(['message' => 'fooo'])
]);

谢谢!

在表单类型中,您必须给出约束(此处为OneQuestionOneAnswer(而不是约束验证器。

尝试这样的事情

->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => [new OneQuestionOneAnswer()]
]);

你忘了告诉symfony如何找到约束的验证器,所以在OneQuestionOne.php Answer中添加

public function validatedBy()
{
return get_class($this).'Validator';
}

最新更新