10 Replies Latest reply on May 20, 2009 2:28 AM by Jan Andersson

    Variant to wiki example on validation in modal panel

    Yannick Lazzari Newbie


      I just wanted to share a variant to the following wiki article (http://labs.jboss.com/wiki/ModalPanelValidation) that explains how to prevent a modal panel from closing when there's at least one error in the message queue. Perhaps someone else already thought of this but here it is anyways. By the way, this assumes that you are using facelets but I'm sure an equivalent is possible with JSP pages as well.

      All my facelets templates share a common template. So, they all look something like this:

      <?xml version='1.0' encoding='UTF-8' ?>
      <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <ui:composition xmlns="http://www.w3.org/1999/xhtml"

      In my default.xhtml template, I added the following:

       <a4j:outputPanel ajaxRendered="true">
       <h:form style="display:none" prependId="false">
       <h:inputHidden id="maximumSeverity" value="#{facesContext.maximumSeverity.ordinal}"/>

      Basically, we now have an invisible form that gets refreshed on every postback and contains a hidden field that tells us the maximum severity in the message queue, or null if the queue is empty.

      Next, I have a little utility javascript method like this:

      function ajaxRequestContainsErrors() {
       return document.getElementById("maximumSeverity").value == "2";

      This method simply reads the value of the hidden field and tests if its equal to the ERROR severity ordinal value.

      Since all of this is done in my base template, every facelet client file can now use this little javascript method to see if the last postback to the server generated any errors.

      Finally, the a4j:commandLink or a4j:commandButton that submits a form from within a modal panel can now look like this:

      <a4j:commandButton value="Save" action="#{myController.save}" oncomplete="if (!ajaxRequestContainsErrors()) Richfaces.hideModalPanel('myModalPanelId');"/>

      It might not seem like a big difference with the proposed solution in the wiki but I like the idea of having this javascript method available at any moment in any of my pages. It makes it easier to adjust the behaviour of any javascript code based on the fact that there were errors or not. Plus, it might be because I'm picky but I think it makes more sense to test the value of a hidden field rather than seeing if a given element is present in the DOM or not because we know that it shouldn't be there when there are no error. It would also be very easy to have other javascript methods that test if we have at least one info or one warning message.

      So that's it. That's my 2 cents. Maybe someone will find this useful.