我正在尝试为每个成功注册的用户提供ROLE_USER
角色。我是FOSUserBundle的新手,所以从我在文档中看到的内容来看,它是通过将逻辑插入控制器来完成的。
这是我的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();
}
}
?>
并注册为服务如下:
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 }
但是当我注册一个新用户时,什么也没发生。没有任何角色被设置。
任何帮助都将不胜感激。
答案 0 :(得分:7)
您是否尝试过调用addRole()
FOSUser实体函数,如果您注意到实体中的setRole函数,它会将数组循环到角色并将其传递给addRole
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
return $this;
}
尝试使用addRole()
作为单个角色
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->addRole('ROLE_USER');
$this->um->updateUser($user);
$this->dm->flush();
}