0

i have a form with some inputs that have validation (required=true) and when i click on the cancel button in case of validation error, the cancel button doesn't navigate to previous page, instead it removes the validation error (i think it goes back one step that was before the validation error ?)

here's my code:

<h:form>

<h:inputText value="#{myBean.nickName}" id="nickname" required="true"
requiredMessage="nickname should be specified" />

<h:commandLink immediate="true" id="cancel_link" onclick="history.back(); return false" style="float: left;margin: 118px 189px 0 0;">
 <h:graphicImage width="90" height="28" value="#{resource['images:blu_btnCancel.png']}" />
</h:commandLink>

</h:form>

please advise how to fix that.

Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498

1 Answers1

2

The JavaScript history.back() function takes you to the previous synchronous request, not to the previous view as you seemed to expect.

Even though the history.back() is terrible this way (unreliable, hackable, etc), a quick fix would be to send an ajax request on form submit instead of a synchronous request.

<h:form>
    ...
    <h:commandButton value="submit">
        <f:ajax execute="@form" render="@form" />
    </h:commandButton>
</h:form>

Ajax requests doesn't account as browser history.

A more robust way is to just pass the identifier of the previous view along during navigation and then use <h:link> to link back to it. E.g.

<h:link value="Go to next view" outcome="nextview">
    <f:param name="from" value="#{view.viewId}" />
<h:link>

And then in the nextview.xhtml

<f:metadata>
    <f:viewParam name="from" />
</f:metadata>

...

<h:link ... outcome="#{from}" rendered="#{not empty from}">
    <h:graphicImage ... />
</h:link>

If you're navigating by POST, you might consider using the flash scope to remember the initial view.


Unrelated to the concrete problem, the proper way to use <h:graphicImage> with JSF2 resources is to just use its name attribute instead of its value attribute with a #{resource} which is plain clumsy.

Replace

<h:graphicImage width="90" height="28" value="#{resource['images:blu_btnCancel.png']}" />

by

<h:graphicImage name="images/blu_btnCancel.png" width="90" height="28" />

Note that the library name images is here just replaced by the path name. The usage of the name "images" as library name is highly questionable. See also What is the JSF resource library for and how should it be used?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555