搜索

首页  >  问答  >  正文

根据另一个字段来验证一个字段的约束注解

<p>我在Symfony/5.4中有这个实体类:</p> <pre class="brush:php;toolbar:false;">use DoctrineORMMapping as ORM; use SymfonyComponentValidatorConstraints as Assert; class Assignments { public const SALARY_RANGES = [ 'Red', 'Green', null, ]; /*** @ORMColumn(长度=255,可为空=true) * @AssertChoice(choices=Assignments::SALARY_RANGES, strict=true)*/ private ?string $salaryRange; /*** @ORMManyToOne(targetEntity =“员工”,inversedBy =“分配”) * @ORMJoinColumn(name =“employee_id”,referencedColumnName =“id”,onDelete =“CASCADE”)*/ private ?Employee $employee; }</pre> <p>我需要确保如果employee不为空,则salaryRange具有非空值,反之亦然。是否可以使用约束注解来强制实施这一要求?</p> <p>我一直在尝试使用@AssertCallback,但我无法弄清楚如何获取其他字段的值。也许这甚至不是正确的工具。</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粉321676640478 天前534

全部回复(1)我来回复

  • P粉107991030

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

    只需按照文档进行操作。

    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();
            }
        }
    }

    回复
    0
  • 取消回复