如何获取完整的propertyPath?需要此功能以在jQuery中添加验证案例,因为我已经将旧应用程序重写为新的SF4应用程序。 Odx2ParameterCollectionType是具有动态字段的集合。
有什么办法可以得到这个验证错误?也许您还有其他解决方案,如何使用它?
protected function renderFormErrors(FormInterface $form): JsonResponse
{
$errors = [];
foreach ($form->getErrors(true) as $error) {
$errors[$error->getOrigin()->getName()] = $error->getMessage();
}
return $this->json([
self::RETURN_PARAMETER_STATUS => Response::HTTP_INTERNAL_SERVER_ERROR,
self::RETURN_PARAMETER_ERRORS => $errors
]);
}
实际:
{
"status": 500,
"errors": {
"udsId": "This value should not be blank."
}
}
预期:
{
"status": 500,
"errors": {
"Odx2ParameterCollectionType[parameters][5][udsId]": "This value should not be blank."
}
}
编辑:
好吧,我已经弄清楚了,但是现在我缺少一件事-集合索引,这是我的代码:
foreach ($form->all() as $name => $child) {
if (!$child->isValid()) {
foreach ($child->getErrors(true) as $error) {
$errors[(string) $form->getPropertyPath()][$name][$error->getOrigin()->getName()] = $error->getMessage();
}
}
}
答案 0 :(得分:0)
https://symfonycasts.com/screencast/symfony-rest2/api-problem-class 在此课程中,您可以创建自定义的ApiException和模型以解决问题,并且更加有用...
但是,如果您只想获取无效字段和消息的实际路径,则可以这样做。
<?php
namespace App\Form\Validation;
use Symfony\Component\Form\FormInterface;
class ValidateForm
{
static function renderFormErrors(FormInterface $form)
{
$errorModel = new FormValidation();
foreach ($form->getErrors(true) as $error)
{
$path = $error->getCause()->getPropertyPath();
if (empty($path)) {
break;
}
$path = preg_replace("/^(data.)|(.data)|(\\])|(\\[)|children/", '', $path);
$message = $error->getCause()->getMessage();
$errorModel->errors[$path] = $message;
}
return $errorModel; // or convert to json and return.
}
}
class FormValidation
{
public $message ="Validation Error";
public $errors = [];
}
答案 1 :(得分:0)
const REGEX_EXPLODE_COLLECTION_PATH = "/^(data.)|(.data)|(\\])|(\\[)|children/";
$errors = [];
foreach ($form->all() as $name => $child) {
if (!$child->isValid()) {
foreach ($child->getErrors(true) as $error) {
$propertyPath = $error->getCause()->getPropertyPath();
$path = preg_replace(self::REGEX_EXPLODE_COLLECTION_PATH, '', $propertyPath);
list($collection, $index, $field) = explode('.', $path);
$errors[(string) $form->getPropertyPath()][$collection][$index][$field] = $error->getMessage();
}
}
}
感谢Nairi Abgaryan,这是我的解决方案,非常适合我:-)