【问题标题】:Retrieve InputText value foreach row in JSF dataTable, which is not a property object检索 JSF dataTable 中每一行的 InputText 值,这不是属性对象
【发布时间】:2014-04-30 16:55:27
【问题描述】:

如何为 JSF dataTable 中的每一行检索 inputText 值,因为该数据不是我们在循环中迭代的对象中的属性。

(此处为 0 作为默认值)。我无法更改 Class 属性(此处为 Product)

<h:form>

  <p:dataTable var="product" value="#{bean.products}">

  <p:column headerText="Id">
    <h:outputText value="#{product.id}" />
  </p:column>

  <p:column headerText="Name">
    <h:outputText value="#{product.name}" />
  </p:column>

  <p:column headerText="Quantity">
      <h:inputText size="3" value="0" />
  </p:column>

</p:dataTable>

 <h:commandButton value="Submit" action="#{bean.submit}"/>
</h:form>

Bean.class

@ManagedBean

...

   public void submit() {
    List<Product> products = this.getProducts();

    for(Product product : list) {
         System.out.println("Product.name : "+ Product.name  );
        System.out.println("Quantity : "+ ?? );
     }
   }

【问题讨论】:

    标签: jsf jsf-2 datatable attributes


    【解决方案1】:

    Product(或其ID)为键将其绑定到Map

    例如

    private List<Product> products;
    private Map<Product, Long> quantities;
    
    @EJB
    private ProductService productService;
    
    @PostConstruct
    public void init() {
        products = productService.list();
        quantities = new HashMap<>();
    }
    
    public void submit() {
        for (Product product : products) {
            Long quantity = quantities.get(product);
            System.out.println("Quantity: " + quantity);
        }
    }
    
    // Getters (no setters necessary for those two properties)
    

    <h:inputText size="3" value="#{bean.quantities[product]}" />
    

    【讨论】:

    • 你能在这里解释一下ProductService的内容吗?
    【解决方案2】:

    您可以使用访问者模式来获取值。像这样的:

                table.visitTree(VisitContext.createVisitContext(faces),
                    new VisitCallback() { 
                        @Override public VisitResult visit(VisitContext vc, UIComponent component) {
                            if (component.equals(quantity) && quantity.getValue() != null) {
                                cart.addItem(
                                    (Product) table.getRowData(), 
                                    (Integer) quantity.getValue());
                            }
                            return VisitResult.ACCEPT;
                        }
                    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 2012-11-10
      • 2016-05-28
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多