如何使用外部數據數組填充選項選項?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
;
}
....
}
這是正確的解決方案嗎?
您是否使用EventListeners? –
要麼這樣做,要麼將您的表單變成服務,並通過服務注入依賴關係並使用構造函數。 http://symfony.com/fr/doc/current/reference/dic_tags.html#form-type-extension –
或通過控制器傳遞它。 – DevDonkey