how to return json encoded form errors in symfony

前端 未结 6 2045
臣服心动
臣服心动 2020-12-08 03:22

I want to create a webservice to which I submit a form, and in case of errors, returns a JSON encoded list that tells me which field is wrong.

currently I only get a

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 03:47

    PHP has associative arrays, meanwhile JS has 2 different data structures : object and arrays.

    The JSON you want to obtain is not legal and should be :

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

    So you may want to do something like this to build your collection :

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

    (assuming the getId() method exist on $error objects)

提交回复
热议问题