Search code examples
jqueryjsfprimefacesjsf-2

Show modal optionally when commandButton clicked


I have a problem that I need to show a modal based on the value of the input field, so I write some value in the input field, click Save button, based on the value I should run db query, if result is present then show modal, otherwise not. What is the best approach?

A problem is that I need to have separate onclick, oncomplete events.

 <p:commandButton id="save_button"
  value="Save"
  update="@([id*=modalId]) @form"
  onclick="jQuery('#modalId').show();"
  action="#{cc.attrs.saveAction}">
  </p:commandButton>


   <p:inputNumber required="true"
   value="#{bean.number}">
   </p:inputNumber>

Solution

  • You can set the db result in your backing bean and then change the .show() invocation to the oncomplete attribute, so you can conditionally show the modal panel depending on the query result.

    public class BackingBean{
        private Object dbResult;
    
        public Object getDbResut(){ return dbResult; }
    
        public void executeDbQuery(){
              dbResult = yourDbApi.doSomeQuery();
        }
    }
    
    
    <p:commandButton id="save_button"
      value="Save"
      update="@([id*=modalId]) @form"
      actionListener="#{bean.executeDbQuery}">
      action="#{cc.attrs.saveAction}"
      ocomplete="#{not empty bean.dbResult ? 'jQuery('#modalId').show();' : ''}">
      </p:commandButton>
    
    
       <p:inputNumber required="true"
       value="#{bean.number}">
       </p:inputNumber>
    

    actionListener executes before action , so its garanteed that after your action call the oncomplete would take the correct bean.dbResult