jump to navigation

Final solution to checkbox problem February 14, 2006

Posted by rossoft in CakePHP.

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>"


1. Naonak - March 14, 2006

It’s the same problem with form with a radio. I don’t sucess to adapt this code to it.

2. rossoft - March 29, 2006

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’));

3. rossoft - May 22, 2006

There’s no need for this, it’s already at core

4. marcio - June 6, 2006

Good information.

5. joeri poesen - September 26, 2006

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′));

6. alan - April 16, 2007

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);


7. anon - April 15, 2008

i have to select the code and scroll over with mouse to see the rest of the text. maybe its my browser problem.

8. siva - December 1, 2008

multiple checkbox

9. Pradeep - June 23, 2010

But now there is a problem.If we pass id of check box to the javascript file it will not recognize.so wht should we do for that problem.Any suggessions guys.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: