Writing the changes automatically when the user makes any change through the UI is often the most convenient option, but it might have undesirable side effects – the user may see unsaved changes if some other part of the application uses the same business object instance. To prevent that, you either need to use a copy of the edited object or use manual writing to only update the object when the user wants to save.
The method reads values from a business object instance into the UI components.
Java
Assuming binder
has already been configured as in previous examples with a TextField
bound to the name property, this example would show the value “John Doe” in that field.
Even if the user has not edited a field, all validation errors will be shown if we explicitly validate the form or try to save the values to a business object.
Java
// This will make all current validation errors visible
BinderValidationStatus<Person> status = binder.validate();
if (status.hasErrors()) {
notifyValidationErrors(status.getValidationErrors());
}
Trying to write the field values to a business object will fail if any of the bound fields has an invalid value. There are different methods that let us choose how to structure the code for dealing with invalid values.
Handling a checked exception
Checking a return value
Java
boolean saved = binder.writeBeanIfValid(person);
if (saved) {
} else {
notifyValidationErrors(binder.validate().getValidationErrors());
}
Binder keeps track of which bindings have been updated by the user and which bindings are in an invalid state. It also fires an event when this status changes. We can use that event to make the save and reset buttons of our forms become enabled or disabled depending on the current status of the form.
Java
Automatic Saving
Java
Binder<Person> binder = new Binder<>();
// Field binding configuration omitted, it should be done here
Person person = new Person("John Doe", 1957);
binder.setBean(person);
Button saveButton = new Button("Save", event -> {
if (binder.validate().isOk()) {
// person is always up-to-date as long as there are no
// validation errors
MyBackend.updatePersonInDatabase(person);
}