Nouman_Khurram
Nouman_Khurram

Reputation: 52

How to redirect to a page after printing with primefaces Printer?

I have used the primefaces printer and wanted to redirect to previous page after printing.I used Printer like this:

   <p:commandButton  value="Print" type="button" title="Print" actionListener="#{currentpage.redirect}"> 
        <f:ajax execute="@this"/>
        <p:printer target="printer" />
    </p:commandButton> 

In redirect method of currentpage bean i deleted the record which works fine but if i try to redirect it to previous page it doesn't do anything.

public void redirect(ActionEvent actionevent) {
              /* Deleted the record */ 
}

Please guide me if i can do this way or anyother way. Thanks in advance.

Upvotes: 2

Views: 5471

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

There are several misconceptions in your code:

  • actionListener method can not fire a redirect. That could be done in action
  • An ajax request cannot fire a redirect. Ajax is meant to work as an asynchronous request to the server and get the desired result to the current view and handle the response to update the view without refreshing the page nor without navigating.
  • If using Primefaces components, you should work with them for efficiency in your page. For example, <p:commandButton> should work with <p:ajax> rather than <f:ajax>. But in this case, <p:commandButton> already has ajax capabilities built-in, so there's no need to use any of these ajax components.

After knowing this, you know that your design should change to this:

<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this">
    <p:printer target="printer" />
</p:commandButton>

And the method declaration to:

//parameterless
public void redirect() {
    /* Deleted the record */ 
}

PrimeFaces let's you add behavior when the ajax request is complete by usage of oncomplete attribute. This attribute receives the name of a javascript function that will be invoked right when the ajax request finishes without problems. In this method, you can add the logic for your redirection:

<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this" oncomplete="redirect()">
    <p:printer target="printer" />
</p:commandButton>

<script type="text/javascript>
    redirect = function() {
        window.location.href = '<desired url>';
    }
</script>

Upvotes: 3

Related Questions