Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 Custom Constraint atPath not working

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.

like image 476
Glen Elkins Avatar asked Oct 18 '25 08:10

Glen Elkins


2 Answers

This is a little old now, but this works for me.

change

atPath('overrideDate')

to

atPath('[overrideDate]')

Craig

like image 66
Craig Rayner Avatar answered Oct 21 '25 11:10

Craig Rayner


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.

like image 23
Collin Krawll Avatar answered Oct 21 '25 12:10

Collin Krawll