Artisan Développeur

Qualité, amélioration continue, agilité.

Add default ROLE to user when registering, with FOS User bundle

Add default when registering a new user with FOS user bundle.

I want to add a default ROLE to all my users when they use registration on my web app, but I had some difficulties.

This is my working files : Listener default ROLE user fos user bundle

You have to add a listener to the REGISTRATION_SUCCESS event dispatch by FOS user bundle. You need to create a class, and make it implements « EventSubscriberInterface » .

When you have your class, you have to register it as a service in service.yaml (or xml).

But, before I succeed, I try to add ROLE_USER by default, and no matter what I code, test, write, try, implements, spell, cast… No way to have this default ROLE to my user, database field was empty.

After some search, I found why in FOS User Bundle code :

yourProjectRoot/vendor/friendsofsymfony/user-bundle/Model/UserInterface.php :

interface UserInterface extends AdvancedUserInterface, \Serializable
{
    const ROLE_DEFAULT = 'ROLE_USER';
    const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';
Fos user bundle default static role

In :

yourProjectRoot/vendor/friendsofsymfony/user-bundle/Model/User.php

 

public function addRole($role)
    {
        $role = strtoupper($role);
        if ($role === static::ROLE_DEFAULT) {
            return $this;
        }

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

        return $this;
    }

(line of code from FOS userBundle repo on github)

If you try to add ROLE_USER, as ROLE_USER is ROLE_DEFAULT, you role is not added to $this->roles[] and not persisted, it is why even with a good working listener, ROLE_USER is never write into user account details in database.

Resources :

 

Leave a reply

Your email address will not be published.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.