php - Symfony 验证类:未定义的属性 $groups
问题描述
我有以下验证类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()]
]);
推荐阅读
- firebase - 除云存储规则外如何匹配?
- python - 循环通过python默认字典
- c# - 无法完全避免表格闪烁
- javascript - 如何将 facebook messenger 聊天机器人连接到 mongodb 数据库以通过与 messenger bot 交互来发布请求并获取响应
- sql - Bigquery:获取表名作为列值
- fullcalendar - 当开始时间在晚上 11:00 左右时,事件在完整日历的日视图和周视图中拆分
- python - 使用 Python 将 HTML 标记添加到文本中
- javascript - 如何使用 forEach 列出部分总和
- matrix - 从无向图中提取集群/节点集
- c - 父进程和主进程之间的区别以及如何检测主进程?