I've the next form:

class Application_Form_RegistrationForm extends Zend_Form{

    public function init(){

        $country = $this->createElement('select', 'country');
        $country->setLabel('country: ')

        $email = $this->createElement('text', 'email_address');
        $email->setLabel('Email Address: ')

        $register = $this->createElement('submit', 'register');
        $register->setLabel('Create new Account')

            $country, $email, $register




Their email list from the nations can be found inside a table country inside a database.

Can there be anyway I'm able to populate the nation dropdown list using the country names in the database?

Any assistance is appreciated.


You sure can.

Within the init method you are able to set the choices with something similar to this, presuming $db is really a Zend_Db adapter:

$options = $db->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');

Just in case you have not seen the fetchPairs method, it develops an assortment, in which the first column return becomes the important thing, and also the second column the worthiness.

You could do this it from controller's action (or perhaps Service Layer, if to become meticulous), in case your list's content is dependent from some conditions. Usage:

$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

Obviously, to include values from DB you have to fetch them first.

See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.select for additional techniques available.

The easiest way is to produce a new class for that element:

Put this in "/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']);

After which combine it with the shape by doing this:

class Application_Form_RegistrationForm extends Zend_Form{
    public function init() {
        $this->addElement(new Application_Form_Element_CountrySelect('country_id'));