vaadin / flow-components

Java counterpart of Vaadin Web Components
99 stars 65 forks source link

Validate the dialog on confirm before closing #1497

Open heruan opened 5 years ago

heruan commented 5 years ago

When I add a confirm/reject/cancel listener, I should be able to prevent the dialog from closing if certain conditions aren't met. Something like:

var amount = new NumberField();
var dialog = new ConfirmDialog();
dialog.setHeader("How many items you want to ship?");
dialog.add(amount);
dialog.addConfirmListener(event -> {
    if (!amount.isValid()) {
        event.preventClosing();
    }
});

Another option could be set some sort of validation on the dialog itself, for example:

var amount = new NumberField();
var dialog = new ConfirmDialog();
dialog.setHeader("How many items you want to ship?");
dialog.add(amount);
dialog.addConfirmListener(event -> {
    if (!amount.isValid()) {
        dialog.setValid(false);
    }
});

Related to vaadin/vaadin-confirm-dialog-flow#55.

javier-godoy commented 3 years ago

The current implementation closes the dialog after dispatching a confirm event https://github.com/vaadin/vaadin-confirm-dialog/blob/master/src/vaadin-confirm-dialog.js#L347-L350

One workaround would be calling event.getSource().setOpened(true); from the confirmation listener (when the validation fails). That present an inconvenient flicker (since the dialog was already closed in the client-side while the server was processing the event).

Another approach is "overriding" the client-side method, after calling open():

dialog.open();
dialog.getElement().executeJs("return")
   .then(json->dialog.getElement().executeJs("this._confirm=function(){this.dispatchEvent(new CustomEvent('confirm'));}")); 

and then explicitly close() the dialog when the validation succeeds.

web-padawan commented 3 years ago

The correct solution on the client side would be allowing calling event.preventDefault on the confirm event.

See how this behavior is implemented in vaadin-overlay component.

joelpop commented 7 months ago

Yes, I would also like to be able to prevent the dialog from automatically closing upon pressing the confirm button. I also tried the "reopen" workaround and don't like the close/open flicker.

An alternative to a confirmEvent.preventDefault() call would be to have a setAutoCloseOnConfirm(false) method on the dialog itself.