Powerful Ajax with Update and Process attributes in PrimeFaces

Hi,

PrimeFaces has a very easy and powerful ajax infrastructure using update and process attributes in ajaxified components. Let’s have this following condition:

There is a required inputText field, and also below that you have a dependent 2 h:selectOneMenu components that needs to be ajaxified. Let’s say those two selectOneMenu’s are for country – city, and last requirement is you have to add the selected city to a datatable. A little complicated screen maybe, but which requirement is not? :).Here is the final output we want :

Let’s do the coding. We need a required inputText for the description and a county city selector as follows :


<h:form>

   Description:<br/>
  <h:inputText label="description" required="true" id="description" requiredMessage="Description is required" />

  <p:panel header="Location Selection" id="locationSelector">
   <h:panelGrid columns="2">
      <h:outputText value="Select Country" />
      <h:selectOneMenu id="country" value="#{locationController.country}">
          <f:selectItem itemLabel="Select a Country" itemValue="" />
          <f:selectItems value="#{locationController.allCountries}" />
          <p:ajax update="city" process="country" event="change" actionListener="#{locationController.chooseCountry}" />
      </h:selectOneMenu>

      <h:outputText value="Select City" />
      <h:selectOneMenu id="city" value="#{locationController.city}" >
         <f:selectItem itemLabel="Select a City" itemValue="" />
         <f:selectItems value="#{locationController.cities}" />
      </h:selectOneMenu>
   </h:panelGrid>
   <br />

   <p:commandLink actionListener="#{locationController.selectLocation}" update="selectedCities" process="locationSelector" >
      <h:outputText value="select city" />
   </p:commandLink>
  </p:panel>
</h:form>

The tricky part here is the <p:ajax update="city" process="country" event="change" actionListener="#{locationController.chooseCountry}" /> part. This one does an ajax request when the h:selectOneMenu is changed ( event=”change” ), the selectOneMenu with the id country is processed ( process=”country” ), as only the country part is important while filling the city selector selectOneMenu ( note that we do not have a required message error due to description field, as we never process it even if they are in the same form), and finally refresh city selectOneMenu ( update=”city” ) to refresh the city selector. This way we have minimum load on the server, and we do not fight with validation errors.

Let’s move on to the p:datatable part, think we have a very basic table below for selected Cities :

<p:panel id="selectedCities" header="Selected Cities">
   <p:dataTable value="#{locationController.selectedCities}" var="city">
      <p:column>
          <f:facet name="header">
              City Name
          </f:facet>
         <h:outputText value="#{city.name} ( #{city.country.name} )"/>
     </p:column>
  </p:dataTable>
</p:panel>

Same way as p:ajax works, the p:commandLink will work as follow, update the table ( update=”selectedCities” ), but process the location selector div ( process=”locationSelector” ) as we need to use city and country in our action listener. Easy huh?

I think, this is one of the most powerful side of the PrimeFaces. You can do ajax request without having any validations errors.

I am leaving you the delete command link in the datatable as an exercise 😉

Advertisements

27 thoughts on “Powerful Ajax with Update and Process attributes in PrimeFaces

  1. Acaba bunun richfaces uygulaması var mı acaba? Veya nasıl yapılıo orda bilginiz varmı?
    Bir sürü yere baktım fakat bir türlü tam cevabı veren bi yer bulamadım. Siz tam benim istediğim şeyi anlatmıssınız.
    Bir de kullandıgın bean leri post edebilirseniz çok sevinirim?

    • Selam,

      richfaces uygulamasi yok ne yazikki :). ama richfaces’de

      <a4j:support event="change" diyerek combobox'lari degistirebilirsiniz.

      JSF 2.0 kullaniyorsaniz, f:ajax'la da yapabilirsiniz bu arada.

      • Uygulamanın olmadığı müjdesi için teşekkürler 😛

        Richfaces da yapılmıs birkaç örneğini gördüm ama içinden çıkamadığım tek şey <a4j:support event="change" dedikten sonra bir de action attribute'i var support'un. Bu actiona da bean deki işi yapan metod yazılıyor. Örneğin: action="#{actionBean.reInitilizeAuditFirms}" gibi. diger combo box'a bu metod da parametre veriliyor heralde. Bu parametre nasıl veriliyor yani üzerinde işlem yaptığımız combobox da neyi seçtiğimizi digeri nasıl anlıyor? O action da neler oluyor merak ettigim bu acıkcası? 🙂

  2. Please, can you show us what do you do in locationController.chooseCountry and locationController.selectLocation? Thanks

    • Hi,

      in chooseCountry, what I did is :

      cities = country.getCities();

      and in selectLocation
      selectedCities.add( city );

      nothing more.

      As city and country are already set by Primefaces, I do not have to do anything else

  3. If I add the 3rd drop down list, then it not working. Explain a bit clearer: So from your example, u select country, then list of cities generated. So i add a county drop down list, so that if i select a city, list of counties will generate

    And let say that below are the items in the city drop down list
    A
    B
    C
    D
    where C, D are what return from #{document.cities}. If I click on B, then method “test()” get invoke it. but if I click on C or D then test() does not get invoke at all. Any idea how to fix it?

  4. I would like to add PrimeFaces to my JBOSS SEAM project to use chart component.
    I do not find the right way to configure it. Can you help me,please?

  5. Hello, I’m trying to implement a country, region, city selection and it’s very similar to you example. Is there a sample war with you complete code to download?

    thanks?

  6. I’ve tried also with 4 levels menu : Country, Region, Department and City and it’s not working. the actionListener is not always called.

    it’s strange but I have a menu displayed in the browser for the department that show 5 elements, but when I display the source I only see 2. and that 2 elements are the only one that fire the action even.

    this is what I see when I display the source

    Select a Departement

    mondep
    tondep

    this is what I get when I do inspect Element in Safari

    Select a Departement
    mondep
    Aisne
    Oise
    Somme
    tondep

    and this is my source:

    Description:

  7. In the source, I have the 2 static element that works and the 3 dynamic one that will display correctly in the browser but not in the “source of the html page”.

    The Country and Region levels are working. that’s the 3rd level that doesn’t work.

    f:selectItem itemLabel=”mondep” itemValue=”mondep”
    f:selectItems value=”#{locationController.allDepartements}”
    f:selectItem itemLabel=”mondep” itemValue=”tondep”

  8. I got this error.What I am missing?
    javax.servlet.ServletException: /cartelera/dashboard.xhtml @14,62 Tag Library supports namespace: http://primefaces.prime.com.tr/ui, but no tag was defined for name: selectOneMenu
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:323)

    root

  9. helow, I am having this issue when i use ajax with SelectOneMenu
    Cause: java.lang.ClassCastException: org.primefaces.component.behavior.ajax.AjaxBehavior cannot be cast to java.util.List.

  10. There you go
    selectOneMenu value=”#{estudanteController.estado.estadoId}”
    f:selectItem itemValue=”” itemLabel=”Selecione”
    f:selectItems value=”#{estudanteController.listEstado}” var=”estado”
    itemValue=”#{estudanteController.estado.estadoId}”

  11. Hi. There is a mistake in your text.
    Where it says:
    The tricky part here is the <p:ajax update="locationSelector"…

    It should read:
    The tricky part here is the <p:ajax update="city"…

    Caused me some confusion. Great post though, thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s