如何获取与 symfony 验证错误相关的对象
How to get objects related to symfony validation errors
我有一个实体,我在保存到我的控制器之前对其执行验证。
/** @var ConstraintViolationList $errors */
$errors = $this->validator->validate($entity);
因此,当验证失败时,我会得到 ConstraintViolation
个对象的列表。
如何检索这些错误的相关对象?我的目标是 return 将错误映射到每个实体(这将在前端突出显示无效元素)。
我将使用对象中的自定义字段而不是 id - 所有对象在保存到数据库之前都有它,因此前端可以区分它们。
我想我应该编写自己的约束规范化器,但它对相关对象的错误一无所知。
ConstraintViolationList
的行为类似于 ConstraintViolationInterface
实现的迭代器。从每个 ConstraintViolationInterface
对象,您可以调用 getPropertyPath
方法,该方法为您提供 属性 根数据无效元素的路径(根数据可以使用 getRoot
方法从任何ConstraintViolationInterface
实施。
use Symfony\Component\PropertyAccess\PropertyAccess;
// ...
foreach ($errors as $error) {
$invalidElementAccessor = PropertyAccess::createPropertyAccessor();
$invalidElement = $invalidElementAccessor->getValue($error->getRoot(), $error->getPropertyPath());
// Do something with element
}
我有一个实体,我在保存到我的控制器之前对其执行验证。
/** @var ConstraintViolationList $errors */
$errors = $this->validator->validate($entity);
因此,当验证失败时,我会得到 ConstraintViolation
个对象的列表。
如何检索这些错误的相关对象?我的目标是 return 将错误映射到每个实体(这将在前端突出显示无效元素)。
我将使用对象中的自定义字段而不是 id - 所有对象在保存到数据库之前都有它,因此前端可以区分它们。 我想我应该编写自己的约束规范化器,但它对相关对象的错误一无所知。
ConstraintViolationList
的行为类似于 ConstraintViolationInterface
实现的迭代器。从每个 ConstraintViolationInterface
对象,您可以调用 getPropertyPath
方法,该方法为您提供 属性 根数据无效元素的路径(根数据可以使用 getRoot
方法从任何ConstraintViolationInterface
实施。
use Symfony\Component\PropertyAccess\PropertyAccess;
// ...
foreach ($errors as $error) {
$invalidElementAccessor = PropertyAccess::createPropertyAccessor();
$invalidElement = $invalidElementAccessor->getValue($error->getRoot(), $error->getPropertyPath());
// Do something with element
}