CakePHP 2.0 Select form Multiple selected
Asked Answered
L

2

5

I have have this dropdown menu where you can select multiple values. Now let's say I want to edit my info and make a dropdown menu with multiple selected values. Trying to figure out how it goes, but no results.

Let's say I have:

$selected = array(3, 4);
$options = array(1,2,3,4);

echo $this->Form->select('Attendees', $options,array('multiple' => true, 'selected' => $selected));

I've used this code, but nothing is selected.

Lavonna answered 19/9, 2012 at 9:32 Comment(0)
L
7

Ok found a way, appearantly it needs to be like this:

$selected = array(2, 3);
$options = array(1, 2, 3, 4);

echo $this->Form->input('Attendees', array('multiple' => true, 'options' => $options, 'selected' => $selected));

Will output:

  • 1
  • 2
  • 3 checked
  • 4 checked

The $selected checks the index key of each element rather the value itself.

Lavonna answered 19/9, 2012 at 9:48 Comment(2)
@Jleagle Nope, cause the selected will check the array index number or value. In this case [0] => 1, [1] => 2, [2] => 3, [3] => 4. So [2] and [3] are selected.Lavonna
Oops, in my head I was thinking you had done this: $options = array(1=>1, 2=>2, 3=>3, 4=>4);Sesame
F
0

I'm creating the multi-select as follows in cakePHP 3.9:

 echo $this->Form->input($tableName . '[' . $marker . ']', [
                'type' => 'select',
                'options' => $options,
                'val' => $selected,
                'multiple' => true,
                'id' => $tableName . '-' . $num,
            ]);

instead of 'selected' it uses 'val' to pre-select: https://book.cakephp.org/3/en/views/helpers/form.html#creating-select-pickers

Just in case someone doesn't notice the version and gets stuck with the previous solution, like me :)

Fretwork answered 7/5, 2021 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.