Rumen Panchev
Rumen Panchev

Reputation: 498

Set ROLE_USER after registration in Symfony with FOSUserBundle

I'm trying to set the default role (ROLE_USER) for every user after his registration. I've tried something like this in the FOS RegistrationController:

$user->setRoles(array('ROLE_USER'));

But after registration in the fos_users table, the role column is empty. Any ideas why?

Upvotes: 1

Views: 1003

Answers (1)

famas23
famas23

Reputation: 2280

To make possible to persist default role in database one need to override User::setRoles() method into your User entity:

public function addRole($role)
  { $role = strtoupper($role);

    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }

    return $this;
 }

Ther's 2 other idea to do that tric :
1)The easyest way is to override the entity constructor:

public function __construct()
{
    parent::__construct();
    $this->roles = array('ROLE_USER'); }

2)The second way is to register an Event Listener on the REGISTRATION_SUCCESS event and use the $event->getForm()->getData() to access the user and modify it, take a look:

// src/Acme/DemoBundle/EventListener/RegistrationListener.php   
namespace Acme\DemoBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
enter code here
class RegistrationListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
        );
    }

    public function onRegistrationSuccess(FormEvent $event)
    {
        $rolesArr = array('ROLE_USER');

        /** @var $user \FOS\UserBundle\Model\UserInterface */
        $user = $event->getForm()->getData();
        $user->setRoles($rolesArr);
    }
}

Also, the service needs to be registered as follows:

// src/Acme/DemoBundle/Resources/config/services.yml
services:
    demo_user.registration_listener:
        class: Acme\DemoBundle\EventListener\RegistrationListener
        arguments: []
        tags:
            - { name: kernel.event_subscriber }

Upvotes: 1

Related Questions