I have a very simple page that simply prompts the user for a name and will then create a resource with that name. When the user hits the submit button, I would like to directly navigate him to the page for the just created entity. So my page looks like this:
<h:form id="form">
<p:fieldset legend="Create new">
<p:panelGrid columns="2">
<h:outputText value="Name" />
<p:inputText value="#{createBean.entity.name}" />
</p:panelGrid>
<p:commandButton value="Create Entity" ajax="false"
action="#{createBean.submit}">
</p:commandButton>
</p:fieldset>
</h:form>
The submit
action of the createBean
should now persist the entity. This, as a side effect, assigns a ID to the entity. And now I would like to navigate to this entity.
public void submit() {
/* Persist entity, entity.getId() will now
return a meaningful value. */
FacesContext context = FacesContext.getCurrentInstance();
NavigationHandler handler = FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
// How could I pass the ID?
handler.handleNavigation(context, null, "pretty:entity-detail");
}
The mapping of entity-detail
looks like this:
<url-mapping id="entity">
<pattern value="/entities" />
<view-id value="/views/entity/list.xhtml"/>
</url-mapping>
<url-mapping parentId="entity" id="entity-detail">
<pattern value="/view/#{id}" />
<view-id value="/views/entity/entityDetail.xhtml"/>
</url-mapping>
For the record: using Apache MyFaces 2.1.5 and PrettyFaces 3.3.2.
You are using named path parameters in your mapping. In this case you can simply return the viewId from the action method and append a corresponding query parameter.
public String submit() {
/* Persist entity, entity.getId() will now
return a meaningful value. */
long id = ....
return "/views/entity/entityDetail.xhtml?faces-redirect=true&id=" + id;
}
For EL-injected parameters the process is a bit different. See this chapter of the documentation for details.