views:

721

answers:

3

Hi,

I have a HTML table that's generated in a JSP by the displaytag tag library. I would like to suppress any zeros that appear in the table, i.e. they should be replaced by a blank cell. Is there any straightforward way to achieve this?

Cheers, Don

A: 

To my knowledge there isn't an "straightforward" way of handling this. The only data-related config property is whether to display nulls or not.

You're better off handling this before the data gets to to the displaytag tag. Perhaps in the servlet that provides the data or a view helper class.

digitalsanctum
+1  A: 

Create a org.displaytag.decorator.TableDecorator instance, and place it into the table. Use the display:table tag's decorator attribute to place your fully qualified decorator class name into the table (I believe you can instantiate one and then place it in, but this class instantiation is trivial...make sure you have a no-arg constructor for this to work properly).

The methods initRow(...) or startRow() are where you would go through your table object, setting any zeroes you find to null (or, if displaying nulls, a blank space). I recommend initRow, but make sure you use super.initRow() first to easily access the current row object. The reason I recommend this is that startRow must return a String (defaults to returning a null string) which I don't think you need to do.

MetroidFan2002
The initRow() method you`ve suggested I override is declared final
Don
Is it? I only looked at the TableDecorator a second before posting this. However, if you can override startRow(), you can do everything in one place with a single decorator instantiation, rather than instantiating or configuring multiple column decorators.
MetroidFan2002
+1  A: 

I discovered that this can be achieved using a custom implementation of ColumnDecorator.

public class SuppressZeroDecorator implements DisplaytagColumnDecorator {

    /* (non-Javadoc)
     * @see org.displaytag.decorator.DisplaytagColumnDecorator#decorate(java.lang.Object, javax.servlet.jsp.PageContext, org.displaytag.properties.MediaTypeEnum)
     */
    public Object decorate(Object rowObject, PageContext pageContext, MediaTypeEnum mediaType) {

     if (rowObject != null && rowObject.toString().trim().equals("0")) {
      return null;
     }

     return rowObject;
    }
}

The decorator should be declared for each column in the JSP like this:

<display:column property="age" title="Age" decorator="com.example.ZeroColumnDecorator" />
Don