Saturday, August 29, 2009

richfaces pickList - converters

Here are a few things to remember when using richfaces pickList:

1. If the value of your selectItem is a non-String object type, then you need to write a converter. You can have a property on your backing bean to hold an instance of the converter, and you can point the pickList converter to use it.

Like below:

1. -------------- Converter ----------------------------

package org.fastkangaroo.quasimodo.converters;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.fastkangaroo.quasimodo.entities.UserProfile;

public class UserProfileConverter implements Converter {
private Map choiceMap;

public Object getAsObject(FacesContext arg0, UIComponent arg1, String label) {
return choiceMap.get(label);
}

public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
UserProfile userProfile = (UserProfile) obj;
String label = userProfile.getFirstName() + " " + userProfile.getLastName() + " " + userProfile.getMiddleName();
return label;
}

/**
* @param choiceMap the choiceMap to set
*/
public void setChoiceMap(Map choiceMap) {
this.choiceMap = choiceMap;
}

}


2. ------------------ Beacking Bean --------------------------

public class ProjectBean {

...
private UserProfileConverter userProfileConverter;

...

+ getter/setter
}




3. ------------------- XHTML ------------------

<rich:pickList id="memberPickList"
value="#{projectBean.selectedMembers}"
converter="#{projectBean.userProfileConverter}"
validator="#{projectBean.projectMembersValidator}" >
<f:selectItems value="#{projectBean.memberSelection}" />
</rich:pickList>

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I'm glad to read this post, only one question, in the BackingBean I just add this line:

    public UserProfileConverter getUserProfileConverter() {
    if(userProfileConverter==null){
    userProfileConverter= new UserProfileConverter();
    }
    return userProfileConverter;
    }

    Is that rigth?? Only this way let me continue.. in other case the server send me a message "add a converter to memberPickList". Saludos

    ReplyDelete