phpsymfonyfosuserbundlesymfony-2.4

addRole using userManager doesn't work


I'm trying to add roles to user when they are registering in this way:

$em = $this->getDoctrine()->getManager();

$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->createUser();

$user_data = $request->get('user_profile');

$user->setUsername($user_data['rif']);
$user->setEmail($user_data['user']['email']);
$user->setPlainPassword($user_data['user']['password']);
$user->addRole("ROLE_USER");
$userManager->updateUser($user);

All works fine excepts that roles at DB is stored as a:0:{} and I can't find the error, can any give me some advice on this?


Solution

  • I think your problem is that you are trying to add the ROLE_USER role.

    Have you tried adding another role?

    The problem lies in..

    FOS\UserBundle\Model\UserInterface

    const ROLE_DEFAULT = 'ROLE_USER';
    const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';
    

    FOS\UserBundle\Model\User

    public function addRole($role)
    {
        $role = strtoupper($role);
        if ($role === static::ROLE_DEFAULT) {
        // If supplied $role === ROLE_USER just return User object
            return $this;
        }
    
        if (!in_array($role, $this->roles, true)) {
            $this->roles[] = $role;
        }
    
        return $this;
    }
    
    ....
    
    /**
     * Returns the user roles
     *
     * @return array The roles
     */
    public function getRoles()
    {
        $roles = $this->roles;
    
        foreach ($this->getGroups() as $group) {
            $roles = array_merge($roles, $group->getRoles());
        }
    
        // we need to make sure to have at least one role
        $roles[] = static::ROLE_DEFAULT;
    
        return array_unique($roles);
    }
    

    If you add the default role (ROLE_USER) it doesn't actually get added to the list of roles due to it being added, as default, to the roles in the getRoles method.