Zend Framework Form: working with multiselect list

10 Mar

I am writing articles on Zend Framewrok form component since few days. I’ve already discussed how to use select(dropdown) list and radio buttons in separate articles.
In this article I’m going to discuss how to use multiselect in zend framework application.
In your form, write the following code

<?php

class CustomForm extends Zend_Form
{

public function init()
{

$this->setMethod(‘post’);
$this->setAction(”);

$subjects = $this->createElement(‘multiselect’,’subjects’);
$subjects->setLabel(‘Subjects’)

->addMultiOptions(array(
‘en’ => ‘English’,
‘gr’ => ‘German’,
‘sp’ => ‘Spanish’
));

$this->addElement($subjects);

$submit = $this->createElement(‘submit’,’submit’);
$submit->setLabel(‘Submit’);
$this->addElement($submit);

}

}

That’s it, we have now created our form with multiselect. The next step is to get values in the Controller/Action.
Keep in mind that using multiselect you can select one or more options using shift key on your keyboard.
One the form is submitted you can take the form values as

$form = new CustomForm();
$values = $form->getValues();

$values with contain the entire set of values submitted. To get individual values of the multiselect option, you will need the following code.

$subjects = $values[‘subjects’];

Keep in mind that subjects is our element name in the form.

$subjects is an array like the following.

array(2) {
[0] => string(2) “gr”
[1] => string(2) “sp”
}

One Response to “Zend Framework Form: working with multiselect list”

  1. Tom May 21, 2009 at 4:45 pm #

    I think ‘de’ is a little more common abr for German ..

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: