captain holly java blog

struts form boolean checkbox

Posted in Uncategorized by mcgyver5 on September 22, 2009

We all understand that when a checkbox is not checked on a form, it is not present in the request object. This is the basis for many headaches in web application programming, especially when using multiple form pages. When using multiple form pages, as in a wizard, the struts way around is to have a reset() method that contains some logic for setting the value to false if it doesn’t exist in the request. Again, this applies to situations with a session scoped form.

The documentation for the html:checkbox tag says:

WARNING: In order to correctly recognize unchecked checkboxes, the ActionForm bean associated with this form must include a statement setting the corresponding boolean property to false in the reset() method.
In practice, the only properties that need to be reset are those which represent checkboxes on a session-scoped form. Otherwise, properties can be given initial values where the field is declared.

public void reset(){
    this.citizen = false;
}

There are several confusing posts out there in forums about how to populate checkboxes when viewing forms with existing data. One says to have a hidden form field with the same name as the checkbox. Another has us jumping out of struts and using regular JSP tags with logic. Both of these are unnecessary and have potentially bad repercussions later.
The real solution is to use a html:checkbox with a name equal to that of a bean and the property equal to the name of the boolean variable in that bean that the checkbox captures. The following will check or uncheck the checkbox depending on the value of “citizen” in the applicantBean:

<html:checkbox name="applicantBean" property="citizen" value="true">

to work this, your code must invent an empty applicant bean before loading the blank form, or struts will whine that there is no such thing as “applicantBean” in any scope.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: