Preserve panelMenu state across redirects
allenc May 27, 2010 10:53 PMIn the past I avoided using RichFaces panelMenu because I coudn't get the state of the menu to preserve across redirects.I found several posts on the subject, but the solutions seemed complex to me. So I finally bit the bullet and came up with a simple approach.
Here is the view:
<h:form> <rich:panelMenu style="width:200px" expandSingle="true" selectedChild="#{panelPage}"> <rich:panelMenuGroup label="One" expanded="#{panelGroups[0]}" > <rich:panelMenuItem id="test1" action="#{pmenu.go('test1')}" label="Test Page 1" mode="server" /> <rich:panelMenuItem id="test2" action="#{pmenu.go('test2')}" label="Test Page 2" mode="server" /> </rich:panelMenuGroup> <rich:panelMenuGroup label="Two" expanded="#{panelGroups[1]}"> <rich:panelMenuItem id="test3" action="#{pmenu.go('test3')}" label="Test Page 3" mode="server" /> <rich:panelMenuItem id="test4" action="#{pmenu.go('test4')}" label="Test Page 4" mode="server" /> </rich:panelMenuGroup> </rich:panelMenu> </h:form>
Here is the bean:
@Name("pmenu") @Scope(ScopeType.SESSION) public class PanelMenuBean { @In(required=false) @Out Boolean[] panelGroups; @Out private String panelPage; public String go(String to) { this.panelPage = to; return "/" + to + ".xhtml"; } public String init() { panelGroups = new Boolean[5]; for (int i = 0; i < 5; i++) panelGroups[i] = false; panelGroups[0] = true; return go("test1"); } }
The Seam component hosts an array of boolean values that hold the expanded/collapsed state of each group. The size of the array needs to match the number of groups.
The go() method accepts a portion of the view id, e.g. for /test1.xhtml
I pass test1
. This value is outjected via panelPage and the panelMenu pulls it into the selectedChild property to highlight the active link. Each panelMenuItem id must match the corresponding view id.
I use the init() method when I navigate in from another area in my app. It initializes the group array to expand the first group and collapse the rest, and returns the default view id.
This approach allows me to include the menu in multiple pages using ui:include or put it in a template. Hope it can help someone else.
Allen