php - 如何在 symfony 中返回 json 编码格式错误

我想创建一个向其提交表单的 Web 服务,如果出现错误,则返回一个 JSON 编码列表,告诉我哪个字段是错误的。

目前我只得到错误消息列表,但没有 html id 或有错误的字段名称

这是我当前的代码

public function saveAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $form = $this->createForm(new TaskType(), new Task());

    $form->handleRequest($request);

    $task = $form->getData();

    if ($form->isValid()) {

        $em->persist($task);
        $em->flush();

        $array = array( 'status' => 201, 'msg' => 'Task Created'); 

    } else {

        $errors = $form->getErrors(true, true);

        $errorCollection = array();
        foreach($errors as $error){
               $errorCollection[] = $error->getMessage();
        }

        $array = array( 'status' => 400, 'errorMsg' => 'Bad Request', 'errorReport' => $errorCollection); // data to return via JSON
    }

    $response = new Response( json_encode( $array ) );
    $response->headers->set( 'Content-Type', 'application/json' );

    return $response;
}

这会给我一个类似的回应

{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
        "Task cannot be blank",
        "Task date needs to be within the month"
    }
}

但我真正想要的是类似的东西

{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
        "taskfield" : "Task cannot be blank",
        "taskdatefield" : "Task date needs to be within the month"
    }
}

我怎样才能做到这一点?

最佳答案

我正在使用它,它运行良好:

/**
 * List all errors of a given bound form.
 *
 * @param Form $form
 *
 * @return array
 */
protected function getFormErrors(Form $form)
{
    $errors = array();

    // Global
    foreach ($form->getErrors() as $error) {
        $errors[$form->getName()][] = $error->getMessage();
    }

    // Fields
    foreach ($form as $child /** @var Form $child */) {
        if (!$child->isValid()) {
            foreach ($child->getErrors() as $error) {
                $errors[$child->getName()][] = $error->getMessage();
            }
        }
    }

    return $errors;
}

https://stackoverflow.com/questions/24556121/

相关文章:

javascript - 定义 "cyclic data structures"

c# - ASP.NET web api 无法获取 application/x-www-form-u

python - 如何以人类可读的格式序列化 Python 对象?

json - 将参数传递给 jq 过滤器

xml - CSV、JSON 和 XML 对于 REST API 的相对优点是什么?

java - 如何使用 Java 和 Jackson 库对 Json 字符串进行多态反序列化?

ruby-on-rails - rails : Restrict API requests to J

java - 如何使用 Jackson 定义可选的 json 字段

java - 为什么 Json 测试程序不起作用?

Java - 嵌套在嵌套中的 Gson 解析