2015-06-19 75 views
3

如何使用外部數據數組填充選項選項?symfony表單選擇字段:從外部數據源設置選項默認數據

$builder->add('gender', 'choice', array(
    'choices' => [array from webservice or other class] 
)); 

文檔只顯示簡單的靜態陣列 http://symfony.com/fr/doc/2.7/reference/forms/types/choice.html#choices

我嘗試了:

控制器:

$event = new Event(); 
$form = $this->createForm(new EventType($this->get('api')), $event); 

形式:

class EventType extends AbstractType 
{ 
    protected $myservice; 

    public function __construct($myservice) 
    { 
     $this->myservice = $myservice; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('titre') 
      ->add('id_rubrique', 'choice', array(
       'choices' => $this->myservice->getRubriques 
     ; 
    } 

    .... 
} 

這是正確的解決方案嗎?

+0

您是否使用EventListeners? –

+3

要麼這樣做,要麼將您的表單變成服務,並通過服務注入依賴關係並使用構造函數。 http://symfony.com/fr/doc/current/reference/dic_tags.html#form-type-extension –

+1

或通過控制器傳遞它。 – DevDonkey

回答

0

例如

->add('education', 'choice', array('label' => 'Education *','choices' => $this->getEducation(), 'required' => true, 'empty_value' => 'select', 'empty_data' => null)) 

$這 - > getEducation()是陣列

//陣列( 'option1Value'=> 'option1Name' ...

2

定義您的形式作爲服務:

services: 
    my.form: 
     class: EventType 
     arguments: 
      - @api 

然後在控制器中:

$event = new Event(); 
$form = $this->createForm('my.form', $event);