-->

How can I assign default role to user in Symfony2

2019-09-01 09:47发布

问题:

I want to assign default role to user after he is registered. I have implemented FOSUserBundle extended by SonataUserBundle. Unfortunetly SonataUserBundle requires FOSUserBundle ~1.3 and event listeners are only since FOSUserBundle 2.0.

Is there another way to solve this problem except eventListener or FOSUserBundle controller override ? Maybe some kind of option in yaml I have missed ? It seems quite standard problem but I am still new in symfony2...

回答1:

You can overwrite the getRoles() method of you user class :

public function getRoles()
{
    $roles = parent::getRoles();

    if ($this->enabled) {
        switch ($this->type) {
            case self::TYPE_1:
                 $roles[] = 'ROLE_TYPE_1';
                 break;

            case self::TYPE_2:
                 $roles[] = 'ROLE_TYPE_2';
                 break;
        }
    }

    return array_unique($roles);
}

edit: add role per user type



回答2:

You could do this using the prePersist method as below:

/**
 * @ORM\Entity
 * @ORM\Table(name="user_users")
 * @ORM\HasLifecycleCallbacks()
 */
class User extends BaseUser
{   
    ...

    /**
     * @ORM\PrePersist()
     */
    public function setDefaultRole(){
        $this->addRole( 'ROLE_NAME' );
    }
}

The prePersist is launched just before the entity is stored in the database, when you create an User element. You can read about this in http://docs.doctrine-project.org/en/2.0.x/reference/events.html



回答3:

Coming late but you can simply override the constructor of your User class. I assume you extended Sonata\UserBundle\Entity\BaseUser so your code should be :

namespace Acme\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;

class User extends BaseUser
 {
    public function __construct()
    {
        parent::__construct();
        $this->roles = array('ROLE_ADMIN');
    }
}

You have to use parent::_construct before assigning the roles otherwise Sonata registration controller will override your roles. Hope it helps :)