MultiSelect in Zend Framework 2
Asked Answered
P

3

10

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

Perception answered 11/11, 2012 at 15:2 Comment(0)
P
26

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.

Perception answered 11/11, 2012 at 15:12 Comment(2)
Nice.. How to select multiple options by default? If we have only one then for example, we use like value => '2'. How to do multi-options?Mickens
With this answer the default validator says the input is invalid!!! it says "The input was not found in the haystack" ["regexInvalid"]=> string(53) "Invalid type given. String, integer or float expected"Lunette
C
6

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',
            ),
        ),
    ));
Cushitic answered 2/10, 2014 at 21:12 Comment(0)
V
2
@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);
Vogul answered 6/11, 2020 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.