Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF/PrimeFaces selectOneMenu change view-id

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?

like image 765
karolkpl Avatar asked Dec 28 '22 10:12

karolkpl


1 Answers

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.

like image 154
BalusC Avatar answered Jan 10 '23 00:01

BalusC