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>
Related
I'm looking to combine a post rest method and FOSUserBundle to my symfony 3 application to register new user, so the problem is that when i use to post a new user I got this error Bad Request with "The CSRF token is invalid. Please try to resubmit the form
here is the page that appears when i use to post a new user
This is the registration method :
class DefaultController extends BaseController
{
/**
* #Route("/register", name="registermethod")
*/
public function registerAction(Request $request)
{
$usermane = $request->query->get('username');
$password = $request->query->get('password');
$email = $request->query->get('email');
/** #var $formFactory FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->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();
$user->setUsername($usermane);
$user->setPlainPassword($password);
$user->setEmail($email);
$form->setData($user);
$form->handleRequest($request);
$form->submit($request->request->all());
if ($form->isSubmitted()) {
if ($user->getUsername() != null) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
/*****************************************************
* Add new functionality (e.g. log the registration) *
*****************************************************/
$this->container->get('logger')->info(
sprintf("New user registration: %s", $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;
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
}
return $this->render('#FOSUser/Registration/register.html.twig', array(
'form' => $form->createView(),
));
}
I'use to post to this method in my angular application so the link is like this http://localhost:8000/showing1?username=azaz&email=asc#gmail.com&password=123456789
Thank you in advance.
I'm not sure if it is advisable but what you can do is.
$form = $formFactory->createForm(['csrf_protection' => false]);
I'd like the user to register, confirm it's email, but being activated manually by an administrator.
Thanks to this page I found the FOSUserEvents::REGISTRATION_CONFIRMED which is called right after clicking on the confirmation link in the email.
Now I'd like to disable the account (see below).
class RegistrationListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRMED => 'onRegistrationCompleted'
);
}
public function onRegistrationCompleted(UserEvent $event) {
// registration completed
// TODO: disable the user. How?
}
}
Or is there any configuration that I missed?
Any ideas?
Thanks in advance!
As I can see, inside FOS\UserBundle\Controller\RegistrationController::
confirmAction() user is enabled:
/**
* Receive the confirmation token from user email provider, login the user.
*
* #param Request $request
* #param string $token
*
* #return Response
*/
public function confirmAction(Request $request, $token)
{
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
...
$user->setConfirmationToken(null);
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);
$userManager->updateUser($user);
...
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
I can think of two things you can do to disable it.
1) write an event listener, that will react on FOSUserEvents::REGISTRATION_CONFIRMED and disable the user => http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html
2) override RegistrationController => https://symfony.com/doc/current/bundles/FOSUserBundle/overriding_controllers.html
I prefer first option.
class RegistrationListener implements EventSubscriberInterface
{
/** #var EntityManager */
private $em;
/**
* #param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRMED => 'onRegistrationCompleted'
);
}
public function onRegistrationCompleted(UserEvent $event) {
// registration completed
// TODO: disable the user. How?
$user = $event->getUser();
$user->setEnabled(false);
$this->em->persist($user);
$this->em->flush();
}
}
I am trying to redirect the user to another form before user get confirmation email. So I after submit of register form I want to redirect user to another form to fill so that I can assign roles to the user. After submission of that form user should get a confirmation email. After confirmation user will login automatically.
Full Code
User management with FUB
RegistrationSuccessListener.php
namespace Usr\UserBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\GetResponseUserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RegistrationSuccessListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'
);
}
public function onRegistrationSuccess(GetResponseUserEvent $event)
{
$url = $this->router->generate('fos_user_registration_success');
$event->setResponse(new RedirectResponse($url));
}
}
And my services.yml
services:
usr_user.registration.success:
class: Usr\UserBundle\EventListener\RegistrationSuccessListener
arguments: ["#router"]
tags:
- { name: kernel.event_subscriber }
I am getting error:
Type error: Argument 1 passed to Usr\UserBundle\EventListener\RegistrationSuccessListener::onRegistrationSuccess() must be an instance of FOS\UserBundle\Event\GetResponseUserEvent, instance of FOS\UserBundle\Event\FormEvent given
RegistrationController.php
namespace Usr\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;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
/**
* Controller managing the registration
*/
class RegistrationController extends BaseController
{
public function registerAction(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 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);
$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->render('FOSUserBundle:Registration:confirmed.html.twig', array(
'user' => $user,
'targetUrl' => $this->getTargetUrlFromSession(),
));
}
private function getTargetUrlFromSession()
{
// Set the SecurityContext for Symfony <2.6
if (interface_exists('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')) {
$tokenStorage = $this->get('security.token_storage');
} else {
$tokenStorage = $this->get('security.context');
}
$key = sprintf('_security.%s.target_path', $tokenStorage->getToken()->getProviderKey());
if ($this->get('session')->has($key)) {
return $this->get('session')->get($key);
}
}
public function registercuccessAction()
{
return $this->render('::base.html.twig', array());
}
}
I know that is not the best practice solution but it can help you, just
change the selected route name.
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']);
}
}
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