- A brief introduction to FieldGroup and BeanFieldGroup in Vaadin
- How bean validation is automatically done in BeanFieldGroup
- The basic challenges we face when using the bean validation
- Possible solutions to the challenges
Vaadin FieldGroup and BeanFieldGroup makes it super easy to develop data entry forms backed by a data model. You can find how to make use of this feature in the respective links listed above.
With BeanFieldGroup we can develop a data entry form backed by a bean item. In this case the data entered in the form will be stored in a POJO(Plain Old Java Object) which we provide. Support for buffering of data, discarding the changes if necessary is already provided by the FieldGroup implementation.
As the BeanFieldGroup is intended to use with a bean, it comes loaded with the facility to do Java Bean validation. The API implements the JSR-303 bean validation API. Actually the bean field group does not do magic. It just adds a validator which is a BeanValidator to every field it binds as shown below.
Person bean = new Person("Mung bean", 100); BeanItem<Person> item = new BeanItem<Person> (bean);
// Create a text field bound to a bean field TextField firstName = new TextField("First Name", item.getItemProperty("name")); // Add the bean validator firstName.addValidator(new BeanValidator(Person.class, "name")); firstName.setImmediate(true);
So if we instead use a BeanFieldGroup it will automatically do the above to add an appropriate validator when we bind the fields as shown below
// Have a bean Person bean = new Person("Mung bean", 100); // Form for editing the bean final BeanFieldGroup<Person> binder = new BeanFieldGroup<Person>(Person.class); binder.setItemDataSource(bean); layout.addComponent(binder.buildAndBind("Name", "name")); layout.addComponent(binder.buildAndBind("Age", "age"));
If we render the above form, the fields will be validated against whatever the constraints that we have defined in the Person bean using validation annotations( @NotNull, @Min, @Max etc).
Overcome firing the validation when the form is first loaded
One problem is the @NotNull validations will be fired up when the form is first rendered if the respective fields are null. Sometimes we do not want to fire all the validations when an empty form is displayed for the first time, but need validations to fire only when the form is submitted.
Usually when we add BeanValidators, Vaadin will fire up all the validations when the form fields are first rendered. This is the default behavior.
To overcome this what we can do is set the setValidationVisible(false) to initially suppress any validation errors and make them not visible. Later set this to true only when the form is first submitted.
field.setValidationVisible(false);
The above method is available in the AbstractField. So you need to cast any TextField, ComboBox or any other field component.