Adding new FOSUserBundle users to a default group on creation

点点圈 提交于 2019-12-03 03:16:21
MoskitoHero

OK, I started working on implementing artworkad's idea.

First thing I did was updating FOSUserBundle to 2.0.*@dev in composer.json, because I was using v1.3.1, which doesn't implement the FOSUserEvents class. This is required to subscribe to my registration event.

// composer.json
"friendsofsymfony/user-bundle": "2.0.*@dev",

Then I added a new service :

<!-- Moskito/Bundle/UserBundle/Resources/config/services.xml -->
<service id="moskito_bundle_user.user_creation" class="Moskito\Bundle\UserBundle\EventListener\UserCreationListener">
    <tag name="kernel.event_subscriber" alias="moskito_user_creation_listener" />
        <argument type="service" id="doctrine.orm.entity_manager"/>
</service>

In the XML, I told the service I needed access to Doctrine through an argument doctrine.orm.entity_manager. Then, I created the Listener :

// Moskito/Bundle/UserBundle/EventListener/UserCreationListener.php

<?php
namespace Moskito\Bundle\UserBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityManager;

/**
 * Listener responsible to change the redirection at the end of the password resetting
 */
class UserCreationListener 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();
        $group_name = 'my_default_group_name';
        $entity = $this->em->getRepository('MoskitoUserBundle:Group')->findOneByName($group_name); // You could do that by Id, too
        $this->user->addGroup($entity);
        $this->em->flush();

    }
}

And basically, that's it !

After each registration success, onRegistrationSuccess() is called, so I get the user through the FormEvent $event and add it to my default group, which I get through Doctrine.

You did not say how your users are created. When some admin creates the users or you have a custom registration action, you can set the group in the controller's action.

$user->addGroup($em->getRepository('...')->find($group_id));

However if you use fosuserbundles build in registration you have to hook into the controllers: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/controller_events.md and use a event listener.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!