Sim*_*est 25 php forms ajax json symfony
我想创建一个我提交表单的web服务,如果有错误,返回一个jason编码列表,告诉我哪个字段是错误的.
目前我只获取错误消息列表,但不是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"
    }
}
我怎样才能做到这一点?
COi*_*Oil 24
我正在使用它,它安静得很好:
/**
 * 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;
}
Sim*_*est 16
我终于在这里找到了这个问题的解决方案,它只需要一个小的修复来遵守最新的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);
这对我来说很有用
 $errors = [];
 foreach ($form->getErrors(true, true) as $formError) {
    $errors[] = $formError->getMessage();
 }