PrimeFaces - Unable to delete rows in datatable - jsf

I am trying to do a basic add and delete db operation using primeface datatable. Add is working fine but cannot get the delete working. When I click on the delete button the delete function is not called.
<h:body>
<h:form>
<p:panel id="toppanel" closable="true" toggleable="true" >
<f:facet name="Store">
<p:outputLabel value="Header" />
</f:facet>
<f:facet name="#Copyright" >
<p:outputLabel value="footer" />
</f:facet>
<p align="left" >
<p:inputText value="#{salesPerson.item.itemId}" id="itemid" >
<f:passThroughAttribute name="placeholder" value="ID"/>
</p:inputText>
<p:inputText value="#{salesPerson.item.itemTitle}" >
<f:passThroughAttribute name="placeholder" value="TITLE"/>
</p:inputText>
<p:inputText value="#{salesPerson.item.itemDesc}" >
<f:passThroughAttribute name="placeholder" value="DESCRIPTION"/>
</p:inputText>
<p:inputText value="#{salesPerson.item.price}" >
<f:passThroughAttribute name="placeholder" value="PRICE"/>
</p:inputText>
</p>
<p align="right" >
<p:commandButton process="#form" id="Create" value="Create" update="out" actionListener="#{salesPerson.addItem()}" />
</p>
<p:dataTable id="out" var="item" value="#{salesPerson.items}" rowKey="#{item.itemId}" selection="#{salesPerson.selectedItems}" >
<p:column selectionMode="multiple" width="1%"/>
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet >
<h:outputText value="#{item.itemId}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="TITLE" />
</f:facet >
<h:outputText value="#{item.itemTitle}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="DESCRIPTION" />
</f:facet >
<h:outputText value="#{item.itemDesc}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="PRICE" />
</f:facet >
<h:outputText value="#{item.price}" />
</p:column>
</p:dataTable>
<p align="right" >
<p:commandButton process="#form" id="delete" value="Delete" update="out" actionListener="#{salesPerson.deleteItem(items)}" />
</p>
</p:panel>
</h:form>
</h:body>
</html>
SalesPerson Bean
This is the controller backing bean
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.parthi.controller;
import javax.inject.Inject;
import com.parthi.model.Item;
import com.parthi.backing.ShoppingBean;
import com.parthi.service.StoreKeeper;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#RequestScoped
#Named
public class SalesPerson implements Serializable{
#Inject
private Item item;
private List<Item> items = new LinkedList<>();
private List<Item> selectedItems = new LinkedList<>();
#EJB
private StoreKeeper storeKeeper;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public List<Item> getSelectedItems() {
System.out.println("Number of items getselected" +selectedItems.size());
return selectedItems;
}
public void setSelectedItems(List<Item> selectedItems) {
System.out.println("Number of items setselected" +selectedItems.size());
this.selectedItems = selectedItems;
}
public void addItem(){
storeKeeper.addItem(item);
// System.out.println("Printing add item");
}
public List<Item> getAllItems() {
// System.out.println("Getting all SalesPerson-items");
items = storeKeeper.getAllItems();
return items;
}
public void deleteItem(List<Item> items){
System.out.println("Reached SalesPerson.deleteItem");
int i =0;
while(i <= items.size()){
storeKeeper.deleteItem(items.get(i));
i++;
System.out.println("deleting..." + items.get(i));
}
}
public List<Item> getItems() {
getAllItems();
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Service EJB
Service is a stateless session bean which perform CRUD operations
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.parthi.service;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.parthi.model.Customer;
import com.parthi.model.Item;
#Stateless
public class StoreKeeper {
#PersistenceContext
private EntityManager em;
public List<Item> getAllItems(){
System.out.println("Getting all StoreKeeper-item");
return em.createQuery("FROM Item p", Item.class).getResultList();
}
public void addItem(Item item){
System.out.println("Printing all StoreKeeper add item");
em.persist(item);
}
public void deleteItem(Item item){
em.merge(item);
em.remove(item);
}
}

Related

ViewScoped Bean get rebuild on commandLink

I am building a CRUD app with a dashboard in which the user should be able to partially reload a widget. This is what I got:
<f:metadata>
<f:viewParam name="customerUuid" value="#
{dashboardManagedBean.customerUuid}" />
<f:event type="preRenderView" listener="#{dashboardManagedBean.init}" />
</f:metadata>
<f:view>
<h:body>
<h:form>
<p:panelGrid>
<p:row>
<p:column>
<p:panelGrid columns="4" styleClass="ui-noborder"
style="float:right;">
<p:outputLabel for="dateFrom" value="From:">
</p:outputLabel>
<p:calendar id="dateFrom" value="#
{dashboardManagedBean.statisticsRequest.dateFrom}"
pattern="dd.MM.yyyy HH:mm:ss" locale="de" readonlyInput="false"
timeInput="true" mode="popup"/>
<p:outputLabel for="dateTo" value="Till:">
</p:outputLabel>
<p:calendar id="dateTo" value="#
{dashboardManagedBean.statisticsRequest.dateTo}" pattern="dd.MM.yyyy
HH:mm:ss" locale="de" readonlyInput="false" timeInput="true"
mode="popup"/>
</p:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
<p:panel id="telemetry" header="Telemetrie"
style="width: 100%" collapsed="true" toggleable="true">
<f:facet name="actions">
<p:commandLink
actionListener="#
{dashboardManagedBean.loadData}"
styleClass="ui-panel-titlebar-icon
ui-corner-all ui-state-default"><h:outputText
styleClass="fa fa-refresh"/>
</p:commandLink>
</f:facet>
</p:panel>
</p:column>
</p:row>
</p:panelGrid>
</h:form>
</h:body>
</f:view>
And the bean looks like this:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
#ManagedBean(name = "dashboardManagedBean")
#ViewScoped #Getter #Setter
public class DashboardManagedBean implements Serializable {
private Customer customer;
private StatisticsRequest statisticsRequest;
private String customerUuid;
public DashboardManagedBean() {
this.customer = new Customer();
this.statisticsRequest = new StatisticsRequest();
}
public void init() {
loadCustomer();
loadData();
}
public void loadData(){
// load the customer data by using his the statisticsRequest
}
public void loadCustomer(){
// load the customer
}
}
The StatisticsRequest Class is just a wrapper for the request data:
#Getter #Setter
public class StatisticsRequest {
private Customer customer;
private Date dateFrom;
private Date dateTo;
public StatisticsRequest(){
java.util.Date da = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(da);
cal.add(Calendar.MONTH, -4);
this.dateFrom = cal.getTime();
this.dateTo = new Date();
}
}
I put this into the constructor of the StatisticsRequest so that I get a reasonable default value when loading the page. However the constructor of the viewscoped bean is called everytime I click on the reload commandLink the date I picked in the calendar is removed and the StatisticsRequest contains the default value again.
Why is this happening?

Primefaces openDialog(dlg.xhtml) reopens with the same data, shouldn't the viewscope beans get destroyed every time I close the dialog?

I'm trying to use a Primefaces dialog to insert an entity object in a database, it works the first time I use the dialog, the keeps the same bean inside the dialog when I try to use it the second time, here is my code:
this is in the file index.xhtml I have a table called patients and this is the footer:
<f:facet name="footer">
<p:outputPanel>
<p:growl id="growl" showDetail="true" />
<p:commandButton value="Add Patient" icon="ui-icon-extlink"
actionListener="#{patientsViewBean.addNewPatientDialog}">
<p:ajax event="dialogReturn"
listener="#{patientsViewBean.onDialogReturn}" update="patients" />
</p:commandButton>
</p:outputPanel>
</f:facet>
the dialog page is addNewDialog.xhtml it contains:
<!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://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add New Patient</title>
<style type="text/css">
.ui-widget {
font-size: 80%;
}
</style>
</h:head>
<h:body>
<p:panel style="margin: 2px;">
<h:form id="form" >
<p:growl id="msgs" showDetail="true" />
<p:panel title="Patient Personal Information" header="Patient Personal Information">
<p:panelGrid style="margin: 2px 2px 2px 2px" columns="2"
columnClasses="label, value">
<p:outputLabel value="First Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.firstName}"
required="true" label="First Name"></p:inputText>
<p:outputLabel value="Father Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.fatherName}"
required="true" label="Father Name"></p:inputText>
<p:outputLabel value="Family Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.familyName}"
required="true" label="Family Name"></p:inputText>
<p:outputLabel value="Mother Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.motherName}"
required="true" label="Mother Name"></p:inputText>
<p:outputLabel value="Birth Date"></p:outputLabel>
<p:calendar id="bdate" value="#{newPatientView.patient.birthDate}"
locale="ar" navigator="true" yearRange="c-120:c" effect="fade"
mask="true" pattern="yyyy-MM-dd" required="true" />
<p:outputLabel value="Birth Place: "></p:outputLabel>
<p:inputText value="#{newPatientView.patient.birthPlace}"
required="false" label="Birth Place"></p:inputText>
</p:panelGrid>
</p:panel>
<p:panel title="Contact Information" header="Contact Information">
<p:remoteCommand name="updateButtonsStatus"
process="#this contactInfoTable:buttons"
update="contactInfoTable:buttons"></p:remoteCommand>
<p:dataTable id="contactInfoTable" var="cntctInfo"
selectionMode="single" rowKey="#{cntctInfo}"
selection="#{newPatientView.cntctInfo}"
value="#{newPatientView.patient.contactInfoList}" editable="true"
widgetVar="cellCntctInfo">
<p:ajax event="rowEditInit"
listener="#{newPatientView.onRowEditInit}"
oncomplete="updateButtonsStatus()" />
<p:ajax event="rowEdit" immediate="true"
listener="#{newPatientView.onRowEdit}" update=":form:msgs"
oncomplete="updateButtonsStatus()" />
<p:ajax event="rowEditCancel"
listener="#{newPatientView.onRowCancel}"
oncomplete="updateButtonsStatus()" />
<p:column headerText="Email">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.email}" />
</f:facet>
<f:facet name="input">
<p:inputText id="emailInput" value="#{cntctInfo.email}"
style="width:95%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Phone">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.phone}" />
</f:facet>
<f:facet name="input">
<p:inputText id="phoneInput" value="#{cntctInfo.phone}"
style="width:95%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.type}" />
</f:facet>
<f:facet name="input">
<p:selectOneMenu id="typeInput" value="#{cntctInfo.type}"
style="width:100%; height: 95%">
<f:selectItem itemLabel="Main" itemValue="Main"></f:selectItem>
<f:selectItem itemLabel="Home" itemValue="Home"></f:selectItem>
<f:selectItem itemLabel="Work" itemValue="Work"></f:selectItem>
<f:selectItem itemLabel="Perm" itemValue="Perm"></f:selectItem>
<f:selectItem itemLabel="Curr" itemValue="Curr"></f:selectItem>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Edit" style="width:32px">
<p:rowEditor />
</p:column>
<f:facet name="footer">
<p:outputPanel id="buttons" autoUpdate="true">
<p:commandButton value="Add New" process="#this contactInfoTable"
actionListener="#{newPatientView.onAddNewContactInfo}"
update="contactInfoTable :form:msgs"
disabled="#{newPatientView.addContactInfoDisabled}" />
<p:commandButton value="Delete Seleced"
process="#this contactInfoTable"
actionListener="#{newPatientView.onDeleteSelectedContactInfo}"
update="contactInfoTable :form:msgs"
disabled="#{newPatientView.deleteSelectedContactInfoDisabled}" />
</p:outputPanel>
</f:facet>
</p:dataTable>
</p:panel>
<p:panel>
<p:commandButton value="Save" actionListener="#{newPatientView.onDialogApprove}"></p:commandButton>
<p:commandButton value="Discard" actionListener="#{newPatientView.onDialogCancel}"></p:commandButton>
</p:panel>
</h:form>
</p:panel>
</h:body>
</html>
I have two baking beans newPatientView with this code:
package me.bttb.crs.beans.patient;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;
import me.bttb.crs.model.ContactInfo;
import me.bttb.crs.model.Ptnt;
#Named
#ManagedBean
#ViewScoped
public class NewPatientView {
#Inject
private PatientDAO patientDAO;
private Ptnt patient;
private List<ContactInfo> cntctInfoList;
private ContactInfo cntctInfo;
private boolean addContactInfoDisabled = false;
private boolean deleteSelectedContactInfoDisabled = true;
boolean confirm = false;
public NewPatientView() {
init();
}
public void init() {
this.setPatient(new Ptnt());
this.setCntctInfoList(new ArrayList<>());
this.getPatient().setContactInfoList(this.getCntctInfoList());
}
/////////////// EVENTS//////////////////
public void onAddNewContactInfo(ActionEvent event) {
if (patient.getContactInfoList() == null)
patient.setContactInfoList(new ArrayList<>());
boolean hasNewRow = patient.getContactInfoList().stream()
.filter(ci -> ci.getEmail() == null && ci.getPhone() == null).count() >= 1;
if (hasNewRow) {
FacesMessage msg = new FacesMessage("Can't add new row", "There is an empty row already!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
ContactInfo cntctInfo = new ContactInfo();
cntctInfo.setType("Main");
cntctInfo.setPrsn(patient);
patient.getContactInfoList().add(cntctInfo);
}
}
public void onDeleteSelectedContactInfo(ActionEvent event) {
if (cntctInfo != null) {
cntctInfoList.remove(cntctInfo);
cntctInfo = null;
}
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
}
public void onRowEdit(RowEditEvent event) {
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
ContactInfo editedContactInfo = (ContactInfo) event.getObject();
boolean moreThanOne = patient.getContactInfoList().stream().filter(ci -> ci.equals(editedContactInfo))
.count() > 1;
if (moreThanOne) {
patient.getContactInfoList().remove(editedContactInfo);
FacesMessage msg = new FacesMessage("Row Removed", "The contact information provided is redundent!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
public void onRowEditInit(RowEditEvent event) {
if (event.getObject() instanceof ContactInfo) {
this.setCntctInfo((ContactInfo) event.getObject());
this.setDeleteSelectedContactInfoDisabled(false);
}
this.setAddContactInfoDisabled(true);
}
public void onRowCancel(RowEditEvent event) {
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
}
public void onDialogCancel() {
RequestContext.getCurrentInstance().closeDialog(null);
}
public void onDialogApprove() {
RequestContext.getCurrentInstance().closeDialog(patient);
}
public PatientDAO getPatientDAO() {
return patientDAO;
}
public void setPatientDAO(PatientDAO patientDAO) {
this.patientDAO = patientDAO;
}
public Ptnt getPatient() {
return patient;
}
public void setPatient(Ptnt patient) {
this.patient = patient;
}
public ContactInfo getCntctInfo() {
return cntctInfo;
}
public void setCntctInfo(ContactInfo cntctInfo) {
this.cntctInfo = cntctInfo;
}
public boolean isAddContactInfoDisabled() {
return addContactInfoDisabled;
}
public void setAddContactInfoDisabled(boolean addContactInfoDisabled) {
this.addContactInfoDisabled = addContactInfoDisabled;
}
public boolean isDeleteSelectedContactInfoDisabled() {
return deleteSelectedContactInfoDisabled;
}
public void setDeleteSelectedContactInfoDisabled(boolean deleteSelectedContactInfoDisabled) {
this.deleteSelectedContactInfoDisabled = deleteSelectedContactInfoDisabled;
}
public List<ContactInfo> getCntctInfoList() {
return cntctInfoList;
}
public void setCntctInfoList(List<ContactInfo> cntctInfoList) {
this.cntctInfoList = cntctInfoList;
}
}
and here is how I call the dialog in patienViewBean:
package me.bttb.crs.beans.patient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import me.bttb.crs.model.Ptnt;
#Named
#ManagedBean
#ViewScoped
public class PatientsViewBean {
#Autowired
private PatientDAO patientDAO;
private List<Ptnt> patients;
private List<Ptnt> filterdPatients;
public PatientsViewBean() {
}
public long getPatientsCount() {
return patientDAO.getPatientsCount();
}
public List<Ptnt> refreshAllPatients() {
this.setPatients(patientDAO.getPatients());
return this.getPatients();
}
public void addNewPatientDialog() {
Map<String, Object> options = new HashMap<String, Object>();
options.put("resizable", false);
options.put("draggable", false);
options.put("modal", true);
//options.put("contentHeight", "95%");
//options.put("height", 400);
//options.put("width", 700);
options.put("closable", false);
RequestContext.getCurrentInstance().openDialog("newPatientDialog", options, null);
}
public void onDialogReturn(SelectEvent event) {
if (event.getObject() != null && event.getObject() instanceof Ptnt) {
patientDAO.addpatient((Ptnt) event.getObject());
refreshAllPatients();
FacesMessage msg = new FacesMessage("Patient Added", "Pateint information added in the database.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("operation canceld", "Nothing is saved to the database.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
////////////////////////////////////
public PatientDAO getPatientDAO() {
return patientDAO;
}
public void setPatientDAO(PatientDAO patientDAO) {
this.patientDAO = patientDAO;
}
public List<Ptnt> getPatients() {
return patients;
}
public void setPatients(List<Ptnt> patients) {
this.patients = patients;
}
public List<Ptnt> getFilterdPatients() {
return filterdPatients;
}
public void setFilterdPatients(List<Ptnt> filterdPatients) {
this.filterdPatients = filterdPatients;
}
}
what am I doing wrong, shouldn't the newPatientView get recreated every time the dialog shows up??
please explain the life cycle of the view here.

Editable Data table in UserWizard with dynamic value selection query

initiate.xhtml
I am using the primefaces wizard to show the sequential flow for an application.In one of the tab namely member details, I have an editable data table .For the Name column,I want the user to select the name from the available list of users having Name,designation,division on clicking a button
I am using another datatable in the dialog box on clicking on a button.
But how can i update the selected value in the original data table after clicking on add button.
<h:body>
<h:form id="compositionmaster">
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:wizard widgetVar="wiz" flowListener="#{userWizard.onFlowProcess}" step="address" >
<p:tab id="address" title="Member Details">
<p:panel header="Member Selection" >
<h:messages errorClass="error"/>
<p:dataTable id="outputtable" var="membertable" value="#{tableBean.compositionRoles}" editable="true" editMode="cell" >
<p:column headerText="Role" >
<h:outputText value="#{membertable.role}" />
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="input">
<p:selectOneMenu value="#{userWizard.user.type}">
<f:selectItem itemLabel="--Select--" itemValue="0" />
<f:selectItem itemLabel="Internal" itemValue="1" />
<f:selectItem itemLabel="External" itemValue="2" />
</p:selectOneMenu>
</f:facet>
<f:facet name="output">
<h:outputText value="#{userWizard.user.type}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column id="namecol" headerText="Name">
<p:commandButton id="basic" value="..." onclick="dlg.show();" type="button" />
<h:outputText value="#{userBean.selectedUser.name}" />
</p:column>
<p:column id="divcol" headerText="Section/Division">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{userBean.selectedUser.division}" />
</f:facet>
<f:facet name="input">
<h:inputText value="#{userBean.selectedUser.division}" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
<p:dialog id="dialog" header="UserList" widgetVar="dlg" >
<h:form id="userform">
<p:dataTable var="user" value="#{userBean.users}" selection="#{userBean.selectedUser}" rowKey="#{user.name}" >
<p:column selectionMode="single"/>
<p:column headerText="Name">
<h:outputText value="#{user.name}" />
</p:column>
<p:column headerText="Division">
<h:outputText value="#{user.division}" />
</p:column>
<f:facet name="footer">
<p:commandButton update=":compositionmaster:namecol" ajax="true" onclick="dlg.hide()" value="Add" id="addmember"/>
</f:facet>
</p:dataTable>
</h:form>
</p:dialog>
UserWizard.java
package committee;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.event.ActionEvent;
import javax.faces.context.FacesContext;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import org.primefaces.event.FlowEvent;
import java.io.Serializable;
import javax.faces.bean.ViewScoped;
import office.UserBean;
#ManagedBean
#ViewScoped
public class UserWizard implements Serializable{
private User user = new User();
private Committee comm =new Committee();
private boolean skip;
private UserBean userbean;
private static final Logger logger = Logger.getLogger(UserWizard.class.getName());
public UserBean getUserbean() {
return userbean;
}
public void setUserbean(UserBean userbean) {
this.userbean = userbean;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Committee getComm() {
return comm;
}
public void setComm(Committee comm) {
this.comm = comm;
}
public void save(ActionEvent actionEvent) {
//Persist user
FacesMessage msg = new FacesMessage("Successful", "Welcome :" + user.getName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isSkip() {
return skip;
}
public void setSkip(boolean skip) {
this.skip = skip;
}
public String onFlowProcess(FlowEvent event) {
System.out.println(event.getOldStep());
System.out.println(event.getNewStep());
System.out.println(skip);
logger.log(Level.INFO, "Current wizard step:{0}", event.getOldStep());
logger.log(Level.INFO, "Next step:{0}", event.getNewStep());
return event.getNewStep();
}
}
UserBean.java
package office;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import committee.User;
import committee.UserDataModel;
import java.util.List;
import java.util.ArrayList;
#ManagedBean
#ViewScoped
public class UserBean implements Serializable{
private List<User> users;
public UserBean() {
users = new ArrayList<User>();
users.add(new User("Kanika","Development"));
users.add(new User("Shreya","Development"));
users.add(new User("Tushti","Development"));
users.add(new User("abc","Marketing"));
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
private User selectedUser;
private UserDataModel userDataModel;
public UserDataModel getUserDataModel() {
return userDataModel;
}
public void setUserDataModel(UserDataModel userDataModel) {
this.userDataModel = userDataModel;
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
}

rich dataTable update issue

I have a problem with rich dataTable
actually I populate that dataTable from a database and a made a column editable by putting an inplaceInput in it the problem is when i submit to the backing bean The values doesn't change the backing bean is populated with old values that initially populated the dataTable :
here is my JSF Code of the table:
<center>
<fieldset><rich:dataTable id="tablefiles"
value="#{fileBean.files}" var="file" rows="8"
iterationStatusVar="it">
<rich:column id="Child_Code">
<f:facet name="header">
<h:outputText value="N°tiers filiale" />
</f:facet>
<h:outputText value="#{file.child_Code}" />
</rich:column>
<rich:column id="Mother_Code">
<f:facet name="header">
<h:outputText value="Nom du groupe" />
</f:facet>
<!-- <h:inputText value="#{file.mother_Code}" />-->
<rich:inplaceInput defaultLabel="Click here to edit"
showControls="false" controlsHorizontalPosition="left"
controlsVerticalPosition="bottom" id="inplaceInput"
value="#{file.mother_Code}"
>
</rich:inplaceInput>
</rich:column>
<rich:column>
<f:facet name="header" roles="#riskuser">
<h:outputText value="Détail" />
</f:facet>
<h:commandLink action="#{fileBean.accesDetail}">
<h:graphicImage value="/images/edit.png" alt="edit"
style="border:0;" title="Détail " />
<f:setPropertyActionListener target="#{fileBean.selectedFile}"
value="#{file}" />
</h:commandLink>
</rich:column>
<f:facet name="footer">
<rich:dataScroller page="#{fileBean.page}" />
</f:facet>
</rich:dataTable> <br />
<h:panelGrid columns="3" id="buttonRow">
<a4j:commandButton value="Save" render="tablefiles" execute="#form"
action="#{fileBean.update}">
</a4j:commandButton>
</h:panelGrid></fieldset>
</center>`<center>
<fieldset><rich:dataTable id="tablefiles"
value="#{fileBean.files}" var="file" rows="8"
iterationStatusVar="it">
<rich:column id="Child_Code">
<f:facet name="header">
<h:outputText value="N°tiers filiale" />
</f:facet>
<h:outputText value="#{file.child_Code}" />
</rich:column>
<rich:column id="Mother_Code">
<f:facet name="header">
<h:outputText value="Nom du groupe" />
</f:facet>
<!-- <h:inputText value="#{file.mother_Code}" />-->
<rich:inplaceInput defaultLabel="Click here to edit"
showControls="false" controlsHorizontalPosition="left"
controlsVerticalPosition="bottom" id="inplaceInput"
value="#{file.mother_Code}"
>
</rich:inplaceInput>
</rich:column>
<rich:column>
<f:facet name="header" roles="#riskuser">
<h:outputText value="Détail" />
</f:facet>
<h:commandLink action="#{fileBean.accesDetail}">
<h:graphicImage value="/images/edit.png" alt="edit"
style="border:0;" title="Détail " />
<f:setPropertyActionListener target="#{fileBean.selectedFile}"
value="#{file}" />
</h:commandLink>
</rich:column>
<f:facet name="footer">
<rich:dataScroller page="#{fileBean.page}" />
</f:facet>
</rich:dataTable> <br />
<h:panelGrid columns="3" id="buttonRow">
<a4j:commandButton value="Save" render="tablefiles" execute="#form"
action="#{fileBean.update}">
</a4j:commandButton>
</h:panelGrid></fieldset>
</center>
Here is My bean code :
package ui.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import business.ISRGGestionGarantieCasa;
import common.pojo.SRGarantieCasa;
#ManagedBean
#SessionScoped
public class GarantiCasaBean implements Serializable {
private static final long serialVersionUID = -1509108399715814312L;
private ISRGGestionGarantieCasa fileService;
private int idMsg;
private int page = 1;
private String id_r;
private List<SRGarantieCasa> files = new ArrayList<SRGarantieCasa>();
private SRGarantieCasa selectedFile, file;
private List<String> suggestions = null;
public List<String> getSuggestions() {
return suggestions;
}
public void setSuggestions(List<String> suggestions) {
this.suggestions = suggestions;
}
public SRGarantieCasa getSelectedFile() {
return selectedFile;
}
public void setSelectedFile(SRGarantieCasa selectedfile) {
this.selectedFile = selectedfile;
}
public ISRGGestionGarantieCasa getFileService() {
return fileService;
}
public void setFileService(ISRGGestionGarantieCasa fileService) {
this.fileService = fileService;
}
public int getIdMsg() {
return idMsg;
}
public void setIdMsg(int idMsg) {
this.idMsg = idMsg;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public String getId_r() {
return id_r;
}
public void setId_r(String id_r) {
this.id_r = id_r;
}
public List<SRGarantieCasa> getFiles() {
return files;
}
public void setFiles(List<SRGarantieCasa> files) {
this.files = files;
}
public String viderChamps() {
// vider les champ
id_r = "";
return null;
}
public String search() {
if (id_r == "") {
files = fileService.getListeFiles();
} else {
files.clear();
files = fileService.getFile(id_r);
}
return null;
}
public String accesDetail() {
return "GCUpdate?faces-redirect=true";
}
public String saveFile() {
fileService.updateFile(selectedFile);
return "GarantieCasa?faces-redirect=true";
}
public String ajoutFile() {
fileService.addfile(file);
return "GarantieCasa?faces-redirect=true";
}
public String addFile() {
return "GarantieCasaAdd?faces-redirect=true";
}
public SRGarantieCasa getFile() {
return file;
}
public void setFile(SRGarantieCasa file) {
this.file = file;
}
public GarantiCasaBean() {
/*
* suggestions = new ArrayList<String>(); suggestions.add("Banana");
* suggestions.add("Cranberry"); suggestions.add("Blueberry");
* suggestions.add("Orange"); suggestions.add("Apple");
* suggestions.add("Strawberry");
*/
}
public void update()
{
for (SRGarantieCasa selectedFile : fileService.getListeFiles()){
System.out.println("GarantieCasaBean : Mother Code :"+selectedFile.getMother_Code());
fileService.updateFile(selectedFile);
}
//return "GarantieCasa?faces-redirect=true";
}
}
and here is the spring conf :
<!-- Service UI -->
<bean id="fileBean" class="ui.bean.GarantiCasaBean" scope="request">
<property name="fileService" ref="SO_GestionFile" />
<property name="file" ref="fileCGC" />
</bean>
<bean id="fileCGC" class="common.pojo.SRGarantieCasa" scope="session" />
I found the same issue in that topic :
Richfaces editable dataTable not setting updated values in Bean
but I the #this , #All doesn't work for me :( please Help me

file upload within a wizard in primefaces - uploaded file does not showing up?

I use the Primefaces manual example for a wizard, and replace one of the tabs by a simple file upload form. I have all the necessary libraries and filter in web-inf for the file upload to work. Running the project with Netbeans does not show any error (the wizard is displayed and the UI responds), but the file is not uploaded and I get no system message from my fileBean class. Any clue where I make a mistake? Is something wrong with my nested form in the index.html? Thx!
index.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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>The rings of scholarship</title>
</h:head>
<h:body>
<h:form>
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:wizard widgetVar="wiz"
flowListener="#{userWizard.onFlowProcess}">
<p:tab id="personal" title="Personal">
<p:panel header="Personal Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value" styleClass="grid">
<h:outputText value="Firstname: *" />
<p:inputText required="true" label="Firstname"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: *" />
<p:inputText required="true" label="Lastname"
value="#{userWizard.user.lastname}" />
<h:outputText value="Age: " />
<p:inputText value="#{userWizard.user.age}" />
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="upload" title="File upload">
<p:panel header="File upload">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{fileBean.file}" mode="simple" />
<p:commandButton value="Submit" action="#{fileBean.save}" ajax="false"/>
</h:form>
</h:panelGrid>
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</p:panel>
</p:tab>
<p:tab id="contact" title="Contact">
<p:panel header="Contact Information">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Email: *" />
<p:inputText required="true" label="Email"
value="#{userWizard.user.email}" />
<h:outputText value="Phone: " />
<p:inputText value="#{userWizard.user.phone}"/>
<h:outputText value="Additional Info: " />
<p:inputText value="#{userWizard.user.info}"/>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="confirm" title="Confirmation">
<p:panel header="Confirmation">
<h:panelGrid id="confirmation" columns="6">
<h:outputText value="Firstname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.lastname}"/>
<h:outputText value="Age: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.age}" />>
<h:outputText value="Email: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.email}" />
<h:outputText value="Phone " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.phone}"/>
<h:outputText value="Info: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.info}" />
<h:outputText />
<h:outputText />
</h:panelGrid>
<p:commandButton value="Submit" update="growl"
actionListener="#{userWizard.save}"/>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</h:body>
</html>
fileBean:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import org.apache.commons.io.IOUtils;
import org.primefaces.model.UploadedFile;
#ManagedBean
#ViewScoped
public class FileBean implements Serializable{
private UploadedFile file;
/**
* Creates a new instance of FileBean
*/
public FileBean() {
}
public UploadedFile getFile() {
System.out.println("we get file");
return file;
}
public void setFile(UploadedFile file) throws FileNotFoundException, IOException {
System.out.println("we set file");
this.file = file;
}
public void save() throws IOException {
System.out.println("we save file");
IOUtils.copy(file.getInputstream(), new FileOutputStream("D:\\" + file.getFileName()));
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputstream()));
String currLine = br.readLine();
Integer counterLines = 0;
while (currLine != null && counterLines < 5) {
System.out.println("currLine is: " + currLine);
counterLines++;
}
}
}
UserWizard:
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.FlowEvent;
#ManagedBean
#ViewScoped
public class UserWizard implements Serializable{
private User user = new User();
private boolean skip;
private static final Logger logger = Logger.getLogger(UserWizard.class.getName());
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void save(ActionEvent actionEvent) {
//Persist user
FacesMessage msg = new FacesMessage("Successful", "Welcome :" + user.getFirstname());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isSkip() {
return skip;
}
public void setSkip(boolean skip) {
this.skip = skip;
}
public String onFlowProcess(FlowEvent event) {
logger.log(Level.INFO, "Current wizard step:{0}", event.getOldStep());
logger.log(Level.INFO, "Next step:{0}", event.getNewStep());
if (skip) {
skip = false; //reset in case user goes back
return "confirm";
} else {
return event.getNewStep();
}
}
}
Start by getting rid of the nested forms... you got one surrounding the wizard and one inside the <p:tab id="upload" title="File upload">
Try removing the inner form from the tab and wrap the wizard with <h:form enctype="multipart/form-data">

Resources