gpt4 book ai didi

php - Symfony 验证类 : Undefined property $groups

转载 作者:行者123 更新时间:2023-12-04 00:30:17 25 4
gpt4 key购买 nike

我有以下验证类 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()]
]);

关于php - Symfony 验证类 : Undefined property $groups,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com