This blog contains the info about Java and J2ee and Ajax and Hibernate

Monday, June 1, 2009

check box problem in struts

PROBLEM IS:At http://jakarta.apache.org/struts/newbie.html there is a question "Why are my checkboxes not being set from ON to OFF?"
The answer states: "If the value of the checkbox is being persisted, either in a session bean or in the model, a checked box can never unchecked by a HTML form -- because the form can never send a signal to uncheck the box. The application must somehow ascertain that since the element was not sent that the corresponding value is unchecked."
It also states to possibly use a radio button. I am in the process of trying to make this work because I am keeping my form in the session. I am going to try to see if I can check for the element being sent.

ANSWER:

There is a very simple solution to the checkbox problem. The trick is to always add a hidden field AFTER the checkbox with the same parameter name but with the value set to "false":

Basically, the hidden parameter ensures that there is some request parameter submitted, which will always set the corresponding ActionForm property. If the checkbox is checked, the 2 parameters will be passed: "booleanProperty=true&booleanProperty=false". But the beanutils code only uses the first parameter to set the value. If the checkbox is left unchecked, then there will be only 1 parameter "booleanProperty=false" which will ensure the property is set.
The HTML spec says that form elements must be submitted in the GET or POST in the order that they are specified in the HTML, and all browsers I have used obey this rule. There is no risk that the hidden parameter will obscure the form field as long as you always put it after the checkbox.
The beauty of this solution is that it places the burden in the hands of the page author where there can be more flexibility. It also allows the page author to invert the meaning of the checkbox without bothering the application developer. All the page author needs to do is reword the caption, and switch the ordering of the values used in the checkbox and hidden fields. Also, it works with string or numeric properties just as easily.

Another possible solution is :
It is just a work around. This solution will fail when you want to call javascript function on clicking of the checkbox. The Another solution is :- override the "reset" method in the form bean and set the checkbox value false to correctly identify the checkbox value from request. If your bean is in session scope and if you don't want to identify the correct value everytime then get the action from request object and set/reset the checkbox value.

No comments: