13 Nov 2011

Working with af:iterator and HashMap values

In this post I'm going to show a couple of examples of using af:iterator component to render HashMap values. Let's say in my managed bean I have the following HashMap:
private Map m = new HashMap(); {
m.put("One",true);
m.put("Two",false);
m.put("Three",true);            
} 

The issue is to render selectBooleanCheckbox for each entry of the map.

In the same manged bean I've got the following getter method:
    public Object[] getMapEntries() {
       return m.entrySet().toArray();
   }

The method returns map's entries as an array. In the jspx code we are going to iterate over this array using af:iterator:
 <af:iterator value="#{ManagedBean.mapEntries}"
              var="row">

        <af:selectBooleanCheckbox text="#{row.key}"
                                 id="sbc2" value="#{row.value}"/>          
 </af:iterator>

And ... probably... that's all. But that would be Ok if we just wanted to render HasMap values in read only mode.

In order to be able to modify HashMap values we can use a little bit different approach. So, in the managed bean we have the following method:
    public Object[] getMapKeys() {
       return m.keySet().toArray();
   }

The method returns an array of the map's keys. And in jspx code we access to the map entries directly using key values:
 <af:iterator value="#{ManagedBean.mapKeys}"
              var="row">

        <af:selectBooleanCheckbox text="#{row}"
                                 id="sbc2" 
                    value="#{ManagedBean.map[row]}"/>          
 </af:iterator>

For sure, the managed bean should have getter method for the map like this:
    public Map getMap() {
       return m;
    }

That's all!