wasimbhalli wasimbhalli - 3 days ago 5
Java Question

How to bind object with h:selectManyCheckbox

I've an object, say Users, which has 10 properties, I want to bind it to h:selectManyCheckbox and want to display two specific fields of it as itemLabel & itemValue of f:selectItems. How can I do that? Please help!

Answer

Use the following in your facelet:

<h:selectManyCheckbox id="yourElementID"
                      value="#{myBean.selectedList}">
  <f:converter converterId="userConverter"/>
  <f:selectItems value="#{myBean.availableItemsList}"
                 var="item"
                 itemLabel="#{item.labelAttribute}"
                 itemValue="#{item.valueAttribute}"/>
</h:selectManyCheckbox>

Replace:

  • myBean with your bean's name

  • selectedList with the list that holds the selected values

  • availableItemsList with the list of
    your items available

  • labelAttribute with the attribute's
    name that you intend to use as item
    label.

  • valueAttribute with the attribute's name that you intend to use as item value

Notice that a converter is referenced in the f:converter element. A h:selectManyCheckbox returns Strings as value. So you need a converter for your User class that converts objects to strings and vice versa. You can implement it as inner class of your managed bean or as separate class.

@FacesConverter(value="userConverter")
public static class UserConverter implements Converter {
  public Object getAsObject(FacesContext facesContext, 
                    UIComponent component, String value) {
    // your code to convert String to Object
  }

  public String getAsString(FacesContext facesContext, 
                    UIComponent component, Object object) {
    // your code to convert Object to String
  }
Comments