Wednesday, July 1, 2009

Zend Framework and dojo checkbox example

Few weeks back, I used dojo check box in my Zend framework application. Scenario was a bit different at that time. I was submitting Zend dojo form on the click event of the checkbox. When I created a form and submitted that onclik, It didn’t give me desired results.
I set its checked value to 1 and unchecked value to 0, however when I submited it always gave me a single value. I was looking for 0 and 1, but it always gave me 0. I thought that It was because I was not using proper submit button for the posting of form.
However when today I used checkbox in normal zend dojo form, it gave me the same result. Oh God, how to fix it.
However as I have played with dojo js files, so I got the solution.
Let’s tell you the trick.
First of all create check box as
$checkbox= $form->createElement(
'checkBox',
'checkbox',
array(
'label' => 'Tricky check box',
'checkedValue' => 1,
'uncheckedValue' => 0
)
);

Now add onclick event to this checkbox element as
$checkbox->setAttrib('onclick','changeValue()');

Now in your view, where you display this form, write the following javascript function
<script>
function changeValue()
{
if(dijit.byId('checkbox').checked){
dijit.byId('checkbox').setValue('1');
} else {
dijit.byId('checkbox').setValue('0');
dijit.byId('checkbox').checked=false;
}

}
</script>

The above code isn’t simple?

Hmm. First we see if we have checked the checkbox, if yes we assign value 1 to it, if not we assign it value 0 and set its checked status to false. This will uncheck the checkbox.

That’s it. Submit your form and you will get desired results.

Doesn’t it help you. Do you have smarter solution than this.

Tell me……

1 comment:

  1. For check boxes I always make two elements:
    input type="hidden" name="is_active" value="0"
    input type="checkbox" name="is_active" value="1"

    This way when its not checked its 0, and when it is, its 1. the order of the inputs is very important, because when the browser submits it, it will override the last named input thats active. In this case the hidden is always active but when the checkbox is checked its set to active and overrides the hidden.

    ReplyDelete