javaprimefacesmenubartabview

How do I set the active tab in Primefaces tabView?


I have a menu bar in which two items on a submenu, both calling the same page:

<p:menubar autoSubmenuDisplay="true">
   <p:submenu label="Perfil">
       <p:menuitem value="Editar" url="perfil.xhtml" />
       <p:menuitem value="Ver" url="perfil.xhtml" />
   </p:submenu>
</p:menubar>

On that page, I have a tabview with two tabs:

<p:tabView dynamic="true">
    <p:tab id="ver" title="Ver perfil">
        <ui:include src="verPerfil.xhtml" />
    </p:tab>
    <p:tab id="editar" title="Editar perfil">
      <ui:include src="editarPerfil.xhtml" />
    </p:tab>
</p:tabView>

How can I set the active tab, so each menu item activate the corresponding tab?


Solution

  • If you want to do this, you can't use the url in the p:menuitem, because we must call a method to changing the tabindex before skipping to the prefil.xhtml page. If you use the url, the method will be invoked after we skip to the prefil.xhtml page .

    First, you can use the action field of the p:menuitem, the method returns the address you want to skip to:

    <p:menubar autoSubmenuDisplay="true">
        <p:submenu label="Perfil">
            <p:menuitem value="Editar" action="#{some.editar}" ajax="false"/>
            <p:menuitem value="Ver" action="#{some.ver}" ajax="false" />
        </p:submenu>
    </p:menubar>
    

    These two method do something to change the tabindex like this:

    public String editar() {
        tabindex = 0;
        return "verPerfil";
    }
    
    public String ver() {
        tabindex = 1;
        return "verPerfil";
    }
    

    Then the p:tabView has an attribute named activeIndex. It is the index of the active tab, its default value is 0. So you can do as follows:

    <p:tabView dynamic="true" activeIndex="#{some.tabindex}" >
        <p:tab id="ver" title="Ver perfil">
            <ui:include src="verPerfil.xhtml" />
        </p:tab>
        <p:tab id="editar" title="Editar perfil">
            <ui:include src="editarPerfil.xhtml" />
        </p:tab>
    </p:tabView>
    

    Then each menu item will activate the corresponding tab.