On my Symnfony3 project I noticed that during registration some events are generated where I can override the response. eg. Instead of rendering the default twig template and redirect to just return a JsonResponse with a successMessage.
Therefore I did the following Event Subscriber:
namespace AppBundle\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use AppBundle\Constants\AjaxJsonResponseConstants;
use Symfony\Component\HttpFoundation\JsonResponse;
use FOS\UserBundle\Event\FilterUserResponseEvent;
class UserRegistrationResponseChanger implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
$subscribedEvents=[
// FOSUserEvents::REGISTRATION_INITIALIZE=>[],
FOSUserEvents::REGISTRATION_COMPLETED=>[],
FOSUserEvents::REGISTRATION_SUCCESS=>["setJsonResponseOnSuccess",-1],
FOSUserEvents::REGISTRATION_FAILURE=>["setJsonResponseOnFailure",-1],
// FOSUserEvents::REGISTRATION_CONFIRM=>[],
// FOSUserEvents::REGISTRATION_CONFIRMED=>[]
];
}
public function setJsonResponseOnSuccess(FormEvent $formEvent)
{
$response=['status'=>AjaxJsonResponseConstants::AJAX_ACTION_SUCCESS,'message'=>"User Sucessfully Registered please check your mail."];
$response=new JsonResponse($response);
$formEvent->setResponse($response);
return $response;
}
public function setJsonResponseOnFailure(FormEvent $formEvent)
{
$response=['status'=>AjaxJsonResponseConstants::AJAX_ACTION_FAIL,'message'=>"You cannot register please try again later"];
$response=new JsonResponse($response);
$formEvent->setResponse($response);
return $response;
}
}
Also on my services.yml
I have put the following:
app.user_register.subscriber:
class: AppBundle\EventSubscriber\UserRegistrationResponseChanger
tags:
- { name: app.user_register.subscriber }
And the command
In order to override on how the response will get returned but somehow it fails to do so and redirects to the default page. What I try to acheive it to perform the registration via ajax call instead of rendering the registration page and redirecting.