Thursday, April 08, 2010

html:checkbox gotcha

Was in the midst of testing a JSP that utilized the html:checkbox form input and what I quickly noted was that the checkbox values that were unchecked were not calling the settter methods in the JSP's corresponding Action. Upon inquiring with the finer brains in my area, Ahmed, co-worker in the next cube, helped by pointing out that his experience was that unchecked checkboxes are ignored and to handle the default settings in the Form's reset method. Sure enough he was right. Here is an excerpt from Apache's Struts site here:
A problem with a checkbox is that the browser will only include it in the request when it is checked. If it is not checked, the HTML specification suggests that it not be sent (i.e. omitted from the request). 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.

The recommended approach for Struts applications is to use the reset method in the ActionForm? to set all properties represented by checkboxes to null or false. The checked boxes submitted by the form will then set those properties to true. The omitted properties will remain false. Another solution is to use radio buttons instead, which always submit a value.

It is important to note that the HTML specification recommends this same behavior whenever a control is not "successful". Any blank element in a HTML form is not guaranteed to submitted. It is therefor very important to set the default values for an ActionForm? correctly, and to implement the reset method when the ActionForm? might kept in session scope.

No comments: