How do I select selectManyCheckBox to return something other than List <String>?

This is a template that I will use again and again if I earn it. I have a Log.LogKey enumeration name that I want the user to select instances of. So this person has the following:

<h:form id="testForm" > <h:selectManyCheckbox value="#{test.selectedKeys}" > <f:selectItems value="#{test.allKeys}" var="lk" itemLabel="#{lk.display}" itemValue="#{lk}" /> </h:selectManyCheckbox> <h:commandButton value="Do It" action="#{test.doNothng}" /> </h:form> 

The enumeration has a getter called getDisplay () . The selectItems attribute invokes this correctly because the row that receives the visualization for the user. And bean support has the following:

 public class Test implements Serializable { private List<Log.LogKey> selectedKeys = null; public List<Log.LogKey> getAllKeys() { return Arrays.asList(Log.LogKey.values()); } public List<Log.LogKey> getSelectedKeys() { return selectedKeys; } public void setSelectedKeys(List selected) { System.out.println("getSelecgedKeus() got " + selected.size()); int i = 0; for (Object obj : selected) { System.out.println(i++ + " is " + obj.getClass() + ":" + obj); } } public String doNothng() { return null; } 

}

So, in the submit form, the setSelectedKeys array (selected) is called with a list of strings, not a Log.LogKey list. The link to # {lk} in the selectItems tag converts the object to a string. What would be the right way to do this?

+4
source share
1 answer

You need to specify the converter. JSF EL is not aware of the general type of List because it is lost at runtime. When you do not explicitly specify a converter, JSF does not convert the presented String values ​​and simply populates their list.

In your specific case, you can use the built-in JSF EnumConverter , you just need the super() type of enum in the constructor:

 package com.example; import javax.faces.convert.EnumConverter; import javax.faces.convert.FacesConverter; @FacesConverter(value="logKeyConverter") public class LogKeyConverter extends EnumConverter { public LogKeyConverter() { super(Log.LogKey.class); } } 

To use it, simply declare it as follows:

 <h:selectManyCheckbox value="#{test.selectedKeys}" converter="logKeyConverter"> ... </h:selectManyCheckbox> 

See also:

+5
source

All Articles