[Form] EventSubscriber as service

New topics about Symfony 2 should go here

Moderators: dcobalt, tiagojsag

[Form] EventSubscriber as service

Postby NOP-erator » Tue Apr 10, 2012 12:08 am

I'm trying to use dynamic form generation as described here
http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

In my EventSubscriber I'm adding Entity-type fields with a custom query builder. No matter if I use the custom query builder or a function in the repository class of the entity, I cannot access other services. I need the security.context to add information about the currently logged in user to my query. What is the best way to achieve this?
It seems wrong to pass a service to the form contructor that passes the service to the event subscriber constructor which uses the service to return a query builder, doesn't it?
NOP-erator
Junior Member
 
Posts: 17
Joined: Thu May 19, 2011 6:33 pm

Re: [Form] EventSubscriber as service

Postby blogsh » Tue Apr 10, 2012 5:40 pm

I'd define the new form type as a service and also the subscriber. Then I'd pass the security context to the subscriber and the subscriber to the form type.

Code: Select all
class AddNameFieldSubscriber implements EventSubscriberInterface
{
    private $securityContext;
    private $factory;

    public function __construct(FormFactoryInterface $factory, SecurityContextInterface $securityContext)
    {
         $this->... = ...;
    }

    ...
}


Code: Select all
class ProductType extends AbstractType
{
    private $subscriber;

    public function __construct(AddNameFieldSubscriber $subscriber)
    {
         $this->subscriber = $subscriber;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->addEventSubscriber($this->subscriber);
        ....
    }

   ....
}


Code: Select all
services:
    my_subscriber:
        class: MyBundle\AddNameFieldSubscriber
        arguments: [@form.factory, @security.context]

    my_type:
         class: MyBundle\ProductType
         arguments: [@my_subscriber]
         tags:
             - { name: form.type, alias: my_type }
         


You can read about defining form types as services here: http://symfony.com/doc/current/cookbook ... _type.html
blogsh
Faithful Member
 
Posts: 501
Joined: Thu Mar 03, 2011 9:35 pm
Location: Germany

Re: [Form] EventSubscriber as service

Postby NOP-erator » Tue Apr 10, 2012 11:19 pm

Thank you very much for that answer. I will try that and report.
NOP-erator
Junior Member
 
Posts: 17
Joined: Thu May 19, 2011 6:33 pm


Return to General Symfony 2 discussion

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 10 guests