我想创建一个向其提交表单的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"
}
}
我该如何实现?
我终于在这里找到了解决该问题的方法,它只需要进行一些小改动就可以适应最新的symfony更改,并且它的工作原理很吸引人:
解决方法是替换第33行
if (count($child->getIterator()) > 0) {
与
if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {
因为,随着在Form \ Button的symfony中的介绍,序列化函数中会出现类型不匹配的情况,该函数期望总是Form \ Form的实例。
您可以将其注册为服务:
services:
form_serializer:
class: Wooshii\SiteBundle\FormErrorsSerializer
然后使用它作为作者的建议:
$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句