Forms 将行添加到带有requestScope托管bean的p:datatable,其中我有一个表单验证

Forms 将行添加到带有requestScope托管bean的p:datatable,其中我有一个表单验证,forms,jsf-2,primefaces,Forms,Jsf 2,Primefaces,我已经阅读了for BalusC的示例,并尝试使用请求范围添加一行,但我发现一个问题是,当我添加 <h:inputHidden binding="#{myBean.dataItemId}" /> 我的页面上的所有按钮都不起作用。起初我以为问题出在转换器上 <h:inputHidden binding="#{myBean.dataItemId}" converter="javax.faces.Integer"/> 但是如果没有转换器,我也会遇到同样的问题 第二个

我已经阅读了for BalusC的示例,并尝试使用请求范围添加一行,但我发现一个问题是,当我添加

<h:inputHidden binding="#{myBean.dataItemId}" />

我的页面上的所有按钮都不起作用。起初我以为问题出在转换器上

<h:inputHidden binding="#{myBean.dataItemId}" converter="javax.faces.Integer"/>

但是如果没有转换器,我也会遇到同样的问题

第二个更有趣的是,从示例代码中,我不理解在向datatable添加新行时,该表如何在之前获取我添加的行

例如,如果我在添加时添加第一行并将数据放在第二行,我意识到add函数创建了一个新的
ArrayList
,我认为它将删除第一行,正如那篇文章顶部的“Notice”块中提到的,它是针对JSF 1.2的。使用JSF2.0视图范围可以更容易地添加行

根据JSF 1.2文章中给出的示例,您只需要做2个更改:

  • 将bean放入视图范围

  • 删除整个
    addCount
    属性及其任何引用

  • 以下是JSF 2.0版本中的一个启动示例:

    @ManagedBean
    @ViewScoped
    public class Bean {
    
        private List<Item> items;
    
        @EJB
        private ItemService service; // Or just DAO. Whatever you want.
    
        @PostConstruct
        public void init() {
            items = service.list();
        }
    
        public void add() {
            items.add(new Item());
        }
    
        public void save() {
            service.save(items);
        }
    
        public List<Item> getItems() { 
            return items;
        }
    
    }
    
    @ManagedBean
    @视域
    公共类Bean{
    私人清单项目;
    @EJB
    private-ItemService;//或者只是DAO。随你怎么做。
    @施工后
    公共void init(){
    items=service.list();
    }
    公共无效添加(){
    添加(新项());
    }
    公共作废保存(){
    服务。保存(项目);
    }
    公共列表getItems(){
    退货项目;
    }
    }
    
    以及以下观点:

    <h:dataTable value="#{bean.items}" var="item">
        <h:column>
            <h:outputText value="#{item.id}" rendered="#{item.id != null}" />
            <h:outputText value="new" rendered="#{item.id == null}" />
        </h:column>
        <h:column>
            <h:outputText value="#{item.name}" rendered="#{item.id != null}" />
            <h:inputText value="#{item.name}" rendered="#{item.id == null}" />
        </h:column>
        <h:column>
            <h:outputText value="#{item.value}" rendered="#{item.id != null}" />
            <h:inputText value="#{item.value}" rendered="#{item.id == null}" />
        </h:column>
    </h:dataTable>
    <h:commandButton value="Add" action="#{bean.add}" />
    <h:commandButton value="Save" action="#{bean.save}" />