Binding Data to Forms

A typical application lets the user fill out structured data and maybe also browse previously entered data. The data that is being entered is typically represented in code as an instance of a business object (bean), for instance a Person in an HR application.

Vaadin Framework provides a Binder class that the developer can use to define how the values in a business object should be bound to the fields shown in the user interface. Binder takes care of reading values from the business object and converting the user’s data between the format expected by the business object and the format expected by the field. The input entered by the user can also be validated, and the current validation status can be presented to the user in different ways.

Tip
Watch the Vaadin 8: Data binding and validation free training video to learn more about creating simple and complex forms, value conversion and validation, and how the Vaadin data model works.

The first step to binding fields for a form is to create a Binder and bind some input fields. There is only one Binder instance for each form and it is used for all fields in that form.

Java

  1. Binder<Person> binder = new Binder<>();
  2. TextField titleField = new TextField();
  3. // Start by defining the Field instance to use
  4. binder.forField(titleField)
  5. // Finalize by doing the actual binding to the Person class
  6. .bind(
  7. // Callback that loads the title from a person instance
  8. Person::getTitle,
  9. // Callback that saves the title in a person instance
  10. Person::setTitle));
  11. TextField nameField = new TextField();
  12. // Shorthand for cases without extra configuration
  13. binder.bind(nameField, Person::getName, Person::setName);

When we have bound field components using our binder, we can use the binder to load values from a person into the field, let the user edit the values and finally save the values back into a person instance.

Java

  1. // The person to edit
  2. // Would be loaded from the backend in a real application
  3. Person person = new Person("John Doe", 1957);
  4. // Updates the value in each bound field component
  5. binder.readBean(person);
  6. Button saveButton = new Button("Save",
  7. event -> {
  8. try {
  9. binder.writeBean(person);
  10. // A real application would also save the updated person
  11. // using the application's backend
  12. } catch (ValidationException e) {
  13. Notification.show("Person could not be saved, " +
  14. "please check error messages for each field.");
  15. }
  16. });
  17. // Updates the fields again with the previously saved values
  18. Button resetButton = new Button("Reset",
  19. event -> binder.readBean(person));

With these basic steps, we have defined everything that is needed for loading, editing and saving values for a form.

The above example uses Java 8 method references for defining how field values are loaded and saved. It is also possible to use a lambda expression or an explicit instance of the callback interface instead of a method reference.

Java

  1. // With lambda expressions
  2. binder.bind(titleField,
  3. person -> person.getTitle(),
  4. (person, title) -> person.setTitle(title));
  5. // With explicit callback interface instances
  6. binder.bind(nameField,
  7. new ValueProvider<Person, String>() {
  8. @Override
  9. public String apply(Person person) {
  10. return person.getName();
  11. }
  12. },
  13. new Setter<Person, String>() {
  14. @Override
  15. public void accept(Person person, String name) {
  16. person.setName(name);
  17. }
  18. });

Binding non-modifiable Data

Non-modifiable data can be also bound to any component or component property with ReadOnlyHasValue helper class. For example, Panel caption can display a person full name:

Java

  1. Panel infoPanel = new Panel();
  2. ReadOnlyHasValue<Person> panelTitle = new ReadOnlyHasValue<>(
  3. person -> infoPanel.setCaption(person.getLastName() + ", " + person.getFirstName()));
  4. binder.forField(panelTitle).bind(person -> person, null);

Validating and Converting User Input

Binder supports checking the validity of the user’s input and converting the values between the type used in business objects and the bound UI components. These two concepts go hand in hand since validation can be based on a converted value, and being able to convert a value is a kind of validation.

Validation

An application typically has some restrictions on exactly what kinds of values the user is allowed to enter into different fields. Binder lets us define validators for each field that we are binding. The validator is by default run whenever the user changes the value of a field, and the validation status is also checked again when saving.

Validators for a field are defined between the forField and bind steps when a binding is created. A validator can be defined using a Validator instance or inline using a lambda expression.

Java

  1. binder.forField(emailField)
  2. // Explicit validator instance
  3. .withValidator(new EmailValidator(
  4. "This doesn't look like a valid email address"))
  5. .bind(Person::getEmail, Person::setEmail);
  6. binder.forField(nameField)
  7. // Validator defined based on a lambda and an error message
  8. .withValidator(
  9. name -> name.length() >= 3,
  10. "Full name must contain at least three characters")
  11. .bind(Person::getName, Person::setName);
  12. binder.forField(titleField)
  13. // Shorthand for requiring the field to be non-empty
  14. // This is conditional on Binding::setAsRequiredEnabled(boolean)
  15. .asRequired("Every employee must have a title")
  16. .bind(Person::getTitle, Person::setTitle);
Note
Binder.forField works like a builder where forField starts the process, is followed by various configuration calls for the field and bind acts as the finalizing method which applies the configuration.

The validation state of each field is updated whenever the user modifies the value of that field. The validation state is by default shown using AbstractComponent.setComponentError which is used by the layout that the field is shown in. Whenever an error is set, the component will also get a v-<component>-error class name, e.g. v-textfield-error. This error class will by default add a red border on the component. The component will also get a tooltip that shows the error message text.

We can also customize the way a binder displays error messages to get more flexibility than what setComponentError provides. The easiest way of customizing this is to configure each binding to use its own Label that is used to show the status for each field.

Note
The status label is not only used for validation errors but also for showing confirmation and helper messages.

Java

  1. Label emailStatus = new Label();
  2. binder.forField(emailField)
  3. .withValidator(new EmailValidator(
  4. "This doesn't look like a valid email address"))
  5. // Shorthand that updates the label based on the status
  6. .withStatusLabel(emailStatus)
  7. .bind(Person::getEmail, Person::setEmail);
  8. Label nameStatus = new Label();
  9. binder.forField(nameField)
  10. // Define the validator
  11. .withValidator(
  12. name -> name.length() >= 3,
  13. "Full name must contain at least three characters")
  14. // Define how the validation status is displayed
  15. .withValidationStatusHandler(status -> {
  16. nameStatus.setValue(status.getMessage().orElse(""));
  17. nameStatus.setVisible(status.isError());
  18. })
  19. // Finalize the binding
  20. .bind(Person::getName, Person::setName);

It is possible to add multiple validators for the same binding. The following example will first validate that the entered text looks like an email address, and only for seemingly valid email addresses it will continue checking that the email address is for the expected domain.

Java

  1. binder.forField(emailField)
  2. .withValidator(new EmailValidator(
  3. "This doesn't look like a valid email address"))
  4. .withValidator(
  5. email -> email.endsWith("@acme.com"),
  6. "Only acme.com email addresses are allowed")
  7. .bind(Person::getEmail, Person::setEmail);

In some cases, the validation of one field depends on the value of some other field. We can save the binding to a local variable and trigger a revalidation when another field fires a value change event.

Java

  1. Binder<Trip> binder = new Binder<>();
  2. DateField departing = new DateField("Departing");
  3. DateField returning = new DateField("Returning");
  4. // Store return date binding so we can revalidate it later
  5. Binder.BindingBuilder<Trip, LocalDate> returnBindingBuilder = binder.forField(returning)
  6. .withValidator(returnDate -> !returnDate.isBefore(departing.getValue()),
  7. "Cannot return before departing");
  8. Binder.Binding<Trip, LocalDate> returnBinder = returnBindingBuilder.bind(Trip::getReturnDate, Trip::setReturnDate);
  9. // Revalidate return date when departure date changes
  10. departing.addValueChangeListener(event -> returnBinder.validate());

Conversion

You can also bind application data to a UI field component even though the types do not match. In some cases, there might be types specific for the application, such as custom type that encapsulates a postal code that the user enters through a TextField. Another quite typical case is for entering integer numbers using a TextField or a Slider. Similarly to validators, we can define a converter using a Converter instance or inline using lambda expressions. We can optionally specify also an error message.

Java

  1. TextField yearOfBirthField = new TextField("Year of birth");
  2. binder.forField(yearOfBirthField)
  3. .withConverter(
  4. new StringToIntegerConverter("Must enter a number"))
  5. .bind(Person::getYearOfBirth, Person::setYearOfBirth);
  6. // Slider for integers between 1 and 10
  7. Slider salaryLevelField = new Slider("Salary level", 1, 10);
  8. binder.forField(salaryLevelField)
  9. .withConverter(Double::intValue, Integer::doubleValue)
  10. .bind(Person::getSalaryLevel, Person::setSalaryLevel);

Multiple validators and converters can be used for building one binding. Each validator or converter is used in the order they were defined for a value provided by the user. The value is passed along until a final converted value is stored in the business object, or until the first validation error or impossible conversion is encountered. When updating the UI components, values from the business object are passed through each converter in the reverse order without doing any validation.

Note
A converter can be used as a validator but for code clarity and to avoid boilerplate code, you should use a validator when checking the contents and a converter when modifying the value.

Java

  1. binder.forField(yearOfBirthField)
  2. // Validator will be run with the String value of the field
  3. .withValidator(text -> text.length() == 4,
  4. "Doesn't look like a year")
  5. // Converter will only be run for strings with 4 characters
  6. .withConverter(
  7. new StringToIntegerConverter("Must enter a number"))
  8. // Validator will be run with the converted value
  9. .withValidator(year -> year >= 1900 && year < 2000,
  10. "Person must be born in the 20th century")
  11. .bind(Person::getYearOfBirth, Person::setYearOfBirth);

You can define your own conversion either by using callbacks, typically lambda expressions or method references, or by implementing the Converter interface.

When using callbacks, there is one for converting in each direction. If the callback used for converting the user-provided value throws an unchecked exception, then the field will be marked as invalid and the message of the exception will be used as the validation error message. Messages in Java runtime exceptions are typically written with developers in mind and might not be suitable to show to end users. We can provide a custom error message that is used whenever the conversion throws an unchecked exception.

Java

  1. binder.forField(yearOfBirthField)
  2. .withConverter(
  3. Integer::valueOf,
  4. String::valueOf,
  5. // Text to use instead of the NumberFormatException message
  6. "Please enter a number")
  7. .bind(Person::getYearOfBirth, Person::setYearOfBirth);

There are two separate methods to implement in the Converter interface. convertToModel receives a value that originates from the user. The method should return a Result that either contains a converted value or a conversion error message. convertToPresentation receives a value that originates from the business object. Since it is assumed that the business object only contains valid values, this method directly returns the converted value.

Java

  1. class MyConverter implements Converter<String, Integer> {
  2. @Override
  3. public Result<Integer> convertToModel(String fieldValue, ValueContext context) {
  4. // Produces a converted value or an error
  5. try {
  6. // ok is a static helper method that creates a Result
  7. return Result.ok(Integer.valueOf(fieldValue));
  8. } catch (NumberFormatException e) {
  9. // error is a static helper method that creates a Result
  10. return Result.error("Please enter a number");
  11. }
  12. }
  13. @Override
  14. public String convertToPresentation(Integer integer, ValueContext context) {
  15. // Converting to the field type should always succeed,
  16. // so there is no support for returning an error Result.
  17. return String.valueOf(integer);
  18. }
  19. }
  20. // Using the converter
  21. binder.forField(yearOfBirthField)
  22. .withConverter(new MyConverter())
  23. .bind(Person::getYearOfBirth, Person::setYearOfBirth);

The provided ValueContext can be used for finding Locale to be used for the conversion.

Loading from and Saving to Business Objects

Once all bindings have been set up, you are ready to actually fill the bound UI components with data from your business object. Changes can be written to the business object automatically or manually.

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.

Manual Reading and Writing

The readBean method reads values from a business object instance into the UI components.

Java

  1. Person person = new Person("John Doe", 1957);
  2. binder.readBean(person);

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.

To avoid showing lots of errors to the user, validation errors are not shown until the user edits each field after the form has been bound or loaded.

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. Notification.show("Validation error count: "
  5. + status.getValidationErrors().size());
  6. }

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

Java

  1. try {
  2. binder.writeBean(person);
  3. MyBackend.updatePersonInDatabase(person);
  4. } catch (ValidationException e) {
  5. Notification.show("Validation error count: "
  6. + e.getValidationErrors().size());
  7. }

Checking a return value

Java

  1. boolean saved = binder.writeBeanIfValid(person);
  2. if (saved) {
  3. MyBackend.updatePersonInDatabase(person);
  4. } else {
  5. Notification.show("Validation error count: "
  6. + binder.validate().getValidationErrors().size());
  7. }
Note
Note, if you need to write the values passing the validation regardless of having one or more failing validators, you can use binder.writeBeanAsDraft(person).

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

  1. binder.addStatusChangeListener(event -> {
  2. boolean isValid = event.getBinder().isValid();
  3. boolean hasChanges = event.getBinder().hasChanges();
  4. saveButton.setEnabled(hasChanges && isValid);
  5. resetButton.setEnabled(hasChanges);
  6. });

Automatic Saving

Instead of manually saving field values to a business object instance, we can also bind the values directly to an instance. In this way, Binder takes care of automatically saving values from the fields.

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. // Loads the values from the person instance
  5. // Sets person to be updated when any bound field is updated
  6. binder.setBean(person);
  7. Button saveButton = new Button("Save", event -> {
  8. if (binder.validate().isOk()) {
  9. // person is always up-to-date as long as there are no
  10. // validation errors
  11. MyBackend.updatePersonInDatabase(person);
  12. }
  13. });
Warning
When using the setBean method, the business object instance will be updated whenever the user changes the value in any bound field. If some other part of the application is also using the same instance, then that part might show changes before the user has clicked the save button.

Binding Beans to Forms

The business objects used in an application are in most cases implemented as Java beans or POJOs. There is special support for that kind of business object in Binder. It can use reflection based on bean property names to bind values. This reduces the amount of code you have to write when binding to fields in the bean.

Java

  1. Binder<Person> binder = new Binder<>(Person.class);
  2. // Bind based on property name
  3. binder.bind(nameField, "name");
  4. // Bind based on sub property path
  5. binder.bind(streetAddressField, "address.street");
  6. // Bind using forField for additional configuration
  7. binder.forField(yearOfBirthField)
  8. .withConverter(
  9. new StringToIntegerConverter("Please enter a number"))
  10. .bind("yearOfBirth");
Note
Code using strings to identify properties will cause exceptions during runtime if the string contains a typo or if the name of the setter and getter methods have been changed without also updating the string.

If you have a Bean Validation implementation available in your classpath and want to use JSR 303 Bean Validation annotations then a BeanValidationBinder should be used. BeanValidationBinder extends Binder class so it has the same API but its implementation automatically adds a bean validator which takes care of JSR 303 constraints. Constraints defined for properties in the bean will work in the same way as if configured when the binding is created.

Java

  1. public class Person {
  2. @Max(2000)
  3. private int yearOfBirth;
  4. //Non-standard constraint provided by Hibernate Validator
  5. @NotEmpty
  6. private String name;
  7. // + other fields, constructors, setters, and getters
  8. ...
  9. }

Java

  1. BeanValidationBinder<Person> binder = new BeanValidationBinder<>(Person.class);
  2. binder.bind(nameField, "name");
  3. binder.forField(yearOfBirthField)
  4. .withConverter(
  5. new StringToIntegerConverter("Please enter a number"))
  6. .bind("yearOfBirth");

Constraint annotations can also be defined on the bean level instead of being defined for any specific property.

There are some number of predefined constraint annotations that mark a bound field as required using BeanValidationBinder.setRequiredIndicatorVisible. By default @NotNull, @NotEmpty and @Size (if min() value is greater than 0) configures the field as required. It’s possible to change this behavior using the BeanValidationBinder.setRequiredConfigurator method.

Note
Bean level validation can only be performed once the bean has been updated. This means that this functionality can only be used together with setBean. You need to trigger validation manually if using readBean and writeBean.

Validation errors caused by that bean level validation might not be directly associated with any field component shown in the user interface, so Binder cannot know where such messages should be displayed.

Similarly to how the withStatusLabel method can be used for defining where messages for a specific binding should be showed, we can also define a Label that is used for showing status messages that are not related to any specific field.

Java

  1. Label formStatusLabel = new Label();
  2. Binder<Person> binder = new Binder<>(Person.class);
  3. binder.setStatusLabel(formStatusLabel);
  4. // Continue by binding fields

We can also define our own status handler to provide a custom way of handling statuses.

Java

  1. // We will first set the status label's content mode to HTML
  2. // in order to display generated error messages separated by a <br> tag
  3. formStatusLabel.setContentMode(ContentMode.HTML);
  4. BinderValidationStatusHandler<Person> defaultHandler = binder.getValidationStatusHandler();
  5. binder.setValidationStatusHandler(status -> {
  6. // create an error message on failed bean level validations
  7. List<ValidationResult> errors = status.getBeanValidationErrors();
  8. // collect all bean level error messages into a single string,
  9. // separating each message with a <br> tag
  10. String errorMessage = errors.stream().map(ValidationResult::getErrorMessage)
  11. // sanitize the individual error strings to avoid code injection
  12. // since we are displaying the resulting string as HTML
  13. .map(errorString -> Jsoup.clean(errorString, Whitelist.simpleText()))
  14. .collect(Collectors.joining("<br>"));
  15. // finally, display all bean level validation errors in a single label
  16. formStatusLabel.setValue(errorMessage);
  17. formStatusLabel.setVisible(!errorMessage.isEmpty());
  18. // Let the default handler show messages for each field
  19. defaultHandler.statusChange(status);
  20. });

Using Binder with Declarative Layouts

We can use Binder to connect data to a form that is defined in the declarative format.

This is the design HTML file that we can create using Vaadin Designer:

HTML

  1. <vaadin-form-layout size-full>
  2. <vaadin-text-field _id="name"
  3. caption="Name"></vaadin-text-field>
  4. <vaadin-text-field _id="yearOfBirth"
  5. caption="Year of birth"></vaadin-text-field>
  6. <vaadin-button _id="save">
  7. Save
  8. </vaadin-button>
  9. </vaadin-form-layout>

This is the companion Java file that Vaadin Designer creates for us based on the design.

Java

  1. @DesignRoot
  2. @AutoGenerated
  3. public class PersonFormDesign extends FormLayout {
  4. protected TextField name;
  5. protected TextField yearOfBirth;
  6. protected Button save;
  7. public PersonFormDesign() {
  8. Design.read(this);
  9. }
  10. }

Based on those files, we can create a subclass of the design that uses a Binder to automatically connect bean properties to field instances. This will look at all instance fields that are of a Field type in the class and try to find a bean property with the same name.

Java

  1. public class PersonForm extends PersonFormDesign {
  2. private Binder<Person> binder
  3. = new Binder<>(Person.class);
  4. public PersonForm(Person person) {
  5. binder.bindInstanceFields(this);
  6. binder.readBean(person);
  7. save.addClickListener(event -> {
  8. if (binder.writeBeanIfValid(person)) {
  9. MyBackend.updatePersonInDatabase(person);
  10. }
  11. });
  12. }
  13. }

We can also bind some of the fields before calling bindInstanceFields. In this way, fields that require special configuration can still be configured manually while regular fields can be configured automatically.

Java

  1. binder.forField(yearOfBirth)
  2. .withConverter(
  3. new StringToIntegerConverter("Please enter a number"))
  4. .bind(Person::getYearOfBirth, Person::setYearOfBirth));
  5. binder.bindInstanceFields(this);
Note
If you need to bind nested proprerties with bindInstanceFields method, you need to instantiate the Binder using:

Java

  1. Binder<Person> binder = new Binder<>(Person.class,true);