PrimeFaces table selection, For two approve and disapprove columns - jsf

I have developed an approval screen(for user creation). There I have included two states which were approval and disapproval. Currently it takes the reading only as approval and it doesn't check disapproval. approval process is working fine for me. but I want to have disapproval part as well.
I want to improve my code to take separate readings for above mentioned two different states.
How can I get the approval and disapproval objects to two separate List??? Cant find example for two selection ways in primeface.
I want to know how do i get a column selection as approve and disapprove.
I have the following screen
I have the following datatable
<p:dataTable id="userApprovals" var="user" value="#{userApprovalBean.userApprovals}"
selection="#{userApprovalBean.selectedUser}"
widgetVar="usersTable"
rowKey="#{user.username}"
reflow="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
paginator="true" rows="10" style="margin-bottom:20px">
<f:facet name="header">
<h:commandLink style="float:right;">
<p:graphicImage name="/images/excel.png" width="24" />
<p:dataExporter type="xls" target="userApprovals" fileName="cars" />
</h:commandLink>
User Approval
<h:commandLink style="float:right;">
<p:graphicImage name="/images/pdf.png" width="24" />
<p:dataExporter type="pdf" target="userApprovals" fileName="cars" />
</h:commandLink>
<p:commandButton id="toggler" type="button" value="Columns"
style="width:100px;float:left;" icon="ui-icon-calculator" />
<p:columnToggler datasource="userApprovals" trigger="toggler" />
</f:facet>
<p:column sortBy="#{user.username}">
<f:facet name="header">
<h:outputText value="Username" />
</f:facet>
<h:outputText value="#{user.username}" />
</p:column>
<p:column sortBy="#{user.firstName}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.firstName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Geneder" />
</f:facet>
<h:outputText value="#{user.gender}" />
</p:column>
<p:column style="width:160px;">
<f:facet name="header">
<h:outputText value="Address" />
</f:facet>
<h:outputText value="#{user.addressLine1}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="User Role" />
</f:facet>
<h:outputText value="#{user.userRole.userRoleDescription}" />
</p:column>
<p:column sortBy="#{user.entUser}">
<f:facet name="header">
<h:outputText value="Created User" />
</f:facet>
<h:outputText value="#{user.entUser}" />
</p:column>
<p:column styleClass="myTable">
<f:facet name="header">
<h:outputText value="Created Date" />
</f:facet>
<h:outputText value="#{user.entDate}" />
</p:column>
<p:column style="width:60px;float:center;" >
<f:facet name="header">
<h:outputText value="View" />
</f:facet>
<p:commandLink update=":form:documentPanel" oncomplete="PF('documentDialog').show()" title="View Detail" styleClass="ui-icon ui-icon-search">
<f:setPropertyActionListener value="#{user}" target="#{userApprovalBean.gridUser}" />
</p:commandLink>
</p:column>
<p:column selectionMode="multiple" style="width:55px;text-align:center">
</p:column>
<p:column selectionMode="multiple" style="width:55px;text-align:center">
</p:column>
<f:facet name="footer">
<p:commandButton process="userApprovals" update=":form:multiCarDetail"
icon="ui-icon-search" value="Selected Records" style="width:200px;height:22px"
oncomplete="PF('multiCarDialog').show()" />
</f:facet>
</p:dataTable>
I have the following Bean
public class UserApprovalBean {
private List<UserDetail> userApprovals;
private String recordStatus;
private List<UserDetail> selectedUser;
private UserDetail gridUser;;
private FacesContext context;
private UserDetail loggedUserDetail;
#PostConstruct
public void init(){
try {
context = FacesContext.getCurrentInstance();
userApprovals = UserApprovalDao.getInstance().findAllUserApproval();
//selectedUser.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void submitData(){
context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
RequestContext context1 = RequestContext.getCurrentInstance();
boolean dataFill = true;
if (selectedUser.isEmpty()) {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Validation Error", "You need to select something....!");
FacesContext.getCurrentInstance().addMessage(null, message);
context1.addCallbackParam("loggedIn", dataFill);
}
else{
try{
for(UserDetail ud: selectedUser){
ud.setRecordStatus("ACTIVE");
ud.setApprovedUser(loggedUserDetail.getUsername());
ud.setApprovedDate(new Timestamp(System.currentTimeMillis()));
UserApprovalDao.getInstance().update(ud);
}
context.getApplication().getNavigationHandler()
.handleNavigation(context, null,
"/approveUserForm.xhtml?faces-redirect=true");
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void refresh() {
HttpServletRequest req = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
context = FacesContext.getCurrentInstance();
if (req.getMethod().equalsIgnoreCase("GET")) {
try {
reload();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void reload() {
clear();
loadData();
}
private void clear() {
userApprovals.clear();
}
private void loadData() {
try {
userApprovals = UserApprovalDao.getInstance().findAllUserApproval();
loggedUserDetail = (UserDetail) context.getExternalContext()
.getSessionMap().get("user");
} catch (Exception e) {
e.printStackTrace();
}
}
public List<UserDetail> getUserApprovals() {
return userApprovals;
}
public void setUserApprovals(List<UserDetail> userApprovals) {
this.userApprovals = userApprovals;
}
public String getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(String recordStatus) {
this.recordStatus = recordStatus;
}
public List<UserDetail> getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(List<UserDetail> selectedUser) {
this.selectedUser = selectedUser;
}
public UserDetail getGridUser() {
return gridUser;
}
public void setGridUser(UserDetail gridUser) {
this.gridUser = gridUser;
}
public UserDetail getLoggedUserDetail() {
return loggedUserDetail;
}
public void setLoggedUserDetail(UserDetail loggedUserDetail) {
this.loggedUserDetail = loggedUserDetail;
}
}

You can use p:selectBooleanCheckbox in approval and disapproval column with unique value objects and can easily get the approval and disapproval selection list using If condition

Related

p:dataTable filtered, sorted, paginated results get displayed in a single row

I'm working on a theme for an app I'm making with PrimeFaces 6.2 (community edition) and I'd like to get my simulated DAO objects working before I proceed with my css templating.
I've got an issue I came across in the past and I can't find the right answer for it again. Would someone point out an error I've made somewhere in my code?
Details:
I've made a somewhat complex DataTable using PrimeFaces LazyDataModel with little help from PrimeFaces Showcase pages. My main issue is, when I write something in the filter fields or click on any column headers to do data sorting or even click on pagination buttons I get an unexpexted data rendering issue.
Filtered, sorted and paginated results get displayed in a single concatenated row what I don't want. I've posted images and code further below for insight.
Also, I'd like to point out:
No exceptions in JS console.
No exceptions in Java console.
don't mind the missing pagination icons (text-indent: 0;)
XHTML:
<h:form id="input-form-dt2">
<H4>DATA TABLE - LAZY MODEL</H4>
<div class="flex-container">
<p:outputPanel id="dev-input-panel-13">
<p:dataTable var="DOTable" value="#{dtModelLazy.DOTList}" paginator="true" rows="10" rowKey="#{DOTable.userID}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50" selectionMode="single" selection="#{dtModelLazy.selectedObj}" id="DTModelB" lazy="true">
<p:ajax event="rowSelect" listener="#{dtModelLazy.onRowSelect}" update="input-form-dt2:dlgDTOObjDetail" oncomplete="PF('DTObjDialog').show()" />
<p:column headerText="User ID" sortBy="#{DOTable.userID}" filterBy="#{DOTable.userID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{DOTable.name}" filterBy="#{DOTable.name}" filterMatchMode="contains">
<h:outputText value="#{DOTable.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{DOTable.surname}" filterBy="#{DOTable.surname}" filterMatchMode="contains">
<h:outputText value="#{DOTable.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{DOTable.age}" filterBy="#{DOTable.age}" filterMatchMode="contains">
<h:outputText value="#{DOTable.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{DOTable.address}" filterBy="#{DOTable.address}" filterMatchMode="contains">
<h:outputText value="#{DOTable.address}" />
</p:column>
<p:column headerText="City" sortBy="#{DOTable.city}" filterBy="#{DOTable.city}" filterMatchMode="contains">
<h:outputText value="#{DOTable.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{DOTable.postCode}" filterBy="#{DOTable.postCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{DOTable.countryCode}" filterBy="#{DOTable.countryCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{DOTable.phoneNumber}" filterBy="#{DOTable.phoneNumber}" filterMatchMode="contains">
<h:outputText value="#{DOTable.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{DOTable.photoID}" filterBy="#{DOTable.photoID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.photoID}" />
</p:column>
</p:dataTable>
<p:dialog id="dlgDTOObjDetail" header="DataTable Object Detail" widgetVar="DTObjDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="DTObjDetail">
<p:panelGrid columns="2" rendered="#{not empty dtModelLazy.selectedObj}" columnClasses="label,value">
<h:outputText value="User ID: " />
<h:outputText value="#{dtModelLazy.selectedObj.userID}" />
<h:outputText value="Name: " />
<h:outputText value="#{dtModelLazy.selectedObj.name}" />
<h:outputText value="Surname: " />
<h:outputText value="#{dtModelLazy.selectedObj.surname}" />
<h:outputText value="Age: " />
<h:outputText value="#{dtModelLazy.selectedObj.age}" />
<h:outputText value="Address: " />
<h:outputText value="#{dtModelLazy.selectedObj.address}" />
<h:outputText value="City: " />
<h:outputText value="#{dtModelLazy.selectedObj.city}" />
<h:outputText value="Post code: " />
<h:outputText value="#{dtModelLazy.selectedObj.postCode}" />
<h:outputText value="Country code: " />
<h:outputText value="#{dtModelLazy.selectedObj.countryCode}" />
<h:outputText value="Phone number: " />
<h:outputText value="#{dtModelLazy.selectedObj.phoneNumber}" />
<h:outputText value="Photo hash: " />
<h:outputText value="#{dtModelLazy.selectedObj.photoID}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</p:outputPanel>
</div>
<hr></hr>
</h:form>
LAZY MODEL:
public class DataTableModelLazy extends LazyDataModel<DODataTable> {
private static final long serialVersionUID = -2647349397077805782L;
private List<DODataTable> datasource;
public DataTableModelLazy(List<DODataTable> datasource) {
this.datasource = datasource;
}
#Override
public DODataTable getRowData(String rowKey) {
for(DODataTable dtObj : datasource) {
if(dtObj.getUserID().equals(rowKey))
return dtObj;
}
return null;
}
#Override
public Object getRowKey(DODataTable dtObj) {
return dtObj.getUserID();
}
#Override
public List<DODataTable> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
List<DODataTable> data = new ArrayList<DODataTable>();
//filter
for(DODataTable dtObj : 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);
Field field = dtObj.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
String fieldValue = String.valueOf(field.get(dtObj));
field.setAccessible(false);
if(filterValue == null || fieldValue.startsWith(filterValue.toString())) {
match = true;
} else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
}
if(match) {
data.add(dtObj);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new DataTableModelLazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.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;
}
}
}
VIEW BEAN:
#Named("dtModelLazy")
#ViewScoped
public class DataGeneratorBeanLazy implements Serializable {
private static final long serialVersionUID = -5918527333909822277L;
private LazyDataModel<DODataTable> DOTList;
private DODataTable selectedObj;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
DOTList = new DataTableModelLazy(dataGen.createDTObjects(1500));
}
public LazyDataModel<DODataTable> getDOTList() {
return DOTList;
}
public void setDOTList(LazyDataModel<DODataTable> dOTList) {
DOTList = dOTList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("DataTable object selected!", ((DODataTable) event.getObject()).getUserID());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public DODataTable getSelectedObj() {
return selectedObj;
}
public void setSelectedObj(DODataTable selectedObj) {
this.selectedObj = selectedObj;
}
}
Update 1
I have modified the update property as update="input-form-dt2:dlgDTOObjDetail"to meet the suggestion provided. Also, I added the id property for the dialog. The issue still remains.
Update 2
I've changed my approach and started with the basic DataTable first. Also, I've stripped the .xhtml to a bare minimum. It contains only a form with the DataTable inside like so:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<div>
UI components design
</div>
<h:form id="input-form-dt1">
<h4>DATA TABLE - BASIC</h4>
<p:dataTable id="DTableA" var="dataObject" value="#{dataTableBean.objectList}" paginator="true" rows="10" rowKey="#{dataObject.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50">
<p:column headerText="User ID" sortBy="#{dataObject.userID}" filterBy="#{dataObject.userID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{dataObject.name}" filterBy="#{dataObject.name}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{dataObject.surname}" filterBy="#{dataObject.surname}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{dataObject.age}" filterBy="#{dataObject.age}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{dataObject.address}" filterBy="#{dataObject.address}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.address}" />
</p:column>
<p:column headerText="City" sortBy="#{dataObject.city}" filterBy="#{dataObject.city}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{dataObject.postCode}" filterBy="#{dataObject.postCode}" filterMatchMode="contains" >
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{dataObject.countryCode}" filterBy="#{dataObject.countryCode}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{dataObject.phoneNumber}" filterBy="#{dataObject.phoneNumber}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{dataObject.photoID}" filterBy="#{dataObject.photoID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.photoID}" />
</p:column>
</p:dataTable>
</h:form>
</ui:composition>
As you can see I've also removed all event listeners. I've added a new field to my data object (id of type Integer) and bound DataTables rowKey to it (previously bound to userID of type String - not a good idea). My DataTable backing bean is now as basic as it can be:
#Named("dataTableBean")
#ViewScoped
public class DataTableBean implements Serializable {
private static final long serialVersionUID = -1662465661106141910L;
private List<DTObject> objectList;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
setObjectList(dataGen.createDTObjects(1500));
}
public List<DTObject> getObjectList() {
if (objectList == null) {
return new ArrayList<>();
} else {
return objectList;
}
}
public void setObjectList(List<DTObject> objectList) {
this.objectList = objectList;
}
}
Now, there are no custom filters, sorters or paginators of any type, not even a data model, just raw data objects in a simple list. The output result is exactly the same as before when paginator buttons are clicked or data gets filtered. All resulting data still gets displayed in a single concatenated line.
ANSWER:
As Kukeltje pointed out in the comments I've made a complete nonsense in my main container and added an autoupdate component to it. That component messed up my data table events, loading data without a table to hold it. Once I've removed the component from my main container, everything worked out. Here is the code for my main container (commented out the troublemaker).
<div id="content-window">
<p:outputPanel id="content-panel">
<ui:include src="#{contentLoaderBean.mainContent}" />
<!-- <p:autoUpdate /> -->
</p:outputPanel>
</div>
The only situations I've seen this happening is when the datatable is fully updated in addtion to a partial update of the datatable via an event (page or filter or sort or...) In the rowSelect you do seem to update the full form which contains the datatable as well. That is bad practice and can as mentioned result in what you seem so remove that.
But...in your question there are no filter ajax events that explicitly update the full datatable so that cannot cause it. Yet with 99% vertainty there is something fully updates the datatable. Three options
there is something in your live code you left out of the datatable in your question
There is something else outside the code you posted that plays havoc (an autoupdate e.g),
an update from the server side is being done in a method

jsf Target Unreachable, 'null' returned null in join table

i got an error on my datatable "Target Unreachable, 'null' returned null", it caused by one column with join with another table, normally i initiate everything in my beans, this is my code, someone can enlighten me please ?
#ManagedBean
#ViewScoped
public class locationBean extends LazyDataModel<Location> {
private Location selectedLocation;
private List<Location> locations;
private List<SelectItem> selectoneitemclient;
#PostConstruct
public void init() {
this.locations = new ArrayList<Location>();
this.selectoneitemclient = new ArrayList<SelectItem>();
this.selectedLocation = new Location();
}
public List<SelectItem> getSelectoneitemclient() {
ClientDao clientdao = new ClientDaoImpl();
List<Client> clients = clientdao.selectItems();
for (Client cl : clients) {
SelectItem selectitem = new SelectItem(cl.getCodecl(), cl.getNom());
this.selectoneitemclient.add(selectitem);
}
return selectoneitemclient;
}
public List<Location> getLocations() {
LocationDao locationdao = new LocationDaoImpl();
this.locations = locationdao.findAll();
return locations;
}
location.xhtml
<h:form id="formDataTable">
<p:dataTable var="location" value="#{locationBean.locations}" rowKey="#{location.codeloc}" paginatorPosition="bottom" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{locationBean.selectedLocation}" id="tableLocation">
<p:ajax event="rowSelect" listener="#{locationBean.onRowSelect}" update=":formDisplay" oncomplete="PF('dialogLocationDisplay').show()" />
<f:facet name="header">
Listes des réservations
</f:facet>
<p:column headerText="Type client" filterBy="#{location.client.typecl}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.typecl}" />
</p:column>
<p:column headerText="Nom" filterBy="#{location.client.nom}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.nom}" />
</p:column>
<p:column headerText="Tel" filterBy="#{location.client.tel}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.tel}" />
</p:column>
<p:column headerText="Email" filterBy="#{location.client.email}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.client.email}" />
</p:column>
<p:column headerText="Date Debut" filterBy="#{location.datedebut}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.datedebut}" />
</p:column>
<p:column headerText="Date Fin" filterBy="#{location.datefin}"
footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{location.datefin}" />
</p:column>
<p:column headerText="Gestion">
<p:commandButton id="btnUpdate" update=":formUpdate" oncomplete="PF('dialogLocationUpdate').show()" icon="ui-icon-pencil" title="modifier">
<f:setPropertyActionListener value="#{location}" target="#{locationBean.selectedLocation}"/>
</p:commandButton>
<p:commandButton id="btnDelete" update=":formDelete" oncomplete="PF('dialogLocationDelete').show()" icon="ui-icon-trash" title="supprimer">
<f:setPropertyActionListener value="#{location}" target="#{locationBean.selectedLocation}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form id="formUpdate">
<p:dialog header="modifier une reservation" widgetVar="dialogLocationUpdate" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="detailLocationUpdate" style="text-align:center;">
<p:panelGrid columns="2" columnClasses="label,value">
<h:outputText value="Client: " />
<p:selectOneMenu value="#{locationBean.selectedLocation.client.codecl}">
<f:selectItem itemLabel="- Selectionner un client -" itemValue = "" />
<f:selectItems value="#{locationBean.selectoneitemclient}" />
</p:selectOneMenu>
<h:outputText value="Titre: " />
<p:inputText value="#{locationBean.selectedLocation.titre}" />
LocationDaoImpl.java
#Override
public List<Location> findAll() {
List<Location> listloc = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String sql = "FROM Location l inner join fetch l.client";
try {
session.beginTransaction();
listloc = session.createQuery(sql).list();
session.beginTransaction().commit();
} catch (Exception e) {
if (session != null) {
session.close();
}
e.printStackTrace();
}
return listloc;
}
#Override
public boolean update(Location loc) {
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
Location locdb = (Location) session.load(Location.class, loc.getCodeloc());
locdb.setCodeloc(loc.getCodeloc());
locdb.setTitre(loc.getTitre());
locdb.setClient(loc.getClient());
locdb.setDatedebut(loc.getDatedebut());
locdb.setDatefin(loc.getDatefin());
locdb.setTotalttc(loc.getTotalttc());
session.update(locdb);
session.getTransaction().commit();
flag = true;
} catch (Exception e) {
flag = false;
if (session != null) {
session.close();
}
e.printStackTrace();
}
return flag;
}

Disable Datatable commandlinks when in editmode

I have I datatable. I want to disable the commandlinks when I go to rowedit mode by pressing on the edit link:
JSF:
<p:growl id="messages" showDetail="true" />
<p:dataTable value="#{employeeBean.employees}"
var="employee" id="employeeDTable"
editable="true">
<p:ajax event="rowEdit" listener="#{employeeBean.edit}" update=":employeeForm:messages" />
<p:ajax event="rowEditCancel" listener="#{employeeBean.undoEdit}" update=":employeeForm:messages" />
<p:column id="id" headerText="Id">
<h:outputText value="#{employee.id}"/>
</p:column>
<p:column id="firstname" headerText="Voornaam">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{employee.firstName}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{employee.firstName}" label="firstname"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column id="editButtonsId" headerText="">
<p:rowEditor />
</p:column>
<p:column id="cashbook" headerText="">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" /> <!-- DISABLE THIS IN EDITMODE -->
</h:panelGroup>
</div>
</p:column>
</p:dataTable>
CODE:
#Component("employeeBean")
#Scope("session")
public class EmployeeBean {
List<EmployeeModel> employees;
private EmployeeModel employeeModel;
#Autowired
private EmployeeService employeeService;
public EmployeeBean() {
if(employeeService == null){
employeeService = ServiceRepository.getInstance().getEmployeeService();
}
employeeModel = new EmployeeModel();
if(employees == null){
this.employees = this.employeeService.getEmployees();
}
}
public void edit(RowEditEvent event) {
EmployeeModel employee = ((EmployeeModel) event.getObject());
EmployeeModel updatedEmployee = this.employeeService.updateEmployee(employee);
if(updatedEmployee != null){
FacesMessage msg = new FacesMessage("Employee Edited", employee.getFirstName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
public void undoEdit(RowEditEvent event) {
}
public EmployeeModel getEmployeeModel() {
return employeeModel;
}
public void setEmployeeModel(EmployeeModel employeeModel) {
this.employeeModel = employeeModel;
}
public List<EmployeeModel> getEmployees() {
return employees;
}
public void setEmployees(List<EmployeeModel> employees) {
this.employees = employees;
}
}
Put your link and disabled link inside a <p:cellEditor/>
<p:column id="cashbook" headerText="">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" />
</h:panelGroup>
</div>
</f:facet>
<f:facet name="input">
<div align="center">
<h:panelGroup id="cashbookPanel">
<p:commandLink disabled="true" title="Cashbook" update="employeeDTable" styleClass="ui-icon ui-icon-cart" />
</h:panelGroup>
</div>
</f:facet>
</p:cellEditor>
</p:column>

Primefaces - datatable column filter textbox not appearing

I'm using PF 4.0 and I have a datatable that is lazily loaded and i'm trying to add a filter textbox to the "name" column, but the textbox is not appearing. What am I missing?
...
<p:dataTable var="user" value="#{userGroupBacking.users}" editable="true" id="userTable" paginator="true" rows="20"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}" lazy="true"
filteredValue="#{userGroupBacking.filteredUsers}" >
<p:ajax event="rowEdit" listener="#{userGroupBacking.onEdit}" />
<p:column headerText="User" filterBy="#{user.name}" filterMatchMode="contains">
<h:outputText value="#{user.name}" />
</p:column>
...
backing bean:
#ManagedBean(name="userGroupBacking")
#ViewScoped
public class UserGroupBacking {
#ManagedProperty(value="#{accessBacking}")
private AccessBacking accessBacking;
public void setAccessBacking(AccessBacking accessBacking) {
this.accessBacking = accessBacking;
}
#PostConstruct
public void init() {
this.ds = databaseBacking.getDs();
if(isLoggedIn()) {
loadData();
}
}
/**
* Checks that the user is logged in
* #return
*/
public boolean isLoggedIn() {
return accessBacking.isHasAccess();
}
public LazyDataModel<User> getUsers() {
return users;
}
public List<Group> getGroups() {
return groups;
}
public List<Group> getSelectedGroups() {
return selectedGroups;
}
public List<SelectItem> getGroupsAsSelectItems() {
return groupsAsSelectItems;
}
public List<SelectItem> getUsersAsSelectItems() {
return usersAsSelectItems;
}
public String getNewGroup() {
return newGroup;
}
public void setNewGroup(String newGroup) {
this.newGroup = newGroup;
}
public List<User> getFilteredUsers() {
return filteredUsers;
}
public void setFilteredUsers(List<User> filteredUsers) {
this.filteredUsers = filteredUsers;
}
}
I figured it out. It seems that in PF 4.0, you need the filterBy code to change from:
<p:column headerText="User" filterBy="#{user.name}" filterMatchMode="contains">
<h:outputText value="#{user.name}" />
</p:column>
to:
<p:column headerText="User" filterBy="name" filterMatchMode="contains">
<h:outputText value="#{user.name}" />
</p:column>
I am just curious, is this the actual code you have in your page. Cause it should wrapped up inside <p:cellEditor> as shown in primefaces showcase
http://www.primefaces.org/showcase-labs/ui/datatableRowEditing.jsf
some thing like
<p:column headerText="Model" style="width:30%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{car.model}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{car.model}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>

updating rowediting datatable of primefaces and saving it in the database

I'm using prime faces 3.4.2 and I'm trying to update an entity that contains a list of another object, using a row editing datatable. My problem is that when I validate the change , the simple attributes of the entity are updated in the database , but the list is not. I don't know how to save the whole object in the data base.
here you find the editing page :
`
<p:panel style="width:1000px; ;font: lighter 70.5% Arial, Helvetica, sans-serif ; " header="Informations Générales">
<p:growl id="growl" showDetail="true" sticky="true" style="font-size: small;" />
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel value="Société" />
<p:inputText id="custSoc" value="#{CustomerCtrl.selectedCust.company}"/>
<h:outputLabel value="Secteur d'activité" />
<p:inputText id="custActivite" value="#{CustomerCtrl.selectedCust.secteurActivite}" />
<h:outputLabel value="Nom du propriétaire" />
<p:inputText id="custprop" value="#{CustomerCtrl.selectedCust.proprietaire}" />
</h:panelGrid>
<p:tabView id="tabView">
<p:tab title="Coordonnées">
<p:growl id="messages" showDetail="true"/>
<p:dataTable var="cu" value="#{CustomerCtrl.selectedCust.coordonnee}" id="carList" editable="true">
<f:facet name="header">
Coordonnées
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column colspan="5" headerText="Adresses" />
<p:column colspan="5" headerText="Contacts" />
</p:row>
<p:row>
<p:column headerText="Num" style="width:2cm"/>
<p:column headerText="Rue/Avenue" style="width:3cm"/>
<p:column headerText="Code postal" style="width:2cm" />
<p:column headerText="Ville" style="width:2.5cm" />
<p:column headerText="Pays" style="width:2.5cm" />
<p:column headerText="Fixe" style="width:2cm"/>
<p:column headerText="Mobile" style="width:2cm"/>
<p:column headerText="Fax" style="width:2cm"/>
<p:column headerText="E-mail" style="width:3.7cm"/>
<p:column headerText=" " />
</p:row>
</p:columnGroup>
<p:ajax event="rowEdit" listener="#{CustomerCtrl.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="#{CustomerCtrl.onCancel}" update=":form:messages" />
<p:column headerText="Num">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.number}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.number}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Rue/Avenue">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.street}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.street}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Code postal">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.zipcode}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.zipcode}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Ville">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.city.text}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{cu.city.text}" style="width:100%">
<f:selectItems value="#{CustomerCtrl.cityList}" style="width:100%"
var="city"
itemLabel="#{city}"
itemValue="#{city}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Pays" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.country.text}" style="width:100%" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{cu.country.text}" style="width:100%">
<f:selectItems value="#{CustomerCtrl.countryList}" style="width:100%"
var="color"
itemLabel="#{color}"
itemValue="#{color}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fixe">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.phone}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.phone}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Mobile" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.mobile}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.mobile}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fax" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.fax}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.fax}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="E-mail" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cu.email}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{cu.email}" style="width:90%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
</p:column>
</p:dataTable>
</p:tab>
<p:tab title="Compte">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel value="Login" />
<p:inputText id="userLogin" value="#{CustomerCtrl.selectedCust.login}" />
<h:outputLabel value="Mot de passe" />
<p:password id="userpass" value="#{CustomerCtrl.selectedCust.password}" />
</h:panelGrid>
</p:tab>
<p:tab title="Applications">
<h:panelGrid columns="2" cellpadding="5">
</h:panelGrid>
</p:tab>
<p:tab title="Interventions">
<h:panelGrid columns="2" cellpadding="5">
</h:panelGrid>
</p:tab>
</p:tabView>
</p:panel>
<br/>
`
and here is my managedbean :`#ManagedBean(name = "CustomerCtrl")
#ViewScoped
public class CustomerController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idSelected;
private Customer selectedCust ;
private Coordonnee selectedCoord = new Coordonnee();
private Coordonnee filteredCoord = new Coordonnee();
private List<Customer> filteredCusts;
private int cityId;
private int countryId;
private List<SelectItem> cityList = new ArrayList<SelectItem>();
private List<SelectItem> countryList = new ArrayList<SelectItem>();
private List<Customer> custmrs = new ArrayList<Customer>();
private List<Coordonnee> coordonnees = new ArrayList<Coordonnee>();
private Coordonnee selectedCustomerCoordonne;
#EJB
private SettingsBean settingBean;
public CustomerController() {
if (selectedCust != null) {
coordonnees = (List<Coordonnee>) settingBean.FindCoordonneeByCustomer(selectedCust.getId());
}
}
public void createCustomer() {
System.out.println("hello createCustomer");
System.out.println("selectedcust :"+selectedCust.getCompany());
System.out.println("selectedcustCoordonnee 1 :"+selectedCustomerCoordonne);
if(selectedCust==null){
System.out.println("entré");
selectedCust= new Customer();
System.out.println("nouvelle instance créé");
settingBean.createCustomer(selectedCust);
settingBean.createCoordonnee(selectedCustomerCoordonne);
System.out.println("Nouveau client " + selectedCust.getCompany() + " ajoutée");
}
else{
System.out.println("editer");
selectedCust.setCoordonnee(coordonnees);
settingBean.editCustomer(selectedCust);
System.out.println("client " + selectedCust.getCompany() + " édité");
}
}
public List<Customer> getCustmrs() {
custmrs = settingBean.findAllCustomers();
return custmrs;
}
public void setCustmrs(List<Customer> custmrs) {
this.custmrs = custmrs;
}
public void preRenderView() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(true);
}
public Customer getSelectedCust() {
if (selectedCust == null) {
selectedCust = (Customer) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("selectedCust");
System.out.println("Par session");
if (selectedCust == null) {
selectedCust = new Customer();
selectedCust.setCoordonnee(new ArrayList<Coordonnee>());
} else
selectedCust.setCoordonnee(settingBean
.FindCoordonneeByCustomer(selectedCust.getId()));
}
return selectedCust;
}
public void setSelectedCust(Customer selectedCust) {
this.selectedCust = selectedCust;
}
public List<Customer> getFilteredCusts() {
return filteredCusts;
}
public void setFilteredCusts(List<Customer> filteredCusts) {
this.filteredCusts = filteredCusts;
}
public List<Coordonnee> getCoordonnees() {
if (selectedCust != null) {
coordonnees = (List<Coordonnee>) settingBean.FindCoordonneeByCustomer(selectedCust.getId());
}
return coordonnees;
}
public void setCoordonnees(List<Coordonnee> coordonnees) {
this.coordonnees = coordonnees;
}
public void setCustomerToEdit(Customer customerToEdit) {
}
public String removeCustomer() {
if (selectedCust != null) {
System.out.println("in delete");
String selected = selectedCust.getCompany();
System.out.println("supprimer " + selected + "");
custmrs.remove(selectedCust);
settingBean.removeCustomer(selectedCust);
System.out.println("client supprimé");
}
return "";
}
public String removeCustomercoordonnee() {
if (selectedCustomerCoordonne != null) {
System.out.println("coordonne in delete");
String selected = selectedCustomerCoordonne.getEmail();
System.out.println("supprimer " + selected + "");
settingBean.removeCustomerCoordonnee(selectedCustomerCoordonne);
System.out.println("coordonne supprimé");
}
return "";
}
public String editCustomer() {
if (selectedCust != null) {
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("selectedCust", selectedCust);
System.out.println("selected "
+ FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().get("selectedCust"));
}
return "customeradd.xhtml?faces-redirect=true";
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public List<SelectItem> getCityList() {
cityList = new ArrayList<SelectItem>();
List<City> Listcity = settingBean.findAllCity();
for (City c : Listcity) {
cityList.add(new SelectItem(c.getId(), c.getText()));
}
return cityList;
}
public void setCityList(List<SelectItem> cityList) {
this.cityList = cityList;
}
public List<SelectItem> getCountryList() {
cityList = new ArrayList<SelectItem>();
List<Country> Listcountry = settingBean.findAllCountry();
for (Country c : Listcountry) {
countryList.add(new SelectItem(c.getId(), c.getText()));
}
return countryList;
}
public void setCountryList(List<SelectItem> countryList) {
this.countryList = countryList;
}
public int getIdSelected() {
return idSelected;
}
public void setIdSelected(int idSelected) {
this.idSelected = idSelected;
}
public Coordonnee getSelectedCustomerCoordonne() {
return selectedCustomerCoordonne;
}
public void setSelectedCustomerCoordonne(
Coordonnee selectedCustomerCoordonne) {
this.selectedCustomerCoordonne = selectedCustomerCoordonne;
}
public Coordonnee getSelectedCoord() {
return selectedCoord;
}
public void setSelectedCoord(Coordonnee selectedCoord) {
this.selectedCoord = selectedCoord;
}
public Coordonnee getFilteredCoord() {
return filteredCoord;
}
public void setFilteredCoord(Coordonnee filteredCoord) {
this.filteredCoord = filteredCoord;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Cliquer sur enregistrer pour valider la modification", ((Coordonnee) event.getObject()).getCustomer().getCompany());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Modification annulée", ((Coordonnee) event.getObject()).getCustomer().getCompany());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}`
Pleaaase help me to save the both objects.

Resources