Pha*_*007 5 database zend-framework populate zend-form
我有以下表格:
<?php
class Application_Form_RegistrationForm extends Zend_Form{
public function init(){
$country = $this->createElement('select', 'country');
$country->setLabel('country: ')
->setRequired(true);
$email = $this->createElement('text', 'email_address');
$email->setLabel('Email Address: ')
->setRequired(true);
$register = $this->createElement('submit', 'register');
$register->setLabel('Create new Account')
->setIgnore(true);
$this->addElements(array(
$country, $email, $register
));
}
}
?>
Run Code Online (Sandbox Code Playgroud)
国家列表存在于country数据库的表中.
无论如何,我可以使用数据库中的国家/地区名称填写国家/地区下拉列表吗?
任何帮助表示赞赏.
谢谢
你确定可以.
在init方法中,您可以使用类似的设置选项,假设$ db是Zend_Db适配器:
$options = $db->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
$country->setMultiOptions($options);
Run Code Online (Sandbox Code Playgroud)
如果你还没有看到fetchPairs方法,它会构建一个数组,其中第一列返回成为键,第二列返回值.
如果列表的内容取决于某些条件,您可以从控制器的操作(甚至在服务层中,如果要一丝不苟)这样做.用法:
$form->getElement('country')->addMultiOption('1','USA'); //add single value
$form->getElement('country')->addMultiOptions(array('1'=>'USA', '2'=>'Canada')); //add values by array
$form->getElement('country')->setMultiOptions(array('1'=>'USA', '2'=>'Canada')); //set values by array
Run Code Online (Sandbox Code Playgroud)
当然,要从DB添加值,您需要先获取它们.
有关更多可用方法,请参阅http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.select.
最好的方法是为元素创建一个新类:
将其放入“/application/form/element/CountySelect.php”
class Application_Form_Element_CountrySelect extends Zend_Form_Element_Select {
public function init() {
$oCountryTb = new Application_Model_Country();
$this->addMultiOption(0, 'Please select...');
foreach ($oCountry->fetchAll() as $oCountry) {
$this->addMultiOption($oCountry['id'], $oCountry['name']);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其添加到表单中:
class Application_Form_RegistrationForm extends Zend_Form{
public function init() {
$this->addElement(new Application_Form_Element_CountrySelect('country_id'));
}
}
Run Code Online (Sandbox Code Playgroud)