Hi all! Various UIComponents implements the ValueChangeListener interface, but when a value changes, I don’t found a way obtain the old value from this or another source.
Exist another method to obtain the old value? Or even a event that fires before the change, to prevent it in certain conditions?
I really shouldn’t try thinking about programming this late at night, but I guess you could always save the old value as a field inside the listener you add to the component - set it first in the constructor and then update it at every valid valuechangeevent and it should keep up to date. Or it could be some other data container, doesn’t really matter, as long as the listener has access to it. Depends on how and when you want to commit your changes (always? only when form is valid?) and what (if anything) you are using as the propertydatasource, I should think.
I think this approach is not really good, because when ValueChangeEvent occurs the component already has new value set. So after resetting it to the old value you will see the value chages from old to a new one and then back. Of course, it happens very fast, but anyway it is noticable and annoying. So I’d not recommend to use this approach. But t I’m not sure if it is possible to preventing value change in any other way. Could someone suggest any other way, please?
Otherwise, you would probably need to customize the UI component for this if you don’t want to keep track of the values yourself. When a ValueChangeEvent is fired, it is too late to prevent the change (modifications have already been made, potentially other listeners notified, …) so the most you could do would be to reset the old value based on some value you have cached.
Bumping this after many years, for Vaadin 7 reasons: I’m trying to create a simple
TextField that allows only
Double values to be stored in it, but the documentation for
DoubleValidator says:
@deprecated in Vaadin 7.0. Use an Double converter on the field instead.
Is there a way to simply prevent change (and maybe display an error notification) when a
Converter throws a
ConversionException ?
EDIT: I’ve written a small wrapper around TextField that does more or less what I want – it keeps track of the last “valid” value in a field. It doesn’t automatically revert to this value, though, which is maybe better design anyway.
// A TextField whose value is a decimal number.
public class NumberField extends TextField {
Double lastValid = 0.0;
public NumberField(String caption) {
super(caption);
setConverter(new StringToDoubleConverter());
}
public Double getDouble() {
try {
lastValid = (Double) getConvertedValue();
setComponentError(null);
} catch (Converter.ConversionException e) {
setComponentError(new UserError("Invalid number"));
}
return lastValid;
}
}