views:

213

answers:

2

I have a bean:

public ProjectServiceImpl {    
   public List<Project> getAllProjects () { ... }
}

I want to list all these projects as items in <h:selectManyListbox>. When user selects one or more items and press submit button, selected items should be converted into projects.

I'm confused a little about how to list items and how correspondent converter should look like?

+1  A: 

To list items in a <h:selectManyListbox> you need to use <f:selectItems> and point the value at a list of SelectItem objects.

The way I normally approach this is to loop through the projects and convert each project into a SelectItem. At the same time, I also store the projects in a HashMap using the SelectItem value as the key. Then when you need to get the list of project objects, you can loop through the selected values and grab the objects from the map.

If you do not want to create the HashMap, you can use the position of the Project in the List as the SelectItem value and look up the projects that way.

Colin Gislason
His problem is more how to use a non-standard object like `Project` as select item, not how to create select items.
BalusC
I just thought I'd give an alternative.
Colin Gislason
+1  A: 

You need to implement Converter#getAsString() so that the desired Java Object is been represented in an unique string representation which can be used as HTTP request parameter. Using the database technical ID (the primary key) is very useful here.

public String getAsString(FacesContext context, UIComponent component, Object value) {
    // Convert the Project object to its unique String representation.
    return String.valueOf(((Project) value).getId());
}

Then you need to implement Converter#getAsObject() so that the HTTP request parameter (which is per definition String) can be converted back to the desired Java Object (Project in your case)`.

public Object getAsObject(FacesContext context, UIComponent component, String value) {
    // Convert the unique String representation of Project to the actual Project object.
    return projectDAO.find(Long.valueOf(value));
}

Finally just associate this converter with the object type in question, JSF will then take care about conversion when Project comes into the picture no need to specify a converterId or a f:converter:

<converter>
    <converter-for-class>com.example.Project</converter-for-class>
    <converter-class>com.example.ProjectConverter</converter-class>
</converter>

This way you can just create SelectItem with Project as value.

You can get some background info and more ideas out of this blog article: http://balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html

BalusC