Search code examples
zend-frameworkzend-form

How to handle multi-select boxes in a zend framework form?


Just wondering how it works and how to handle the information.

Let's say I have a form like this:

$multi = new Zend_Form_Element_Multiselect('users');
$multi->setMultiOptions(array(
    //'option value' => 'option label'
    '21' => 'John Doe',
    '22' => 'Joe Schmoe',
    '23' => 'Foobar Bazbat'
));
$form->addElement($multi);

If a user selects one, or multiple values from a multi-select box...

  • How do I get the value that the user selected?
  • Does it return in array? or what?
  • How can I tell how many items the user selected?

Solution

  • Using a multi select element like this one:

    $multi = new Zend_Form_Element_Multiselect('users');
    $multi->setMultiOptions(array(
        //'option value' => 'option label'
        '21' => 'John Doe',
        '22' => 'Joe Schmoe',
        '23' => 'Foobar Bazbat'
    ));
    $form->addElement($multi);
    

    You can get the values of the element like this:

    public function indexAction()
    {
        $form = new MyForm();
    
        $request = $this->getRequest();
        if ($request->isPost()) {
    
            if ($form->isValid($request->getPost())) {
    
                $values = $form->getValues();
                $users = $values['users']; //'users' is the element name
                var_dump $users;
            }
        }
        $this->view->form = $form;
    }
    

    $users will contain an array of the values that have been selected:

    array(
        0 => '21',
        1 => '23'
    )