Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsf working with collection/map

Can I bind my h:dataTable/rich:dataTable with some Map? I found that h:dataTable can work only with List object and deleting in List can be very heavy.

like image 784
udar_molota Avatar asked Jun 12 '12 13:06

udar_molota


2 Answers

If you want to have only one method in your backing bean that provides the map, you can do something like this:

class Bean {
  public Map<T,U> getMap() {
    return yourMap;
  }
}

and use this in your JSF view

<h:dataTable value="#{bean.map.keySet().toArray()}" var="key"> 
   <h:outputText value="#{bean.map[key]}"/> 
</h:dataTable>

This converts the key set into an array, which can be iterated by the datatable. Using the "()"-expression requires Unified Expression Language 2 (Java EE 6).

like image 200
tine2k Avatar answered Sep 22 '22 10:09

tine2k


Yes, that's right. dataTable, ui:repeat and friends only work with Lists.

You can just add a managed bean method that puts map.keySet() or map.values() into a list depending on which you want to iterate over.

Typically when I want to iterate a map from a JSF view, I do something like

<h:dataTable value="#{bean.mapKeys}" var="key"> 
   <h:outputText value="#{bean.map[key]}"/> 
</h:dataTable>

with managed bean property

class Bean {
   public List<T> mapKeys() {
     return new ArrayList<T>(map.keySet());
   }
} 

or something like that.

Of course, this makes the most sense if you're using something like TreeMap or LinkedHashMap that preserves ordering.

like image 29
wrschneider Avatar answered Sep 22 '22 10:09

wrschneider