Search code examples
javapopupreturn-valuevaadin23

Vaadin v.23 how to create a popup window that will return a value on closing


I am still learning Vaadin while trying to make my application. I have a button with click listener. Upon click it shall open a popup window, passing in an object. In this popup window I have several text fields and buttons to edit this object. I created a class extending VerticalLayout which contains these components. When popup windows closed, it should return updated object to the main layout. I can't find neither in Javadocs, nor in tutorials a way to do it. In older versions of Vaadin there was a component Window which does not longer exist. If someone can point me to the right direction, I will appreciate.


Solution

  • The component you are looking for is called Dialog. Dialogs don't have a "return value" (just like Windows in older versions) - you just maintain the state of the application to get the value the user has entered in the Dialog. If you want to do something when the Dialog is closed, you can use a listener for that.

    Example:

        private String name; 
    
        @Override
        public void openNameDialog() {
        
            Dialog dialog = new Dialog();
            TextField nameTextField = new TextField("Enter name");
            nameTextField.addValueChangeListener(e -> {
               name = e.getValue(); 
            });
            Button closeButton = new Button("close", e -> { dialog.close(); });
            dialog.add(nameTextField, closeButton);
            dialog.addOpenedChangeListener(e -> {
                // if dialog was closed
                if (!e.isOpened()) {
                    // do something with the `name` 
                    System.out.println("Value entered in Dialog: " + name);
                }
            });
            dialog.open();
        }