Note by a reader (called skrebbel): HtmlHelper::checkbox fixes this problem without javascript, by combining a misfeature of HTML with a misfeature of PHP: it first inserts a hidden input with the “off” value (like 0), and then the checkbox with an appropriate “on” value (like 1), both with exactly the same name. In case of exact duplicate names for fields, PHP discards all but the last one. Additionally, HTML/HTTP only sends a checkbox value if it is checked - no value at all is sent when the checkbox is unchecked, which result in the hidden value not being ‘overwritten’ (in PHP, at least) by the checkbox value.

Using booleans and checkboxes

A pattern in Cake, that I want to make a View helper method of.

A Boolean field in DB, like a Person’s hasMustache property is represented in as an integer: 0 is off, 1 is on.

THe visual representation would be in an INPUT CHECKBOX, with the value in a HIDDEN INPUT field. That hidden field would have the Cake name of the field.

The checkbox would just fire off a JavaScript function to switch between 0 and 1 on the hidden field’s value.

The example HTML:

    <script type="text/javascript">
    /**
      * Switch given value of ID's from 1 to 0, or vice versa.
      */
    function switchActive(id)
    {
        el = document.getElementById(id);
        el.value = (el.value != 1) ? 1 : 0 ;
    }
    </script>
    <!-- Hidden FORM field to hold the value of the Boolean field -->
    <input type="hidden" name="data[Person][hasMustasche]"  id="activeid" value="1" />
 
    <p>
    <label for='activator'>Show on page:</label>
    <input type="checkbox" id='activator' checked='checked' onchange="switchActive('activeid')"  />
    </p>

The example Cake view code:

 
<label for='activator'>Is the product sold out?</label>
<p>
<!-- Hidden FORM field to hold the value of the Boolean field -->
<?php 
echo $html->hidden("Product/soldout", array( "id"=>"soldoutid" ) ); 
?></p>
 
<input type="checkbox" id='activator' <?php echo ($html->tagValue("Product/soldout")==0) ? "" : "checked='checked'" ;?> onchange="switchActive('soldoutid')"  />
 
</p>
 
 
docs/booleans_for_checkboxes.txt · Last modified: 2006/08/05 03:02 by skrebbel