views:

774

answers:

3

I have HTML table in JSF web application. I am generating rows dynamically using <ui:repeat>. I want a counter for each row. How can I get this? Any help?

Ssimilar to rowKeyVar in rich faces dataTable.

+1  A: 

You can't do it nicely with the ui:repeat, but you can do so with the h:dataTable. Bind the component to a UIData property in the backing bean. It has a getRowIndex() method which does exactly what you need:

<h:dataTable binding="#{bean.table}" value="#{bean.list}" var="item">
    <h:column><h:outputText value="#{bean.table.rowIndex + 1}" /></h:column>
    <h:column><h:outputText value="#{item.someProperty}" /></h:column>
    <h:column><h:outputText value="#{item.otherProperty}" /></h:column>
</h:dataTable>

Here I am adding 1 to UIData#getRowIndex() because it is zero-based. You may find the Using datatables article useful to learn more about datatables.

If you actually want a bit more control over the table layout (especially using colspans/rowspans, which are lacking in the real JSF h:dataTable tag), then an alternative is to use the JSTL c:forEach tag which has a varStatus attribute which gives you a handle to the loop status.

<table>
    <c:forEach items="#{bean.list}" var="item" varStatus="loop">
        <tr>
            <td><h:outputText value="#{loop.index + 1}" /></td>
            <td><h:outputText value="#{item.someProperty}" /></td>
            <td><h:outputText value="#{item.otherProperty}" /></td>
        </tr>
    </c:forEach>
</table>
BalusC
I will try the second approach. c:forEach. Thanks BalusC
abhishek
The major disadvantage of `c:forEach` is that you cannot use input components in the table easily. With a `h:dataTable` you can easily create an editable datatable and JSF will manage all the data collecting and updating fully itself.
BalusC
A: 

There is no counter for each row in ui:repeat. As BalusC said you can go for h:datatable. Another idea is indirectly you can add a additional index method in bean for each object in the list in serverside and get that in jsf and manipulate it.

valli
+2  A: 

Since you are using richfaces, you can do it with its iteration tag (<a4j:repeat>), which is a bit more appropriate than using <c:forEach>, and which is like an extension to <ui:repeat>

<table>
    <a4j:repeat value="#{bean.list}" var="item" rowKeyVar="idx">
        <tr>
            <td><h:outputText value="#{idx + 1}" /></td>
            <td><h:outputText value="#{item.someProperty}" /></td>
            <td><h:outputText value="#{item.otherProperty}" /></td>
        </tr>
    </c:forEach>
</table>
Bozho
Ah yes, he tagged RichFaces, but didn't tell about it in message. This is definitely preferred above `c:forEach`.
BalusC