Reputation: 5830
I have the following validation class 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;
}
}
}
}
With the associated constraint 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';
}
But when the form is submitted I get the following error:
[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)"} []
In the documentation there is nothing about a property $groups
(but the error get solved when I add that property to OneAnswerValidator
class). Any idea why is this happening?
By the way, I am adding the constraint in a Form Type class:
->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => new OneAnswerValidator(['message' => 'fooo'])
]);
Thanks!
Upvotes: 6
Views: 3358
Reputation: 15
You forget to tell symfony how to find the validator to your constraint, so in OneQuestionOneAnswer.php add
public function validatedBy()
{
return \get_class($this).'Validator';
}
Upvotes: -1
Reputation: 1155
In your Form Type you have to give the Constraint (here OneQuestionOneAnswer) and not the ConstraintValidator.
Try something like this
->add('answers', EntityType::class, [
'class' => Answer::class,
'choice_label' => 'title',
'label' => 'Respuesta',
'multiple' => true,
'constraints' => [new OneQuestionOneAnswer()]
]);
Upvotes: 11