Zend Framework

Archive for March 10th, 2009

Zend Framework Form: working with multiselect list

Posted by Faheem Abbas on March 10, 2009

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”
}

Posted in Zend Framework | 1 Comment »