9

I have Primefaces TabView with two Tab like:

<p:tabView dynamic="true" cache="false"
           onTabShow="scrollBottom(#{stanzaBean.activeIndex})"
           tabChangeListener="#{messaggioBean.onTabChange}"
           activeIndex="#{stanzaBean.activeIndex}" >

it works fine, except that when I change the Tab the activeIndex isn't updated on the Server and it returns always the default value. I'm using primefaces 2.2.1.

Thank you.

Roberto de Santis
  • 868
  • 5
  • 15
  • 26

3 Answers3

14

Going by the PrimeFaces ShowCase example, if you give each tab an id:

<p:tabView tabChangeListener="#{indexBean.onTabChange}" >
    <p:tab title="tab 0" id="tab0"></p:tab>
    <p:tab title="tab 1" id="tab1" ></p:tab>
    <p:tab title="tab 2" id="tab2"></p:tab>               
</p:tabView>

you can get that tab id in the tabChangeListener.

public void onTabChange(TabChangeEvent event) {       
    System.out.println("tab id = " + event.getTab().getId());
}

Then you'll know which tab was selected.


Edit:

There is an open PrimeFaces issue 1640 TabView: Wrong activeIndex in TabChangeListener, always 0 on the problem you are having.


Edit 2:

With PrimeFaces 5.0 and up the tabChangeListener is no longer available on the tabView element but should be used via an explicit ajax tag with a tabChange event.

 <p:tabView id="analysisSections" value="#{analysisBean.analysis.sections}" var="section" activeIndex="#{analysisBean.activeIndex}">
      <p:ajax event="tabChange" listener="#{analysisBean.onTabChange}"/>

Also you can directly get index of tab:

public void onTabChange(TabChangeEvent event) {
    activeIndex = ((TabView) event.getSource()).getIndex();
}

with all these changes, activeIndex works properly.

Kukeltje
  • 12,223
  • 4
  • 24
  • 47
Mark
  • 16,772
  • 9
  • 42
  • 55
8

this worked for me:

public void onTabChange(TabChangeEvent event) {
        Tab activeTab = event.getTab();
        tabPanelIndex = ((TabView)event.getSource()).getChildren().indexOf(activeTab);
    }
4

Although the question was related to PrimeFaces 2.2.1, I like to mention that in modern PrimeFaces versions (tested with version 6.2) there is no need to trigger a separate event when attribute dynamic is set to true and cache is set to false. By using this attribute combination the active index is automatically updated on the server when another tab is selected.

Facelet:

<p:tabView activeIndex="#{stanzaBean.activeIndex}"
           cache="false"
           dynamic="true">

Bean:

@Named
@ViewScoped
public class StanzaBean implements Serializable {

    private int activeIndex;

    public int getActiveIndex() {
        return activeIndex;
    }

    /**
     * Automatically called whenever a tab changes and dynamic="true"
     * and cache="false".
     */
    public void setActiveIndex(int activeIndex) {
        this.activeIndex = activeIndex;

        // do other stuff when tab changes
    }

}
ltlBeBoy
  • 1,242
  • 16
  • 23