Search code examples
javajqueryajaxjsf-2

Best Practice for submitting a JSF 2 form that might use ajax if we have an error response from the submit


I have a submit button that submits to a database using the button below. If this button return "error", I want to use an AJAX to remove the form and its content and add a text in place of the form.

Edit:

The reason of staying in the same page after clicking the submit button is because, the same CMS content above and below the form is used on both the current page and redirected page after submit. Thus, its easier to just remove form and display the error page. This will avoid the whole page to reload due to redirect.

</h:form id="myForm">
  ...
  <h:commandButton action="#{testBean.submitForm}"
                   type="submit" value="Create Button">
  </h:commandButton>
</h:form>

Solution

  • Remember to use <h:head> and <h:body> instead of <head> and <body>.

    <h:panelGroup id="mypanelgroup">   
        <h:outputText value="#{testBean.errorMessage}" rendered="#{testBean.errorMessage ne null}" />
    
        <h:form rendered="#{testBean.errorMessage eq null}">
            <!--  -->
            <h:commandButton value="submit" action="#{testBean.submitForm()}">
               <f:ajax execute="@form" render=":mypanelgroup"></f:ajax> 
            </h:commandButton>
        </h:form>
    </h:panelGroup>
    
    
    @ManagedBean
    public class TestBean {
    
        private String errorMessage = null;
    
        public String getErrorMessage() {
            return errorMessage;
        }
    
        public void submitForm(){
            // .....
            //if(error){
                this.errorMessage = "My error Message";
            //} 
        }
    }
    

    Initially, the <h:outputText> is not rendered because errorMessage by default was set to null.