根据另一个字段来验证一个字段的约束注解
P粉321676640
2023-07-23 17:52:28
<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>
只需按照文档进行操作。
https://symfony.com/doc/5.3/reference/constraints/Callback.html