脚本宝典收集整理的这篇文章主要介绍了php – zf2 form:使用来自数据库的数据填充select字段,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
>使用第一个模块(FrOption),管理员可以管理网站表单选项.所有选项都存储在db表中,如下所示:
ID | FIELD_NamE | FIELD_VALUE
1 |国内|德国|
2 |国内|法国|
3 |性别|男|
4 |性别|女|
5 | TIPO |汽车|
6 | TIPO |飞|
…
>在我的模块(FrITem)中,我构建了一个需要一些“field_name”字段的表单.
我的“项目”表格如下:
ID |名称| id_tipo |
1 |菲亚特| 5 |
2 |莎| 6 |
3 |福特| 5 |
4 |法国航空6 |
…
(id_tipo是一个选项FK)
还要考虑:
>我的实体有“tipo”属性,setter getter
>我已经构建了一个ItemHydrator来将id_tipo db字段“映射”为“tipo”实体属性
>作为测试,我在表单类中添加了这个字段,在视图和编辑模式下一切正常:
$this->add( 'tyPE' => 'Zend\Form\Element\Select','name' => 'id_tipo','options' => array ( 'label' => 'Tipo','empty_option' => 'Select','value_options' => array ('5' => 'Car','6' => 'Fly' ) )
);
现在我想“链接”这两个模块:value_options应该是来自FrOption的动态数组,所以我正在寻找实现这个要求的最佳方法.
>添加到我的FrOption / src / FrOption / Service / FrOption.PHP服务类getOptionByName($fieldName)方法
>在FrItem / Module.PHP中检索服务,然后使用getOptionByName将数据全部注入到Form中.
这可能是一个明智和有效的解决方案吗?在性能方面你对它有什么看法(选项表可以增长)?
如果有的话,你用什么样的解决方案来解决类似的问题?
谢谢
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'); $form = new testForm ($dbAdapter);
namespace Test\Form; use Zend\Form\Form; use Zend\Db\Adapter\AdapterInterface; use Zend\Db\Adapter\Adapter; class TestForm extends Form { PRotected $adapter; public function __construct(AdapterInterface $dbAdapter) { $this->adapter =$dbAdapter; parent::__construct("Test Form"); $this->setattribute('method','post'); //your select field $this->add(array( 'type' => 'Zend\Form\Element\Select','name' => 'name','tabindex' =>2,'options' => array( 'label' => 'Author','empty_option' => 'Please select an author','value_options' => $this->getOptionsForSelect(),) )); // another fields } public function getOptionsForSelect() { $dbAdapter = $this->adapter; $sql = 'SELECT id,name From newsauthor where active=1 ORDER BY sortorder ASC'; $statement = $dbAdapter->query($sql); $result = $statement->execute(); $selectData = array(); foreach ($result as $res) { $selectData[$res['id']] = $res['name']; } return $selectData; } }
以上是脚本宝典为你收集整理的php – zf2 form:使用来自数据库的数据填充select字段全部内容,希望文章能够帮你解决php – zf2 form:使用来自数据库的数据填充select字段所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。