GoProtege
GoProtege

Reputation: 93

JSF h:dataTable creates single empty cell when no records

Is there any way to prevent an h:datatable from creating an empty row when the backing value is empty? More specifically: I have a collection of data to be displayed in 3 columns in an h:dataTable with column headers. The thead always needs to be displayed, regardless of if there are elements in the list. This works fine, but when no elements are in the list, a single, empty row/cell is created in the tbody. Is there a way to prevent this?

Thanks!

Sample method from backing bean. For testing i've tried returning both null or an empty list. Same result for both.

    public List<LocationsDecorator> getLocations() {
    return null;
}

JSF fragment:

<h:dataTable styleClass="locations" id="locations1"
    var="nearestLoc" value="#{confirmationBean.locations}">
    <h:column>
        <!-- column header -->
        <f:facet name="header">Address</f:facet>
        <!-- row record -->
            #{nearestLoc.adddress}
        </h:column>
    <h:column>
        <!-- column header -->
        <f:facet name="header">Distance</f:facet>
        <!-- row record -->
            #{nearestLoc.distance}
        </h:column>
    <h:column>
        <!-- column header -->
        <f:facet name="header">Hours of Operation</f:facet>
        <!-- row record -->
        <h:dataTable styleClass="locations" var="data"
            value="#{nearestLoc.hoursOfOperation}">
            <h:column>     
                #{data}
                </h:column>
        </h:dataTable>

    </h:column>

</h:dataTable>

Resulting HTML(The "<tr><td></td></tr>" in the tbody is the problem):

<table id="contact:locations1" class="locations">
<thead>
<tr>
<th scope="col">Address</th>
<th scope="col">Distance</th>
<th scope="col">Hours of Operation</th>
</tr>
</thead>
<tbody>
<tr><td></td></tr></tbody>
</table>

Upvotes: 9

Views: 4315

Answers (3)

BalusC
BalusC

Reputation: 1108632

Specify a separate style for an empty table. E.g.

table.empty tbody td {
    border: 0;
}

And add it conditionally.

<h:dataTable ... styleClass="locations #{empty component.value ? 'empty' : ''}">

Upvotes: 5

licaomeng
licaomeng

Reputation: 947

Thanks for BalusC's suggestion, but I tried it, it did not work. It may be other reasons result in. I fixed BalusC's code a little, it works now:

table.locations.empty tbody td {
    border-color: rgba(0, 0, 0, 0);
}

Upvotes: 0

TaylorSmolik
TaylorSmolik

Reputation: 126

You might be able to avoid the column header disapearing if you instead wrap your method in an outputText tag

Example:

  <h:column>
    <!-- column header -->
    <f:facet name="header">Address</f:facet>
    <!-- row record -->
       <h:outputText value="#{nearestLoc.adddress}" />
    </h:column>

This way the column itself does not depend on the values

Upvotes: 0

Related Questions