0

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...

Greg Motyl
  • 2,478
  • 17
  • 31

3 Answers3

1

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

Airam
  • 2,048
  • 2
  • 18
  • 36
  • I tried your solution, but it doesn't work. SonataUserBundle uses xml notation, so i have defined in user.orm.xml: `` but it's never executed (cache cleared...) method is defined User calss... – Greg Motyl May 17 '14 at 19:12
1

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 :)

0

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

rolebi
  • 1,181
  • 9
  • 13