How to dynamically add and remove a tab in a p: tabView component

I am trying to add PrimeFaces <p:tab> dynamically. When adding a second tab, I get the following exception:

"java.lang.IllegalStateException: component identifier tab0 already found in view."

How can i solve this?

Here is the view code:

 <h:form prependId="false"> <p:tabView id="tabview" dynamic="true" cache="false" binding="#{testBean.tabView}" activeIndex="#{testBean.activeTab}" > <h:commandButton value="Close" action="#{testBean.removeTab}"/> </p:tabView> <h:commandButton value="Add Tab" action="#{testBean.addTab}"/> </h:form> 

Here is the bean code:

 public String addTab() { String tabId="tab"+id; System.out.println("Gen Id: "+tabId); tab = new Tab(); tab.setTitle("Title: "+tabId); tab.setId(tabId); System.out.println("Tab Id: "+tab.getId()); tabView.getChildren().add(id,this.tab); id++; return "tabtest.jsf"; } public String removeTab() { tabView.getChildren().remove(activeTab); return "tabtest.jsf"; } 
+4
source share
2 answers

Do not manually create components if you can just do everything in the view. This construct will fail if the bean is in a wider scope than the request scope. See Also, for example. The bind attribute duplicates the identifier of the component found in the view

Follow the example of the TabView with Model showcase, which allows you to dynamically populate tabs using a smart model and <p:tabView value="..." var="..."> like <ui:repeat> / <h:dataTable> .

eg. this view

 <h:form> <p:tabView value="#{bean.tabs}" var="tab"> <p:tab title="#{tab.title}"> #{tab.content} <p:commandButton value="Close" action="#{bean.remove(tab)}" update="@form" /> </p:tab> </p:tabView> <p:commandButton value="Add Tab" action="#{bean.add}" update="@form" /> </h:form> 

with this controller

 @ManagedBean @ViewScoped public class Bean implements Serializable { private List<Tab> tabs; @PostConstruct public void init() { tabs = new ArrayList<>(); } public void add() { tabs.add(new Tab("tab" + tabs.size(), "some content")); } public void remove(Tab tab) { tabs.remove(tab); } public List<Tab> getTabs() { return tabs; } } 

and this model

 public class Tab { private String title; private String content; public Tab(String title, String content) { this.title = title; this.content = content; } public String getTitle() { return title; } public String getContent() { return content; } } 
+11
source

This is because the same ID is created for the new tab (the one that the ur adds). To avoid this, add the variable to id as

 <p:tabView id="tabview_#{testBean.i}" dynamic="true" cache="false"binding="#{testBean.tabView}" activeIndex="#{testBean.activeTab}" > <h:commandButton value="Close" action="#{testBean.removeTab}"/> </p:tabView> 
0
source

All Articles