JsonResponse中没有显示任何表单错误 - Symfony

时间:2016-03-15 10:43:45

标签: json symfony

我有一个注册表单,其中包含在User实体类中验证的字段。验证工作正常,但是我无法在其中返回带有表单错误消息的JsonResponse。

我的注册表单控制器方法如下所示:

    /**
     * @Route("/register", name="register")
     */
    public function registerAction(Request $request)
    {
        $user = new User();
        $form = $this->createForm(RegistrationType::class, $user);
        $form->handleRequest($request);
        $errors = "";

        if ($form->isSubmitted())
        {
            if ($form->isValid())
            {
                $password = $this->get('security.password_encoder')
                    ->encodePassword($user, $user->getPlainPassword());
                $user->setPassword($password);

                $user->setIsActive(1);
                $user->setLastname('none');

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                return new JsonResponse(
                    array(
                        'message' => 'Success! User registered!',
                    ), 200);
            }
            else
            {
                $errors = ($this->get('validator')->validate($form));

                return new JsonResponse(
                    array(
                        'message' => 'Not registered',
                        'errors'  => $errors,
                    ), 400);
            }
        }

        return $this->render(
            'ImmoBundle::Security/register.html.twig',
            array('form' => $form->createView(), 'errors' => $errors)
        );
    }

当我提交包含无效数据的注册表单时,我收到以下json响应:

  

{" message":"未注册","错误":{}}

实际上我希望"错误":{}会包含一些错误字段,但它并不存在。有谁知道这里的问题是什么?

UPD:

我的RegistrationType如下所示:

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', TextType::class)
            ->add('email', EmailType::class)
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options' => array('label' => 'Password'),
                'second_options' => array('label' => 'Repeat password'),
                'invalid_message' => "Passwords don't match!",
            ))
            ->add('register', SubmitType::class, array('label' => 'Register'));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
                'data_class'        => 'ImmoBundle\Entity\User',
                'csrf_protection'   => true,
                'csrf_field_name'   => '_token',
                'csrf_token_id'     => 'authenticate',
            ));
    }
}

UPD2:找到解决方案。我需要执行此迭代,然后调用getMessage():

$allErrors = ($this->get('validator')->validate($form));

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

1 个答案:

答案 0 :(得分:2)

在您致电$form->handleRequest($request);

时验证表单

要获取表单错误,请使用getErrors方法

$errors = $form->getErrors(true); // $errors will be Iterator

将errors对象转换为messages数组,您可以使用此响应中的代码 - Handle form errors in controller and pass it to twig

这是我在其中一个项目中处理错误的原因

 $response = $this->get('http.response_formatter');
 if (!$form->isValid()) {
     $errors = $form->getErrors(true);
     foreach ($errors as $error) {
         $response->addError($error->getMessage(), Response::HTTP_BAD_REQUEST);
     }

     return $response->jsonResponse(Response::HTTP_BAD_REQUEST);
 }

它对我有用。

这也可以帮助你 - Symfony2 : How to get form validation errors after binding the request to the form

  

您必须通过明确为每个字段设置选项,在表单类型中将error_bubbling设置为true。