Partial process and update with fragments
For enhanced AJAX capabilities, PrimeFaces offers the <p:fragment>
component, which offers partial processing and updating with the AJAX request triggered by a component that resides inside the fragment itself. This component is useful and easy to use when multiple sections exist for a form with a different action for each section since there'll be no need to specify ID's for component processing and updating.
How to do it…
Let's define two fragments to retrieve data for registering a user into a system, one for user name input and the other for user address input. The definition of these two fragments would be as follows with the respective input fields marked with the required
attribute:
<p:fragment autoUpdate="true"> <p:fieldset legend="Basic Info"> <p:outputLabel for="name" value="Name:" /> <p:inputText id="name" value="#{fragmentBean.userName}" required="true" /> <p:commandButton value="Save" actionListener="#{fragmentBean.saveUserInfo}" /> </p:fieldset> </p:fragment> <p:fragment autoUpdate="true"> <p:fieldset legend="Address"> <p:outputLabel for="address" value="Address:" /> <p:inputText id="address" value="#{fragmentBean.address}" required="true" /> <p:commandButton value="Save" actionListener="#{fragmentBean.saveAddressInfo}" /> </p:fieldset> </p:fragment>
How it works…
When we click on the Save button of the Address section, only the Address input text will be processed and the Name input will be left intact. Since the Address input is a required field, we will get that field drawn in red for the error in the following image, but only that one since a descendant command button of the second fragment invokes the action.
The PrimeFaces Cookbook Showcase application
This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x compatible application server, such as JBoss WildFly and Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter1/fragment.jsf
.