Question

How would it be possible to retrieve an inputText value foreach row in JSF dataTable, since this data is not an attribute in the object on which we iterate in the loop.

(here 0 as default value). I can't change the Class properties (here 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 : "+ ?? );
     }
   }
Was it helpful?

Solution

Bind it to a Map with Product (or its ID) as key.

E.g.

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)

with

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

OTHER TIPS

You can use the visitor pattern to get the values. Something like this:

            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;
                    }
                });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top