Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 351
Andrew Avatar asked Dec 11 '09 20:12

Andrew


3 Answers

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'
)
like image 78
Andrew Avatar answered Oct 12 '22 14:10

Andrew


$form->getElement('name')->getValue() 

will return the value of $_POST['name']. You can make

$_POST['name'] 

be an array by defining the name of the element with brackets at the end. So in this case, 'name[]'. In the Zend Framework, use an element that extends

Zend_Form_Element_Multi

Please see: http://www.framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.multiselect

For example:

$multi = $form->createElement('multiselect', 'name[]');
$multi->setMultiOptions($options);
$form->addElement($multi);

if ($form->isValid($_POST)) {
    $userSelectedOptions = $form->getElement('name')->getValue();
}
like image 30
Brad Avatar answered Oct 12 '22 13:10

Brad


See the answer from brad. The especial part is the name of the element

$multi = $form->createElement('multiselect', 'name[]');

if you call the element with squares it will be handled as an array by the browser (not a zf behavior). Otherwise you'll get only the first selected element

like image 27
Alwin Kesler Avatar answered Oct 12 '22 14:10

Alwin Kesler