问题描述
我想在用户注册后将默认角色分配给.我已经实施了Sonatauserbundle扩展的FosuserBundle.不幸的是,奏鸣曲需要fosuserbundle〜1.3,事件听众仅是因为fosuserbundle 2.0.
除了EventListener或FosuserBundle Controller覆盖外,还有另一种方法可以解决此问题吗?也许我错过了YAML的某种选择?这似乎是标准的问题,但我仍然是Symfony2 ...
推荐答案
您可以覆盖用户类的getroles()方法:
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); }
编辑:添加每个用户类型的角色
其他推荐答案
您可以使用以下的预科师方法来执行此操作:
/** * @ORM\Entity * @ORM\Table(name="user_users") * @ORM\HasLifecycleCallbacks() */ class User extends BaseUser { ... /** * @ORM\PrePersist() */ public function setDefaultRole(){ $this->addRole( 'ROLE_NAME' ); } }
当您创建用户元素时,在实体存储在数据库中之前,就会启动学者.您可以在 http://docs.doctrine-project中读取此信息. .org/en/2.0.x/reference/events.html
其他推荐答案
来晚了,但是您可以简单地覆盖用户类的构造函数.我想你扩展了 Sonata\UserBundle\Entity\BaseUser因此您的代码应为:
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'); } }
您必须在分配角色之前使用parent::_construct否则奏鸣曲注册控制器将覆盖您的角色.希望它有帮助:)
问题描述
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...
推荐答案
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
其他推荐答案
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
其他推荐答案
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 :)