您可以采取几种不同的方法。最终,您的 Form 有一个依赖项,需要注入。我写了一篇关于选择列表的表单依赖项的三个最常见用例的深入博客文章。
我的 BlogPost 涵盖以下场景:
- Zend\Form\Element\Select 通过 DbAdapter
- Zend\Form\Element\Select 通过 TableGateway
- DoctrineModule\Form\Element\DoctrineObject 通过 Doctrine2
在这里,我将仅演示 DbAdapter 方法,而无需过多解释。请参阅我的博文以获得深入的解释。
public function formDbAdapterAction()
{
$vm = new ViewModel();
$vm->setTemplate('form-dependencies/form/form-db-adapter.phtml');
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new DbAdapterForm($dbAdapter);
return $vm->setVariables(array(
'form' => $form
));
}
然后是相应的表单类:
class DbAdapterForm extends Form
{
protected $dbAdapter;
public function __construct(AdapterInterface $dbAdapter)
{
$this->setDbAdapter($dbAdapter);
parent::__construct('db-adapter-form');
$this->add(array(
'name' => 'db-select',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Dynamic DbAdapter Select',
'value_options' => $this->getOptionsForSelect(),
'empty_option' => '--- please choose ---'
)
));
}
// more later...
// Also: create SETTER and GETTER for $dbAdapter!
}
最后但并非最不重要的 DataProvider 函数:
public function getOptionsForSelect()
{
$dbAdapter = $this->getDbAdapter();
$sql = 'SELECT t0.id, t0.title FROM selectoptions t0 ORDER BY t0.title ASC';
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['id']] = $res['title'];
}
return $selectData;
}