如何获得这个完整的propertyPath?因为我已经在新的SF4应用程序中重写了旧的应用程序,所以需要在jQuery中添加验证用例。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();
}
}
}发布于 2019-05-22 02:10:57
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 = [];
}发布于 2019-05-22 02:44:29
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,这是我的解决方案,非常适合我:-)
https://stackoverflow.com/questions/56243684
复制相似问题