Question

In FOSUserBundle, i need to override FOSUserBundle RegistrationController because i need to add this:

if($user->getType()=="Student") {
    $user->addRole("ROLE_Student");
}
else {
    $user->addRole("ROLE_TEACHER");
}

It works when i add it in vendor--->...---->registrationcontroller. That's why i need to override registration controller, but how?

Was it helpful?

Solution

Do not override the controller. You should use the event system! Create an event handler which subscribe to FOSUserEvents::REGISTRATION_COMPLETE and then perform the role addition.

Documentation:

The listener:

class RegistrationListener implements EventSubscriberInterface
{
    public function __construct(/* ... */)
    {
        // ...
    }

    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_COMPLETE => 'addRole',
        );
    }

    public function addRole(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        // Add the role here
        // ...
    }
}

The service definition:

<service id="my_app.event.registration" class="MyApp\Event\RegistrationListener">
    <tag name="kernel.event_subscriber" />
    <!-- ... -->
</service>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top