8

How do I add a row-index column to a grid, that will not be sorted along user-sorting of rows?

The solution must not include changes to any polymer template, but should rather be done in java.

kscherrer
  • 5,486
  • 2
  • 19
  • 59

1 Answers1

8

Index starting at 0

grid.addColumn(TemplateRenderer.of("[[index]]"));

this works, because in the frontend part of the grid there already is an index property available for each row.


Index starting at 1

Edit: This is actually a much simpler way to achieve this than the way I proposed before. You can set a client side renderer for the Web Component with executeJS.
Yes it's still a bit "hacky", but it's still miles better than my own approach.

grid.addColumn(item -> "").setKey("rowIndex");

grid.addAttachListener(event -> {
    grid.getColumnByKey("rowIndex").getElement().executeJs(
            "this.renderer = function(root, column, rowData) {root.textContent = rowData.index + 1}"
    );
});

enter image description here


Related github and vaadin-forum threads:

https://vaadin.com/forum/thread/17471146/grid-start-row-count-from-1,
https://github.com/vaadin/vaadin-grid/issues/1386,
https://vaadin.com/forum/thread/18287678/vaadin-grid-exclude-specific-column-from-sorting,
https://github.com/vaadin/vaadin-grid-flow/issues/803

kscherrer
  • 5,486
  • 2
  • 19
  • 59
  • This is exactly what I needed. Thanks for providing detailed answer. I wonder why there is not a official way to do this, despite the question has been raised many times. I will test it out and update the results. – Aman Verma May 28 '20 at 11:08
  • The same issue is reported here: https://github.com/vaadin/vaadin-grid-flow/issues/803 – ollitietavainen May 28 '20 at 11:12
  • @kscherrer Yes just now tested. Works like a charm now. Appreciate your time and efforts. – Aman Verma May 28 '20 at 11:49
  • That's pretty cool hack. I didn't know that executing js using java on grid was possible this way. Thanks once again @kscherrer ! You saved my day. – Aman Verma May 28 '20 at 21:03
  • In case of grid is paginated. When I go to second page. The index starts from 1 again. Any way to continue the row index value in second page of paginated grid ? – Aman Verma Jun 17 '20 at 02:37
  • @AmanVerma Not sure how your pagination is set up and how it interferes with the `rowIndex`. I am not experienced with paginated grids and can't help you here. – kscherrer Jun 17 '20 at 06:46
  • No problem, thanks for the reply.. However I was using this paginated grid : https://vaadin.com/directory/component/grid-pagination/overview – Aman Verma Jun 17 '20 at 08:46