how to return json encoded form errors in symfony

前端 未结 6 2017
臣服心动
臣服心动 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:42

    This will do the trick. This static method runs recursively through the Symfony\Component\Form\FormErrorIterator delivered by calling $form->getErrors(true, false).

    getErrors(true, false) as $formError) {
                if ($formError instanceof FormError) {
                    $result[$formError->getOrigin()->getName()] = $formError->getMessage();
                } elseif ($formError instanceof FormErrorIterator) {
                    $result[$formError->getForm()->getName()] = self::generateErrorsArrayFromForm($formError->getForm());
                }
            }
            return $result;
        }
    }
    

    Here is the result :

    {
        "houseworkSection": "All the data of the housework section must be set since the section has been requested.",
        "foodSection": {
            "requested": {
                "requested": "This value is not valid."
            }
        }
    }
    

提交回复
热议问题