Monday, January 10, 2011

How to display Arraylist elements in a grid view in JSF

I recently came across a problem where I had to display elements of an ArrayList on a JSF page, in a table. I use Tomahawk JSF implementation. After some struggle, I was able to do it as given below

Let us take an example.
In my page bean I have an ArrayList having the below String elements

List listOfObjs = new ArrayList();

I wanted to display this in a table having 5 columns

Data1   Data2   Data3   Data4   Data5

Let us see how we can do this..

As we know, we cannot mix JSF and JSTL tags in a page, because that will lead to many issues as their lifecycles are different. My approach was to use Tomahawk DataList component, that lets you iterate over a list and then render table rows and columns using JSF code as shown below

        <t:htmlTag value="table">
                <t:dataList value="#{dataBean.listOfObjs}"
                        var="rowObj" rowIndexVar="rowNum" rowCountVar="totRowCount">
                        <f:verbatim rendered="#{rowNum%dataBean.maxCols==0}"><tr></f:verbatim>
                        <t:htmlTag value="td">
                                <h:outputText value="#{rowObj.valueToDisplay}">
                        <f:verbatim rendered="#{rowNum%dataBean.maxCols==dataBean.maxCols-1 ||(rowNum==totRowCount-1) }"></tr></f:verbatim>


It worked just fine.

Blog Archive