[GRID] How to create sums in header row

Hello everyone,
I’m trying to figure how to create, into my Grid, a header row with sums on certain columns.

I’ve searched on site and forum but I didn’t find anything.

Can someone help me please?
Thanks

Hi,

Grid has the method getDefaultHeaderRow(), which you can use to access the default header (which is probably what you want, unless you have multiple header rows). You can access a specific header cell with the HeaderRow method getCell(Object propertyId), which returns a Grid.HeaderCell object based on the property id of your grid’s container data source.

For example, here’s a code snippet that alters each header cell’s textual content to uppercase (Java8 syntax):

Grid.HeaderRow headerRow = grid.getDefaultHeaderRow();
grid.getColumns().forEach(column -> {
    String columnName = (String) column.getPropertyId();
    Grid.HeaderCell cell = headerRow.getCell(columnName);
    cell.setText(columnName.toUpperCase());
});

Note that you can even add components to the header row! In the above example, you could replace the cell.setText(…) row with cell.setComponent(new Button("A button in a grid's header!")); and that would work too.

Hope this helps!

Best regards,
Olli Tietäväinen
Vaadin Developer

Hello!
First of all, thanks for your reply.

I’ve already gathered the header row, and your example it’s ok for that.
What I’m missing is, at this point, how can i make a sum of all my row items?

For example:
I have some records in my grid

What I want is , into my header cell in this column, a total of 557 (which is the sum of all rows values).
Thanks !

Hi,

there are several ways to do that, but the right way depends on your application’s specifics. Generally speaking, you should iterate your records somehow outside the grid and then update the header to show the sum. The grid is built to support lazy loading, so you don’t get access to the individual rows that you could process in a loop. Instead, you might want to look at the grid’s container data source and calculate the sum from its items. In some cases, it could be better to get the sum directly from the backing database.

Best regards,
Olli

Ok, thanks for your help.
I’ll do that in the backend part, because I’m assuming that there’s nothing “build in” into vaadin to get a sum in a fast way like

myGrid.getColumnSum(columnName) , right?

Have a nice day, and thanks again for your time!

Yep, that’s right.

Have fun!