Thursday, 21 April 2011

tag h:selectOneMenu + converter

How to use JSF h:selectOneMenu with a custom converter. Full example included.






=========================================================
XHTML page:


<h:selectOneMenu converter="fooConverter" value="#{managedBean.boo.foo}">
  <f:selectItems value="#{managedBean.fooItems}" var="item" itemLabel="#{item.getLabel()}" itemValue="#{item.getValue().getId()}" />
</h:selectOneMenu> 

==========================================================
Converter:


@FacesConverter( value="fooConverter" )
public class FooConverter implements Converter {

 public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {

 if (submittedValue.trim().equals("")) {

 return null;

 } else {

 try {

  Integer fooId = Integer.parseInt(submittedValue);

  Foo foo = /*use fooId to get foo from DAO or Service Layer*/;
 return foo;

 } catch(Exception e) {

  e.printStackTrace();

 throw new ConverterException(new FacesMessage(
 FacesMessage.SEVERITY_ERROR,
"Conversion Error - Not a valid Foo",
e.getMessage()));

 } 

 }

 }

 

 public String getAsString(FacesContext facesContext, UIComponent component, Object value) {

 if (value == null)

 return null;

 else 

 return ""+((Foo)value).getId();

 }

}


=========================================================
Managed Bean:


//annotations
public class ManagedBean implements Serializable {
public List getFoos() {
List selectItems = new ArrayList();
for(Foo foo: findAllFoos() /*get all foos from DAO or Service Layer*/ ) {
selectItems.add(new SelectItem(foo, foo.getName()));
}
return selectItems;
}
}

=========================================================
Domain Object (POJO):


class Boo {
private Foo foo;
//constructor..
/getters/setters...
}

class Foo {
private Integer id;
private String name;
//constructor...
//getters/setters...
}

=========================================================

References:
http://javaserverfaces-spec-public.java.net/nonav/snapshots/jsf-spec-2.0-20090304/javadocs/javax/faces/model/SelectItem.html
http://www.crazysquirrel.com/computing/java/jsf/converters.jspx
http://balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html

No comments:

Post a Comment