ZF2 从数据库获取值到表单类 [英] ZF2 get values from database into form class
问题描述
在 ZF2 中,假设我有一个 Select
形式:
In ZF2, suppose I have a Select
in the form:
$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',
],
],
]);
如何将数据库查询中的值type 1"、type 2"、type 3"等放入value_options
?
How can I put the values 'type 1', 'type 2', 'type 3', etc. from a database query into value_options
?
推荐答案
通过向表单元素管理器注册自定义选择元素,您可以使用工厂加载所需的表单选项.
By registering a custom select element with the form element manager, you can use a factory to load the required form options.
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
值.
You can then use MyModule\\Form\\Element\\TypeSelect
as the type
value when adding the element to a form.
另外请务必阅读关于自定义表单元素的文档;这描述了如何正确使用表单元素管理器,这对于上述工作至关重要.
Also make sure to read the documentation regarding custom form elements; this describes how to use the form element manager correctly, essential for the above to work.
这篇关于ZF2 从数据库获取值到表单类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!