php – zf2 form:使用来自数据库的数据填充select字段
我正在学习zf2,我正面临一个涉及2个(最终更多)模块一起工作的问题.请注意,我仔细阅读了
this post(及相关的),这对我帮助很大.我将解释一下这个问题:
>使用第一个模块(FrOption),管理员可以管理网站表单选项.所有选项都存储在db表中,如下所示: ID | FIELD_NAME | FIELD_VALUE >在我的模块(FrItem)中,我构建了一个需要一些“field_name”字段的表单. ID |名称| id_tipo | (id_tipo是一个选项FK) 还要考虑: >我的实体有“tipo”属性,setter getter $this->add( 'type' => 'ZendFormElementSelect','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)方法 这可能是一个明智和有效的解决方案吗?在性能方面你对它有什么看法(选项表可以增长)? 谢谢 解决方法
$dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter'); $form = new TestForm ($dbAdapter);
namespace TestForm; use ZendFormForm; use ZendDbAdapterAdapterInterface; use ZendDbAdapterAdapter; 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' => 'ZendFormElementSelect','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; } }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |