OK, zacząłem pracować nad wdrożeniem pomysłu artworkad.
Pierwszą rzeczą, którą zrobiłem było uaktualnienie FOSUserBundle do 2.0.*@dev w composer.json, ponieważ używałem wersji 1.3.1, która nie implementuje klasy FOSUserEvents. Jest to wymagane, aby zapisać się do mojego zdarzenia rejestracji.
// composer.json
"friendsofsymfony/user-bundle": "2.0.*@dev",
Potem dodano nową usługę:
<!-- 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>
W XML, powiedziałem usługę potrzebowałem dostępu do doktryny poprzez argument doctrine.orm.entity_manager
. Następnie utworzyłem odbiornik:
// 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();
}
}
I w zasadzie to wszystko!
Po każdym sukcesie rejestracji wywoływana jest nazwa onRegistrationSuccess()
, więc uzyskujemy użytkownika poprzez FormEvent $event
i dodaję go do mojej domyślnej grupy, którą przechodzę przez Doctrine.
Druga część odpowiedzi wygląda na to, co chcę zrobić. Spróbuję go wdrożyć i zamieścić tutaj odpowiedź jako rozwiązanie. – Weengs