Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Symfony2 form event listener access the service container and how?

Tags:

symfony

As per title, can a Symfony2 form event listener access the service container?

This is an example event listener (for post bind event):

class CustomerTypeSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return array(FormEvents::POST_BIND => 'onPostBind');
    }

    public function onPostBind(DataEvent $event)
    {
        // Get the entity (Customer type)
        $data = $event->getData();

        // Get current user
        $user = null;    

        // Remove country if address is not provided
        if(!$data->getAddress()) :
            $data->setCountry(null);
        endif;
    }

}
like image 610
gremo Avatar asked May 18 '12 14:05

gremo


1 Answers

What do you need to access to service container for?

You can inject any services into your listener using dependency injection (as you define your listener as a service, right?).

You should be able to do something like:

    service.listener:
    class: Path\To\Your\Class
    calls:
      - [ setSomeService, [@someService] ]
    tags:
      - { [Whatever your tags are] }

And in your listener:

private $someService;

public function setSomeService($service) {
    $this->someService = $someService;
}

Where someService is the ID of whatever service you want to inject.

If you want, you can inject the service container with @service_container, but it's probably better to inject only what you need 'cause I think having everything container aware makes you a bit lazy.

like image 169
Chris McKinnel Avatar answered Sep 30 '22 03:09

Chris McKinnel