Имеется datatable на JSF странице с столбцами, которой являются название продукта, его цена и input поле количества этого товара. При нажатии кнопки нужно загрузить в коллекцию элементы из datatable, где значение введенного количества больше 0 (метод addCups()).
Как можно корректно это реализовать?
@ManagedBean
@SessionScoped
public class OrderBean extends SpringBeanAutowiringSupport {
@Autowired
private OrderDAO orderDAO;
@Autowired
private OrderPositionDAO orderPositionDAO;
private Map<Long, Integer> selectedItems = new HashMap<>();
private Integer quantityOfCups;
public Map<Long, Integer> getSelectedItems() {
return selectedItems;
}
public void setSelectedItems(Map<Long, Integer> selectedItems) {
this.selectedItems = selectedItems;
}
public Integer getQuantityOfCups() {
return quantityOfCups;
}
public void setQuantityOfCups(Integer quantityOfCups) {
this.quantityOfCups = quantityOfCups;
}
public void addCups(Long id, Integer numOfCups){
if(numOfCups > 0){
selectedItems.put(id, numOfCups);
}
if(numOfCups == 0){
selectedItems.remove(id);
}
System.out.println(selectedItems);
}
JSF страница
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:form>
<p:dataTable value="#{coffeeBean.allCoffee}" var="coffee">
<p:column>
<h:outputText value="#{coffee.coffeeName}"/>
</p:column>
<p:column>
<h:outputText value="#{coffee.costForCup}"/>
</p:column>
<p:column>
<p:inputText value="#{orderBean.quantityOfCups}"/>
</p:column>
</p:dataTable>
<h:commandButton value="add cups" action="#{orderBean.addCups(coffee.id, orderBean.quantityOfCups)}"/>
</h:form>
</html>
Начнём разбирать код по порядку:
1) coffee видна только в рамках компонента p:dataTable, так как объявлена в внутри него. Параметр coffee.id в выражении #{orderBean.addCups(coffee.id, orderBean.quantityOfCups)} примет значение null.
2) Выражение #{orderBean.quantityOfCups} ссылается на одну переменную и для каждой строчки будет перезаписываться.
Путей решения приведённой задачи может быть много, самые очевидные: добавить в coffeeBean.allCoffee поле количество чашек либо повесить слушатель на поле ввода. Для количества страница:
<p:dataTable value="#{coffeeBean.allCoffee}" var="coffee">
<p:column>
<h:outputText value="#{coffee.coffeeName}"/>
</p:column>
<p:column>
<h:outputText value="#{coffee.costForCup}"/>
</p:column>
<p:column>
<p:inputText value="#{coffee.quantityOfCups}"/>
</p:column>
</p:dataTable>
<h:commandButton value="add cups" action="#{orderBean.addCups()}"/>
bean
public void addCups(){
for(Coffee coffee: coffeeBean.getAllCoffee){
if(coffee.getQuantityOfCups > 0)
selectedItems.put(coffee.getId(), coffee.getQuantityOfCups);
if(coffee.getQuantityOfCups == 0)
selectedItems.remove(coffee.getId());
}
}
Для слушателя:
<p:dataTable value="#{coffeeBean.allCoffee}" var="coffee">
<p:column>
<h:outputText value="#{coffee.coffeeName}"/>
</p:column>
<p:column>
<h:outputText value="#{coffee.costForCup}"/>
</p:column>
<p:column>
<p:inputText value="#{orderBean.quantityOfCups}">
<p:ajax event="change" process="@this" update="@this" listener="#{orderBean.addCups(coffee.id)}"/>
</p:inputText>
</p:column>
</p:dataTable>
bean
public void addCups(Long id){
if(quantityOfCups > 0)
selectedItems.put(id, quantityOfCups);
if(quantityOfCups == 0)
selectedItems.remove(id);
}
public Integer getQuantityOfCups() {
return quantityOfCups;
}
public void setQuantityOfCups(Integer quantityOfCups) {
this.quantityOfCups = quantityOfCups;
}
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости