Ortzi
Ortzi

Reputation: 373

Vaadin combobox validation

I'm trying to validate the value of a combobox with Vaadin. My goal is to avoid committing the form with the selected object's 'myIntegerAttribute' field setted to null. Supose that the combobox stores 'MyBean' class objects.

I'm using a "FilterableListContainer" to bind the data. I tried this, but it seems that the validator is not being fired:

List<MyBean> myBeans = getMyBeansList();
FilterableListContainer filteredMyBeansContainer = new FilterableListContainer<MyBean>(myBeans);
comboBox.setContainerDataSource(filteredMyBeansContainer);
comboBox.setItemCaptionPropertyId("caption");
...
comboBox.addValidator(getMyBeanValidator("myIntegerAttribute"));
...
private BeanValidator getMyBeanValidator(String id){
    BeanValidator validator = new BeanValidator(MyBean.class, id);//TrafoEntity
    return validator;
}

class MyBean {
    String caption;
    Integer myIntegerAttribute;
    ...
}

I don't want to avoid selecting null value in the combobox.

How can I avoid commiting the null value?

Upvotes: 0

Views: 2163

Answers (2)

Alejandro C De Baca
Alejandro C De Baca

Reputation: 908

In Vaadin 7, you would use NullValidator to fail validation when the user's selection is null:

    NullValidator nv = new NullValidator("Cannot be null", false);
    comboBox.addValidator(nv);

To fail validation when a member of the object that corresponds to the user's selection is null, using BeanValidator you would include the @NotNull JSR-303 annotation on the bean class:

public class MyBean {

    String caption;

    @NotNull
    int myIntegerAttribute;

    // etc...
}

Are you using the FilterableListContainer from Viritin? I'm not sure why that would be preventing the validator from being used, but can you explain why you are using it with a combo box?

Upvotes: 1

Ortzi
Ortzi

Reputation: 373

I was implementing the validator in the wrong way. I created a class implementing Vaadin's 'Validator' class:

public class MyBeanValidator implements Validator {
    @Override
    public void validate(Object value) throws InvalidValueException {
        if (!isValid(value)) {
            throw new InvalidValueException("Invalid field");
        }
    }
    private boolean isValid(Object value) {
        if (value == null || !(value instanceof MyBean)
                || ((MyBean) value).getMyIntegerAttribute() == null ) {
            return false;
        }
        return true;
    }
}

And used it in the combobox:

combobox.addValidator(new MyBeanValidator());

Thank you for the answers!

Upvotes: 0

Related Questions