FOSUserBundle override action of a controller - symfony

I'm trying to override the editAction in ProfileController.php but it's doesn't work. I can override template and form with success but not the actions of controllers.
app/config.yml
# FOS UserBundle Configuration
fos_user:
db_driver: orm
firewall_name: main
user_class: Intranet\UserBundle\Entity\User
registration:
form:
type: intranet_user_registration
profile:
form:
type: intranet_user_profile
old src/Intranet/UserBundle/Controller/ProfileController.php
<?php
namespace Intranet\UserBundle\Controller;
use FOS\UserBundle\Controller\ProfileController as BaseController;
class ProfileController extends BaseController
{
/**
* Edit the user
*/
public function editAction(Request $request)
{
var_dump($request) die(); // just for the test
}
}
new src/Intranet/UserBundle/Controller/ProfileController.php
<?php
namespace Intranet\UserBundle\Controller;
use FOS\UserBundle\Controller\ProfileController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ProfileController extends BaseController
{
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #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->bind($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse(
'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
array('form' => $form->createView())
);
}
}
src/Intranet/UserBundle/IntranetUserBundle.php
<?php
namespace Intranet\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class IntranetUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
No error message, SF2 ignore my override :/

Ok I found, the controller need the same use of his parent
Last version of ProfileController :
namespace Intranet\UserBundle\Controller;
/* ALL USE IS REQUIRED !!!! */
use FOS\UserBundle\Controller\ProfileController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ProfileController extends BaseController
{
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #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->bind($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse(
'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
array('form' => $form->createView())
);
}
}

Related

Controller does not read the method from the Repository

Good afternoon,
I have this issue where the Admin Controller is not reading the method findBynom from the UserRepository even everything is included here is my code:
here is the UserRepository:
<?php
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method User|null find($id, $lockMode = null, $lockVersion = null)
* #method User|null findOneBy(array $criteria, array $orderBy = null)
* #method User[] findAll()
* #method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* #param $type
* #return int|mixed|string
*/
public function findBynom($type)
{
return $this->createQueryBuilder('p')
->Where('p.fullname LIKE :type')
->setParameter('type','%'.$type.'%')
->getQuery()
->getResult()
;
}
public function findByMail($type)
{
return $this->createQueryBuilder('p')
->Where('p.email LIKE :type')
->setParameter('type','%'.$type.'%')
->getQuery()
->getResult()
;
}
// /**
// * #return User[] Returns an array of User objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('u')
->andWhere('u.exampleField = :val')
->setParameter('val', $value)
->orderBy('u.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
public function findOneBySomeField($value): ?User
{
return $this->createQueryBuilder('u')
->andWhere('u.activation_token = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
}
and here is the AdminController:
<?php
namespace App\Controller;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use GuzzleHttp\Psr7\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
/**
* #Route("/admin", name="admin_")
*/
class AdminController extends AbstractController
{
/**
* Liste les utilisateur du side
* #Route("/", name="users", methods={"GET"})
*/
public function index(UserRepository $users){
return $this->render("admin/index.html.twig",[
'users'=> $users->findAll()
]);
}
/**
* #Route("/new", name="app_admin_new", methods={"GET", "POST"})
*/
public function new(Request $request, UserRepository $userRepository): Response
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $form->get('Photo')->getData();
$Filename = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('images'),
$Filename
);
$user->setPhoto($Filename);
$userRepository->add($user);
return $this->redirectToRoute('app_admin_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('admin/new.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="app_admin_show", methods={"GET"})
*/
public function show(User $user): Response
{
return $this->render('admin/show.html.twig', [
'user' => $user,
]);
}
/**
* #Route("/{id}/edit", name="app_admin_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, User $user, UserRepository $userRepository): Response
{
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$userRepository->add($user);
return $this->redirectToRoute('app_admin_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('admin/edit.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="app_admin_delete", methods={"POST"})
*/
public function delete(Request $request, User $user, UserRepository $userRepository): Response
{
if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
$userRepository->remove($user);
}
return $this->redirectToRoute('app_admin_index', [], Response::HTTP_SEE_OTHER);
}
/**
* #Route("/{id}/ban", name="admin_ban", methods={"GET", "POST"})
*/
public function ban(Request $request, User $user, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('ban'.$user->getId(), $request->request->get('_token'))) {
$user->setIsBanned(true);
$entityManager->flush();
}
return $this->redirectToRoute('admin_index', [], Response::HTTP_SEE_OTHER);
}
/**
* #Route("/{id}/unban", name="admin_unban", methods={"GET", "POST"})
*/
public function unban(Request $request, User $user, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('unban'.$user->getId(), $request->request->get('_token'))) {
$user->setIsBanned(false);
$entityManager->flush();
}
return $this->redirectToRoute('admin_index', [], Response::HTTP_SEE_OTHER);
}
/**
* #Route("/searchuser", name="utilsearchuser")
*/
public function searchPlan($searchString): JsonResponse
{
$serializer = new Serializer([new ObjectNormalizer()]);
$repository = $this->getDoctrine()->getRepository(User::class);
$users = $repository->findBynom($searchString);
$data=$serializer->normalize($users);
return new JsonResponse($data);
}
}
thanks for your help!
adzdafzferfzfaefzrfzrgd a aefzk ff ae ae ak,er ear ae rea rak aer !
Most likely you didn't specify UserRepository in annotations to your entity. Just declare the repositoryClass parameter in your entity
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User
Then you can get an instance of your repository:
$users = $this->getDoctrine()->getRepository(User::class)->findBynom($searchString);
Or you can specify the UserRepository in an attribute of your method, after which the Dependency Injection Component will include it
/**
* #Route("/searchuser", name="utilsearchuser")
*/
public function searchPlan($searchString, UserRepository $userRepository): JsonResponse
{
$serializer = new Serializer([new ObjectNormalizer()]);
$users = $userRepository->findBynom($searchString);
$data=$serializer->normalize($users);
return new JsonResponse($data);
}

redirect to login after register

when i enabled confirmation email in register fosuserbundle it redirect automaticly to page login and in profilet i have status 302 for routing fos_user_registration_check_email also user is not created and when i disabled confirmation email i haven't any error and user is created.
controller:
/**
* #Route("/register", name="register_babysitter")
*/
public function registerAction(Request $request)
{
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user= new BabySitter();
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form= $this->createForm(BabySitterType::class, $user);
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$this->uploadDocument->upload($user->getPicture(), $this->getParameter('pictures_directory'));
$this->uploadDocument->upload($user->getCriminalRecord(), $this->getParameter('criminalRecord_director_babySitter'));
$this->uploadDocument->uploadIdCard($user->getIdCards(), $user,$this->getParameter('idCard_directory'));
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$response = $event->getResponse();
$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('AppBundle:BabySitter:register.html.twig', array(
'form' => $form->createView()
));
}
config:
fos_user:
db_driver: orm
firewall_name: main
user_class: AppBundle\Entity\User
service:
mailer: fos_user.mailer.twig_swift
from_email:
address: "test#gmail.com"
sender_name: "test#gmail.com"
registration:
confirmation:
enabled: true
help me please and thanks
You can also implements the method confirmAction() and confirmedAction() and to create your own logic:
/**
* Receive the confirmation token from user email provider, login the user.
*
*
* #Route("/register/confirm/{token}", name="registration_confirm")
*
* #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 = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
/** #var $dispatcher 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('register_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.
*
* #Route("/register/confirmed", name="register_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('frontend/register_success.html.twig', array(
'user' => $user,
'targetUrl' => $this->getTargetUrlFromSession(),
));
}
Remember also in the template of the email to use the route registration_confirm.
Basically, in these two actions, you could define the route you want to redirect once your user is register.

FOSUserBundle - Registration controller override error

I am trying to override the registration controller of FOSUserBundle.
Here's my configuration :
services:
project.registration.controller:
class: Project\UserBundle\Controller\RegistrationController
arguments: [ #event_dispatcher,#fos_user.registration.form.factory,#fos_user.user_manager,#security.token_storage]
And the controller so far:
<?php
namespace Project\UserBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
class RegistrationController extends BaseController
{
public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage)
{
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
}
However everytime i try to go to the registration page I meet this error :
Catchable Fatal Error: Argument 1 passed to Project\UserBundle\Controller\RegistrationController::__construct() must implement interface Symfony\Component\EventDispatcher\EventDispatcherInterface, none given, called in C:\wamp\www\cmagic\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Controller\ControllerResolver.php on line 187 and defined
I think I followed for controllers used as services or did I miss a step ?
EDIT : This is for symfony 2.8
It worked for me in Symfony 3, but getParent(){} for bundles is already deprecated in 3.4 version and disabled in 4.
namespace AppBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
namespace AppBundle\Controller;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class RegistrationController extends BaseController
{
/**
* #param Request $request
*
* #return Response
*/
public function registerAction(Request $request)
{
/** #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();
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
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;
}
$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(),
));
}
}

Submitting symfony register controller fosuserbundle does not work

I tried to follow this tutorial to override default controller of fos user bundle [Overriding Default FOSUserBundle Controllers][1]
And i can change controller but when I try to submit button it doesn't work:
<?php
// src/AppBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
/** #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);
var_dump('prova');
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->createForm(RegistrationType::class, $user, [
'method' => 'POST',
]);
//$form = $formFactory->createForm();
//$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
var_dump($form);
if ($form->isValid()) {
var_dump($form);
}
}
return $this->render('#FOSUser/Registration/register.html.twig', array(
'form' => $form->createView(),
));
}
}
The var_dump before the submit work but the var_dump inside
if ($form->isSubmitted()) {
if ($form->isValid()) {
doesn't work . I believe that submit logic is in another code but i don't understand how I can change it.
I don't understand how it's possible. Please help me ?
You don't set a formType to your form, so he have nothing to handle.
Here is a simple example :
$form = $this->createForm(YourFormType::class, $user, [
'method' => 'POST',
]);
Good luck ! :)

PUGXMultiUserBundle: custom profile template

A method to enable custom user profile templates involves modifying the vendor's Configuration.php. Is there a method that does not? Or is this a viable solution? Current method appears below:
Update: I'm thinking my bundle needs to take responsibility for the configuration so I'm in the throes of deciphering and applying the CompilerPassInterface.
[Edit: another way to ask the question - can this be done by prepending the template option with PrependExtensionInterface? If so, how might that work?]
config.yml
pugx_multi_user:
users:
staff:
entity:
class: Acme\MyBundle\Entity\Staff
# factory:
registration:
form:
type: Acme\UserBundle\Form\RegistrationStaffFormType
name: fos_user_registration_form
validation_groups: [Registration, Default]
template: AcmeUserBundle:Registration:staff.form.html.twig
profile:
form:
type: Acme\UserBundle\Form\ProfileStaffFormType
name: fos_user_profile_form
validation_groups: [Profile, Default]
# template line added
template: AcmeUserBundle:Profile:staff.form.html.twig
...
excerpt from PUGX\MultiUserBundle\DependencyInjection\Configuration.php
[Note addition of ->scalarNode('template')->defaultValue(null)->end()]
...
->children()
->arrayNode('profile')
->addDefaultsIfNotSet()
->children()
->arrayNode('form')
->addDefaultsIfNotSet()
->children()
->scalarNode('type')->defaultValue(null)->end()
->scalarNode('name')->defaultValue('fos_user_profile_form')->end()
->arrayNode('validation_groups')
->prototype('scalar')->end()
->defaultValue(array('Profile', 'Default'))
->end()
->end()
->end()
->scalarNode('template')->defaultValue(null)->end()
->end()
->end()
->end()
...
ProfileController (in extended User Bundle)
class ProfileController extends BaseController
{
/**
* Edit the user
*/
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$discriminator = $this->container->get('pugx_user.manager.user_discriminator');
$users = $this->container->getParameter('pugx_user_discriminator_users');
$class = $discriminator->getClass($user);
foreach ($users as $userType) {
if ($userType['entity']['class'] == $class) {
$templateString = $userType['profile']['template'];
if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
$template = 'FOSUserBundle:Profile:edit.html.';
} else {
$l = strrpos($templateString, ".");
$template = substr($templateString, 0, $l + 1);
}
}
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #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->bind($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse(
$template . $this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView())
);
}
I have create a pull request here that handles custom profile templates.
Progress of a sort. It took a while but it became clear I would not be able to add a template parameter to the PUGXMultiUserBundle configuration. So I decided to create my own configuration. Had to be sure to make a couple of other hack-like fixes to my own code, but this at least seems to work. (I won't accept my answer; I'd rather Patt's solution gets implemented.) But here's what I did:
config.yml addition:
vol_user:
staff: VolUserBundle:Profile:staff.form.html.twig
volunteer: VolUserBundle:Profile:volunteer.form.html.twig
admin: VolUserBundle:Profile:admin.form.html.twig
routing.yml change to fos_user_profile (added _edit to parameter name):
fos_user_profile_edit:
resource: "#FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile
Revised controller:
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$discriminator = $this->container->get('pugx_user.manager.user_discriminator');
$users = $this->container->getParameter('pugx_user_discriminator_users');
$class = $discriminator->getClass($user);
$templates = $this->container->getParameter('vol_user');
foreach ($users as $userType) {
if ($userType['entity']['class'] == $class) {
$l = strrpos($class, DIRECTORY_SEPARATOR ) + 1;
$type = strtolower(substr($class, $l));
$templateString = $templates[$type];
if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
$template = 'FOSUserBundle:Profile:edit.html.';
} else {
$l = strrpos($templateString, ".");
$template = substr($templateString, 0, $l + 1);
}
}
}
...
}
Configuration.php
namespace Vol\UserBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {#inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('vol_user');
$rootNode->
children()
->scalarNode('staff')->defaultValue(null)->end()
->scalarNode('volunteer')->defaultValue(null)->end()
->scalarNode('admin')->defaultValue(null)->end()
->end()
->end();
return $treeBuilder;
}
}
VolUserExtension
class VolUserExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('vol_user', $config);
}
}

Resources