PrimeFaces get all row value of datatable - jsf

I am new for prime face. I had a checkbox and textbox value on dataTable.And dataTable will load data from database. Please see my code below
text.xhtml
<?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:c="http://java.sun.com/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="../templates/layout.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:event type="preRenderView" listener="#{kooBean.initEdit}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h:form prependId="false" id="growlForm">
<p:growl id="growl" showDetail="#{applicationBean.isShowDetailMessage()}" />
</h:form>
<h:form id="form">
<p:dataTable id="list" value="#{kooBean.model}" lazy="true" var="kooTable"
rendered="#{kooBean.dataVisible}" paginatorTemplate=" {CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,25,50" rows="10" sortBy="#{kooTable.id}" selection="#{kooBean.selectedCars}"
rowKey=" #{kooTable.id}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:10%;text-align:center" />
<p:column headerText="Description" >
#{kooTable.description}
<p:inputText value=" #{kooTable.param_str}" />
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
bean.java
package my.com.mesiniaga.sphere.web;
import static my.com.mesiniaga.sphere.domain.KooPredicate.nameLike;
import my.com.mesiniaga.sphere.domain.KooTable;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.model.LazyDataModel;
import org.springframework.roo.addon.jsf.managedbean.RooJsfManagedBean;
import org.springframework.roo.addon.serializable.RooSerializable;
import my.com.mesiniaga.sphere.service.KooService;
import my.com.mesiniaga.sphere.service.QueryDslSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Date;
import com.mysema.query.types.Predicate;
#RooSerializable
#RooJsfManagedBean(entity = KooTable.class, beanName = "kooBean")
public class KooBean {
private KooTable kooTable = new KooTable();
private String attribute;
private List<String> cols;
public String userId;
public String emailNotification;
private boolean addGroup = false;
private boolean editGroup = false;
private boolean addGroupUser = false;
private KooTable selectedCar;
private KooTable[] selectedCars;
private final LazyDataModel<KooTable> model = new AbstractQueryDslJpaLazyDataModel<KooTable>() {
#Override
public Predicate getPredicate(){
// LOG.info(getKooTable().getName());
return nameLike(getKooTable().getDescription());
}
//
#Override
public QueryDslSupport<KooTable> getQueryDslSupport(){
return kooService;
}
};
public LazyDataModel<KooTable> getModel() {
return model;
}
public String getUserId() {
return userId;
}
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
public String getEmailNotification() {
return emailNotification;
}
//
// public void setEmailNotification(String emailNotification) {
// this.emailNotification = emailNotification;
// }
public List<String> getCols() {
return cols;
}
public void setCols(List<String> cols) {
this.cols = cols;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public boolean isAddGroup() {
return addGroup;
}
public void setAddGroup(boolean addGroup) {
this.addGroup = addGroup;
}
public boolean isEditGroup() {
return editGroup;
}
public void setEditGroup(boolean editGroup) {
this.editGroup = editGroup;
}
public boolean isAddGroupUser() {
return addGroupUser;
}
public void setAddGroupUser(boolean addGroupUser) {
this.addGroupUser = addGroupUser;
}
public void initCreatePage() {
//Initialize user group listing page
cols = new ArrayList<String>();
cols.add("id");
cols.add("description");
// displayGroupsList();
if (!FacesContext.getCurrentInstance().isPostback()) {
// if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("edit") != null) {
// LOG.info("EDIT....");
// attribute = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer");
// initEdit();
// editGroup = true;
// } else if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("create") != null) {
// LOG.info("CREATE....");
// addGroup = true;
// }
}
}
//
// public String displayGroupsList() {
// findAllGroupses();
// return LIST_NAVIGATION_PAGE;
// }
//
// public String cancelCreateGroup(){
// return LIST_NAVIGATION_PAGE;
// }
//
// public String createGroup() {
// String message = "";
// try {
//
// if (groups.getId() != null) {
// //submit response inquiry
//
// groupsService.responseInquiry(groups);
// message = "message_successfully_updated";
// } else {
// groups.setDescription("none");
// groups.setUpdatedby(1L);
// groups.setUpdatedon(new Date());
// groupsService.create(groups);
// message = "message_successfully_created";
// }
// } catch (NestedRuntimeException e) {
// LOG.error(e.getMostSpecificCause().getMessage(), e);
// message = "Failed to update";
// FacesMessage facesMessage = new FacesMessage(message);
// facesMessage.setDetail(e.getMostSpecificCause()
// .getLocalizedMessage());
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// return null;
// }
// FacesMessage facesMessage = MessageFactory.getMessage(message,
// "groups");
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// // FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
//// reset();
// return LIST_NAVIGATION_PAGE;
// }
public void initEdit() {
System.out.println("init edit !");
// String groupId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("groupId");
// if (groupId != null) {
// addGroupUser = true;
// groupsWithTask = groupsService.findGroupsWithTask(Long.valueOf(groupId));
// groups = groupsWithTask.getGroups();
// if (groupsWithTask.getTask() != null) {
// LOG.info("task name = " + groupsWithTask.getTask().getName());
// }
// }
}
public boolean isDataVisible() {
return true;
}
// public Car[] getSelectedCars() {
// return selectedCars;
// }
// public void setSelectedCars(Car[] selectedCars) {
// this.selectedCars = selectedCars;
// }
public KooTable[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(KooTable[] selectedCars) {
this.selectedCars = selectedCars;
}
public KooTable getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(KooTable selectedCar) {
this.selectedCar = selectedCar;
}
}
Here is my question.When I click view button, I need to get every row of value including checkbox value whether checkbox is checked or nt then update to database. Is it possible?

Related

PrimeFaces DataTable doesn't update when filtered

I'm new to PrimeFaces and to JSF.
I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.
Have you got any suggestions?
I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table
Thank you, any help will be appreciated
<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
<h:form>
<p:dataTable var="car" value="#{dtCar.cars}" widgetVar="carsTable"
emptyMessage="No cars found with given criteria"
filteredValue="#{dtCar.filteredCars}">
<p:column filterBy="#{car.model}" headerText="Model"
footerText="contains" filterMatchMode="contains">
<h:outputText value="#{car.model}" />
</p:column>
<p:column filterBy="#{car.color}" headerText="Color"
footerText="contains" filterMatchMode="contains">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
</h:form>
</h:body>
</html>
Here is the CarBean.java
package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name = "dtCar")
#ViewScoped
public class CarBean {
private List<Car> cars;
private List<Car> filteredCars;
public CarBean() {
setCars(new ArrayList<Car>());
getCars().add(new Car("myModel", "blu"));
getCars().add(new Car("punto", "blu"));
getCars().add(new Car("doblo", "grigio"));
getCars().add(new Car("smart", "blu"));
getCars().add(new Car("twingo", "rosso"));
getCars().add(new Car("twingo", "bianco"));
getCars().add(new Car("doblo", "blu"));
// add more cars
}
// getter setter
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getFilteredCars() {
return filteredCars;
}
public void setFilteredCars(List<Car> filteredCars) {
this.filteredCars = filteredCars;
}
public String loadNewCars() {
if (getCars().get(0).getModel().equals("myModel")) {
getCars().clear();
getCars().add(new Car("gt", "giallo"));
getCars().add(new Car("scirocco", "azzurro"));
getCars().add(new Car("duna", "giallo"));
getCars().add(new Car("diablo", "griggio"));
getCars().add(new Car("cayenne", "rosso"));
getCars().add(new Car("aygo", "azzurro"));
setFilteredCars(null);
}
else {
getCars().clear();
getCars().add(new Car("myModel", "blu"));
getCars().add(new Car("punto", "blu"));
getCars().add(new Car("doblo", "grigio"));
getCars().add(new Car("smart", "blu"));
getCars().add(new Car("twingo", "rosso"));
getCars().add(new Car("twingo", "bianco"));
getCars().add(new Car("doblo", "blu"));
setFilteredCars(null);
}
return null;
}
}
And here is the Car.java
package it.caditech.testtable;
public class Car {
private String model;
private String color;
public Car(String m, String c) {
model = m;
color = c;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
As suggested by #Kukeltje I switch to lazyModel and it works very fine. I followed the example in Primefaces Showcase https://www.primefaces.org/showcase/ui/data/datatable/lazy.xhtml
With lazy model I guess that paginator must be set to true, or else my example doesn't work.
Here's the new version of pagina1.xhtml
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="dt" var="car" value="#{dtCar.lazyModel}" lazy="true" paginator="true" rows="2">
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column filterBy="#{car.model}" headerText="Model">
<h:outputText value="#{car.model}" />
</p:column>
<p:column filterBy="#{car.color}" headerText="Color">
<h:outputText value="#{car.color}"/>
</p:column>
</p:dataTable>
<h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
</h:form>
</h:body>
</html>
Here is CarBean.java
package it.caditech.testtable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.LazyDataModel;
#ManagedBean(name = "dtCar")
#ViewScoped
public class CarBean {
private LazyDataModel<Car> lazyModel;
#PostConstruct
public void init() {
lazyModel = new LazyCarDataModel();
}
public LazyDataModel<Car> getLazyModel() {
return lazyModel;
}
public String loadNewCars() {
((LazyCarDataModel) lazyModel).loadNewCars();
return null;
}
}
Here is the most important part, LazyCarDataModel
package it.caditech.testtable;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
public class LazyCarDataModel extends LazyDataModel<Car> {
private List<Car> datasource = new ArrayList<>();
public LazyCarDataModel() {
loadNewCars();
}
#Override
public Car getRowData(String rowKey) {
for (Car car : datasource) {
if (car.getId().equals(rowKey)) {
return car;
}
}
return null;
}
#Override
public Object getRowKey(Car car) {
return car.getId();
}
#Override
public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
List<Car> data = new ArrayList<Car>();
// filter
for (Car car : datasource) {
boolean match = true;
if (filters != null) {
for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
Object filterValue = filters.get(filterProperty);
BeanInfo info = Introspector.getBeanInfo(Car.class);
String fieldValue = null;
for (PropertyDescriptor p : info.getPropertyDescriptors()) {
if (p.getName().equals(filterProperty)) {
fieldValue = (String) p.getReadMethod().invoke(car, new Object[0]);
}
}
// String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
if (filterValue == null || fieldValue.contains(filterValue.toString())) {
match = true;
}
else {
match = false;
break;
}
}
catch (Exception e) {
match = false;
}
}
}
if (match) {
data.add(car);
}
}
// rowCount
int dataSize = data.size();
setRowCount(dataSize);
// paginate
if (dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch (IndexOutOfBoundsException e) {
return data.subList(first, first + dataSize % pageSize);
}
}
else {
return data;
}
}
protected void loadNewCars() {
if (datasource.isEmpty() || datasource.get(0).getModel().equals("myModel")) {
datasource.clear();
datasource.add(new Car("1", "gt", "giallo"));
datasource.add(new Car("2", "scirocco", "azzurro"));
datasource.add(new Car("3", "duna", "giallo"));
datasource.add(new Car("4", "diablo", "griggio"));
datasource.add(new Car("5", "cayenne", "rosso"));
datasource.add(new Car("6", "aygo", "azzurro"));
}
else {
datasource.clear();
datasource.add(new Car("7", "myModel", "blu"));
datasource.add(new Car("8", "punto", "blu"));
datasource.add(new Car("9", "doblo", "grigio"));
datasource.add(new Car("10", "smart", "blu"));
datasource.add(new Car("11", "twingo", "rosso"));
datasource.add(new Car("12", "twingo", "bianco"));
datasource.add(new Car("13", "twing", "rosa"));
datasource.add(new Car("14", "twist", "frizzante"));
datasource.add(new Car("15", "twelf", "rose"));
datasource.add(new Car("16", "twang", "riga"));
datasource.add(new Car("17", "doblo", "blu"));
}
}
}
I guess that the car Id property and the method getRowData() and getRowKey() can be omitted, for I don't need selection handling in this case.
Try this:
<p:dataTable id="yourDataTable" var="car"...
<p:poll interval="3" update="yourDataTable" />
I think you are mixing two different features, filter data and show updated data all the time. For the second case, you have some options to choice. You can listen for some event and then update you data or maybe you can ask all the time for the incoming new data, like jMarcel`s example.
check your transaction is concurrent.
use the same transaction.

Row selection for dataTable inside dataGrid is not working in Primefaces

I am using primefaces For displaying a datagrid of datatables as follow -
Facelets page:
<h:form name="form">
<p:dataGrid value="#{routeEditingBean.routes}" var="route"
columns="1">
<p:column>
<h:outputText value="#{route.routeId}" />
</p:column>
<p:dataTable value="#{route.routeDetailses}" var="rd"
rowKey="rd.id.employeeId"
selection="#{routeEditingBean.selectedRouteDetails}">
<p:column>
<h:outputText value="#{rd.id.employeeId}" />
</p:column>
<p:column selectionMode="multiple">
</p:column>
</p:dataTable>
<p:commandLink process="#all"
actionListener="#{routeEditingBean.display()}">
<p:graphicImage library="images" name="add-car.jpg"></p:graphicImage>
</p:commandLink>
</p:dataGrid>
</h:form>
Backing-bean:
#ManagedBean
#ViewScoped
public class RouteEditingBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
List<RouteMaster> routes;
List<RouteDetails> selectedRouteDetails;
RouteMaster delrb;
public RouteEditingBean() {
// TODO Auto-generated constructor stub
routes = new ArrayList<RouteMaster>();
Session session = HibernateUtil.getSessionFactory().openSession();
org.hibernate.Transaction transaction = null;
try {
HttpSession httpsession = (HttpSession) FacesContext
.getCurrentInstance().getExternalContext()
.getSession(false);
LoginBean lb = (LoginBean) httpsession.getAttribute("loginBean");
transaction = session.beginTransaction();
Criteria c = session.createCriteria(RouteMaster.class);
List routeMasterList = c.list();
for (Iterator iterator = routeMasterList.iterator(); iterator
.hasNext();) {
RouteMaster routeMaster = (RouteMaster) iterator.next();
System.out.println(routeMaster.getRouteId());
c = session.createCriteria(RouteDetails.class);
c.add(Restrictions.eq("id.routeId", routeMaster.getRouteId()));
Set<RouteDetails> routeDetailses = new HashSet<RouteDetails>();
for (Iterator iterator1 = c.list().iterator(); iterator1
.hasNext();) {
RouteDetails rd = (RouteDetails) iterator1.next();
routeDetailses.add(rd);
}
routeMaster.setRouteDetailses(routeDetailses);
routes.add(routeMaster);
}
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<RouteMaster> getRoutes() {
return routes;
}
public void setRoutes(List<RouteMaster> routes) {
this.routes = routes;
}
public RouteMaster getDelrb() {
return delrb;
}
public void setDelrb(RouteMaster delrb) {
this.delrb = delrb;
}
public List<RouteDetails> getSelectedRouteDetails() {
return selectedRouteDetails;
}
public void setSelectedRouteDetails(List<RouteDetails> selectedRouteDetails) {
this.selectedRouteDetails = selectedRouteDetails;
}
public void deleteEmployee(RouteMaster rm, RouteDetails rd) {
System.out.println(rm.getRouteId());
System.out.println(rd.getId().getEmployeeId());
}
public void display() {
System.out.println("Inside display");
if (selectedRouteDetails == null) {
System.out.println("No selection");
} else {
for (Iterator iterator = selectedRouteDetails.iterator(); iterator
.hasNext();) {
RouteDetails rd1 = (RouteDetails) iterator.next();
System.out.println(rd1.getId().getEmployeeId());
}
}
}
}
When form is Submitted then selected values are returning null. I want to get selected values for all dataTable in dataGrid. Please help.
can you try it this way
List<RouteDetails> selectedRouteDetails = new ArrayList<RouteDetails>();
or
public RouteEditingBean() {
selectedRouteDetails = new ArrayList<RouteDetails>();
.....
}

onRowEdit(RowEditEvent event) in prime faces is not getting me updated value [duplicate]

This question already has an answer here:
Edited/updated values in p:dataTable rowEdit are not available in listener method as they are being overwritten by existing data from database
(1 answer)
Closed 7 years ago.
I am trying to update the row using the jsf with primefaces here is my code for each files but when I debug I am not getting updated value it gives me an old value every-time and persist it same as an old one.
user-type.xhtml
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body style="align:center;">
<div style="width: 100%">
<h:form id="form">
<div style="float: left; width: 54%;">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="userTypesTbl" var="varUserType"
value="#{userTypeTabMenuBean.userTypeMasters}" editable="true"
style="margin-bottom:20px" rowIndexVar="rowIndex">
<f:facet name="header">User Type Managging</f:facet>
<p:ajax event="rowEdit" listener="#{userTypeTabMenuBean.onRowEdit}"
update=":form:msgs" />
<p:ajax event="rowEditCancel"
listener="#{userTypeTabMenuBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Sr.">
#{rowIndex+1}.
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{varUserType.type}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{varUserType.type}" style="width:100%"
label="type" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">View</f:facet>
<p:commandButton update=":form" oncomplete="userTypeDialog.show()"
icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{userType}"
var="#{selectedUserType}"
target="#{userTypeTabMenuBean.selectedUserType}" />
</p:commandButton>
</p:column>
<p:column style="width:32px;">
<f:facet name="header">Edit</f:facet>
<p:rowEditor />
</p:column>
<p:column style="width:32px;align-items: center;">
<f:facet name="header">Delete</f:facet>
<h:commandLink
action="#{userTypeTabMenuBean.deleteAction(varUserType)}">
<h:graphicImage library="images" name="delete.png" height="45%"
width="50%" />
</h:commandLink>
</p:column>
</p:dataTable>
<ui:debug hotkey="x" />
<p:dialog header="User type detail" widgetVar="userTypeDialog"
resizable="false" width="330" showEffect="explode"
hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="ID : " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.id}" />
<h:outputText value="TYPE: " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.type}" />
</h:panelGrid>
</p:dialog>
</div>
<div style="float: right; width: 44%;">
<p:panel menuTitle="Add User Type." header="Add User Type.">
<h:outputText value="User type *:" />
<p:inputText value="#{userTypeTabMenuBean.userType}"
title="Enter User Type.." id="myUserType"
style="margin:0px 10px 0px 10px;"></p:inputText>
<p:commandButton value="Add Type"
action="#{userTypeTabMenuBean.saveAction}" ajax="false">
</p:commandButton>
</p:panel>
</div>
</h:form>
</div>
</h:body>
</html>
UserTypeTabMenuBean.java
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
public List<UserTypeMaster> getUserTypeMasters() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
UserTypeMasterDAO.java
package com.convoy.gpack.dao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.convoy.gpack.hibernate.util.HibernateUtil;
import com.convoy.gpack.pack.models.UserTypeMaster;
public class UserTypeMasterDAO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4005898944892506760L;
public UserTypeMaster getUserTypeById(long long1) {
return null;
}
public List<String> getAllUserTypesInString() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
List<String> userTypeMastersString = new ArrayList<String>();
for (UserTypeMaster userTypeMaster : userTypeMasters) {
userTypeMastersString.add(userTypeMaster.getType());
}
transaction.commit();
session.close();
return userTypeMastersString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<UserTypeMaster> getAllUserTypes() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
transaction.commit();
session.close();
return userTypeMasters;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int saveOrUpdateUserTypeMaster(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
userTypeMaster.setType(userTypeMaster.getType().toUpperCase());
session.saveOrUpdate(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int deleteUserType(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
Thanks in advance ~ :)
Think it might be because of the database values list
#{userTypeTabMenuBean.userTypeMasters}
this always retrieves from the database and that is why getObject() returned an old value ( actually the value from the database)
update the method getUserTypeMasters() as follows
if (userTypeMasters == null){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
return userTypeMasters ;
Exactly Primefaces follows strict structure and I think it is compulsory to add init() method with #PostConstruct annotation.
#PostConstruct
public void init(){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
Here is the solution.
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
// This is the required method to get the datatable list.
#PostConstruct
public void init() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
}
public List<UserTypeMaster> getUserTypeMasters() {
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
init();
} else if (result == -2) {
FacesMessage msg = new FacesMessage("User type already exist..");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
That's it~ :)
Thanks #Swathi for the hint.

#ViewScoped calls post construct each time action is performed

I've asked one thousand of times but no one gives me a valid solution. Please why in my xhtml page the post construct is called all times when i press the button?how can i solve this problem?Please a valid solution. I've read many answers but they don't fit with my problem.I'm in trouble by 1 week.
The scope of my xhtml isn't changed :
update of a render component that updates another component
<!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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:outputLabel for="Name">Name:</p:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<p:outputLabel for="Location">Locations Available:</p:outputLabel>
<p:selectOneMenu id="Location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:selectItems
value="#{addDefaultPackageBean.availableLocations}" />
</p:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.Search()}" value="Ciao" render=":form:Volo" update=":form:Volo :form"></p:commandButton>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo" rendered="#{addDefaultPackageBean.flag}">
<h:panelGrid columns="3" id="voloGrid">
<p:outputLabel for="Volare">Volo:</p:outputLabel>
<p:selectOneMenu for="Volare" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Volare" value="#{addDefaultPackageBean.elelisfly}"
var="Ciao" itemValue="#{Ciao.name}"
itemLabel="#{Ciao.name}" />
</p:selectOneMenu>
<p:commandButton actionListener="#{addDefaultPackageBean.sel()}" value="hotel and escursions" render="#form" update=":form:Hotel :form"/>
</h:panelGrid>
</p:panel>
<p:outputLabel for="Hotel">Hotel:</p:outputLabel>
<p:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</p:selectOneMenu>
<p:message for="Hotel" />
<p:commandButton actionListener="#{addDefaultPackageBean.add}" value="Add" update=":form:Volo :form:Hotel" render="#form" process="#this,:form:Volo,:form:Location"/>
</h:form>
</h:body>
</html>
My bean page:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean implements Serializable {
/**
*
*/
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private Boolean flag=true;
private Boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.elelisfly=new ArrayList<ElementDTO>();
this.availableLocations=new ArrayList<String>();
this.flyElem=new ElementDTO();
}
#PostConstruct
public void init()
{
System.out.print("merda init ");
if(this.getElelisfly().size()==0){System.out.print("Voli vuoto ");}
this.setElelis(elemMgr.getAllElements());
this.selectedEscursions=new ElementDTO[this.getElelis().size()];
this.fly="";
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
System.out.print("entrato nell'ultimo step!il mio hotel è "+hotel);
//System.out.print("entrato nell'ultimo step!il mio hotel è "+this.selectedEscursions[0].getName());
/* //assegno location al pacchetto defpackDTO
this.defpackDTO.setLocation(this.getFlyElem().getLocation());
//assegno location a defpackDTO
this.defpackDTO.getElem().add(this.getFlyElem());
//assegno hotel a defpackDTO
this.AssignElemHotelFromSelection();
//assegno escursioni a defpackDTO
for(int i=0;i<this.selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(this.selectedEscursions[i]);
}
defpackMgr.save(defpackDTO);
*/
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila"+this.fly );
this.setElelis(this.elemMgr.getAllElementsByLocation(this.defpackDTO.getLocation()));
for(ElementDTO e:elelis)
{
System.out.print("elemento della location Haiti "+e.getName());
}
for(ElementDTO e:elelis)
{
System.out.print("elementisfwefsf dei voli "+e.getName());
}
this.AssignElemFlyFromSelection();
System.out.print(this.fly+"Il volo selezionato per la location è "+this.getFlyElem().getName() );
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&((e.getEndingDate().before(this.flyElem.getEndingDate()))))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
System.out.print("ho un escursione tra gli elementi con le date giuste"+e.getName());
this.getElelisescursion().add(e);
}
}
}
}
this.setFlag(true);
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
this.getElelisfly().clear();
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}
Use import javax.faces.bean.ViewScoped; if the managed bean is not a CDI artifact.

p:selectonemenu not working (JSF)

I have this problem.
I wanted to create selectOneMenu for custom select some data. But it's not working and i really don't know why. I spent cca 5 hours with this problem. I'm so desperate.
So some my code:
But when i will pick some item from selectonemenu, selected_id is still 0. Still, still. I tried to do almost everything but without result.
I tried this:
<p:selectOneMenu value="#{medicinesBean.selectedBranch}" required="true" effect="fade" id="listComboBox">
<f:selectItems value="#{medicinesBean.branchesForComboBox}" var="itm" itemLabel="#{itm.name}" itemValue="#{itm.id}" />
</p:selectOneMenu>
Backing Bean class:
/* private members */
private ArrayList<BranchDTO> branchesForComboBox = new ArrayList<BranchDTO>();
private BranchDTO selectedBranch;
/* getter and setters ... */
also i tried this with SelectItem[] model but result was same. NOT WORK.
Then i tried it like:
<p:selectOneMenu value="#{medicinesBean.selected_id}" required="true" effect="fade" id="listComboBox">
<f:selectItem itemLabel="First" itemValue="1"/>
<f:selectItem itemLabel="Second" itemValue="2"/>
<f:selectItem itemLabel="Third" itemValue="3"/>
<f:selectItem itemLabel="Fouth" itemValue="4"/>
</p:selectOneMenu>
/* private members */
private int selected_id;
But still 0. When i used object like value for selectonemenu, always null exception was always returned. So i will be glad for any advice for this.
Thanks
brw. backing bean is ViewScoped and data from DAO are correctly returned so some bug will be in component selectonemenu.
Thanks BalusC, so here is my implementation
Backing Bean
/**
* #author Sajmon
*/
package OraclBeans;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import EJBs.ZoznamLiekovEJB;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="zoznamLiekovBean")
#ViewScoped
public class ZoznamLiekovBean implements Serializable {
#EJB
private ZoznamLiekovEJB listOfMedicineEJB;
/* private members */
private ArrayList<ZoznamLiekovDTO> listOfMedicines;
private ArrayList<PobockaDTO> branchesForCombobox = new ArrayList<PobockaDTO>();
private ZoznamLiekovDTO selectedItem;
private PobockaDTO selectedBranch;
//private SelectItem[] branchesOptions;
//private SelectItem selectedOption;
private int selected_id;
public ZoznamLiekovBean() {
}
#PostConstruct
private void init() {
branchesForCombobox = listOfMedicineEJB.getBranches();
listOfMedicines = listOfMedicineEJB.getLists();
}
public void test() {
System.out.println("ID: " + selected_id);
}
/*
private SelectItem[] addItemsToOptions() {
SelectItem[] data = new SelectItem[branchesForCombobox.size()];
for (int i = 0; i < branchesForCombobox.size(); i++) {
data[i] = new SelectItem(branchesForCombobox.get(i).getId(), branchesForCombobox.get(i).getNazov());
}
return data;
}
*/
/* getters and setters */
/*
public SelectItem[] getBranchesOptions() {
return branchesOptions;
}
public void setBranchesOptions(SelectItem[] branchesOptions) {
this.branchesOptions = branchesOptions;
}
public void setSelectedOption(SelectItem selectedOption) {
this.selectedOption = selectedOption;
}
public SelectItem getSelectedOption() {
return selectedOption;
}
*/
public ArrayList<PobockaDTO> getBranchesForCombobox() {
return branchesForCombobox;
}
public void setBranchesForCombobox(ArrayList<PobockaDTO> branchesForCombobox) {
this.branchesForCombobox = branchesForCombobox;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
return listOfMedicines;
}
public void setListOfMedicines(ArrayList<ZoznamLiekovDTO> listOfMedicines) {
this.listOfMedicines = listOfMedicines;
}
public PobockaDTO getSelectedBranch() {
return selectedBranch;
}
public void setSelectedBranch(PobockaDTO selectedBranch) {
this.selectedBranch = selectedBranch;
}
public ZoznamLiekovDTO getSelectedItem() {
return selectedItem;
}
public void setSelectedItem(ZoznamLiekovDTO selectedItem) {
this.selectedItem = selectedItem;
}
public int getSelected_id() {
return selected_id;
}
public void setSelected_id(int selected_id) {
this.selected_id = selected_id;
}
}
EJB:
/**
* #author Sajmon
*/
package EJBs;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAO.OracleZoznamLiekovDAO;
import java.io.Serializable;
import java.util.ArrayList;
import javax.ejb.Stateless;
#Stateless
public class ZoznamLiekovEJB implements Serializable {
private OracleZoznamLiekovDAO dao = new OracleZoznamLiekovDAO();
public ArrayList<ZoznamLiekovDTO> getLists() {
return dao.getListOfMedicines();
}
public ArrayList<PobockaDTO> getBranches() {
return dao.getBranchesForCombobox();
}
}
DAO:
/**
* #author Sajmon
*/
package OraclDAO;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAOFactory.OracleDAOFactory;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OracleZoznamLiekovDAO implements Serializable {
private String SELECT_ALL = "SELECT Z.id_zoznamu, P.nazov_pobocky, L.nazov_lieku FROM Zoznam_liekov Z "
+ "JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)"
+ "JOIN Liek L ON (Z.id_lieku = L.id_lieku)";
private String SELECT_BRANCHES = "SELECT DISTINCT P.id_pobocky, P.nazov_pobocky FROM Zoznam_liekov Z JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)";
public OracleZoznamLiekovDAO() {
}
public ArrayList<PobockaDTO> getBranchesForCombobox() {
ArrayList<PobockaDTO> data = new ArrayList<PobockaDTO>();
PobockaDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_BRANCHES);
rs = ps.executeQuery();
while (rs.next()) {
item = new PobockaDTO();
item.setId(rs.getInt(1));
item.setNazov(rs.getString(2));
data.add(item);
}
System.out.println("Data imported to list successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
ArrayList<ZoznamLiekovDTO> data = new ArrayList<ZoznamLiekovDTO>();
ZoznamLiekovDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_ALL);
rs = ps.executeQuery();
while (rs.next()) {
item = new ZoznamLiekovDTO();
item.setId(rs.getInt(1));
item.getPobocka().setNazov(rs.getString(2));
item.getLiek().setNazov(rs.getString(3));
data.add(item);
}
System.out.println("List of Medicines imported successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
}
And XHTML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Zoznam liekov - prehľad</title>
<link rel="stylesheet" type="text/css" href="../style.css" />
</h:head>
<h:body>
<div id="out">
<h:form id="mainForm">
<p:selectOneMenu value="#{zoznamLiekovBean.selected_id}" required="true" effect="fade" id="zoznamComboBox">
<f:selectItems value="#{zoznamLiekovBean.branchesForCombobox}" var="itm" itemLabel="#{itm.nazov}" itemValue="#{itm.id}"/>
</p:selectOneMenu>
<p:commandButton immediate="true" styleClass="submitClass" value="Generuj zoznam" update="dialogText" actionListener="#{zoznamLiekovBean.test()}"/>
<p:dataTable style="width: 1100px" widgetVar="zoznamLiekovTable" selection="#{zoznamLiekovBean.selectedItem}" selectionMode="single" rowKey="#{item.id}" var="item" value="#{zoznamLiekovBean.listOfMedicines}" rows="5" rowsPerPageTemplate="5,10,15,20"
paginator="true" paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink}">
<p:column>
<f:facet name="header">ID:</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column>
<f:facet name="header">Pobočka:</f:facet>
<h:outputText value="#{item.pobocka.nazov}"/>
</p:column>
<p:column>
<f:facet name="header">Liek:</f:facet>
<h:outputText value="#{item.liek.nazov}"/>
</p:column>
</p:dataTable>
<p:dialog widgetVar="test" showEffect="explode" hideEffect="explode">
<h:outputText id="dialogText" value="#{zoznamLiekovBean.selected_id}"/>
</p:dialog>
</h:form>
</div>
</h:body>
</html>
Remove immediate="true" from the commandButton. You are skipping the whole Apply Request Value phase - Update Model value phase with that. That's why your value is always null or 0.
Check this out

Resources