I think I found an issue with grid.addColumnReorderListener() and sorted columns. In the example I have three columns and the columns are sorted in another order as initial created. By adding the reorder-listener I want to get the new column order to be able to store it in the database. Everytime I call grid.setColumnOrder() the listener was triggered and that was the reason why I removed the listener before sorting and added it afterwards again.
I wrote a small example to reproduce it. Everytime listener.remove() and grid.addColumnReorderListener() is called the layout will be destoryed. Comment the two lines out, the layout is displayed correct.
Do I use it wrong or it is a bug? Is there another way to get the order of a grid?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomStringUtils;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.Grid.Column;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.data.provider.DataProvider;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.shared.Registration;
public class TestGrid extends VerticalLayout {
private Registration listener;
public TestGrid() {
List<Content> list = new ArrayList<>();
ListDataProvider<Content> dataProvider = DataProvider.ofCollection(list);
Grid<Content> grid = new Grid<>();
grid.setItems(dataProvider);
grid.setColumnReorderingAllowed(true);
for (int i = 0; i < 3; i++) {
Column<Content> column = grid.addColumn(data -> {
int length = (int)(Math.random() * 50);
char[] charSet = {'a','b','c','d'};
return RandomStringUtils.random(length, charSet);
});
column.setKey("key" + i);
column.setHeader("Header " + i);
column.setResizable(true);
}
grid.getColumnByKey("key2").setVisible(false);
final List<String> sortedColumns = Arrays.asList(new String[] { "key2", "key0", "key1"});
grid.setColumnOrder(sortedColumns.stream().map(c -> grid.getColumnByKey(c)).collect(Collectors.toList()));
listener = grid.addColumnReorderListener(listener -> {});
Button button = new Button("click");
button.addClickListener(l -> {
listener.remove(); // TODO remove this line and it is working
grid.getColumnByKey("key2").setVisible(true);
grid.setColumnOrder(sortedColumns.stream().map(c -> grid.getColumnByKey(c)).collect(Collectors.toList()));
listener = grid.addColumnReorderListener(listener -> {}); // TODO remove this line and it is working
list.clear();
list.add(new Content());
dataProvider.refreshAll();
});
add(button, grid);
}
private static class Content {
}
}