Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeFaces "tabChange" event with dynamic number of tabs

Tags:

jsf

primefaces

I need to get title of currently active tab inside my TabView. TabView is constructed with dynamic number of tabs with listener attached to "tabChanged":

<p:tabView value="#{bean.list}" var="listItem">
  <p:ajax event="tabChange" listener="#{listenerBean.onChange}" />
  <p:tab title="#{listItem.stringProperty}">
  </p:tab>
</p:tabView>

The problem is that TabChangeEvent object received by onChange(TabChangeEvent event) always contains first tab instead of the active one.

public void onChange(TabChangeEvent event) {
    event.getTab().getTitle(); //allways returns title of first tab
}

This behavior is only true for dynamic number of tabs in TabView if I define each tab explicitly, TabChangeEvent works fine.

Any suggestions? Thanks.

I use PrimeFaces 3.5 with JSF2.1 and Servlets 2.5

like image 397
troy Avatar asked Nov 10 '22 19:11

troy


1 Answers

The following minimal example worked for my like a charm by printing the title of the tab to activate every time I click on it:

page.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <f:view>
        <h:head/>
        <h:body>
            <h:form>
                <p:tabView value="#{bean.items}"
                           var="item">
                    <p:ajax event="tabChange"
                            listener="#{bean.printTitle}"
                            update="@form"/>
                    <p:tab title="#{item}">
                    </p:tab>
                </p:tabView>
            </h:form>
        </h:body>
    </f:view>
</html>

Bean.java

import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.primefaces.event.TabChangeEvent;

@Named
@ViewScoped
public class Bean implements Serializable {

    private final List<String> items = Arrays.asList("Hello", "This", "Is", "TabView");

    public List<String> getItems() {
        return items;
    }

    public void printTitle(TabChangeEvent event) {
        System.out.println("title = [" + event.getTab().getTitle() + "]");
    }
}
like image 108
Smutje Avatar answered Nov 15 '22 12:11

Smutje