Simple, direct way how to use SelectItems with Seam. (without custom annotations)
How to add EMPTY element into SelectItems.
@Name("listBean")
.......
private List listOfYourObjects;
private Map<String,Object> model;
.......
private void fillMaps(){
model = getModel();
model.clear();
model.put("(Empty)","-1"); // Add EMPTY element if needed
for (Object o: listOfYourObjects) {
String label = o.toString();
model.put(label, o );
}
}
public Map<String,Object> getModel(){ // f:selectItems value
if (model==null){
model = new TreeMap<String,Object>();
}
return model;
}
public Converter getConverter() {
return new ReferenceConverter(listOfYourObjects);
}
.......
ReferenceConverter implementation
package ###########;
import java.io.Serializable;
import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
public class ReferenceConverter implements Converter, Serializable{
private static final long serialVersionUID = -6268456071880135380L;
private static final String EMPTY = "__EMPTY__";
private List<Object> values;
public ReferenceConverter(List vals) {
this.values = vals;
}
public String getAsString(FacesContext facesContext,
UIComponent component,
Object obj)
{
if (obj == null) return EMPTY;
if ("-1".equals(obj)) return EMPTY;
String val = "" + obj.hashCode();
return val;
}
public Object getAsObject(FacesContext facesContext,
UIComponent component,
String str)
throws ConverterException
{
if (str == null || str.length()==0 || EMPTY.equals(str)) {
return null;
}
int hash = Integer.parseInt(str);
for (Object val : values) {
if ( val!=null && val.hashCode()==hash ) {
return val;
}
}
return null;
}
}
Usage on page:
<h:selectOneMenu value="#{value}" converter="#{listBean.converter}">
<f:selectItems value="#{listBean.model}" ></f:selectItems>
</h:selectOneMenu>
Comments