symfony2:在控制器中获取表单错误

symfony2 : Get form errors in controller

我通过 AJAX CALL 验证了我的表单,但无法检索 "error messages".

这是我输入的内容:

$newRdvForm = $this->createForm(new RdvType());

$newRdvForm->handleRequest($request);

if ($newRdvForm->isValid()) { 
   // set of instructions to be performed when the form is valid
}
else {

   $errors= array();

   foreach ($newRdvForm->getErrors() as $key => $error) {
        $errors[$key] = $error->getMessage();
   }   

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

   return $response; 

}

我用的是 symfony 2.7。上面的代码不会检索错误消息。

也许您的 for myte 是由多个嵌套类型构建的?尝试使用 getErrors(true)

http://symfony.com/doc/current/components/form/introduction.html#accessing-form-errors

/**
 * get Error Messages From Form.
 * @param \Symfony\Component\Form\Form $form
 * @return array
 */
protected function getErrorMessages(\Symfony\Component\Form\Form $form) {
  $errors = array();
 if ($form->count() > 0) {
    foreach ($form->all() as $child) {
        if (!$child->isValid()) {
           $errors[$child->getName()] = (String) $form[$child->getName()]->getErrors();
        }
     }
 }
 return $errors;
}

对于表单中的错误列表,您可以将其保留在数组中

   foreach ($form->getErrors(true, false) as $error) {
                $errors[] = $error->current()->getMessage();
            }