package com.vaadin.data.fieldgroup;
import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
private Class<T> beanType;
private static Boolean beanValidationImplementationAvailable = null;
+ private final Map<Field<?>, BeanValidator> defaultValidators;
public BeanFieldGroup(Class<T> beanType) {
this.beanType = beanType;
+ this.defaultValidators = new HashMap<Field<?>, BeanValidator>();
}
@Override
return super.buildAndBind(caption, propertyId);
}
+ @Override
+ public void unbind(Field<?> field) throws BindException {
+ super.unbind(field);
+
+ BeanValidator removed = defaultValidators.remove(field);
+ if (removed != null) {
+ field.removeValidator(removed);
+ }
+ }
+
@Override
protected void configureField(Field<?> field) {
super.configureField(field);
// Add Bean validators if there are annotations
- if (isBeanValidationImplementationAvailable()) {
+ if (isBeanValidationImplementationAvailable()
+ && !defaultValidators.containsKey(field)) {
BeanValidator validator = new BeanValidator(beanType,
getPropertyId(field).toString());
field.addValidator(validator);
if (field.getLocale() != null) {
validator.setLocale(field.getLocale());
}
+ defaultValidators.put(field, validator);
}
}
package com.vaadin.tests.server.validation;
+import junit.framework.Assert;
+
import org.junit.Test;
import com.vaadin.data.Validator.InvalidValueException;
+import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.data.validator.BeanValidator;
import com.vaadin.tests.data.bean.BeanToValidate;
+import com.vaadin.ui.Field;
public class TestBeanValidation {
@Test(expected = InvalidValueException.class)
validator.validate("123.45");
}
+ @Test
+ public void testBeanValidationNotAddedTwice() {
+ // See ticket #11045
+ BeanFieldGroup<BeanToValidate> fieldGroup = new BeanFieldGroup<BeanToValidate>(
+ BeanToValidate.class);
+
+ BeanToValidate beanToValidate = new BeanToValidate();
+ beanToValidate.setFirstname("a");
+ fieldGroup.setItemDataSource(beanToValidate);
+
+ Field<?> nameField = fieldGroup.buildAndBind("firstname");
+ Assert.assertEquals(1, nameField.getValidators().size());
+
+ try {
+ nameField.validate();
+ } catch (InvalidValueException e) {
+ // NOTE: causes are empty if only one validation fails
+ Assert.assertEquals(0, e.getCauses().length);
+ }
+
+ // Create new, identical bean to cause duplicate validator unless #11045
+ // is fixed
+ beanToValidate = new BeanToValidate();
+ beanToValidate.setFirstname("a");
+ fieldGroup.setItemDataSource(beanToValidate);
+
+ Assert.assertEquals(1, nameField.getValidators().size());
+
+ try {
+ nameField.validate();
+ } catch (InvalidValueException e) {
+ // NOTE: if more than one validation fails, we get the number of
+ // failed validations
+ Assert.assertEquals(0, e.getCauses().length);
+ }
+
+ }
+
}