This is one problem i faced when i worked with select-many and select-one menus in Java Server Faces. For any one who have worked with JSF knows that you have to use custom converters in order to populate select-many and select-on menus with ur own data types.
if i elaborate on this a little bit, Select menus are not just there to show simple value-label pairs. you can give directly an object to its value and one of its fields as the label. for an example,
public ArrayList<SelectItem> getLandSelectList() {
if (landSelectList != null) {
return landSelectList;
}
landSelectList = new ArrayList<SelectItem>();
List<Land> landList = this.getLandList();
for (int i = 0; i < landList.size(); i++) {
landSelectList.add(new SelectItem(landList.get(i), landList.get(i)
.getLandsName_DE()));
}
return landSelectList;
}
The returning Select list can be taken to a select one or a select many list box like..
<h:selectOneMenu id=”listBoxLand”
value=”#{userManagerBean.land}” required=”true”>
<f:selectItems value=”#{userManagerBean.landSelectList}” />
</h:selectOneMenu>
<h:message for=”listBoxLand” />
This component will set the selected land object directly to the backing bean. If you used simple value(some text or the id) – label pair. you should again query for the object from the selected id and save in the backing bean. but in this way that extra trouble will be handled by JSF.
The problem is if you do it just like this with out anything else.. you will get a wired validation error saying “Validation Error: Value is not valid“. This is where you start googling and debugging. Well after some hours of googling..(couldn’t do much debugging because this is a exception thrown by JSF framework) and reading about 10 to 20 forums i found out that the object which is loaded and the object wich was selected will be compared when setting to the backing bean. So if your object’s Class has not overridden the equals method this error message is shown.
So what you have to do is. if you are using your own data Objects for the select menus or in that case for any other JSF tag where you will use converters. You have to override the Equals method. Probably do the comparison with the Id, or with some unique value in that data Object. That’s it.. The problem solved. In my case the equals methods looks like
// overridden equals method
public boolean equals(Object obj) {
if (!(obj instanceof Land)) {
return false;
}
Land land = (Land) obj;return (this.id == land.id);
}
Yeah hope this will be useful to some one.. !! I will write another post on how to use Java Collections when working with Select-Many menus.