cakephp checkbox multiple select just sends the value of last selected checkbox

社会主义新天地 提交于 2020-01-03 17:45:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!