jsf - 如何在 p :tabView component 中动态添加和删除选项卡

标签 jsf dynamic primefaces tabview

我正在尝试添加一个 PrimeFaces <p:tab>动态。在添加第二个选项卡时,我收到以下异常:

"java.lang.IllegalStateException: Component ID tab0 has already been found in the view".



我该如何解决这个问题?

这是 View 代码:
<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>

这是 bean 代码:
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";
}

最佳答案

如果一切都可以在 View 中完成,请不要手动创建组件。如果 bean 的范围比请求范围更广,则此构造将失败。另见例如Binding attribute causes duplicate component ID found in the view

按照展示示例“TabView with Model ”,它允许您通过健全的模型和 <p:tabView value="..." var="..."> 动态填充选项卡。像 <ui:repeat>/<h:dataTable> .

例如。这种看法

<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>

使用这个 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;
    }

}

和这个模型
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;
    }

}

关于jsf - 如何在 p :tabView component 中动态添加和删除选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7308535/

相关文章:

java - JSF 2 动态表单和 Bean 验证 JSR 303

java - 为什么通知栏不起作用?

java - JSF setLocale 不能正常工作

java - 将 commandLink 嵌套到输出格式

image - PrimeFaces imageCropper 不显示可选区域

android - 在线程中创建动态 tableLayout

ios - Firebase 动态链接在 iOS 上不起作用

Angular2(点击)动态加载组件 View

jsf - <p :commandButton> not working when disable ="true" initially

jsf - Spring webflow & PrimeFaces 表达式语言-bean 方法被解释为 websphere 中的属性而不是 tomcat