Friday, October 3, 2014

Programatically add tabs and contents using PrimeFaces.

Example code for adding new tabs and contents dynamically.

XHTML
<h:form id="form">
    <p:tabView id="tabview"

               cache="false"

               activeIndex="0"

               dynamic="true"

               binding="#{tabbedView.tabView}">

        <p:tab title="a">

            <p:outputLabel value="aaa" />

        </p:tab>

        <p:tab title="b">

            <p:outputLabel value="bbb" />

        </p:tab>

        <p:tab title="c">

            <p:outputLabel value="ccc" />

        </p:tab>

    </p:tabView>

    <p:outputLabel value="dynamic content" />

    <p:inputText id="dynamicText" value="#{tabbedView.dynamicText}" />

    <p:commandButton value="add tab"

                     process="@this,dynamicText"

                     update="tabview"

                     actionListener="#{tabbedView.addNewTab}">

    </p:commandButton>
    
</h:form>


ManagedBean
@ManagedBean

public class TabbedView {

    private TabView tabView;

    private String dynamicText;

    @PostConstruct

    public void init() {

        tabView = new TabView();

    }

    public TabView getTabView() {

        return tabView;

    }

    public void setTabView(TabView tabView) {

        this.tabView = tabView;

    }

    public String getDynamicText() {

        return dynamicText;

    }

    public void setDynamicText(String dynamicText) {

        this.dynamicText = dynamicText;

    }


    public void addNewTab(ActionEvent event) {

        OutputLabel label = new OutputLabel();

        label.setValue(dynamicText);

        Tab newTab = new Tab();

        newTab.setTitle(UUID.randomUUID().toString());

        newTab.getChildren().add(label);

        tabView.getChildren().add(newTab);

    }

}

1 comment:

  1. Nice post, thank you!
    What also would be nice to describe, is how to add ui:includes in these tabs. It is quite challenging.

    ReplyDelete