Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultiSelect in Zend Framework 2

There was a Zend_Form_Element_Multiselect in Zend Framework 1.12. How to achieve the same result in Zend Framework 2.0 ? I only see Zend\Form\Element\MultiCheckbox and Zend\Form\Element\Select

like image 470
bogatyrjov Avatar asked Nov 11 '12 15:11

bogatyrjov


3 Answers

Ok, I found the answer myself and it wasn't easy to read out of the official documentation, rather an experiment solution :

        $this->add(array(
            'type' => 'Zend\Form\Element\Select',
            'attributes' => array(
                'multiple' => 'multiple',
            ),
            'name' => 'langs',
            'options' => array(
                'label' => 'langs',
                'value_options' => array(
                    '0' => 'French',
                    '1' => 'English',
                    '2' => 'Japanese',
                    '3' => 'Chinese',
                ),
            ),
        ));

Just add

        'attributes' => array(
            'multiple' => 'multiple',
        ),

to your setup.

like image 163
bogatyrjov Avatar answered Oct 27 '22 03:10

bogatyrjov


One addition to Jevgeni's answer: make sure you add "[]" to the element name, otherwise you'll end up with only the last value selected. It's a PHP issue, nothing to do with ZF2. So the final config looks like this:

$this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'attributes' => array(
            'multiple' => 'multiple',
        ),
        // NOTE the addition of "[]" to the name:
        'name' => 'langs[]',
        'options' => array(
            'label' => 'langs',
            'value_options' => array(
                '0' => 'French',
                '1' => 'English',
                '2' => 'Japanese',
                '3' => 'Chinese',
            ),
        ),
    ));
like image 5
dougB Avatar answered Oct 27 '22 02:10

dougB


@user2003356

for already selected options add in options:

'value' => array( '0' => '1',
                  '1' => '3'  )

or in crontroller:

$form->bind($elements);
$form->get('langs')->setValue(['1','3']); form->bind($elements);
like image 1
Buli Avatar answered Oct 27 '22 02:10

Buli