1

I have a

<a4j:commandButton action="#{myBean.doCalculation}"
                   oncomplete="redirectBrowser()" />

However, if there is an error at myBean.doCalculation(), then oncomplete attribute is always invoked. How do I let it depend on result of action method?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Lurtz
  • 429
  • 2
  • 8
  • 17

3 Answers3

4

You can check for errors in the oncomplete event and redirect when none are found. It can be done like this

oncomplete="#{facesContext.maximumSeverity == null ? 'redirectBrowser()' : 'doSomethingElse()'}"
Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72
Giorgos Dimtsas
  • 12,019
  • 3
  • 29
  • 40
  • There is really no problem with a4j:commandButton and navigation - it's not designed to be used for navigation. One option is to use for navigation. – Max Katz Apr 05 '11 at 16:33
3

If you're on JSF 2.0, you can use FacesContext#isValidationFalied() to check if validation has failed or not:

oncomplete="if (#{not facesContext.validationFailed}) redirectBrowser()"

However, just performing redirect in the action method is more clean:

public String doCalculation() {
    // ...

    if (success) {
        return "nextPage.xhtml?faces-redirect=true";
    } else {
        return null;
    }
}

Yet more clean would be to just do the validation by a Validator. This way the action method will simply not be invoked at all when the validation has failed.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for this answer! It was very helpful. To respectfully disagree with one point, doing the redirect in the action method is less clean -- IMHO allowing redirection by returning a string is a design flaw in Faces... – wprl May 11 '12 at 20:51
  • 2
    It's absolutely not a design flaw. PRG is one of the most commonly used web design patterns: http://en.wikipedia.org/wiki/Post/Redirect/Get However, using POST forms for *plain vanilla* navigation from page X to page Y is in turn absolutely a design flaw (by the developer, not by JSF). See also http://stackoverflow.com/questions/4317684/when-should-i-use-houtputlink-instead-of-hcommandlink – BalusC May 11 '12 at 20:52
  • Sorry, lazy's not the word I was looking for. Nothing wrong with PRG; it's just a clunky syntax is what I'm getting at. It seems odd to return a string rather than call some redirect method. – wprl May 11 '12 at 21:23
2

Well, just looking for facesContext.maximumSeverity == null is not enough, there may be a warning as current max severity, that should redirect, too. Instead, write a method that looks if there are any max severities of priority error...

Jens Kreidler
  • 364
  • 1
  • 4
  • 10