使用Symfony 2.8,此代码$this->container
为空。
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');
}
....
}
我的EntrarYPreregistroFormSubscriber
服务配置为:
pmktconcursos.entrarypreregistro.form.subscriber:
class: PMKT\ConcursosBundle\EventListener\EntrarYPreregistroFormSubscriber
calls:
- [ setContainer,[ "@service_container" ] ]
我在$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)"}
我错过了什么吗?
答案 0 :(得分:1)
您正在制作表单事件监听器,因此在表单类型中您有类似$builder->addEventSubscriber(new EntrarYPreregistroFormSubscriber());
的内容,因此您可以看到表单事件监听器的工作方式与常规事件监听器略有不同。由于您是创建对象的人,因此您应该调用setContainer($serviceContainer)
。要做到这一点,你应该在你的Form Type中有服务容器。为此,您应该在控制器中创建表单时将其作为选项传递
// 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,
));
}