MultiSelect in Zend Framework 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);
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.
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',
),
),
));