2016-06-09 28 views
0

對於Symfony 2.8,此代碼$this->container爲空。嘗試使用ContainerAwareInterface時容器未設置

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)"} 

我缺少的東西?

+1

爲什麼你不使用通常的方式來傳遞參數到服務?只需將容器定義爲參數,並將其傳遞給構造函數? –

+0

這是我使用Denis的解決方案。即使如此,我很好奇我在做什麼使用特質的問題。 – vmarquez

回答

1

您正在製作表單事件監聽器,因此在您的表單類型中,您有類似於$builder->addEventSubscriber(new EntrarYPreregistroFormSubscriber());的內容,因此您可以看到,表單事件監聽器與常規事件監聽器略有不同。因爲你是創建對象的人,所以你應該打電話給setContainer($serviceContainer)。要做到這一點,你應該在你的表單類型中有服務容器。要做到這一點,你應該通過它作爲選項,同時在控制器中創建你的表格

// 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, 
    )); 
} 
+0

恩丹尼斯,這是我正在考慮的一個解決方案(另一個解決方案是服務配置中的特定服務,以及您在評論中獲得的所需服務)。感謝您的推薦。我會用你從這個答案開始的理由給它一個深刻的思考,只是爲了看看我是否能夠提供更清晰的解決方案。 – vmarquez

+0

無論如何,如果你的第二個解決方案是從服務配置中刪除調用並將其轉換爲參數,那麼你需要在表單類型中使用新的EntrarYPreregistroFormSubscriber($ serviceContainer) –

相關問題