I try to set the current authenticated user within a SonataAdminBundle Form:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('content')
->add('slug')
//->add('user')
;
}
Since I don't want the user to select/choose it's own user, I guess I'd like to set the username during the procedure the form was sent by the user (without any user object). (Note: I'd like to use this in a couple of forms, so I'll need a general solution.)
What I've done now was setting up an EventListener after I've read this: http://symfony.com/doc/current/cookbook/service_container/event_listener.html
class PostListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function prePersist(LifeCycleEventArgs $args)
{
$entity = $args->getEntity();
//Get user
$securityContext = $this->container->get('security.context');
$user = $securityContext->getToken()->getUser();
//Set authenticated user as autor
$entity->setUser($user);
}
}
Including service:
post.listener:
class: Backender\BlogBundle\Listener\PostListener
calls:
- [ setContainer, [ @service_container ] ]
tags:
- { name: doctrine.event_listener, event: prePersist }
Not sure now, if this is the right approach, because I wan't to specify the form where I want to set the user. (This one will want to set user on every form right?)
With some more research it seems like I've to use an Event Subscriber like this: http://symfony.com/doc/2.0/cookbook/form/dynamic_form_generation.html In this example they use FormEvents::PRE_SET_DATA, I guess in my case I have to use POST_SET_DATA.
Here I've some problems!:
1: I'm quiet new to SonataAdminBundle and there we use protected function configureFormFields(FormMapper $formMapper)... where ->addEventSubscriber()
isn't available?
2: Is this the right way?, I really didn't find any examples like what I need here for sonata-admin.
I'm thankful for every help! Best regards...