根據另一個字段來驗證一個字段的約束註解
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
#