Vaadin Flow revert / undo value change without firing listener again

Viewed 254

(Using Vaadin 18)

I have a value change listener on a combobox that opens a confirm dialog, allowing the user to confirm the change. Because this is within a value change listener, the value has technically already changed. Thus when they select "No" I need to revert the value. There doesn't appear to be any part of the API that can do this, aside from manually setting the value.

But when reverting via setValue(...) the listener fires a second time. I need to prevent it from firing again. Currently the only way I'm able to do it is with an extra "ignoreNextChange" boolean variable, which prevents the logic from running a second time. Is there an easier way to do this? I don't see anyway to add a listener that fires before the value change.

I can't simply ignore all non-client changes, because that breaks the binder. And altering the listener registration won't work from inside the listener because I would also need to add it back, which would cause it to fire anyway.

2 Answers

You are right to assume, that you can not prevent the propagation of the change inside an value change handler (it's happening after the fact).

Your main options are:

  • You react only to "human made" change (from the client). See isFromClient inside the `ValueChangeEvent

  • Or de-couple the UI from the action (give the User some UI to request the change, ask again, then do the change) -- this could be done with a number of ways. One way to do that could be writing your own field wrapping the combo box and only fire a change once the selection is confirmed.

I assume you're using unbuffered Binder, with binder.setBean()? That has the underlying assumption that every write happens directly after the field value changes, not after a "confirm" step. If you want to delay the write (buffered binding), you should use binder.writeBean(bean) once you're ready. Note that this should be done without calling setBean.

Related