我正在使用zend framework 3做一些工作,我需要以表单的形式显示一个select,其中填充了来自数据库的comming选项。我正在使用zend教程博客部分中使用的sql抽象。其目的是显示已经生成的表单,并添加一个简单的select,其中包含从不同表返回的数据,所有表单都使用users表(其中包含国家/地区ID)工作,我希望将该ID链接到正确的表,然后显示select中的所有国家/地区。
谢谢大家。
最佳答案
你将为你的表格写一个工厂。选择该工厂中的数据并通过construct
或某些set
方法传递到表单,然后将该数据用作值选项。
class MyFormFactory implements FactoryInterface {
public function __invoke($container, $options) {
$data = []; // call repository via $container and fetch your data
$form = new MyForm();
$form->setCountries($data);
return $form;
}
}
class MyForm extends \Zend\Form\Form {
private $countries = [];
public function setCountries(array $countries) {
$this->countries = $countries;
}
public function init(){
$this->add([
'type' => Select::class,
'name' => 'countries',
'options' => [
'label' => 'Countries',
'value_options' => $this->countries
]
]);
}
}
把你的表格放在config中的factories键下
return [
'form_elements' => [
'factories' => [
MyForm::class => MyFormFactory::class
]
]
];
现在,当您通过
FormElementManager
调用表单时,您的工厂将触发,它将调用存储库并获取数据,将其传递给表单。别忘了在模块配置中添加
Zend\Form
。这种方法对zf3很好。
关于database - ZF3-填充从数据库中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49609300/