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

    1. // This will make all current validation errors visible
    2. BinderValidationStatus<Person> status = binder.validate();
    3. if (status.hasErrors()) {
    4. notifyValidationErrors(status.getValidationErrors());
    5. }

    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

    1. boolean saved = binder.writeBeanIfValid(person);
    2. if (saved) {
    3. } else {
    4. notifyValidationErrors(binder.validate().getValidationErrors());
    5. }

    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

    1. Binder<Person> binder = new Binder<>();
    2. // Field binding configuration omitted, it should be done here
    3. Person person = new Person("John Doe", 1957);
    4. binder.setBean(person);
    5. Button saveButton = new Button("Save", event -> {
    6. if (binder.validate().isOk()) {
    7. // person is always up-to-date as long as there are no
    8. // validation errors
    9. MyBackend.updatePersonInDatabase(person);
    10. }