Using Wicket’s CheckBoxMultipleChoice

      No Comments on Using Wicket’s CheckBoxMultipleChoice

When I started with Wicket, I remember fighting with CheckBoxMultipleChoice for hours trying to get it to work. I just used it again today and was surprised at how easy it is to use once you’re familiar with how Wicket works. So for anyone struggling with it, here’s how to do it.

Say we want to display a list of Projects associated with a User and we want to do it with the CheckBoxMultipleChoice. The projects which the user currently has access to should be checked initially. Checking or unchecking boxes will add or remove access to projects.

You can accomplish this with the following code:

[sourcecode language=”java”]
add(new CheckBoxMultipleChoice(“projects”, new Model(userProjects), allProjects));

Assuming you have a span with wicket:id=”projects” in your HTML, this will display a checkbox for each project found in the “allProjects” list. Those which are also in the “userProjects” list will be checked. After submitting the form, the “userProjects” list will hold those which were checked when the form was submitted.

Note: I have omitted a renderer – that’s because my Project class has a toString() method which returns its name. That’s allows Wicket to render it correctly without an explicit renderer.

Second thing to note is that “userProjects” must be an ArrayList of Projects, not a List (as your service method would normally return it). The reason for this is that the Model demands a Serializable class so the easiest thing is to define userProjects as follows:

[sourcecode language=”java”]
ArrayList userProjects = new ArrayList(service.getUserProjects());

The choices parameter (allProjects) can be a List, so you can use it straight from your service method.

Hope that helps anyone trying to use CheckBoxMultipleChoice for the first time.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.