Question

I'm using FOSUB in my Symfony app to to manage my users. I overrided the register template and controller to use Ajax and customize some stuff. It works fine if the user proceeds to registration with no errors. But if something is wrong (ex. different paswwords) the $form->isValid() returns false but the $form->getErrors() array is empty. After some research I still don't know how to retrieves those errors. Anyone got an idea ? Thanks :) Here is my controller:

public function registerAction(Request $request)
{
    if($request->isXmlHttpRequest())
    {
        $returnArray = array();
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
        $form->setData($user);

        if ('POST' === $request->getMethod()) {
            $form->bind($request);

            if ($form->isValid()) {
                $event = new FormEvent($form, $request);
                $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
                $userManager->updateUser($user);

                if (null === $response = $event->getResponse()) {
                    $returnArray[] = array("success" => "Registration confirmed.");
                    $returnArray[] = array("info" => "An email has been send.");
                }

                    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                return new Response(json_encode($returnArray));
            }
            else
            {
                foreach($form->getErrors() as $error)
                    $returnArray[] = array("error" => $error->getMessage());

                return new Response(json_encode($returnArray));
            }
        }
    }
    return new Response("This is not XHR");
}
Was it helpful?

Solution

To show the error of the password fields you must display the errors on the password field. {{ form_errors(form.plainPassword.first) }}. If you just do {{ form_errors(form.plainPassword) }} the errors are not returning because the errors aren't bubbling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top