HtmlPickList convert submittedValue to Object
nkr1pt Feb 16, 2009 6:01 PMHi,
I have a HtmlPickList that is bound to a List object called users, and it is filled with selectitems like this programmatically:
for (User user : userManager.createDummyUsers()) { SelectItem item = new SelectItem(user, user.getUsername()); users.add(item); }
the value is the user object, and the label is user.getUsername()
Also, a converter is registered on the picklist because it only accepts String objects:
<rich:pickList id="usersPickList" showButtonsLabel="false" rendered="false"> <f:selectItems value="#{selectUsersModule.users}" /> <f:converter converterId="UserConverter" /> </rich:pickList>
The code for the UserConverter looks like this:
public class UserConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String string) throws ConverterException { if (string == null || string.trim().equals("")) { return string; } User user = new User(); StringTokenizer hyphenTokenizer = new StringTokenizer(string, "-"); int hyphenCount = 0; while (hyphenTokenizer.hasMoreTokens()) { String token = hyphenTokenizer.nextToken(); if (hyphenCount == 0) { user.setUsername(token); } if (hyphenCount == 1) { user.setEmail(token); } hyphenCount++; } return user; } @Override public String getAsString(FacesContext context, UIComponent component, Object object) throws ConverterException { User user = null; if (object instanceof User) { user = (User)object; return user.getUsername() + "-" + user.getEmail(); } return ""; }
basically, the getAsString() method takes the username and email fields from the user object and creates a String from it in the format username-email, while the getAsObject() method does the exact opposite.
This seems to work fine when debugging.
Th eproblem is that a have a commandButton on the page whose action is not being called after the getAsObject() method from the converter completes.
When I leave the converter out of it or when setting immediate=true on the commandButton, the action method is being called just fine.
But in that case, I'm getting the submiitedValue from the picklist but the conversion didn't happen so it returns the value as a String instead of as a User object.
FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot viewRoot = context.getViewRoot(); UIComponent form = viewRoot.findComponent("form"); UIComponent selectUsersContainer = form.findComponent("selectUsersModule"); HtmlPickList pickList = (HtmlPickList)selectUsersContainer.findComponent("usersPickList"); pickList.setConverter(new UserConverter()); Object submittedValue = pickList.getSubmittedValue();
Here I would like submittedValue to be of type User instead of String.
What am I doing wrong?
Thx