CakePHP multiple checkbox array HTML the right way

纵然是瞬间 提交于 2020-01-15 06:10:44

问题


CakePHP's form generator for checkboxes ... when passing the following into the name:

<?php echo $this->Form->checkbox('checkList[]', array( 'value'=>1,'id' => 'holiday'.$holidaysDays['id'], 'error' => false, 'placeholder' => false,'div'=>false,'label'=>false,'class' => 'approveHolidayCheckbox', 'data-off-text'=>'No', 'data-on-text' =>'Yes', 'hiddenField'=>true) ); ?>

outputs:

<input type="checkbox" name="data[HolidaysApproval][checkList[]]" value="1" id="holiday238" class="approveHolidayCheckbox" data-off-text="No" data-on-text="Yes">

I read here:http://network-13.com/thread/3647-Creating-checkbox-arrays-with-CakePHP that the solution is adding a full stop to the field name (as below), where multiple checkboxes are output on the page. Is this the 'right' way to do this?

Couldn't see this particular scenario anywhere in the documentation.

<?php echo $this->Form->checkbox('checkList.', array( 'value'=>1,'id' => 'holiday'.$holidaysDays['id'], 'error' => false, 'placeholder' => false,'div'=>false,'label'=>false,'class' => 'approveHolidayCheckbox', 'data-off-text'=>'No', 'data-on-text' =>'Yes', 'hiddenField'=>true) ); ?>

回答1:


Yes this is the correct way of doing this. When CakePHP builds the field names it uses PHP's explode() method. So checklist. essentially does the following:-

$fieldname = explode('.', 'checklist.');

Which results in:-

Array
(
    [0] => checkList
    [1] => 
)

So you would get inputs with the name data[Model][checklist][].

You can similarly use this for hasMany like fields, e.g. $this->Form->field('Model..name'); which would give you inputs with the name data[Model][][name].

Take a look at the FormHelper and you should easily be able to see how it builds the field names.



来源:https://stackoverflow.com/questions/31234298/cakephp-multiple-checkbox-array-html-the-right-way

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