我使用FOSuser与SonataUserBundle,我试图添加一个用户到客户组每次有人注册,但它不起作用。我没有得到任何错误,但我也没有添加组…我尝试了两种方法:
1)我重写了registrationController,并使confirmAction像这样保存新组:
/**
* Tell the user his account is now confirmed
*/
public function confirmedAction()
{
$repository = $em->getRepository('ApplicationSonataUserBundle:Group');
$group = $repository->findOneByName('Clients');
$em = $this->getDoctrine()->getEntityManager();
$user = $this->getUser();
$user->addGroup($group);
$this->em->flush();
$userManager = $this->get('fos_user.user_manager');
$userManager->updateUser($user);
}
}
2)创建一个eventListener并在那里进行分组:
<?php
namespace ApplicationSonataUserBundleEventListener;
use FOSUserBundleFOSUserEvents;
use FOSUserBundleEventFormEvent;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use DoctrineORMEntityManager;
/**
* Listener responsible to change the redirection at the end of the password resetting
*/
class GrouppingListener implements EventSubscriberInterface
{
protected $em;
protected $user;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
);
}
public function onRegistrationSuccess(FormEvent $event)
{
$this->user = $event->getForm()->getData();
$entity = $this->em->getRepository('ApplicationSonataUserBundle:Group')->findOneByName('Clients'); // You could do that by Id, too
$this->user->addGroup($entity);
$this->em->flush();
}
}
我的组实体被这样扩展:
<?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ApplicationSonataUserBundleEntity;
use SonataUserBundleEntityBaseGroup as BaseGroup;
/**
* This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
*
* @author <yourname> <youremail>
*/
class Group extends BaseGroup
{
/**
* @var integer $id
*/
protected $id;
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
}
这些选项都不起作用…我这样做是基于其他stackoverflow的答案…为什么行不通呢?
您在两个案例中都缺少persist
。为了使实体变得可管理,它首先需要被持久化。
$user->addGroup($group);
$this->em->flush();
在你的控制器动作中将此改为:
$user->addGroup($group);
$this->em->persist($user);
$this->em->flush();
教条手册中的一段:
实体可以通过传递给EntityManager#persist($entity)方法来持久化。通过在某些实体上应用持久化操作,该实体变成MANAGED,这意味着它的持久化从现在开始由EntityManager管理。因此,当调用EntityManager#flush()时,这样一个实体的持久状态随后将与数据库正确同步。