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 » .
[pastacode lang= »php » user= »nicolas-san » repos= »https://github.com/nicolas-san/fosUserDefaultRole/ » path_id= »https://github.com/nicolas-san/fosUserDefaultRole/blob/master/MyBundle/EventListener/RegistrationSuccessListener.php » revision= » » highlight= » » lines= » » provider= »github »/]
When you have your class, you have to register it as a service in service.yaml (or xml).
[pastacode lang= »php » user= »nicolas-san » repos= »https://github.com/nicolas-san/fosUserDefaultRole/ » path_id= »https://github.com/nicolas-san/fosUserDefaultRole/blob/master/MyBundle/Ressources/Config/services.yml » revision= » » highlight= » » lines= » » provider= »github »/]
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 :
[pastacode lang= »php » message= »Fos user bundle default static role » highlight= » » provider= »manual »]
interface UserInterface extends AdvancedUserInterface, \Serializable
{
const ROLE_DEFAULT = 'ROLE_USER';
const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';
[/pastacode]
In :
yourProjectRoot/vendor/friendsofsymfony/user-bundle/Model/User.php
[pastacode lang= »php » message= » » highlight= » » provider= »manual »]
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;
}
[/pastacode]
(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 :