[英]In FOSUserBundle, How to initially set user role on REGISTRATION_COMPLETED event?
I'm trying to give each successfully registered user a ROLE_USER
role. 我试图给每个成功注册的用户一个
ROLE_USER
角色。 I'm new to FOSUserBundle, So from what I've read in the documentation, It's done by hocking logic into the controllers. 我是FOSUserBundle的新手,所以从我在文档中看到的内容来看,它是通过将逻辑插入控制器来完成的。
Here's my NewUserGroupSet
Event listener: 这是我的
NewUserGroupSet
事件监听器:
<?php
namespace Tsk\TstBundle\EventListener;
use Doctrine\ODM\MongoDB\DocumentManager;
use FOS\UserBundle\Doctrine\UserManager;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class NewUserGroupSet implements EventSubscriberInterface
{
protected $um;
protected $dm;
public function __construct(UserManager $um, DocumentManager $dm)
{
$this->um = $um;
$this->dm = $dm;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_COMPLETED => "onRegistrationSuccess",
);
}
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->setRoles(array('ROLE_USER'));
$this->um->updateUser($user);
$this->dm->flush();
}
}
?>
And is registered as a service as follows: 并注册为服务如下:
parameters:
tsk_user.group_set.class: Tsk\TstBundle\EventListener\NewUserGroupSet
services:
tsk_user.group_set:
class: %tsk_user.group_set.class%
arguments: [@fos_user.user_manager, @doctrine.odm.mongodb.document_manager]
tags:
- { name: kernel.event_subscriber }
But when I register a new user, Nothing happens. 但是当我注册一个新用户时,什么也没发生。 No roles is being set whatsoever.
没有任何角色被设置。
Any help would be appreciated. 任何帮助,将不胜感激。
Have you tried calling addRole()
FOSUser entity function,if you notice the setRole function in entity it is looping through the array to roles and passing it to addRole
您是否尝试过调用
addRole()
FOSUser实体函数,如果您注意到实体中的setRole函数,它会将数组循环到角色并将其传递给addRole
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
return $this;
}
Try with addRole()
for single role 尝试使用
addRole()
作为单个角色
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->addRole('ROLE_USER');
$this->um->updateUser($user);
$this->dm->flush();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.