2

I have a jsf page with

<h:inputText required="true"> attribute. When I click on my add button, I want to see an error if the field is blank.

I have a <f:message> to display this.

But how can I escape (cancel) the page with that field blank? In my case it continually posts the error message and I have to enter something in the field to go to another page.

fareed
  • 3,034
  • 6
  • 37
  • 65
DougMH
  • 105
  • 1
  • 8

3 Answers3

4

If your cancel button is a POST requests e.g. <p:commandButton>,<h:commandButton>, <p:commandLink>, or <h:commandLink>

You can put your cancel button outside the form that has the <h:inputText> so that form is not submitted

<h:form>
    <h:inputText value="#{bean.string}" required="true"/>
</h:form>
<h:form>
     <p:commandButton value="Cancel" action="anotherpage.xhtml"/>
</h:form>


If you are navigating without any actions or method invocation, then you can use GET requests e.g. <h:button>, <p:button>, <h:link> or <h:outputLink>.

Example:

 <h:form>
    <h:inputText value="#{bean.string}" required="true"/>
    <p:button value="Cancel" outcome="anotherpage.xhtml"/>
 </h:form>
fareed
  • 3,034
  • 6
  • 37
  • 65
  • 1
    there is no such thing as THE "correct" answer. There is almost always a better (even if unpractical) answer given a specific scenario, but never the "correct" one. Any answer that solves the problem, even the ugliest, is a correct one. – Mindwin Remember Monica Jul 16 '13 at 11:52
2

You can use immediate="true" in your <p:commandButton>. Then it will skip the validation.

For example:

<p:commandButton action="#{managedBean.action}" value="Cancel" immediate="true" />
Isuru Perera
  • 1,905
  • 1
  • 11
  • 23
  • immediate="true" will skip validation phase, so by setting this to commandbutton will work – Yogesh Kulkarni Mar 05 '13 at 06:10
  • 2
    Using `immediate="true"` in the command button basically skip few phases in JSF lifecycle. It's better to understand how JSF lifecycle works. Following is a good article to read. http://www.ibm.com/developerworks/library/j-jsf2/ – Isuru Perera Mar 05 '13 at 11:40
1

Just don't process the form on submit if you want to cancel or navigate away.

I.e. don't do

<h:form>
    ...
    <p:commandButton value="Cancel" action="#{bean.cancel}" />
</h:form>

But just do

<h:form>
    ...
    <p:commandButton value="Cancel" action="#{bean.cancel}" process="@this" />
</h:form>

Or, better if you're only returning a navigation outcome in cancel() method anyway

<h:form>
    ...
    <p:button value="Cancel" outcome="otherpage.xhtml" />
</h:form>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555