Set up registration FOSUserBundle with FOSRestBundle REST API - php

Problem fixed, check my answer.
I'm building a registration endpoint on my Symfony2.7 rest api.
I am using FosRestBundle and FosUserBundle
Here is the user model :
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct() {
parent::__construct();
// your own logic
}
}
\
Here is the UserType form :
\
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email')
->add('username', null)
->add('plainPassword', 'repeated', array(
'type' => 'password',
'first_options' => array('label' => 'password'),
'second_options' => array('label' => 'password_confirmation'),
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
'csrf_protection' => false,
));
}
/**
* #return string
*/
public function getName()
{
return 'user';
}
}
And this the post user controller :
public function postUserAction(\Symfony\Component\HttpFoundation\Request $request) {
$user = new \AppBundle\Entity\User();
$form = $this->createForm(new \AppBundle\Form\UserType(), $user);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$view = $this->view(array('token'=>$this->get("lexik_jwt_authentication.jwt_manager")->create($user)), Codes::HTTP_CREATED);
return $this->handleView($view);
}
return array(
'form' => $form,
);
}
The problem is that when i submit wrong information, or empty information, the server return a bad formated 500 error with doctrine / mysql details of null value for not null row in state of a json response with the list of bad formated entries.
Any idea on how to fix this behaviour ?
How come the validation get by passed and

Ok after spending a lot of time reading the FOSUserBundle code, and particularly the registration controller and the form factory, i came up with a fully working solution.
Before doing anything don't forget to disable CSRF in your symfony2 configuration.
Here is the controller I use to register :
public function postUserAction(\Symfony\Component\HttpFoundation\Request $request) {
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new \FOS\UserBundle\Event\GetResponseUserEvent($user, $request);
$dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
$event = new \FOS\UserBundle\Event\FormEvent($form, $request);
$dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);
}
$dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_COMPLETED, new \FOS\UserBundle\Event\FilterUserResponseEvent($user, $request, $response));
$view = $this->view(array('token' => $this->get("lexik_jwt_authentication.jwt_manager")->create($user)), Codes::HTTP_CREATED);
return $this->handleView($view);
}
$view = $this->view($form, Codes::HTTP_BAD_REQUEST);
return $this->handleView($view);
}
Now the tricky part was submiting the form using REST. The problem was that when I sent i JSON like this one :
{
"email":"xxxxx#xxxx.com",
"username":"xxx",
"plainPassword":{
"first":"xxx",
"second":"xxx"
}
}
The API was responding like nothing was submited.
The solution is that Symfony2 is waiting for you to encapsulate your form data in the form name !
The question was "I didnt create this form so i dont know what is its name..".
So i went again in the bundle code and found out that the form type was fos_user_registration and the getName function was returning fos_user_registration_form.
As a result i tried to submit my JSON this way :
{"fos_user_registration_form":{
"email":"xxxxxx#xxxxxxx.com",
"username":"xxxxxx",
"plainPassword":{
"first":"xxxxx",
"second":"xxxxx"
}
}}
And voila! it worked.
If you are struggling setting up your fosuserbundle with fosrestbundle and LexikJWTAuthenticationBundle just ask me i'll be glad to help.

Another way is this registration without the forms from FOSUserBundle.
Make a POST Request with params: email, user, password.
public function postUserAction(Request $request)
{
$userManager = $this->get('fos_user.user_manager');
$email = $request->request->get('email');
$username = $request->request->get('user');
$password = $request->request->get('password');
$email_exist = $userManager->findUserByEmail($email);
$username_exist = $userManager->findUserByUsername($username);
if($email_exist || $username_exist){
$response = new JsonResponse();
$response->setData("Username/Email ".$username."/".$email." existiert bereits");
return $response;
}
$user = $userManager->createUser();
$user->setUsername($username);
$user->setEmail($email);
$user->setLocked(false);
$user->setEnabled(true);
$user->setPlainPassword($password);
$userManager->updateUser($user, true);
$response = new JsonResponse();
$response->setData("User: ".$user->getUsername()." wurde erstellt");
return $response;
}

#Adel 'Sean' Helal your way doesn't work, at least with last versions of FOSRestBundle, FOSUserBundle and Symfony with Flex. I almost shoot myself in the head trying to make it work. At the end I found the solution and it's pretty simple. Only parse the request is required.
Fragment of my controller code
...
$form->setData($user);
// THIS LINE DO THE MAGIC
$data = json_decode($request->getContent(), true);
if ($data === null) {
throw new BadRequestHttpException();
}
$form->submit($data);
if ( ! $form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
return new JsonResponse($this->getFormErrors($form), Response::HTTP_BAD_REQUEST);
}
...
The composer.json dependencies:
...
"symfony/lts": "^3",
"symfony/flex": "^1.0",
"friendsofsymfony/rest-bundle": "^2.3",
"friendsofsymfony/user-bundle": "^2.0",
"lexik/jwt-authentication-bundle": "^2.4",
...
My functional test code:
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\Container;
class ApiUserControllerTest extends WebTestCase
{
/**
* #var Container
*/
private $container;
public function setUp()
{
self::bootKernel();
$this->container = self::$kernel->getContainer();
}
public function testRegistration()
{
$userData = [
'username' => 'test',
'email' => 'test#email.com',
'plainPassword' => [
'first' => 'test123', 'second' => 'test123'
]
];
$client = $this->container->get('eight_points_guzzle.client.rest');
$response = $client->post(
'api/registration',
['json' => $userData]
);
$bodyResponse = \GuzzleHttp\json_decode($response->getBody(), true);
$this->assertEquals(201, $response->getStatusCode());
$this->assertArrayHasKey('token', $bodyResponse);
$this->assertNotEmpty($bodyResponse['token']);
}
}

Related

Render new template contain successfully message after resetting password

I'm using Fosuserbundle and I want to render new template contain successfully message after resetting password. but I don't know how can I override the ResettingController file in order to render the template. here is the controller :
public function resetAction(Request $request, $token)
{
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.resetting.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
$form->getErrors(true);
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_SUCCESS, $event);
$this->render('FOSUserBundle:Resetting:reset.html.twig', array(
'token' => $token,
'form' => $form->createView(),
));
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('FOSUserBundle:Resetting:reset.html.twig', array(
'token' => $token,
'form' => $form->createView(),
));
}
I'm not using FosUserBundle and I'm not sure your code snippet abow is origin Fos controller. In your case, I don't think you needs to override the controller. Just listen to FOSUserEvents::RESETTING_RESET_SUCCESS event, create your own response and set back to the event $event->setResponse($response), your response will be used by Fos controller. When create your response, you can render any template path with any parameters as you want.
Here is an example:
class ResettingListener implements EventSubscriberInterface
{
/**
* #var EngineInterface
*/
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents()
{
return [FOSUserEvents::RESETTING_RESET_SUCCESS => 'onResettingResetSuccess'];
}
/**
* #param FormEvent $event
*/
public function onResettingResetSuccess(FormEvent $event)
{
$response = $this->templating->render('YourBundle:Location:resetting.html.twig', [
'form' => $event->getForm()->createView()
]);
$event->setResponse($response);
}
}
And register as service:
<service id="your_bundle.listener.resetting" class="Vendor\YourBundle\EventListener\ResettingListener">
<argument type="service" id="templating" />
<tag name="kernel.event_subscriber" />
</service>

Overriding FOSUserBUndle Controllers Symfony 2

I want to override FOS\UserBundle\Controller\RegistrationController to add some functionalities (to manage the fields I add in my registration form etc).
I do not know why, after overriding it, symphony ignores my controller. This is not the first time, I also tried to override others ... never found solutions ...
<?php
namespace FP\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
class RegistrationController extends BaseController
{
public function registerAction()
{
$response = parent::registerAction();
echo "FPUserBundle";
// do custom stuff
return $response;
}
}
.
<?php
namespace FP\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class FPUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
.
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\UserBundle\Controller;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;
/**
* Controller managing the registration
*
* #author Thibault Duplessis <thibault.duplessis#gmail.com>
* #author Christophe Coevoet <stof#notk.org>
*/
class RegistrationController extends Controller
{
public function registerAction(Request $request)
{
echo "FOSUserBundle";
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);//active l'user
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
$event = new FormEvent($form, $request);
//--- ajout des données pour les champs ajoutés ---
$user->setDateInscrip(new \DateTime());
$user->setRoles(array('ROLE_USER'));
//--------- Fin de l'ajout ---------
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Tell the user to check his email provider
*/
public function checkEmailAction()
{
$email = $this->get('session')->get('fos_user_send_confirmation_email/email');
$this->get('session')->remove('fos_user_send_confirmation_email/email');
$user = $this->get('fos_user.user_manager')->findUserByEmail($email);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
}
return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
'user' => $user,
));
}
/**
* Receive the confirmation token from user email provider, login the user
*/
public function confirmAction(Request $request, $token)
{
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user->setConfirmationToken(null);
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
/**
* Tell the user his account is now confirmed
*/
public function confirmedAction()
{
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->redirect($this->generateUrl('fp_user_inscrip', array('user' => $user)));
/*
return $this->render('FPPlatformBundle:Index:index.html.twig', array(
'user' => $user,
));*/
}
}
Despite these codes, when I run the check, "FPUserBundle" is not displayed, while "FOSUserBundle" appears well ...
Check that you've added the new Bundle into app/AppKernel.php::registerBundles function.
Overriding Classes (Controllers are classes too!) will give the new class all the futures that the base-class has (except direct access to private methods or properties). But do not forget that the base-class still can be used beside the new class. It dependence's which class you instantiate.
$a = new BaseClass();
vs
$a = new NewClass();
So the question is which one will Symfony use? And THAT is what you can manage with the routing. as long this is in your app/config/routing.yml:
fos_user:
resource: "#FOSUserBundle/Resources/config/routing/all.xml"
Symfony will use the original FOSUserBundle controllers. Just find those xml files in the vendor/FOS.. directory and copy them to your own project. Change above showed rule to your own bundle and change the controllernames in the xml files. Of course you could write your own .yml files too.
read more

Ignore password when admin user (from Backend) updates any user profile with FOSUserBundle

I'm facing a problem like the one posted here but since I have not a UserFormType I don't know how to solve this. The idea is not to ask for password each time I (logged in as admin and with right permissions) will change a user profile field like email for example. This is my code:
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($id);
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->container->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
if ('POST' === $request->getMethod())
{
$form->handleRequest($request);
if ($form->isValid())
{
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$userManager->updateUser($user);
}
}
return array(
'form' => $form->createView(),
'id' => $user->getId()
);
}
Resuming, how do I avoid ask for password each time I want to update a user profile, any help?
So it looks like the problem stems from the fact you're letting FOSUserBundle do everything for you, which is fair enough but makes it harder to tweak behaviour. You can override various things to change how it works, but my own application doesn't use FOSUserBundle at all for managing users after they're registered, you can simply create your own simple form to do it, e.g.:
class UserType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', 'text')
->add('email', 'email')
->add('save', 'submit');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Your\Bundle\Entity\User',
));
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName()
{
return 'user';
}
}
And then your controller would stay reasonably similar, except no separate Form Factory needed and use your UserType:
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($id);
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
//Don't need this!
//$formFactory = $this->container->get('fos_user.profile.form.factory');
//$form = $formFactory->createForm();
//$form->setData($user);
$form = $this->createForm(new UserType(), $user);
if ('POST' === $request->getMethod())
{
$form->handleRequest($request);
if ($form->isValid())
{
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$userManager->updateUser($user);
}
}
return array(
'form' => $form->createView(),
'id' => $user->getId()
);
}
Not sure of the detail of your View etc, but you just need to render the Form and things should be golden!
Hope I haven't got the wrong end of the stick.

How to prevent "confirm form resubmission" popup after failed form submission

When form submission fails, same webform is presented to user with the error messages which is fine however, when they hit F5 or use back/forward buttons of browser, "Confirm re-submission" popup appears. How can prevent this action?
Note: I used to use redirection method in CodeIgniter without losing error messages but I don't know how to handle same kind of process in Symfony since I'm new to it. Any solution is acceptable though.
Controller:
namespace Se\HirBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Se\HirBundle\Entity\Task;
use Se\HirBundle\Form\Type\TaskType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class TodoController extends Controller
{
public function indexAction()
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task, array('action' => $this->generateUrl('todo_new')));
return $this->render('SeHirBundle:Default:todo.html.twig',
array('page' => 'Todo', 'form' => $form->createView()));
}
public function newAction(Request $request)
{
if ($request->getMethod() == 'POST')
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task, array('action' => $this->generateUrl('todo_new')));
$form->handleRequest($request);
if ($form->isValid())
{
$task = $form->get('task')->getData();
$due = $form->get('due')->getData();
$data = $form->getData();
echo '<pre>'; print_r($data);
return new Response("Well done: $task - $due");
}
else
{
return $this->render('SeHirBundle:Default:todo.html.twig',
array('page' => 'Todo', 'form' => $form->createView()));
}
}
else
{
return new Response('Only POST method accepted');
}
}
}
Error bubbling true is what groups all of the errors together. Set this false.
The error popup is based on your browser. I'm not sure that can be shut off via Symfony. The
required => false
should have done this already.
Trick is to keep form data in a session and populate form type with the data stored in same session for failing forms submissions. Data stays in session until successful form submission.
Full example is here: Preventing 'Confirm form resubmission' dialog in symfony applications
/**
* #Route("/interest", service="my_test_bundle.controller.interest")
*/
class InterestController
{
private $formFactory;
private $router;
public function __construct(
FormFactoryInterface $formFactory,
RouterInterface $router
) {
$this->formFactory = $formFactory;
$this->router = $router;
}
/**
* #Method({"GET"})
* #Route("", name="interest_index")
* #Template()
*
* #param Request $request
*
* #return array
*/
public function indexAction(Request $request)
{
$form = $this->createForm();
$session = $request->getSession();
if ($session->has($this->getFormName())) {
$request->request->set(
$this->getFormName(),
unserialize($session->get($this->getFormName()))
);
$request->setMethod('POST');
$form->handleRequest($request);
}
return ['interest_form' => $form->createView()];
}
/**
* #Method({"POST"})
* #Route("", name="interest_create")
*
* #param Request $request
*
* #return RedirectResponse
*/
public function createAction(Request $request)
{
$session = $request->getSession();
$form = $this->createForm();
$form->handleRequest($request);
if ($form->isValid()) {
// Do something with: $form->getData();
$session->remove($this->getFormName());
$routeName = 'home_or_success_route';
} else {
$session->set(
$this->getFormName(),
serialize($request->request->get($this->getFormName()))
);
$routeName = 'interest_index';
}
return new RedirectResponse($this->router->generate($routeName));
}
private function createForm()
{
return $this->formFactory->create(
InterestType::class,
new Interest(),
[
'method' => 'POST',
'action' => $this->router->generate('interest_create'),
'attr' => ['id' => $this->getFormName()],
]
);
}
private function getFormName()
{
return InterestType::NAME;
}
}

Access to service overriding FOS User Bundle Controller

I'm new in Symfony2,
I'm trying to override a controller using a service inside
This is the register controller
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
/** #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);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request));
$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()) {
$url = $this->container->get('router')->generate('easy_app_user_profile');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
//create UserInfo
$doctrine = $this->container->get('doctrine');
$userInfo = new UserInformation();
$userInfo->setUser($user);
//save the userInfo
$em = $doctrine->getManager();
$em->persist($userInfo);
$em->flush();
//add user first login
$loginManager = $this->get('user_login_manager');
$loginManager->saveUser($request, $user);
return $response;
}
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
near the end I'm using
$loginManager = $this->get('user_login_manager');
$loginManager->saveUser($request, $user);
But I can't use get because this is not extending Controller.
So I don't know how to access to my service in this controller
Thanks
$this->get('some_service') is only a helper shortcut defined in the symfony base controller. Look at you code above and see how all the services are called:
$loginManager = $this->container->get('user_login_manager');
Btw. if you are using the latest version of FOSUserBundle (dev-master), then the new event system might fit better than overriding the controller. REGISTER_COMPLETED may fit for you use case. If you take a look in the controller code above, you can see, when the event is dispatched. You should fairly use events than controller overriding.

Categories