search

Home  >  Q&A  >  body text

Validate a field's constraint annotation against another field

<p>I have this entity class in Symfony/5.4:</p> <pre class="brush:php;toolbar:false;">use DoctrineORMMapping as ORM; use SymfonyComponentValidatorConstraints as Assert; classAssignments { public const SALARY_RANGES = [ 'Red', 'Green', null, ]; /*** @ORMColumn(length=255, nullable=true) * @AssertChoice(choices=Assignments::SALARY_RANGES, strict=true)*/ private ?string $salaryRange; /*** @ORMManyToOne(targetEntity="Employee", inversedBy="assignments") * @ORMJoinColumn(name="employee_id", referencedColumnName="id", onDelete="CASCADE")*/ private ?Employee $employee; }</pre> <p>I need to make sure that if employee is not null, then salaryRange has non-null value and vice versa. Is it possible to use constraint annotations to enforce this requirement?</p> <p>I've been trying to use @AssertCallback but I can't figure out how to get the value of the other field. Maybe it's not even the right tool. </p> <pre class="brush:php;toolbar:false;">/*** @AssertCallback({"ExampleValidator", "assertEmployeeOnlyCallback"})*/</pre> <pre class="brush:php;toolbar:false;">public static function assertEmployeeOnlyCallback(mixed $data, ExecutionContextInterface $context): void { // `$data` contains value from `salaryRange` but, where is `employee`? }</pre> <p><br /></p>
P粉321676640P粉321676640495 days ago553

reply all(1)I'll reply

  • P粉107991030

    P粉1079910302023-07-24 10:28:57

    Just follow the documentation.

    https://symfony.com/doc/5.3/reference/constraints/Callback.html

    class Author
    {
        // ...
        private int $field = 1;
        private string $otherField;
       /**
        * @Assert\Callback
        */    
        public function validate(ExecutionContextInterface $context, mixed $payload): void
        {
            
            if ($this->field > 1 && $this->otherField != '') {
                $context->buildViolation('Your validation message')
                    ->atPath('toherField')
                    ->addViolation();
            }
        }
    }

    reply
    0
  • Cancelreply