Assigning multi options to dropdown in zend framework

31 Oct

After writing some post on my blog I got a question from a developer. “how to assign multioption to <select> tag?”. The answer is quite simple

Add the following code to your controller.

$form=new Zend_Form();

$dropdown= new Zend_Form_Element_Select(“dropdown”);

$dropdown->setLabel(“Country:”);

$dropdown->setMultiOptions(array(

“United States”,

“United Kingdom”,

“Canada”,

“Australia”

));

$form->addElement($dropdown);

The code above will create the following dropdown.

Zend Framework Form dropdown

Zend Framework Form dropdown

The code is self explanatory. First we are creating Zend_Form instance. Then create select element, set its label and setMultiOptions. The method setMultiOptions() take array of values.

Better to pass the following array.

array(

“1” => “United States”,

“2” => “United Kingdom”,

“3” => “Canada”,

“4” =>”Australia”

)

If you pass the above array, select element will create following html

<select name=”dropdown” id=”dropdown”>

<option value=”1”>United States</option>

<option value=”2”>United Kingdom</option>

<option value=”3”>Canada</option>

<option value=”4”>Australia</option>

</select>

3 Responses to “Assigning multi options to dropdown in zend framework”

  1. lmcosorio December 7, 2008 at 4:54 pm #

    Hi,

    Nice example! I’ve been looking for some time for an example regarding linked/dynamic select boxes, ex. you choose a country and the cities select box box is populated with the country cities, all this with databases queries.
    Have you implemented something similar? If so, do you mind sharing?

    Regards,

    Luis

  2. Outsourcing India January 19, 2009 at 12:40 pm #

    Hi,
    Thanks. I added like this. It is working for me.

    $form=new Zend_Form();

    $dropdown= new Zend_Form_Element_Select(”dropdown”);

    $dropdown->setLabel(”Country:”);

    $dropdown->setMultiOptions(array($recordset)); // $recordset is collection of record which is from database

    $form->addElement($dropdown);
    Mark

  3. Sathya March 30, 2010 at 1:00 am #

    Thanks🙂 I know there’s a way to simply pass it in when you create the element, but it’s so hard to remember that I’ll just use this way for now.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: