Grid: Find out which items have been edited (for persisting into the databa

I’ve implemented an editable grid in the same way as described in Vaadin’s doc “Editing Items Inside Grid”:

Binder<Todo> binder = grid.getEditor().getBinder();

Binding<Todo, Boolean> doneBinding = binder.bind(
    doneField, Todo::isDone, Todo::setDone);

Column<Todo, String> column = grid.addColumn(
    todo -> String.valueOf(todo.isDone()));

column.setEditorBinding(doneBinding);

All works fine, the edited data are written to my list of beans (items).

BUT: I would like to persist it also to the database. How can I …

  1. variant: … find out, which beans (items) have been changed/inserted/deleted by the grid? I would like to create a “Save Grid Data”-Button and this shouldn’t persist beans (items), that haven’t been changed.
  2. variant: … trigger persistence into the database just after changing/inserting/deleting a bean (item)?

The recommended way I think is to go with option 2.

If you are using buffered mode Grid editor, then you could hook into this event:

https://vaadin.com/download/release/8.3/8.3.2/docs/api/com/vaadin/ui/components/grid/Editor.html#addSaveListener-com.vaadin.ui.components.grid.EditorSaveListener-

Unfortunately I’m not using buffered mode.

But I’ve now solved it with a solution for variant 1:

I’ve written a Setter wrapper, which is a nested class of my CustomGrid. This setter has to be used in the binding. It adds the edited beans to a global HashSet of the CustomGrid:

	...
	
	private Set<Bean> editedBeans = new HashSet();
	
	...
	
	private class SetterWrapper<FieldValue> implements Setter<Bean, FieldValue> {
		
		private Setter<Bean, FieldValue> setter;
		private ValueProvider<Bean, FieldValue> correspondingGetter;
		
		public SetterWrapper(Setter<Bean, FieldValue> setter, ValueProvider<Bean, FieldValue> correspondingGetter) {
			this.setter = setter;
			this.correspondingGetter = correspondingGetter;
		}

		@Override
		public void accept(Bean bean, FieldValue fieldvalue) {
			if (!Objects.equals(fieldvalue, correspondingGetter.apply(bean))) {
				setter.accept(bean, fieldvalue);
				editedBeans.add(bean);
			}
		}
			
	}

Interesting solution.

For future reference, if you need edit (and other) events in un-buffered mode you can use this add-on

https://vaadin.com/directory/component/gridfastnavigation-add-on

Great! Thank you!