Spring MVC's checkboxes tag and support for enum

Using Spring MVC's checkboxes (or radiobuttons) tag to render form inputs for an enum property is easy and clean...once you know how. After a little gnashing of teeth, due to the fact that I needed a specific display order for all options, I found the following solution:

Here's the tag in my jsp

<form:checkboxes itemValue="value" itemLabel="label"  path="user.degrees" items="${degreeLabels }" />

Here's the way I populated my model map to retain ordering. (I placed this code in my FormController's referenceData method)
List labelValues = new ArrayList<LabelValue>();        for (Degree d : Degree.values()) {            labelValues.add(new LabelValue(d.name(), d.name()));        }        Map model = new HashMap();        model.put("degreeLabels", labelValues);
FYI, I ripped the LabelValue class used above from Matt Riable's excellent Appfuse project. The constructor takes two arguments which are mapped to the properties "value" and "label" and these properties have the typical pojo getters and setters.
You can see from the path on my tag that degrees is a property on my User object...which is the target of my form. Here's what that looks like...I threw in my Hibernate annotations for the curious:
private Set<Degree> degrees = new HashSet<Degree>();    @CollectionOfElements    @Enumerated(EnumType.STRING)    public Set<Degree> getDegrees() {        return degrees;    }    public void setDegrees(Set<Degree> degrees) {        this.degrees = degrees;    }
It's probably obvious, but here's what the Degree enum looks like:
public enum Degree {    BA,BS,BN,BSW,MA,MS,MBA,MSN,MSW,MD,JD,PhD,PharmD,PsyD,Other;}

Share Comments