Time for action – the Dialog component close event listener

Let us see how we can register a listener for the close event using the following steps:

  1. Create a Dialog component and register a close event listener using the <p:ajax> tag:
    <h:form id="form3" style="width: 400px;">
      <p:messages id="msgs" for="SampleDialog"/>
      <p:panel header="Dialog - Close Event Listener">
        <p:commandButton value="ShowDialog" onclick="dlg3.show();" type="button" /> 
        
        <p:dialog id="SampleDialog" header="Sample Dialog" widgetVar="dlg3" width="300" height="50" 
              showEffect="bounce"  hideEffect="explode" closeOnEscape="true">
          <p:ajax event="close" update="msgs" listener="#{dialogController.handleDialogClose}"/>
          <p:outputLabel value="PrimeFaces Dialog"/> 
        </p:dialog>
      </p:panel>
    </h:form>
  2. Implement the handleDialogClose() method to handle the close event:
    public void handleDialogClose(CloseEvent event) 
    {  
      String msg = event.getComponent().getId() + " dialog is closed";
      FacesContext facesContext = FacesContext.getCurrentInstance();  
      FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);  
      facesContext.addMessage("SampleDialog", message);  
    }

What just happened?

We have created a dialog and hooked-up a close event listener using <p:ajax event="close" update="msgs" listener="#{dialogController.handleDialogClose}"/>. So when dialog is closed, the event listener method handleDialogClose() will be invoked. In handleDialogClose() we have added a INFO FacesMessage to FacesContext. As we have specified to update the <p:messages id="msgs"/> component with update="msgs", the message is displayed as SampleDialog dialog is closed. Similarly, we can register event listeners for minimize and maximize events.

Working with a Dialog component containing forms

We can create Dialog components containing other complex components including forms, data tables, and so on. In our TechBuzz application, we will have a register link in the menu bar and when the user clicks on the register link, we will show a dialog containing a registration form. If there are any validation errors, the registration form should be redisplayed with error messages, otherwise the user should be registered, close the dialog, and display a registration success message.