Auto-generating a form based on a bean - Vaadin 6 style Form

In Vaadin 6 it is easy to get a completely auto generated form based on a bean instance by creating a BeanItem and passing that to a Form. Using FieldGroup this requires a few extra lines as FieldGroup never adds fields automatically to any layout but instead gives that control to the developer.

Given a bean such as this Person:

Java

  1. public class Person {
  2. private String firstName,lastName;
  3. private int age;
  4. // + setters and getters
  5. }

You can auto create a form using FieldGroup as follows:

Java

  1. public class AutoGeneratedFormUI extends UI {
  2. @Override
  3. public void init(VaadinRequest request) {
  4. VerticalLayout layout = new VerticalLayout();
  5. setContent(layout);
  6. FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
  7. // We need an item data source before we create the fields to be able to
  8. // find the properties, otherwise we have to specify them by hand
  9. fieldGroup.setItemDataSource(new BeanItem<Person>(new Person("John", "Doe", 34)));
  10. // Loop through the properties, build fields for them and add the fields
  11. // to this UI
  12. for (Object propertyId : fieldGroup.getUnboundPropertyIds()) {
  13. layout.addComponent(fieldGroup.buildAndBind(propertyId));
  14. }
  15. }
  16. }