问题
I am not getting the value of all the checkboxes selected. It just gives me the value of last selected checkbox
here is the code
foreach($apps as $app){
echo $this->Form->input('Application.id', array('type'=>'checkbox','multiple' => 'checkbox' , 'id'=>$app['Application']['description'], 'div'=>false,'type'=>'checkbox','value' => $app['Application']['description'],'label'=>$app['Application']['description']));
}
and on submit I get the very last checkbox which is LASTCHECKBOX
object(CakeRequest) {
params => array(
'plugin' => null,
'controller' => 'groups',
'action' => 'add',
'named' => array(),
'pass' => array()
)
data => array(
'Application' => array(
'id' => 'LASTCHECKBOX'
)
)
query => array()
url => 'groups/add'
base => ''
webroot => '/'
here => '/groups/add'
}
回答1:
i think it is because of "value".
in your case use "options" => array(1, 2, 3)
you should better never set value, default or anything like that in the view. use the controller action to set a default. than it should work fine.
if ($this->request->isPost()) {
} else {
$this->request->data['Model']['fieldname'] = 'defaultvalue';
}
回答2:
For multiple checkboxes you need to have []
as the last part of the name HMTL attribute (see this answer for more explanation).
This is done in CakePHP using the 'select' type of input. If you look at the Form Helper select documentation for 2.0 (but applies to v1.2+ as well) you don't need the loop you just need to create a multiple select using checkboxes:
<?php
$options = array(
'Value 1' => 'Label 1',
'Value 2' => 'Label 2'
);
echo $this->Form->select('Model.field', $options, array(
'multiple' => 'checkbox'
));
?>
So I think for you you don't need the foreach($apps
you need to modify $apps to be in in a similar format to $options
.
<?php
$apps = array(
'App Id 1' => 'Description 1',
'App Id 2' => 'Description 2'
);
echo $this->Form->select('Application.id', $apps, array(
'multiple' => 'checkbox'
));
?>
Should ouput:
<div class="input select">
<label for="ApplicationId">Id</label>
<input name="data[Application][id]" value="" id="ApplicationId" type="hidden">
<div class="checkbox">
<input name="data[Application][id][]" value="App Id 1" id="ApplicationId1" type="checkbox">
<label for="ApplicationId1">Description 1</label>
</div>
<div class="checkbox">
<input name="data[Application][id][]" value="App Id 2" id="ApplicationId2" type="checkbox">
<label for="ApplicationId2">Description 2</label>
</div>
</div>
来源:https://stackoverflow.com/questions/10049995/cakephp-checkbox-multiple-select-just-sends-the-value-of-last-selected-checkbox