How to invoke a command button without validating all required inputs?

Víctor Pariente picture Víctor Pariente · Jun 28, 2012 · Viewed 22.3k times · Source

I'm trying to make a redirection from index.xhtml to registerFirstTime.xhtml.

The code in the page index.xhtml is:

<h:form id="content" style="margin-top: 1em;">
    <p:panel id="panel" header="LOGIN">
        <p:messages id="msgs" globalOnly="true"/>
        <h:panelGrid columns="3">
            <h:outputLabel value="e-mail" />
            <p:inputText id="name" required="true" value="#{UserBean.email}"
                requiredMessage="Required: e-mail" display="icon">
            </p:inputText>
            <p:message id="msgName" for="name"/>
            <h:outputLabel value="Password" />
            <p:password id="password" required="true" value="#{UserBean.password}"
                requiredMessage="Required: Password" display="icon" feedback="false">
            </p:password>
            <p:message id="msgPassword" for="password"/>
        </h:panelGrid>
        <h:panelGrid columns="2">
            <p:commandButton value="Login" actionListener="#{UserBean.validate}" update="msgNombre, msgPassword, msgs"/>
            <h:commandButton value="Register for the first time" action="register"/>
        </h:panelGrid>
    </p:panel>
</h:form>

While, the content of the redirection, in faces-config.xml, is:

<navigation-rule>
    <from-view-id>index.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>register</from-outcome>
        <to-view-id>registerFirstTime.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

Until the input name and password are filled, you can't do the redirect. How I can get do the redirection of the record without taking into account the required fields? Thanks! =)

Answer

BalusC picture BalusC · Jun 28, 2012

Add immediate="true" to the command button which should skip processing of all input field which do not have the immediate="true" attribute.

<h:commandButton value="Register for the first time" action="register" immediate="true" />

Unrelated to the concrete problem, please note that you're technically not sending a redirect here. This basically sends a forward, i.e. the URL in the browser address bar remains the URL of the login page. You need to add <redirect/> to the <navigation-case>. Also please note that navigation cases are an leftover of JSF 1.x. Since JSF 2.x you can perform "implicit navigation" whereby you just specify the view ID as outcome.

<h:commandButton value="Register for the first time" action="registerFirstTime?faces-redirect=true" immediate="true" />

This way you can get rid of the navigation case altogether.