Is there an easy way to add a row to a grid?

Hi

I am looking for a way to add a new row to a grid. I am able to edit a row using an editor but I can not add a row.

I am using CallbackDataProvider to fetch data.

Any tip much appreciated

Adam

You have to tell the dataprovider to update:

grid.getDataProvider().refreshAll();

to show the new state.

INPUTsys Chris Peter:
You have to tell the dataprovider to update:

grid.getDataProvider().refreshAll();

to show the new state.

I read rows from database using provider and attach the provider to a grid. Grid reflects read data. But how can I add a new bean to underlying collection of beans. If I could add a bean then I can refresh the grid to represent a new state.

Hi Adam

The Grid component has no means to add an item to your DB. If you want to add and delete items using a Grid, then I can recommend the [Crud]
(https://vaadin.com/components/vaadin-crud/java-examples) component. There you just have to define your own NewItemListener, DeleteListener, etc where you invoke the repository methods to actually add/delete items from DB.

All this is also possible with a Grid, but you will have to make your own “Add new” Button outside of the Grid, and implement it so that it adds an item to the db, and then refreshes the data provider of the grid. The point is that you don’t add the new item to the grid, but to your database, and then just refresh the grid. Here is some idea of how to do that

Button addNewItem = new Button("Add new item", click -> {
	Foo newItem = fooRepository.save(new Foo());
	fooGrid.getDataProvider().refreshAll();
}
Button deleteSelectedItems = new Button("Delete selected items", click -> {
	Set<Foo> selectedItems = fooGrid.getSelectedItems();
	for (Foo item : selectedItems) {
		fooRepository.delete(item);
	}
	fooGrid.getDataProvider().refreshAll();
});
// disable delete button if no item is selected
deleteSelectedItems.setEnabled(false);
fooGrid.addSelectionListener(event -> {
	deleteSelectedItems.setEnabled(event.getAllSelectedItems().size() > 0);
});