2
votes

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
If you loop a couple of checkboxes, then yes, the fullstop in the end will produce something like checklist[0], checklist[1] etc.Skatch

1 Answers

3
votes

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.