Search code examples
gwttwitter-bootstrap-3gwtbootstrap3

Set focus to an Input in a gwtbootstrap3 Modal


I want to set the focus to a certain field (org.gwtbootstrap3.client.ui.Input) in a dialog (org.gwtbootstrap3.client.ui.Modal) before the dialog shows up. The use case seem quite common, if you have a dialog with a single field like the Upload text or Add feed dialogs right here. However I could not figure out how to set the focus to this particular gwtbootstrap3 component.

The Input component does have a setFocus(true) method. I assumed that setting the focus before showing the dialog would not work, which it doesn't. So the logical solution is to put the method call inside a ScheduledCommand. Like this:

Scheduler.get().scheduleDeferred(new ScheduledCommand() {

    @Override
    public void execute() {
        textField.setFocus(true);
    }

});

That usually works with GWT standard components, but does not seem to help in this case. I found a way to get notified once the dialog is shown through a ModalShowHandler. Like this:

modal.addShowHandler(new ModalShowHandler() {

    @Override
    public void onShow(ModalShowEvent evt) {
        textField.setFocus(true);
    }

});

I even tried to combine both, adding a deferred call to the handle. No luck. Any ideas?


Solution

  • You should be listening on the ModalShownEvent (note: Shown, not Show).

    ModalShowEvent is fired when the modal is requested (for example, programmatically) to be shown.

    ModalShownEvent is fired when the modal is actually shown.

    This somewhat confusing naming is based on the events of the native Bootstrap Modal's events: show.bs.modal and shown.bs.modal.

    ModalShownEvent combined with the usual Scheduler#scheduleDeferred should do the trick.