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
MultiSelect in Zend Framework 2
Asked Answered
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.
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
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',
),
),
));
@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);
© 2022 - 2024 — McMap. All rights reserved.