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

symfony

Solution

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.

Problem

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; } } ```

Original source