搜尋

首頁  >  問答  >  主體

根據另一個字段來驗證一個字段的約束註解

<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粉321676640497 天前566

全部回覆(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
  • 取消回覆