private void bind(BEAN bean) {
setFieldValue(bean);
- onValueChange = getField()
- .addValueChangeListener(e -> storeFieldValue(bean, true));
+ onValueChange = getField().addValueChangeListener(e -> {
+ binder.setHasChanges(true);
+ storeFieldValue(bean, true);
+ });
}
@Override
private BinderStatusHandler statusHandler;
+ private boolean hasChanges = false;
+
/**
* Returns an {@code Optional} of the bean that has been bound with
* {@link #bind}, or an empty optional if a bean is not currently bound.
* nothing.
*/
public void unbind() {
+ setHasChanges(false);
if (bean != null) {
bean = null;
bindings.forEach(BindingImpl::unbind);
*/
public void load(BEAN bean) {
Objects.requireNonNull(bean, "bean cannot be null");
+ setHasChanges(false);
bindings.forEach(binding -> binding.setFieldValue(bean));
}
// Item validator failed, revert values
bindings.forEach((BindingImpl binding) -> binding.setBeanValue(bean,
oldValues.get(binding)));
+ } else {
+ // Save successful, reset hasChanges to false
+ setHasChanges(false);
}
return itemValidatorErrors;
}
}
}
+ /**
+ * Sets whether the values of the fields this binder is bound to have
+ * changed since the last explicit call to either bind, save or load.
+ *
+ * @param hasChanges
+ * whether this binder should be marked to have changes
+ */
+ private void setHasChanges(boolean hasChanges) {
+ this.hasChanges = hasChanges;
+ }
+
+ /**
+ * Check whether any of the bound fields' values have changed since last
+ * explicit call to bind, save or load. Unsuccessful save operations will
+ * not affect this value.
+ *
+ * @return whether any bound field's value has changed since last call to
+ * bind, save or load
+ */
+ public boolean hasChanges() {
+ return hasChanges;
+ }
}
Assert.assertEquals(1, results.size());
}
+ @Test
+ public void binderHasChanges() throws ValidationException {
+ binder.forField(nameField)
+ .withValidator(Validator.from(name -> !"".equals(name),
+ "Name can't be empty"))
+ .bind(Person::getFirstName, Person::setFirstName);
+ Assert.assertFalse(binder.hasChanges());
+ binder.bind(p);
+ Assert.assertFalse(binder.hasChanges());
+
+ nameField.setValue("foo");
+ Assert.assertTrue(binder.hasChanges());
+ binder.load(p);
+ Assert.assertFalse(binder.hasChanges());
+
+ nameField.setValue("bar");
+ binder.saveIfValid(new Person());
+ Assert.assertFalse(binder.hasChanges());
+
+ nameField.setValue("baz");
+ binder.save(new Person());
+ Assert.assertFalse(binder.hasChanges());
+
+ nameField.setValue("");
+ binder.saveIfValid(new Person());
+ Assert.assertTrue(binder.hasChanges());
+ }
}