Question

When I enter edit mode of my Table, I want to have data validation on all fields in that Table.

First, a couple of notes:

  • I'm using Vaadin 7, so the Bean Validation addon sadly won't work.
  • I know the implementation of JSR-303 works, because I tried adding a BeanValidator to a TextField without issues.

Now, I have a perfectly working table for which I am using a BeanItemContainer to keep my Person beans inside.

The Person bean looks as follows:

public class Person {

    @Size(min = 5, max = 50)
    private String firstName;

    @Size(min = 5, max = 50)
    private String lastName;

    @Min(0)
    @Max(2000)
    private int description;

    ... getters + setters...
}

Person beans are added to the BeanItemContainer, which in turn is set to the container data source with setContainerDataSource()

The BeanValidator was added to the table like so:

table.addValidator(new BeanValidator(Person.class, "firstName"));

When I run the application, I have two problems:

  1. When I run the application, the table shows up as intended. However, when I edit the fields and set one of the firstName fields to, say, "abc" - no validation error is shown and the value is accepted How am I supposed to get BeanValidator to work on all of my tables fields?

  2. When I use table.setSelectable(true) or table.setMultiSelect(true), I get this error:

    com.vaadin.server.ServiceException: java.lang.IllegalArgumentException: [] is not a valid value for property firstName of type class com.some.path.vaadinpoc.sampleapp.web.Person How am I supposed to get BeanValidator to work with Selectable/MultiSelect?

Please advice

Thanks!

Was it helpful?

Solution

You'll need to add the validators to the editable fields themselves, not to the table. (Table itself is a field => the Validator from table.addValidator validates the value of the Table => the value of the table is the selected itemId(s) => the BeanValidator fails)

You can add the validators to the fields that by using a custom TableFieldFactory on the table. Here's a very simple one-off example for this scenario - clearly, if you need to do this with a lot of different beans/tables, it'll be worth creating a more generic/customizable factory

  table.setTableFieldFactory(new DefaultFieldFactory() {
  @Override
  public Field<?> createField(Item item, Object propertyId, Component uiContext) {
    Field<?> field = super.createField(item, propertyId, uiContext);
    if (propertyId.equals("firstName")) {
      field.addValidator(new BeanValidator(Person.class, "firstName"));
    }
    if (propertyId.equals("lastName")) {
      field.addValidator(new BeanValidator(Person.class, "lastName"));
    }
    if (propertyId.equals("description")) {
      field.addValidator(new BeanValidator(Person.class, "description"));
    }
    return field;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top