ZF2 从数据库中获取值到表单 class
ZF2 get values from database into form class
在 ZF2 中,假设我有一个 Select
的形式:
$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
?
通过使用表单元素管理器注册自定义 select 元素,您可以使用工厂加载所需的表单选项。
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;这描述了如何正确使用表单元素管理器,这对于上述工作至关重要。
在 ZF2 中,假设我有一个 Select
的形式:
$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
?
通过使用表单元素管理器注册自定义 select 元素,您可以使用工厂加载所需的表单选项。
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;这描述了如何正确使用表单元素管理器,这对于上述工作至关重要。