Multiple validator instances added to field when using JSR 303 validation

Hello,
I’m using Vaadin 7.0.0.beta11. I have a Form with BeanFieldGroup. It seems that validator instances are added to field every time fieldGroup.setItemDataSource() is called.

I’m using setItemDataSource() calls to change data bound to a form. The use case is that I have table that displays some bean data, and when I click on table row, all bean data should appear in a form for edit. So, in table’s itemClick() handler I do: fieldGroup.setItemDataSource(event.getItem()); The problem is, that for every click, another validator gets added for every field in the form.

I have created simple example to reproduce:


public class HelloWorld extends UI {
	private static final long serialVersionUID = 1L;

	@Override
	protected void init(VaadinRequest request) {

		VerticalLayout content = new VerticalLayout();
		setContent(content);

		final BeanFieldGroup<TestBean> fieldGroup = new BeanFieldGroup<TestBean>(TestBean.class);

		final FormLayout form = new FormLayout();
		form.addComponent(fieldGroup.buildAndBind("Name", "name"));
		content.addComponent(form);

		fieldGroup.setItemDataSource(new TestBean());
		fieldGroup.setItemDataSource(new TestBean());
	}

	public static class TestBean {

		@Size(min = 0, max = 5)
		private String name = "";

		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
}

The two calls to “fieldGroup.setItemDataSource(new TestBean());” will result in 2 validators added to form item, and 2 validator messages will be displayed on validation error.
Am I doing something wrong here?

Thanks.

Hi,
it is the protected method FieldGroup.configureField() overridden in BeanFieldGroup that will add the BeanValidators anew to the fields each time the item data source is changed. This appears to me as a flaw in the API since I too would expect setItemDataSource() to only change the data source and not the configuration of the field group. There is a workaround though that you could try: remove all validators from the fields before calling setItemDataSource():

for (Field field : fieldGroup.getFields()) {
    field.removeAllValidators();
}

fieldGroup.setItemDataSource(...);

It’s not particularly pretty, but it should work.

Thanks for your answer, I too came up with the solution of manually cleaning validators before calling fieldGroup.setItemDataSource(), but your code is more simple, and works :slight_smile:

But should I raise ticket for this? Doesn’t seems like this should be expected behavior…?

Yes, I think this should be reported. From my point of view, this seems like a flaw in the implementation.

I have the same problem. Have you already reported the bug?


New ticket opened