I'm building my first serious Symfony2 project. I'm extending the FOSUserBundle for my user/group management, and I'd like new users to be automatically added to a default group.
I guess you just have to extend the User entity constructor like this :
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->groups = new \Doctrine\Common\Collections\ArrayCollection();
// Get $defaultGroup entity somehow ???
...
// Add that group entity to my new user :
$this->addGroup($defaultGroup);
}
But my question is how do I get my $defaultGroup entity in the first place?
I tried using the entity manager from within the entity, but then I realized it was stupid, and Symfony was throwing an error. I googled for this, but found no real solution except maybe setting up a service for that... although this seems quite unclear for me.
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.
Related
I use FOSUserEvents after submit form but the subscriber call twice.
In this way my captcha is valid the first time and not valid the second
this is my code
<?php
namespace AppBundle\EventListener;
class CaptchaSubscriber implements EventSubscriberInterface
{
private $router;
private $requestStack;
private $templating;
/**
* RedirectAfterRegistrationSubscriber constructor.
*/
public function __construct(RouterInterface $router, RequestStack $requestStack, \Twig_Environment $templating)
{
$this->router = $router;
$this->requestStack = $requestStack;
$this->templating = $templating;
}
public function onRegistrationInit(GetResponseUserEvent $event)
{
if ($this->requestStack->getMasterRequest()->isMethod('post')) {
...handle captcha...
}
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit'
];
}
}
my symfony is 3.3
UPDATE
I added
$event->stopPropagation();
with this snippet the code works, but i don't know if it is the best practice
In my case of symfony 4.2 it depends on the service definition if it occures or not.
My Subscriber gets registered twice if I define the service like this:
# oauth process listener
app.subscriber.oauth:
class: App\EventListenerSubscriber\OauthSubscriber
arguments: ['#session', '#router', '#security.token_storage', '#event_dispatcher', '#app.entity_manager.user', '#app.fos_user.mailer.twig_swift']
tags:
- { name: kernel.event_subscriber }
But it gets registerd only once if I chenge the definition to this:
# oauth process listener
App\EventListenerSubscriber\OauthSubscriber:
arguments: ['#session', '#router', '#security.token_storage', '#event_dispatcher', '#app.entity_manager.user', '#app.fos_user.mailer.twig_swift']
tags:
- { name: kernel.event_subscriber }
I posted a bug report on github and got immediately an answer, that in newer symfony versions event listeners and subscribers get registered automatically with their class name as key (under some default conditions - must read on that topic).
So there is no need to register them explicitely as services.
I we do this anyway, but using an arbitrary key instead of class name, there will be two services.
If you are using Autowiring/Autoconfiguration, it's possible that you've added the subscriber service you show above, twice. I've done it myself when I first added the autowiring, but I also had the subscriber listed explicitly in the configuration as well.
You can see what events are registered (and check if any are registered more than once to perform the same service/action) with:
bin/console debug:event-dispatcher
I'm using FOSUserBundle on Symfony2.
I extended the User class to have additional fields, therefore I also added the new fields in the twigs.
One of those fields is a licence code. When a user fills in that field I want to perform a connection to DB to look if that license is valid. If not returns an error, if yes creates an event in the "licenceEvents" table assigning the current user to that license.
[EDIT] As suggested I created a custom validator (which works like a charm), and I'm now struggling with the persisting something on DB once the user is created or updated.
I created an event listener as follows:
<?php
// src/AppBundle/EventListener/UpdateOrCreateProfileSuccessListener.php
namespace AppBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\ORM\EntityManager; //added
class UpdateOrCreateProfileSuccessListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router, EntityManager $em)
{
$this->router = $router;
$this->em = $em; //added
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_COMPLETED => array('onUserCreatedorUpdated',-10),
FOSUserEvents::PROFILE_EDIT_COMPLETED => array('onUserCreatedorUpdated',-10),
);
}
public function onUserCreatedorUpdated(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$code = $user->getLicense();
$em = $this->em;
$lastEvent = $em->getRepository('AppBundle:LicenseEvent')->getLastEvent($code);
$licenseEvent = new LicenseEvent();
// here I set all the fields accordingly, persist and flush
$url = $this->router->generate('fos_user_profile_show');
$event->setResponse(new RedirectResponse($url));
}
}
My service is like follows:
my_user.UpdateOrCreateProfileSuccess_Listener:
class: AppBundle\EventListener\UpdateOrCreateProfileSuccessListener
arguments: [#router, #doctrine.orm.entity_manager]
tags:
- { name: kernel.event_subscriber }
The listener is properly triggered, manages to create the connection to DB as expected, but gives me the following error
Catchable Fatal Error: Argument 1 passed to AppBundle\EventListener\UpdateOrCreateProfileSuccessListener::onUserCreatedorUpdated()
must be an instance of AppBundle\EventListener\FilterUserResponseEvent,
instance of FOS\UserBundle\Event\FilterUserResponseEvent given
I must be missing something very stupid...
Another question is: I don't want to change the redirect page, so that if the original page was the "email sent" (after a new user is created) let's go there, otherwise if it's a profile update show the profile page.
I recently implemented the FOSUserBundle in my website as the login procedure. I want it to expand the Author class. So whenever a new user is registered via the FOSUSerBundle a new entry is created in the Author class. Inside the Author class I set slug, createdAt and other useful parameters. The field I want to pass to Authot entity from FOSUserBundle is the "Name" field. Then I want to cascade the FOSUser entity and if its deleted, delete also the Author entity.
So schematically FOSUserBundle.username => Author.name
I do not know how to implement this code except that it has a #ORM/OneToOne relationship. Any ideas please?
You'll have to insert the Author manually after your user registration is completed. The FOSUserBundle provides a way to hook into events like post registration completion. You can create a listener to the FOSUserEvents::REGISTRATION_COMPLETED event and create your Author entity there.
See documentation here: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/controller_events.md
For example:
services.yml:
services:
my_user_registration_service:
class: MyBundle\EventListener\MyUserRegistrationListener
arguments: [#doctrine.orm.entity_manager]
tags:
- { name: kernel.event_subscriber }
MyUserRegistrationListener:
namespace MyBundle\EventListener;
use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use MyBundle\Entity\Author;
class EventSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_COMPLETED => 'addAuthor',
);
}
public function addAuthor(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$author = new Author();
$author->setName($user->getUsername();
$this->em->persist($author);
$this->em->flush();
}
}
I have been using Silex for my latest project and I was trying to follow along with the "How to Dynamically Modify Forms Using Form Events" in the Symfony cookbook. I got to the part that uses the entity field type and realized it is not available in Silex.
It looks like the symfony/doctrine-bridge can be added to my composer.json which contains the "EntityType". Has anyone successfully got entity type to work in Silex or run into this issue and found a workaround?
I was thinking something like this might work:
$builder
->add('myentity', new EntityType($objectManager, $queryBuilder, 'Path\To\Entity'), array(
))
;
I also found this answer which looks like it might do the trick by extending the form.factory but haven't attempted yet.
I use this Gist to add EntityType field in Silex.
But the trick is register the DoctrineOrmExtension form extension by extending form.extensions like FormServiceProvider doc says.
DoctrineOrmExtension expects an ManagerRegistry interface in its constructor, that can be implemented extending Doctrine\Common\Persistence\AbstractManagerRegistry as the follow:
<?php
namespace MyNamespace\Form\Extensions\Doctrine\Bridge;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Silex\Application;
/**
* References Doctrine connections and entity/document managers.
*
* #author Саша Стаменковић <umpirsky#gmail.com>
*/
class ManagerRegistry extends AbstractManagerRegistry
{
/**
* #var Application
*/
protected $container;
protected function getService($name)
{
return $this->container[$name];
}
protected function resetService($name)
{
unset($this->container[$name]);
}
public function getAliasNamespace($alias)
{
throw new \BadMethodCallException('Namespace aliases not supported.');
}
public function setContainer(Application $container)
{
$this->container = $container['orm.ems'];
}
}
So, to register the form extension i use:
// Doctrine Brigde for form extension
$app['form.extensions'] = $app->share($app->extend('form.extensions', function ($extensions) use ($app) {
$manager = new MyNamespace\Form\Extensions\Doctrine\Bridge\ManagerRegistry(
null, array(), array('default'), null, null, '\Doctrine\ORM\Proxy\Proxy'
);
$manager->setContainer($app);
$extensions[] = new Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension($manager);
return $extensions;
}));
I am starting with Symfony2 and I am trying to override FOS\UserBundle\Form\Handler\RegistrationFormHandler of FOSUserBundle.
My code is:
<?php
namespace Testing\CoreBundle\Form\Handler;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;
use Testing\CoreBundle\Entity\User as UserDetails;
class RegistrationFormHandler extends BaseHandler
{
protected function onSuccess(UserInterface $user, $confirmation)
{
// I need an instance of Entity Manager but I don't know where get it!
$em = $this->container->get('doctrine')->getEntityManager();
// or something like: $em = $this->getDoctrine()->getEntityManager
$userDetails = new UserDetails;
$em->persist($userDetails);
$user->setId($userDetails->getId());
parent::onSuccess($user, $confirmation);
}
}
So, the point is that I need an instance of Doctrine's Entity Manager but I don't know where/how get it in this case!
Any idea?
Thanks in advance!
You should not use EntityManager directly in most of the cases. Use a proper manager/provider service instead.
In case of FOSUserBundle service implementing UserManagerInterface is such a manager. It is accessible through fos_user.user_manager key in the service container (which is an allias to fos_user.user_manager.default). Of course registration form handler uses that service, it is accessible through userManager property.
You should not treat your domain-model (i.a. Doctrine's entities) as if it was exact representation of the database-model. This means, that you should assign objects to other objects (not their ids).
Doctrine is capable of handling nested objects within your entities (UserDetails and User objects have a direct relationship). Eventually you will have to configure cascade options for User entity.
Finally, UserDetails seems to be a mandatory dependency for each User. Therefore you should override UserManagerInterface::createUser() not the form handler - you are not dealing with user's details there anyway.
Create your own UserManagerInterface implementation:
class MyUserManager extends \FOS\UserBundle\Entity\UserManager {
/**
* {#inheritdoc}
*/
public function createUser() {
$user = parent::createUser();
$user->setUserDetails(new UserDetails());
// some optional code required for a proper
// initialization of User/UserDetails object
// that might require access to other objects
// not available inside the entity
return $user;
}
}
Register your own manager as a serive inside DIC:
<service id="my_project.user_manager" class="\MyProject\UserManager" parent="fos_user.user_manager.default" />
Configure FOSUserBundle to use your own implementation:
# /app/config/config.yml
fos_user:
...
service:
user_manager: my_project.user_manager