I have a form that has a date type and a checkbox type, the date type is only a required field when the checkbox is checked.
So the checkbox is called overrideDates and the date field is overrideDate
So i created a constraint like this:
<?php
namespace App\Validator\Constraints\Instruction;
use App\Validator\Validators\Instruction\MainInstructionValidator;
use Symfony\Component\Validator\Constraint;
/**
* Class MainInstructionConstraint
* @package App\Validator\Constraints\Instruction
* @Annotation
*/
class MainInstructionConstraint extends Constraint{
/**
* @var string
*/
public $overrideDatesError = "You Must Enter An Override Date";
/**
* @return string
*/
public function getTargets() : string{
return self::CLASS_CONSTRAINT;
}
/**
* @return string
*/
public function validatedBy() : string{
return MainInstructionValidator::class;
}
}
And a validator like this:
<?php
namespace App\Validator\Validators\Instruction;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Class MainInstructionValidator
* @package App\Validator\Validators\Instruction
*/
class MainInstructionValidator extends ConstraintValidator{
/**
* @param mixed $instruction
* @param Constraint $constraint
*/
public function validate($instruction, Constraint $constraint){
if($instruction->isOverridingDates()){
// make sure the override date is set
if(!is_null($instruction->getOverrideDate()) || !is_a($instruction->getOverrideDate(),'DateTime')){
$this->context->buildViolation($constraint->overrideDatesError)
->atPath('overrideDate')->addViolation();
}
}
}
}
The validation is working perfectly fine, and error message is coming in from the constraint fine, but for some reason it's not displaying on the form from the following:
form_errors(form.overrideDate)
I was under the impression that is what atPath() is for so i can tell it which form field to display the error on since i am passing the entire entity to the validator.
This is a little old now, but this works for me.
change
atPath('overrideDate')
to
atPath('[overrideDate]')
Craig
For me the problem was that I had error_bubbling turned on. If error_bubbling is turned on, it will override atPath and bubble the error up the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With