displaytag external paging/sorting and getting true row number

Michael C. Rosenstein picture Michael C. Rosenstein · Jun 8, 2009 · Viewed 10.3k times · Source

I'm using external paging/sorting with a custom TableDecorator and the following DisplayTag table in a JSP:

<display:table id="ixnlist" name="pageScope.itemList" sort="external"
  decorator="org.mdibl.ctd.pwa.displaytag.decorator.IxnTableWrapper">

   <display:column title="Row" property="rowNum" />

   ...more columns...
</display:table> 

In the table decorator, getListIndex() returns the row number relative only to the current page, not to the overall list (i.e., if we're displaying 100 objects per page, then getListIndex() returns "0" at the top of page 2, not "100").

/**
 * Returns the row number data for the current row.
 *
 * @return String containing row number heading.
 */
public String getRowNum() {
    final StringBuilder out = new StringBuilder(8);
    out.append(nf.format(getListIndex() + 1))
       .append('.');
    return out.toString();
}

Is it possible in the table decorator to somehow get the row number reflecting the correct offset? Displaytag is aware of the offset someplace, as it uses it to format the pagination links.

The displaytag docs do not address this question, and the ${row_rowNum} implicit object works identically to getListIndex() in the decorator.

Yes, it's possible to do this by adding a row-number column to the paginated SQL and having the TableDecorator use that if available, but I'd rather not rely on the DAO for that kind of metadata. The following TableDecorator method takes advantage of a rownum column if it exists, otherwise it uses getListIndex():

/**
 * Returns the row number data for the current row.
 *
 * @return String containing row number heading.
 */
public String getRowNum() {
    final StringBuilder out = new StringBuilder(8);
    final Map row = (Map) getCurrentRowObject();

    // Use 'rnum' column for external pagination if it exists.
    // Kludgy way of doing this.
    if (row.get("rnum") != null) {
        out.append(nf.format(row.get("rnum")));
    } else {
        out.append(nf.format(getListIndex() + 1));
    }
    out.append('.');
    return out.toString();
}

Thanks.

/mcr

Answer

Marcus Leon picture Marcus Leon · Jun 9, 2009

You should be able to calculate the correct overall index value by referencing the page number which is in the request.

Code something like this your TableDecorator class should work:

public String getIndex() {
   int numItemsPerPage = 100;
   int page = Integer.parseInt(getPageContext().getRequest().getParameter("page"));
   int index = getListIndex();

   return ((page - 1) * numItemsPerPage) + index + 1;
}