vmarquez
vmarquez

Reputation: 1377

Container not being set when trying to use ContainerAwareInterface

With Symfony 2.8, this code $this->container is null.

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class EntrarYPreregistroFormSubscriber implements EventSubscriberInterface, ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function preSetData(FormEvent $event)
    {
        $l = $this->container->get('logger');
        $l->notice('GOT LOGGER');
    }

    ....
}

And my EntrarYPreregistroFormSubscriber service is configured as:

pmktconcursos.entrarypreregistro.form.subscriber:
    class: PMKT\ConcursosBundle\EventListener\EntrarYPreregistroFormSubscriber
    calls:
        - [ setContainer,[ "@service_container" ] ]

I am getting exception at $l = $this->container->get('logger');

request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\FatalErrorException: "Error: Call to a member function get() on a non-object" at /Users/vmarquez/Proyectos/GrupoPMKT/Promoticket/current/dev/chedraui1607/chedraui1607/src/PMKT/ConcursosBundle/Form/EventListener/EntrarYPreregistroFormSubscriber.php line 30 {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalErrorException(code: 0): Error: Call to a member function get() on a non-object at /Users/vmarquez/Proyectos/GrupoPMKT/Promoticket/current/dev/chedraui1607/chedraui1607/src/PMKT/ConcursosBundle/Form/EventListener/EntrarYPreregistroFormSubscriber.php:30)"}

Am I missing something?

Upvotes: 0

Views: 626

Answers (1)

Denis Alimov
Denis Alimov

Reputation: 2891

You are making Form Event Listener, so inside your Form Type you have something like $builder->addEventSubscriber(new EntrarYPreregistroFormSubscriber()); so you can see that Form Event Listeners works with a little difference that a regular Event Listener. As it is you who creates the object, so it is you should call setContainer($serviceContainer). To do that you should have service container inside you Form Type. To do that, you should pass it as option while creating your form in controller

// in controller
$object = ...;
$form = $this->createForm(new YourFormType(), $object, array('service_container' => $this->get('service_container')));

// in YourFormType
$listener = new EntrarYPreregistroFormSubscriber();
$listener->setContainer($options['service_container']);
$builder->addEventSubscriber($listener);
...
// in setDefaultOptions method
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        ...
        'service_container' => null,
    ));
}

Upvotes: 1

Related Questions