2017-03-01 18 views
1

我試圖獲取值形成我在parameters.yml的Symfony:如何獲得在AbstractType

# parameters.yml 
parameters: 
    ... 
    objects: {object1: 1, object2: 2, object3: 3} 

聲明數組但從parameters.yml值一次我嘗試從「物」該文件使用此代碼

$builder->add('list', ChoiceType::class, array ('objects' => $this->container->getParameter('categories'))); 

我收到以下錯誤

Notice: Undefined property: Project\Bundle\Form\EntityType::$container 

有什麼建議?

回答

1

如果您聲明Project\Bundle\Form\EntityTypea service,您將能夠將數據以及其所需的任何其他服務注入到該數據中。當您將其包含在內時,您仍然可以將該類型稱爲EntityType::class,因爲Symfony會認識到該類被定義爲服務。

它會使測試多一點「有趣」雖然

1

你必須注入你的類裏面的ContainerInterface。

services.yml

form.my_entity_type: 
    class: AppBundle\Form\MyEntityType 
    arguments: 
    - '@service_container' 
    tags: 
    - { name: form.type } 

MyEntityType

/** @var ContainerInterface */ 
protected $container; 

/** 
* @param ContainerInterface $container 
*/ 
public function __construct(ContainerInterface $container) 
{ 
    $this->container = $container; 
} 

** 
* @param FormBuilderInterface $builder 
* @param array    $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $params = $this->container->getParameter('my-params'); 
    .... 
+0

我想補充的是,你必須包含(使用):使用的Symfony \分量\ DependencyInjection \ ContainerInterface; – MilanG

相關問題