2016-03-13 60 views
0

在ZF2,假設我在表單中有一個SelectZF2獲取值從數據庫到窗體類

$this->add([ 
     'type' => 'Zend\Form\Element\Select', 
     'name' => 'someName', 
     'attributes' => [ 
      'id' => 'some-id', 
     ], 
     'options' => [ 
      'label' => 'Some Label', 
      'value_options' => [ 
       '1' => 'type 1', 
       '2' => 'type 2', 
       '3' => 'type 3', 
      ], 
     ], 
    ]); 

我怎樣才能把值「類型1」,「2型」,「3型」等從數據庫查詢到value_options

回答

2

通過向表單元素管理器註冊自定義選擇元素,可以使用工廠來加載所需的表單選項。

namespace MyModule\Form\Element; 

class TypeSelectFactory 
{ 
    public function __invoke(FormElementManager $formElementManager) 
    { 
     $select = new \Zend\Form\Element\Select('type'); 
     $select->setAttributes(] 
      'id' => 'some-id', 
     ]); 
     $select->setOptions([ 
      'label' => 'Some Label', 
     ]); 

     $serviceManager = formElementManager->getServiceLocator(); 
     $typeService = $serviceManager->get('Some\\Service\\That\\Executes\\Queries'); 

     // getTypesAsArray returns the expected value options array 
     $valueOptions = $typeService->getTypesAsArray(); 

     $select->setValueOptions($valueOptions); 

     return $select; 
    } 
} 

而所需的配置爲module.config.php

'form_elements' => [ 
    'factories' => [ 
     'MyModule\\Form\\Element\\TypeSelect' 
      => 'MyModule\\Form\\Element\\TypeSelectFactory', 
    ] 
], 

添加元素的形式時,可以再使用MyModule\\Form\\Element\\TypeSelect作爲type值。

另外請務必閱讀documentation regarding custom form elements;這裏描述瞭如何正確使用表單元素管理器,這對於上面的工作是必不可少的。

+0

男人,你搖滾!在SO上閱讀你的其他答案。你很棒! –

+0

只需要注意一點:在表單中,我需要將此元素添加到'public function init()'中,作爲zend文檔的鏈接。 –

+0

你可以告訴,如何將一個額外的參數('$ id')傳遞給'TypeSelectFactory'的'$ typeService = $ serviceManager-> get('Some \\ Service \\ That \\ Executes \\ Queries') ;'? –