Checkbox and Database

By starkman

To make life somewhat easier, database columns that will be rendered as checkboxes should be of type tinyint (or number) with values of zero and one (where 1 is checked).

The definition of the html->checkbox function is (note: title is not used):

checkbox($fieldName, $title = null, $htmlAttributes = array(), $return = false)

Whether or not the checkbox is checked is based on the htmlAttributes array. To illustrate what I mean, these $htmlAttribute arrays will result in a checked checkbox:

array('value'=>1)
array('value'=>0)
array('checked'=>1)
array('checked'=>0)
array('checked'=>'checked')

A bit of odd code does make the value of 0 (zero) also check the checkbox, so do not do this

echo $html->checkbox('Model/column', null, array('value'=>$ind));

and expect the checkbox to be unchecked if $ind is zero. It seems this would be the right thing to do to optimize your code, however, it does not work as expected.

So, to create a checkbox you’d write the easiest thing possible:

echo $html->checkbox('Model/column');

and CakePHP will make it checked for you (no extra code required).

Leave a Reply