Search code examples
javascriptjsfprimefacesjsf-2jsf-2.2

Get the returned value from managed bean in javascript


In my application I call a Javascript event which calls a p:remoteCommand named checkPageLayoutsAreSelected as following :

$('selector').on('click', function (e) {
  checkPageLayoutsAreSelected();
});

This is the p:remoteCommand :

<p:remoteCommand name="checkPageLayoutsAreSelected" actionListener="#{beanFormDashboard.checkPageLayoutsAreSelected}" />

This p:remoteCommand will call a method in the beanFormDashboard managed bean which will return a Boolean value :

public Boolean checkPageLayoutsAreSelected(){
    for(DashboardPage dp : dashboardPageList){
        if(dp.getModel() == 0){
            return false;
        }
    }
    return true;
}

So I want to get the returned value by the checkPageLayoutsAreSelected() from the managed bean in the Javascript code.

Something like this :

$('selector').on('click', function (e) {
  var returnedValue = checkPageLayoutsAreSelected();
});

How can I do that?


Solution

  • checkPageLayoutsAreSelected doesn't return a value or even a promise but you can Ajaxicaly return value.

    <p:remoteCommand name="checkPageLayoutsAreSelected"
         action="#{beanFormDashboard.checkPageLayoutsAreSelected()}"
         oncomplete="getLayoutAreSelectedResult(xhr, status, args);"
    />
    

    And in the method checkPageLayoutsAreSelected() you use RequestContext provided by PF to send result back to client:

    public void checkPageLayoutsAreSelected() {
       Boolean result=true;
       for(DashboardPage dp : dashboardPageList){
            if(dp.getModel() == 0){
                result= false;
            }
       }
       RequestContext reqCtx = RequestContext.getCurrentInstance();        
       reqCtx.addCallbackParam("returnedValue", result);
    }
    

    And in the Javascript callback function getLayoutAreSelectedResult(xhr, status, args) you will have the returned value:

    $('selector').on('click', function (e) {
        checkPageLayoutsAreSelected();
        window.getLayoutAreSelectedResult= function(xhr, status, args) {
           var returnedValue = args.returnedValue;
           console.log(returnedValue);
        }
    });