MainelyDesign.com Blog

Checkbox - setting the default state

Posted on 04/17/2009 at 08:31 am by Kevin Wentworth
Viewed 10,258 times | 0 comments

I ran across a rather simple problem (I thought) that took a little searching to figure out.  All I had to do was create a checkbox form input that I wanted to have checked by default.  I tried 'default'=>'checked', which didn't work.  I also tried 'checked'=>true and 'checked'=>1, but that works every time, even if validation fails and the user had unchecked the checkbox, it will be checked again (Not good usability). 

The solution lies in a less-than-automagic approach.  Too bad this request wasn't built-in, it would have solved the issue: https://trac.cakephp.org/ticket/5711. You need to look at the value being passed for the field and determine the value of checked: should it be 'checked'=>true or false. 

In my controller, when empty($this->data) I set the field value to 1 (my default checked value):

  1. $this->data['ModelName']['field'] = 1;

I did the following in my view:

  1. $check_options = array('label'=>'My checkbox label', 'type'=>'checkbox');
  2. if($this->data['ModelName']['field'] == 1) {
  3.     $check_options['checked'] = true;
  4. }
  5. echo $form->input('ModelName.field', $check_options);

This way, when the ModelName.field does not equal 1 (unchecked) then $check_options array will not have the option setting the field to checked.

Thanks to the following resources:

 for pointing me in the right direction.

Cheers,

-Kevin Wentworth

 

Bookmark and Share

Tags for Checkbox - setting the default state

Cakephp | Web Programming | Forms

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design