Final solution to checkbox problem February 14, 2006
Posted by rossoft in CakePHP.trackback
When you have a form with a checkbox, if you submit the form and the checkbox isn’t checked, then it doesn’t return anything.
In the wiki there is a good solution mixing javascript and hidden inputs.
I have improved this by overriding the tag in tags.ini.php, for doing something like this automatically without any change on your app code.
The tag is:
checkbox = "<input type="hidden" name="data[%1\$s][%2\$s]" id="tag_hidden_%3\$s"/><input type="checkbox" id="tag_%3\$s" onClick="change_%1\$s_%3\$s()" %4\$s /><script type="text/javascript">function change_%1\$s_%3\$s(){ hidden=document.getElementById('tag_hidden_%3\$s'); checkbox=document.getElementById('tag_%3\$s'); hidden.value=(checkbox.checked)? 1:0;} change_%1\$s_%3\$s();</script>"
It’s the same problem with form with a radio. I don’t sucess to adapt this code to it.
Another solution: create a hidden with the same name and default value of 0. Checkbox will override the value if checked.
echo $html->hidden($name,array(’value’=>’0′));
echo $html->checkbox($name,null,array(’value’=>’1′));
There’s no need for this, it’s already at core
Good information.
Thanks, but it kind of irritates me that 2 input fields (one hidden, one checkbox) are needed to reliably transfer a boolean’s state to the DB.
To show a checkbox that is checked by default, I have to do this:
echo $html->checkbox($name, null, array(’value’=>’1′, ‘checked’=>’checked’));
where this would be much more logical, intuitive and concise:
echo $html->checkbox($name, null, array(’checked’=>’checked′));
you can’t be too upset about that… it’s a HTML form element attribute, not a cakephp limitation.
I simply handle the results in the controller:
data['model']['field'] = (isset($this->data['model']['field']) && !empty($this->data['model']['field']) ? true : false);
?>
i have to select the code and scroll over with mouse to see the rest of the text. maybe its my browser problem.
good