Inside my form there is a long row of checkboxes which I want to show as two columns of checkboxes (for reasons related to presentation). So in the following code I split the options into two separate arrays and create two different options by the same name. When I debug($this->request->data);
the 'location' key is always empty. However, the same code works as a single input just fine. What am I doing wrong?
<?php
$count = count($location_options); //$location_options is passed from the controller
$half = round( $count/2 );
$location_options1 = array_slice($location_options, 0, $half, TRUE);
$location_options2 = array_slice($location_options, $half, NULL, TRUE);
//I CAN'T GET THIS TO WORK!!
//echo $this->Form->input('location', array('type'=>'select', 'multiple'=>'checkbox', 'options'=>$location_options1, 'div'=>array('class'=>'col-xs-12 col-sm-6 form-group', 'style'=>'margin-bottom:0;', 'selected'=>$user_location_alert_tag_ids)));
//echo $this->Form->input('location', array('type'=>'select', 'multiple'=>'checkbox', 'options'=>$location_options2, 'div'=>array('class'=>'col-xs-12 col-sm-6 form-group', 'selected'=>$user_location_alert_tag_ids)));
//BUT THIS WORKS JUST FINE
echo $this->Form->input('location', array('type'=>'select', 'multiple'=>'checkbox', 'options'=>$location_options, 'div'=>array('selected'=>$user_location_alert_tag_ids)));
?>
Look at the generated HTML, for each select element a hidden field is generated that ensures that the appropriate key will be present in the data.
Multiple fields with the same name will cause multiple hidden fields to be generated where the last one will overwrite the former ones.
This can be avoided using the hiddenField
option for the additional fields, so that the hidden initializer field is only generated for the first input. Quote from the docs:
If you want to create multiple blocks of inputs on a form that are all grouped together, you should use this parameter on all inputs except the first. If the hidden input is on the page in multiple places, only the last group of input’s values will be saved.
Also you should define a unique ID for both inputs, otherwise you'll end up with invalid HTML as the helper will produce duplicate IDs.
And last but not least your parentheses are probably a little wrong, the selected
key is nested in the div
key, which I guess is wrong in case this is ment to define the selected entries.
echo $this->Form->input('location', array(
'id' => 'location1',
'type' => 'select',
'multiple' => 'checkbox',
'options' => $location_options1,
'div' => array('class' => 'col-xs-12 col-sm-6 form-group', 'style'= > 'margin-bottom:0;')
'selected' => $user_location_alert_tag_ids
)));
echo $this->Form->input('location', array(
'id' => 'location2',
'type' => 'select',
'multiple' => 'checkbox',
'options' => $location_options2,
'div' => array('class' => 'col-xs-12 col-sm-6 form-group'),
'selected' => $user_location_alert_tag_ids
'hiddenField' => false
)));