php 输入框 调用数据库字段,php – zf2 form:使用来自数据库的数据填充select字段...

我正在学习zf2,我正面临一个涉及2个(最终更多)模块一起工作的问题.请注意,我仔细阅读了this post(及相关的),这对我帮助很大.我将解释一下这个问题:

>使用第一个模块(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中.

这可能是一个明智和有效的解决方案吗?在性能方面你对它有什么看法(选项表可以增长)?

如果有的话,你用什么样的解决方案来解决类似的问题?

谢谢

解决方法:

This can be done easily by following the below 2 steps in Zend

Framework2 Step 1.

add The instance of the adapter what instantiating form class in the

controller action

$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

$form = new TestForm ($dbAdapter);

Step 2 in your form

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;

}

}

And here you go you are ready to rock.I hope it helps you

标签:zend-db-table,php,zend-framework2,zend-form

来源: https://codeday.me/bug/20190729/1568425.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值