Zend Framework: Populating DB data to a Zend Form dropdown element

Phantom007 picture Phantom007 · Oct 8, 2010 · Viewed 13.5k times · Source

I have the following 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
        ));




    }

}

?>

The list of the countries are present in a table country in a database.

Is there anyway I can populate the country dropdown list with the country names from the database?

Any help is appreciated.

Thanks

Answer

David Snabel-Caunt picture David Snabel-Caunt · Oct 12, 2010

You sure can.

In the init method you can set the options with something like this, assuming $db is a Zend_Db adapter:

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

In case you haven't seen the fetchPairs method, it builds an array, where the first column return becomes the key, and the second column the value.