php中form表单feild,php – zf2 form:使用来自数据库的数据填充select字段

本文介绍如何在Zend Framework2中利用数据库适配器填充表单选择字段的选项。通过两步操作实现:一是在控制器动作中实例化表单类并传入数据库适配器;二是在表单类构造函数中设置数据库适配器,并定义表单元素及通过执行SQL语句获取数据来填充选择字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值