Validate a field's constraint annotation against another field
P粉321676640
P粉321676640 2023-07-23 17:52:28
0
1
522
<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粉321676640
P粉321676640

reply all(1)
P粉107991030

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();
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!