How to assign roles upon successful registration?

I am using fos user bundle and pugx multi user bundle. I have read all the documentation and I am familiar with Symfony. The pugx multi-user package has a sample at every point, but one: successful registration.

  • Samples of overriding controllers for generating forms => ok
  • Samples of overriding templates for creating forms => ok
  • Samples of a successful successful registration sample => nothing.

Here is my code:

class RegistrationController extends BaseController { public function registerAction(Request $request) { $response = parent::registerAction($request); return $response; } public function registerTeacherAction() { return $this->container ->get('pugx_multi_user.registration_manager') ->register('MyBundle\Entity\PersonTeacher'); } public function registerStudentAction() { return $this->container ->get('pugx_multi_user.registration_manager') ->register('MyBundle\Entity\PersonStudent'); } } 

The problem is ->get('pugx_multi_user.registration_manager') , which the manager returns. In fos user overring controllers help they get either form or form.handler . I have hard times to β€œlink” them with the manager pugx_multi_user.

What code should be placed in registerTeacherAction() for setting roles for a teacher, and in registerStudentAction() - setting roles for successful registration of a student?

+7
symfony controller fosuserbundle pugxmultiuserbundle
source share
1 answer

Solution 1 (Doctrine Listener / Subscriber)


You can easily add the prePersist listener / subscriber doctrine, which adds roles / groups to your objects depending on their type before saving.

Listener

 namespace Acme\YourBundle\EventListener; use Doctrine\ORM\Event\LifecycleEventArgs; use Acme\YourBundle\Entity\Student; class RoleListener { public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); $entityManager = $args->getEntityManager(); // check for students, teachers, whatever ... if ($entity instanceof Student) { $entity->addRole('ROLE_WHATEVER'); // or $entity->addGroup('students'); // ... } // ... } } 

Service Configuration

 # app/config/config.yml or load inside a bundle extension services: your.role_listener: class: Acme\YourBundle\EventListener\RoleListener tags: - { name: doctrine.event_listener, event: prePersist } 

Solution 2 (LifeCycle Doctrine Callbacks):


Using lifecycle callbacks , you can integrate role / group operations directly into your entity.

 /** * @ORM\Entity() * @ORM\HasLifecycleCallbacks() */ class Student { /** * @ORM\PrePersist */ public function setCreatedAtValue() { $this->addRole('ROLE_WHATEVER'); $this->addGroup('students'); } 

Solution 3 (Event Manager):


Register an event listener / subscriber for the fos_user.registration.success event.

How to create an event listener / EventDispatcher .

+9
source share

All Articles