How to add a button to add new tabs next to the last tab?

Does anyone know how to add a button to add new tabs located next to the last created tab? If it’s not clear what I am, just look at the tabs in your browser and the button to add a new tab ;-), which is exactly what I want to manage.

I am using MyFaces + PrimeFaces.

+5
source share
1 answer

You can use <p:tabView>to display dynamic tabs based on some beans collection. You can present the β€œAdd” tab as the last tab of the tab. You can, if necessary, in a different way. You can use <p:ajax event="tabChange">to connect a tab change listener, in which you can check if the "Add" tab has been opened, and then add a new tab.

eg.

<h:form id="form">
    <p:tabView id="tabs" value="#{bean.tabs}" var="tab" widgetVar="w_tabs">
        <p:ajax event="tabChange" listener="#{bean.changeTab}" oncomplete="if (args.newTabIndex) w_tabs.select(args.newTabIndex)" />
        <p:tab title="#{tab.title}">
            <p>#{tab.content}</p>
        </p:tab>
    </p:tabView>
</h:form>

with

@ManagedBean
@ViewScoped
public class Bean implements Serializable {

    private List<Tab> tabs;

    @PostConstruct
    public void init() {
        // Just a stub. Do your thing to populate tabs.
        // Make sure that the last tab is the "Add" tab.
        tabs = new ArrayList<Tab>();
        tabs.add(new Tab("tab1", "content1"));
        tabs.add(new Tab("tab2", "content2"));
        tabs.add(new Tab("Add...", null));
    }

    public void changeTab(TabChangeEvent event) {
        int currentTabIndex = ((TabView) event.getComponent()).getActiveIndex();
        int lastTabIndex = tabs.size() - 1; // The "Add" tab.

        if (currentTabIndex == lastTabIndex) {
            tabs.add(lastTabIndex, new Tab("tab" + tabs.size(), "content" + tabs.size())); // Just a stub. Do your thing to add a new tab.
            RequestContext requestContext = RequestContext.getCurrentInstance();
            requestContext.update("form:tabs"); // Update the p:tabView to show new tab.
            requestContext.addCallbackParam("newTabIndex", lastTabIndex); // Triggers the oncomplete.
        }
    }

    public List<Tab> getTabs() {
        return tabs;
    }

}

The class Tabin this example is a simple javabean with titleand properties content. oncompletein <p:ajax>necessary, because the contents of the tab would otherwise disappear after adding a new tab (which is pretty much like a PF error, after all, I used 3.3).

+6
source

All Articles