Implementing the update operation

The update CRUD operation is implemented through the Grid.Editor class. Enabling the editor is as easy as calling the following:

grid.getEditor().setEnabled(true);

However, the Editor needs a way to know what kind of input component to use for each column, and also where to get the values for these input components, and how to set the values back in the bean once the user edits them. This is done with the help of two methods: Grid.Editor.getBinder , and Grid.Column.setEditorBinding. You should be familiar with the Binder class in the Vaadin Framework; it is a utility class that allows you to connect setters and getters with input components, as well as validators, converters, and other configurations for data-binding. You can get the Binder instance by calling the getBinder method:

Binder<User> binder = grid.getEditor().getBinder();
The basic idea of the Binder class is that you can specify an input component and bind a getter and a setter:
binder.bind(textField, User::getFirstName, User::setLastName);.
If you are not familiar with the Binder class, go through the must-read documentation at: https://vaadin.com/docs/v8/framework/datamodel/datamodel-forms.html.

With the Editor enabled, we can set an input component for each column. For example, we can use a TextField for the First Name column using the setEditorBinding method as follows:

grid.addColumn(User::getFirstName)
.setCaption("First Name")
.setEditorBinding(binder
.forField(new TextField())
.bind(User::getFirstName, User::setFirstName));

The setEditorBinding accepts a Binding instance that we can easily get from the binder. We use the forField method in the Binder to specify a new TextFieldand the bind method, which returns an instance of Binding, to configure the corresponding getter and setter in the User bean. The end result is that when you double-click a row in the Grid, the Editor will present a new TextField in the first name cell, which will set its value to what User::getFirstName returns, and will call User::setFirstName, passing the value in the TextField when you click the Save button.

Be careful when you set several editor bindings and copy/paste code. You might forget to change one of the three method references, which would result in strange behaviors, such as values not being updated or values being updated in wrong fields in the bean.

In order to persist the edited User instance, we need to add an EditorSaveListener, which, conveniently, is a functional interface. We add this listener using the addSaveListener as follows:

grid.getEditor().addSaveListener(e -> save(e.getBean()));

The save method can be simply implemented as follows:

public class EditableGridCrud extends Composite {
...

private void save(User user) {
UserRepository.save(user);
refresh();
}
...
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset