根据另一个字段来验证一个字段的约束注解
P粉321676640
P粉321676640 2023-07-23 17:52:28
0
1
549
<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粉321676640
P粉321676640

全部回复(1)
P粉107991030

只需按照文档进行操作。

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();
        }
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板