Question

I'm using JSF2 and PrimeFaces3. How can I write selectOneMenu that would invoke JSF navigation to redirect user to another page when he change option in menu?

Was it helpful?

Solution

Attach an ajax listener and let it navigate by NavigationHandler.

E.g.

<h:form>
    <h:selectOneMenu value="#{navigator.outcome}">
        <f:selectItem itemLabel="Select page..." />
        <f:selectItem itemValue="page1" itemLabel="Page 1" />
        <f:selectItem itemValue="page2" itemLabel="Page 2" />
        <f:selectItem itemValue="page3" itemLabel="Page 3" />
        <f:ajax listener="#{navigator.navigate}" />
    </h:selectOneMenu>
</h:form>

(the above example expects page1.xhtml, page2.xhtml and page3.xhtml in the same context; you can even make it a <f:selectItems> instead)

with

private String outcome;

public void navigate() {
    FacesContext context = FacesContext.getCurrentInstance();
    NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
    navigationHandler.handleNavigation(context, null, outcome + "?faces-redirect=true");
}

The ?faces-redirect=true is not necessary, but it effectively sends a redirect so that the URL in browser address bar will properly change which is better for user experience and bookmarkability of the pages.

OTHER TIPS

You could have something like:

<p:selectOneMenu value="#{myBean.mySelectedPage}">
           <f:selectItem itemValue="http://www.yahoo.com" itemLabel="yahoo"  />
           <f:selectItem itemValue="http://www.google.com" itemLabel="google" />
           <f:selectItem itemValue="search.jsf" itemLabel="search" />
           <p:ajax event="change" listener="#{myBean.myNavigationMethod}" />
 </p:selectOneMenu>

and on your navigationMethod you have:

String myPage = mySelectedPage
FacesContext.getCurrentInstance().getExternalContext().redirect(myPage);

The first two selectItem are for a full url and the last one is for another page in your web application(be careful that the extension must be the one set in your web.xml - it could be .jsf, .xhtml, .htm etc)

Instead of using ajax navigation use the following:

<p:selectOneMenu value="#{navigator.outcome}" onchange="window.location =this.options[this.selectedIndex].value">                      
    <f:selectItem itemLabel="Select page..." />
    <f:selectItem itemValue="page1" itemLabel="Page 1" />
    <f:selectItem itemValue="page2" itemLabel="Page 2" />
    <f:selectItem itemValue="page3" itemLabel="Page 3" />
    <p:ajax event="change" listener="#{navigator.navigate}" />
</p:selectOneMenu>

This works even if the session times out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top