PrimeFaces Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – adding callback parameters using RequestContext.addCallbackParam()

In this section, we will see how to add callback parameters to an AJAX response payload by performing the following steps:

  1. Create a form with an input field and submit button using the following code:
    <h:form id="form1">
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText id="emailId" value="#{requestContextController.emailId}" required="true"/>
        
        <p:commandButton id="submitBtn" value="Submit" actionListener="#{requestContextController.handleSubmit}" 
        oncomplete="handleComplete(xhr, status, args)"/>
      </h:panelGrid>
      <h:outputText value="You have Entered : #{requestContextController.emailId}" />
    
    </h:form>
  2. Implement the oncomplete callback JavaScript function handleComplete() as follows:
    <script type="text/javascript">  
      function handleComplete(xhr, status, args) 
      {  
        if(args.validationFailed) {
          alert("Validation Failed");  
        }   
        else {        
          var text = "Email Id :"+ args.emailId + "\n"+"FirstName :"+args.user.firstName+"\nLastName "+args.user.lastName;
          alert(text);      
        }  
      }  
    </script>
  3. In the action handler method, add callback parameters using the RequestContext.addCallbackParam() method as follows:
    public void handleSubmit(ActionEvent ae)
    {
      RequestContext context = RequestContext.getCurrentInstance();
    context.update("form1");
    
    context.addCallbackParam("emailId", emailId);
    User user = new User();
    user.setFirstName("Optimus");
    user.setLastName("Prime");
    context.addCallbackParam("user", user); 
    }

What just happened?

In the action handler method, we have added callback parameters using RequestContext.addCallbackParam("paramName", paramValue).

We have created a JavaScript callback function handleComplete(xhr, status, args) to be executed on completion of the AJAX request.

By default, the validationFailed callback parameter is added implicitly if JSF validation fails. So, initially we are checking whether there are any validation failures and then we will display, emailId, user's firstName and lastName extracted from the args parameter, which we have added using the RequestContext.addCallbackParam() method. The user object that we added as a callback parameter is converted into JSON format as {"firstName":"Optimus", "lastName":"Prime"}.

Scrolling to a component

We can use the RequestContext.scrollTo() method to scroll to a component after an AJAX request is completed:

RequestContext.getCurrentInstance().scrollTo("clientId");

Internally, this method will call the JavaScript function PrimeFaces.scrollTo("clientId"). So you can directly use this in your JavaScript to scroll to any component.