Validate a field's constraint annotation against another field
<p>I have this entity class in Symfony/5.4:</p>
<pre class="brush:php;toolbar:false;">use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
classAssignments
{
public const SALARY_RANGES = [
'Red',
'Green',
null,
];
/*** @ORMColumn(length=255, nullable=true)
* @AssertChoice(choices=Assignments::SALARY_RANGES, strict=true)*/
private ?string $salaryRange;
/*** @ORMManyToOne(targetEntity="Employee", inversedBy="assignments")
* @ORMJoinColumn(name="employee_id", referencedColumnName="id", onDelete="CASCADE")*/
private ?Employee $employee;
}</pre>
<p>I need to make sure that if employee is not null, then salaryRange has non-null value and vice versa. Is it possible to use constraint annotations to enforce this requirement?</p>
<p>I've been trying to use @AssertCallback but I can't figure out how to get the value of the other field. Maybe it's not even the right tool. </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>