我在Symfony/5.4中有这个实体类:
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
class Assignments
{
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;
}
我需要确保如果employee不为空,则salaryRange具有非空值,反之亦然。是否可以使用约束注解来强制实施这一要求?
我一直在尝试使用@AssertCallback,但我无法弄清楚如何获取其他字段的值。也许这甚至不是正确的工具。
/**
* @AssertCallback({"ExampleValidator", "assertEmployeeOnlyCallback"})
*/
public static function assertEmployeeOnlyCallback(mixed $data, ExecutionContextInterface $context): void
{
// `$data` contains value from `salaryRange` but, where is `employee`?
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
只需按照文档进行操作。
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(); } } }