Clear form in p:dialog on close after failed action/method call

23,698

Solution 1

Try this:

  1. Put your dialog inside a form (dialogInputForm)

  2. Add the attribute update=":dialogInputForm"

  3. Nest the resetInput tag within the button that opens the dialog and specify the target as the just created form

The commandButton:

<p:commandButton process="@this" actionListener="#{bean.prepare}" update=":dialogInputForm" oncomplete="thirdPartyDialog.show()" value="Open Input Dialog" >
     <p:resetInput target=":dialogInputForm" />
</p:commandButton>

And the form which contais the dialog

<h:form id="dialogInputForm" >
 ... your dialog ...
</h:form>

Solution 2

This worked for me, place this ajax event in the dialog. When the dialog is closed, the validations will be cleaned

<p:dialog id="dlgAddress"
              header="Address Edit"
              widgetVar="dialogAddress"
              dynamic="true"
              modal="false"
              closable="false"
              resizable="false"
              styleClass="dlgAddress"
              visible="#{addressform.showDlgAddress}">
        <ui:include src="addressform.xhtml"/>

   <p:ajax event="close" update="dlgAddress" resetValues="true" />

</p:dialog>
Share:
23,698
mousouchop
Author by

mousouchop

Updated on July 09, 2022

Comments

  • mousouchop
    mousouchop almost 2 years

    I've got a form within a p:dialog component being submitted via AJAX. The form in the dialog is via a ui:include of another .xhtml containing just the form and its components (no, I am not nesting forms; the dialog itself is not within any form). The included page's backing bean is 'ViewScoped'.

    MOST things function fine:

    • On successful validation, the form will execute the save method; after a successful save, the dialog closes; opening a subsequent record shows proper record information from the database.
    • On unsuccessful validation, the submitted values persist and the dialog remains open and displays validation errors, fixing the invalid fields and resubmitting results in a successful save.

    The problem comes in when the action called by the p:commandButton fails. In the event that it fails, the dialog remains open and displays "Error saving changes" via h:messages to the user; additionally, the submitted values still persist in the input fields. This is fine (and even desired) while the form remains open, however-- upon closing the dialog and reopening it, the submitted values are STILL in the text fields. This is bad because it gives the user the impression that the save did succeed (as the h:messages component is now blank due to the dialog update).

    So far I have tried the following, NONE of which have remedied the problem:

    • 1.1) Setting the backing bean of the included form to a new instance of the bean on dialog open.
    • 1.2) Since the bean is now a new instance, I am also repopulating the address object with details from a data bean.
    • 2.1) Disabling the close button on the dialog and adding a p:commandButton "Cancel" button with a p:resetInput component in it to close the dialog/reset the form. (dialog closes, but submitted values in form persist).
    • 2.2) Calling a method from this p:commandButton that removes the RequestMap for the included form's backing bean.
    • 2.3) Tried with the button set to both immediate=true and immediate=false.
    • 2.4) Tried with the button set to process=@this, a similar tactic I have used to close a form to ensure it will have fresh fields upon reopening.

    You would think between setting the backing bean to a new instance, and repopulating the address object I would be seeing a fresh form, but NOPE.

    Here is some of the source:

    Portion of mainform.xhtml

        <p:dialog id="dlgAddress"
                  header="Address Edit"
                  widgetVar="dialogAddress"
                  dynamic="true"
                  modal="false"
                  closable="false"
                  resizable="false"
                  styleClass="dlgAddress"
                  visible="#{addressform.showDlgAddress}">
            <ui:include src="addressform.xhtml"/>
        </p:dialog>
    

    addressform.xhtml

    <h:form id="fDlgAddress">
        <div id="addresses-container">
            <h:messages id="msgDlgAddress" errorClass="errormsg" infoClass="infomsg1" layout="table"/>
            <h:panelGrid columns="1"
                         styleClass="pgAddresses"
                         rendered="#{!addressform.address.exists}">
                <h:outputText value="No active #{addressform.address.atypCode} address found."
                              styleClass="record-not-exists"/>
                <h:outputText value="Use the form below to create one."/>
            </h:panelGrid>
            <p:panelGrid columns="2"
                         styleClass="pgDlgForm pgAddresses">
                <h:outputLabel value="Address Type"/>
                <h:inputText id="atypCode1"
                             value="#{addressform.address.atypCode}"
                             disabled="true"
                             rendered="#{addressform.address.exists}"/>
                <h:selectOneMenu id="atypCode2"
                                 value="#{addressform.address.atypCode}"
                                 rendered="#{!addressform.address.exists}">
                    <f:selectItems value="#{addressform.atypCodeList}"
                                   var="atyp"
                                   itemValue="#{atyp}"
                                   itemLabel="#{atyp}"/>
                </h:selectOneMenu>
                <h:outputLabel value="Street 1" 
                               for="street1"/>
                <h:inputText id="street1"
                             value="#{addressform.address.addressLine1}"/>
                <h:outputLabel value="Street 2" 
                               for="street2"/>
                <h:inputText id="street2"
                             value="#{addressform.address.addressLine2}"/>
                <h:outputLabel value="Street 3" 
                               for="street3"/>
                <h:inputText id="street3"
                             value="#{addressform.address.addressLine3}"/>
                <h:outputLabel value="Street 4" 
                               for="street4"/>
                <h:inputText id="street4"
                             value="#{addressform.address.addressLine4}"/>
                <h:outputLabel value="City" 
                               for="city"/>
                <h:inputText id="city"
                             value="#{addressform.address.city}"
                             required="true"
                             requiredMessage="Please enter a city."/>
                <h:outputLabel value="State" 
                               for="statCode"/>
                <h:selectOneMenu id="statCode"
                                 value="#{addressform.address.stateCode}">
                    <f:selectItem itemLabel="Select State/Province"
                                  itemValue=""/>
                    <f:selectItems value="#{states.statesList}"
                                   var="stat"
                                   itemValue="#{stat.statCode}"
                                   itemLabel="#{stat.statDesc}"/>
                </h:selectOneMenu>
                <h:outputLabel value="Zip Code" 
                               for="zipCode"/>
                <h:inputText id="zipCode"
                             value="#{addressform.address.zip}"/>
                <h:outputLabel value="Country" 
                               for="natnCode"/>
                <h:selectOneMenu id="natnCode"
                                 value="#{addressform.address.nationCode}"
                                 required="true"
                                 requiredMessage="Please choose a nation.">
                    <f:selectItem itemLabel="Select Country"
                                  itemValue=""/>
                    <f:selectItems value="#{nations.nationsList}"
                                   var="natn"
                                   itemValue="#{natn.natnCode}"
                                   itemLabel="#{natn.natnDesc}"/>
                </h:selectOneMenu>
                <h:outputLabel value="From Date" 
                               for="fromDate"/>
                <p:calendar id="fromDate"
                            value="#{addressform.address.fromDate}"
                            showButtonPanel="true"/>
                <h:outputLabel value="To Date" 
                               for="toDate"/>
                <p:calendar id="toDate"
                            value="#{addressform.address.toDate}"
                            showButtonPanel="true"/>
                <h:outputLabel value="Inactivate"
                               for="inactivateAddress"
                               rendered="#{addressform.address.exists}"/>
                <h:selectBooleanCheckbox id="inactivateAddress"
                                         value="#{addressform.address.inactivate}"
                                         rendered="#{addressform.address.exists}"/>
                <h:outputLabel value="Delete"
                               for="deleteAddress"
                               rendered="#{addressform.address.exists}"/>
                <h:selectBooleanCheckbox id="deleteAddress"
                                         value="#{addressform.address.delete}"
                                         rendered="#{addressform.address.exists}"/>
            </p:panelGrid>
        </div>
        <div class="button-container">
            <p:commandButton value="Save Changes"
                             action="#{addressform.save}"
                             type="submit"
                             ajax="true"
                             process="@form"
                             update="@form"/>
            <p:commandButton value="Cancel"
                             process="@this"
                             onclick="dialogAddress.hide();">
                <p:resetInput target="fDlgAddress"/>
            </p:commandButton>
        </div>
    </h:form>
    

    Recorddetailsform (backing bean for form from which address dialog is called)

    public void showDlgAddress(){
            FacesContext ctx = FacesContext.getCurrentInstance();
            ELResolver resolver = ctx.getApplication().getELResolver();
            RecordDetails recordDetails = (RecordDetails) resolver.getValue(ctx.getELContext(), null, "recordDetails");
    
            //Set addressform backing bean to new instance and load address into it from recordDetails
            resolver.setValue(ctx.getELContext(), null, "addressform", new Addressform());
            Addressform addressform = (Addressform) resolver.getValue(ctx.getELContext(), null, "addressform");
            addressform.setAddress(recordDetails.getAddress());
        }
    

    Addressform (address form's backing bean)

    public void save() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        RequestContext rctx = RequestContext.getCurrentInstance();
        ELResolver resolver = ctx.getApplication().getELResolver();
        Records records = (Records) resolver.getValue(ctx.getELContext(), null, "records");
        RecordDetails recordDetails = (RecordDetails) resolver.getValue(ctx.getELContext(), null, "recordDetails");
        Mainform mainform = (Mainform) resolver.getValue(ctx.getELContext(), null, "mainform");
        Person person = (Person) resolver.getValue(ctx.getELContext(), null, "person");
    
        //Pretty lengthy SQL stuff here. Commented out. Just wanted to display the display logic below for the dialog.
    
        if (errorMsg != null) {//If errorMsg is not null, then error occurred.
            showDlgAddress = true;//Ensures address dialog remains open in event of action error.
            queueErrorMessage(errorMsg);
            rctx.update("dlgAddress");
            return;//break out of method on error.
        } else {
            showDlgAddress = false;
            rctx.update("dlgAddress");
        }
    
        //If everything saves without error, repopulate address and update recordDetails dialog.
        recordDetails.populateAddress(records.getSelectedRecord());
        mainform.updateDlgRecordDetails();
    }
    

    Other Info:

    • JSF2
    • Primefaces 3.5
    • Tomcat 6.0
    • Netbeans
  • mousouchop
    mousouchop about 11 years
    Hmmm... I can try this at work tomorrow, but I think I have already tried this. The result was the p:resetInput caused the form to appear as if no record was loaded, clearing out not only the "stuck" submitted values from the previous record to clear, but also the values of the new incoming record.
  • Grégoire C
    Grégoire C about 10 years
    Incredibly this solution works! I was desperate about this problem of resetting the values of my dialogs. The <p:resetInput target=":dialogInputForm"/> does the trick. Thanks a lot!
  • mousouchop
    mousouchop almost 10 years
    Yes. I've found that this works reliably. I however do nest my forms within my dialog, which does not seem to cause an issue. I think my problem came in when initially tried using @form as the target for <p:resetInput/>. You MUST use an actual form ID in this component, and also update the very same form as in your example above. Thanks.
  • jpangamarca
    jpangamarca about 7 years
    Tried it, works only if target is actually a form, doesn't work if it's a composite component's client id (docs say any parent component would work). Sad. I'll have to concat ids and code would become fragile at some point. But for now it'll do.
  • Nemuga Dev
    Nemuga Dev almost 3 years
    I tried your solution and never worked on a Session Managed Bean
  • Nemuga Dev
    Nemuga Dev almost 3 years
    I tried your solution and never worked on a Session Managed Bean