How to maintain state between page redirection JSf 2.0 - jsf-2

I am making pages where you can upload pictures and then preview them. Both upload and preview work fine. But the problem is if I upload images, then preview it and then come back to the upload images page, the images are gone. Here is my code
<h:panelGrid columns="4"
border=""
width="20%"
style="position: absolute; top: 50px;"
columnClasses="asteriskColumns, nameColumns" >
<h:outputText value="*" />
<h:outputText value="Map: " />
<p:fileUpload id="cityMap"
description="Image"
update="mapImage messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="mapImage"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
<h:outputText value="*" />
<h:outputText value="Image1: " />
<p:fileUpload id="cityImage1"
description="Image"
update="city_Image1 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city_Image1"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
<h:outputText value="*" />
<h:outputText value="Image2: " />
<p:fileUpload id="cityImage2"
description="Image"
update="city_Image2 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city_Image2"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" />
Here is my bean
#ManagedBean
#ViewScoped
#SessionScoped
public class CityDetail {
private StreamedContent image;
private ArrayList images;
private ArrayList imageNames;
private String imagePath = "/resources/images/Untitled.jpg";
private String imagePath1 = "/resources/images" + "/";
public CityDetail() {
images = new ArrayList();
images.add(null);
images.add(null);
images.add(null);
images.add(null);
images.add(null);
imageNames = new ArrayList();
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
// Getting session ID from seession variable that is set in the City_Review Page
cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString());
System.out.println();
}
public void imageUpload(FileUploadEvent event) {
imagePath = "";
// Variable to ensure that the query is always enter to same index.
int index = -1;
String query = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// File
UploadedFile uploadedFile = event.getFile();
// File Name
String fileName = uploadedFile.getFileName();
//File Extension
String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
String path = externalContext.getRealPath("/resources/images") + "/" ;
try {
//<p:fileUpload id="cityMap" .../>
String componentID = event.getComponent().getClientId();
if (componentID.equalsIgnoreCase("cityMap")) {
index = 0;
/**
* UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
*/
query = "UPDATE city set citymap=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityMap_" + cityID + fileExtension);
setImage(imagePath1, "cityMap_" + cityID + fileExtension);
//imagePath = imagePath + "cityMap" + fileExtension;
}
} else if (componentID.equalsIgnoreCase("cityImage1")) {
index = 1;
query = "UPDATE city set cityimage1=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage1_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage1_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage1_" + cityID + fileExtension);
setImage(imagePath1, "cityImage1_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage2")) {
index = 2;
query = "UPDATE city set cityimage2=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage2_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage2_", fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage2_" + cityID + fileExtension);
setImage(imagePath1, "cityImage2_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage3")) {
index = 3;
query = "UPDATE city set cityimage3=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage3_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityImage3_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityImage3_" + cityID + fileExtension);
setImage(imagePath1, "cityImage3_" + cityID + fileExtension);
}
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Exception happen");
FacesContext.getCurrentInstance().addMessage(null, msg);
e.printStackTrace();
// return null;
}
} //end of imageUpload()
private void setImage(String path, String fileName) {
imagePath = path + fileName;
}
Now when I come back to this page after previewing then the images gone. How can I prevent this? Do I make 5 image path variables and then save it somewhere else? But what if I have 50 images. Is there any better option? That when I again come back to upload the page everything remains as it is to this page?

A few things are weird with your code:
You have to select a single scope for your bean, ViewScoped or SesssionScoped.
Should all h:graphicImage components be bound to the same value really?
I can't see the imagePath property of your bean.

Either you store the images in a #SessionScoped bean, or you store them to some persistent storage after you upload them.

Hi here how i done this. First here is my html
<h:form id="cityDetailForm" prependId="false" >
<p:growl id="messages"
showDetail="true" />
<p:panel id="panel1"
style="border-color: #000000;width: 954px;position: absolute;left: 150px;height: 450px;-moz-border-radius: 11px; -webkit-border-radius: 11px; border-radius: 11px; behavior: url(../PIE/PIE.htc)">
<strong Class="MainHeader">
<p:spacer width="10"/> City Detail
</strong>
<h:panelGrid columns="5"
border=""
width="20%"
style="position: absolute; top: 50px;"
columnClasses="asteriskColumns, nameColumns" >
<h:outputText value="*" />
<h:outputText value="Map: " />
<p:fileUpload id="cityMap"
description="Image"
update="city messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="city"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false">
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="city"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image1: " />
<p:fileUpload id="cityImage1"
description="Image"
update="Image1 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image1"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image1"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image2: " />
<p:fileUpload id="cityImage2"
description="Image"
update="Image2 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image2"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image2"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image3: " />
<p:fileUpload id="cityImage3"
description="Image"
update="Image3 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image3"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image3"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
<h:outputText value="*" />
<h:outputText value="Image4: " />
<p:fileUpload id="cityImage4"
description="Image"
update="Image4 messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener="#{cityDetail.imageUpload}" >
</p:fileUpload>
<p:graphicImage id="Image4"
value="#{cityDetail.imagePath}"
width="80"
height="50"
cache="false" >
<f:event type="preRenderComponent" listener="#{cityDetail.putImage}" />
</p:graphicImage>
<p:commandLink update="Image4"
action="#{cityDetail.removeImage}"
style="color: #0d5b7f;text-decoration: underline">
<h:outputText value="remove" />
</p:commandLink>
</h:panelGrid>
<h:commandButton id="preview"
value="Preview"
action="#{cityDetail.preview}"
style="position: absolute; top: 350px;"
styleClass="ButtonStyle" />
<h:commandButton id="save"
value="Save"
actionListener="#{cityDetail.sendImagesToDatabase}"
action="#{cityDetail.save}"
style="position: absolute; top: 350px; left: 90px;"
styleClass="ButtonStyle" />
<h:commandButton id="cancel"
value="Cancel"
action="#{cityDetail.cancel}"
style="position: absolute; top: 350px; left: 165px;"
styleClass="ButtonStyle" />
</p:panel>
</h:form>
and now here is my bean
#ManagedBean
#ViewScoped
#SessionScoped
public class CityDetail {
private StreamedContent image;
private ArrayList images;
private ArrayList imageNames;
private String imagePath = "/resources/images/Untitled.jpg";
private String imagePath1 = "/resources/images" + "/";
private boolean remove = false;
private String once;
private static int x = 0;
// Set in the City_Review Page, in session variable
public int cityID;
/** Creates a new instance of CityDetail */
public CityDetail() {
/**
* If we come from cityView.xhtml page then this contain value. We are using this because we
* want that when user come from cityView.xhtml page then old values should be retain.
*/
imageNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames");
images = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImages");
if (imageNames == null) {
imageNames = new ArrayList();
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
imageNames.add("");
} //end of if()
if (images == null) {
images = new ArrayList();
images.add("");
images.add("");
images.add("");
images.add("");
images.add("");
}
// Getting session ID from seession variable that is set in the City_Review Page
cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString());
once = ConnectionUtil.session.getAttribute("once").toString();
if (once.equalsIgnoreCase("true")) {
//SELECT column_name(s) FROM table_name WHERE column_name operator value
String cityMapQuery = "SELECT citymap From city Where cityid='" + cityID + "'";
String cityImage1Query = "SELECT cityimage1 From city Where cityid='" + cityID + "'";
String cityImage2Query = "SELECT cityimage2 From city Where cityid='" + cityID + "'";
String cityImage3Query = "SELECT cityimage3 From city Where cityid='" + cityID + "'";
String cityImage4Query = "SELECT cityimage4 From city Where cityid='" + cityID + "'";
ArrayList cityMapQueryArray = new ArrayList();
cityMapQueryArray.add(cityMapQuery);
ArrayList cityImage1QueryArray = new ArrayList();
cityImage1QueryArray.add(cityImage1Query);
ArrayList cityImage2QueryArray = new ArrayList();
cityImage2QueryArray.add(cityImage2Query);
ArrayList cityImage3QueryArray = new ArrayList();
cityImage3QueryArray.add(cityImage3Query);
ArrayList cityImage4QueryArray = new ArrayList();
cityImage4QueryArray.add(cityImage4Query);
ArrayList mainArray = new ArrayList();
mainArray.add(cityMapQueryArray);
mainArray.add(cityImage1QueryArray);
mainArray.add(cityImage2QueryArray);
mainArray.add(cityImage3QueryArray);
mainArray.add(cityImage4QueryArray);
} //end of if
System.out.println();
} //end of constructor()
//Getters and setters ---------------------
public StreamedContent getImage() {
return image;
}
public void setImage(StreamedContent image) {
this.image = image;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
//public String imageUpload(FileUploadEvent event) {
public void imageUpload(FileUploadEvent event) {
imagePath = "";
// Variable to ensure that the query is always enter to same index.
int index = -1;
String query = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// File
UploadedFile uploadedFile = event.getFile();
// File Name
String fileName = uploadedFile.getFileName();
//File Extension
String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
String path = externalContext.getRealPath("/resources/images") + "/" ;
try {
//<p:fileUpload id="cityMap" .../>
String componentID = event.getComponent().getClientId();
if (componentID.equalsIgnoreCase("cityMap")) {
index = 0;
/**
* UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
*/
query = "UPDATE city set citymap=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID);
boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "cityMap_" + cityID + fileExtension);
// setImage(imagePath1, "cityMap_" + cityID + fileExtension, index);
// imagePath = imagePath1 + "cityMap_" + cityID + fileExtension;
}
} else if (componentID.equalsIgnoreCase("cityImage1")) {
index = 1;
query = "UPDATE city set cityimage1=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage1_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage1_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage1_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage2")) {
index = 2;
query = "UPDATE city set cityimage2=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage2_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage2_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage2_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage3")) {
index = 3;
query = "UPDATE city set cityimage3=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage3_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage3_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage3_" + cityID + fileExtension);
}
} else if (componentID.equalsIgnoreCase("cityImage4")) {
index = 4;
query = "UPDATE city set cityimage4=(?) where cityid=" + cityID;
boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage4_" + cityID);
boolean outcome = ConnectionUtil.createFile("sityImage4_" + cityID, fileExtension ,path, uploadedFile);
if (outcome) {
addImageNameToList(index, "sityImage4_" + cityID + fileExtension);
}
} //end of else if()
// Convert file from input stream to bytes
byte[] byteArray = event.getFile().getContents();
/**
* Add images to list so we can retrieve them when user click on save button
*/
// boolean add = images.add(new Images(query, byteArray));
//Check for multiple clicks on the same Browse Button
// If index has value then replace the value rather then add new value to List
images.set(index, new Images(query, byteArray));
//byteArray used to store picture into database
InputStream ist = new ByteArrayInputStream(byteArray);
/*
* StreamedContent Object used to show the picture in jsf pages. We need to convert
* again bytearray to InputStream
*/
image = new DefaultStreamedContent(ist, "image/jpg");
FacesMessage msg = new FacesMessage(fileName + " succesfully uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
//we dont need to use faces-config to navigate in jsf 2
// return null ;
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Exception happen");
FacesContext.getCurrentInstance().addMessage(null, msg);
e.printStackTrace();
// return null;
} //end of catch (Exception e)
} //end of imageUpload()
/**
* This method called when user click on "save" button on page cityDetail.xhtml .
* This method is called before save() function is executed. Because action listener
* runs first.
* #return
*/
public void sendImagesToDatabase(ActionEvent e) {
ArrayList mainArray = new ArrayList();
for(int i=0; i<images.size(); i++) {
ArrayList innerArray = new ArrayList();
if (images.get(i).equals("")) {
continue;
} else {
Images imageObject =(Images)images.get(i);
String query = imageObject.getQuery();
byte[] image = imageObject.getImageBytes();
innerArray.add(query);
innerArray.add(image);
mainArray.add(innerArray);
}
} //end of for()
int executeDocumentUpdateBatch = ConnectionUtil.executeDocumentUpdateBatch(mainArray);
System.out.println(executeDocumentUpdateBatch);
} //end of sendImagesToDatabase()
/**
* This method is called when user click on "preview" button on page cityDetail.xhtml
* #return
*/
public String preview() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames);
ConnectionUtil.session.setAttribute("cityDetailImages", images);
return "cityView?faces-redirect=true";
} //end of preview()
/**
* This method called when user click on "save" button on page cityDetail.xhtml .
* This method is called after sendImagesToDatabase() function is executed. Because action listener
* runs first.
* #return
*/
public String save() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames);
ConnectionUtil.session.setAttribute("cityDetailImages", images);
return "cityDetail?faces-redirect=true";
//return null;
} //end of save()
public String cancel() {
ConnectionUtil.session.setAttribute("cityDetailImageNames", null);
ConnectionUtil.session.setAttribute("cityDetailImages", null);
return "City_AddUpdate?faces-redirect=true";
} //end of cancel()
private void addImageNameToList(int index, String fileName) {
imageNames.set(index, fileName);
} //end of addImageNameToList()
/**
* This method is called when user click on remove link on page cityDetail.xhtml beside each image.
* We simply set boolean variable "remove" to true so when "update = <p:graphicImage Id />"
* in <p:commandLink /> is called then <p:graphicImage /> with the mentioned ID is called and
* its putImage() method is called. Then in the method we handle remove image procedure.
*/
public void removeImage() {
remove = true;
} //end of removeImage()
/**
* This method is called for every <p:graphicImage /> because we use "type = preRenderComponent"
* on every <p:graphicImage /> . In this method we we set image path and also check whether
* user coming from preview page so we can again set images to the same position.
* #param event
*/
public void putImage(ComponentSystemEvent event) {
boolean test = remove;
boolean found = false;
x++;
int y = x;
GraphicImage image1 = (GraphicImage)event.getComponent();
String imageURL = image1.getUrl();
String imageDir = image1.getDir();
String imageValue = image1.getValue().toString();
String imageId = image1.getClientId();
ArrayList imagesNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames");
if (imagesNames == null) {
for (int i=0; i<imageNames.size(); i++) {
String fileName = imageNames.get(i).toString();
if (fileName.contains(imageId)) {
if (remove) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
//also remove from list so when on preview page this list called using session
// it contains "" for the remove value. Otherwise image deleted from
//cityDetail page but shown when preview is clicked
imageNames.set(i, "");
remove = false;
break;
} else {
imagePath = "";
imagePath = imagePath1 + fileName;
break;
}
} //end of if
} //end of for()
} else { //handle when retrun from preview page
for(int i=0; i<imagesNames.size(); i++) {
String fileName = imagesNames.get(i).toString();
if (fileName.contains(imageId)) {
if (remove) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
imageNames.set(i, ""); //also remove from list
remove = false;
break;
} else {
imagePath = "";
imagePath = imagePath1 + fileName;
break;
}
} else if (fileName.equalsIgnoreCase("")) {
imagePath = "";
imagePath = "/resources/images/Untitled.jpg";
break;
}
} //end of for
}
System.out.println();
System.out.println();
System.out.println();
} //end of putImage
} //end of class CityDetail
Now if i done anything wrong and unusal then please let me know ? because this code is working fine but working fine doesn't mean that it is perfect or correct.
Thanks

Related

p:dataTable RowEdit keeping old values

I'm trying to update a value of a line edited on the datatable (editable = true, row edition). But I always keep getting the old value through the listener. Can you pls tell me where's my mistake? tks..
Here is the code:
<?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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="_template.xhtml">
<ui:define name="conteudo">
<h:form id="certificacao" >
<p:messages globalOnly="false" showSummary="true" showDetail="true" />
<p:growl id="messages" autoUpdate = "true"/>
<p:fieldset legend="Dados da Certificação">
<h:panelGrid columns="3" >
<p:outputLabel value="Nome da Certificação:" for="nomeCertificacao" style="font-weight:bold"/>
<p:inputText id="nomeCertificacao" value="#{certificacaoBean.certificacao.nomeCertificacao}"
required="true" requiredMessage="Nome da certificação não preenchido" >
</p:inputText>
<br/>
<h:outputLabel value="Descrição da Certificação:" for="descCertificacao" style="font-weight:bold"/>
<p:inputText id="descCertificacao" value="#{certificacaoBean.certificacao.descCertificacao}">
</p:inputText>
<br/>
<p:commandButton value="Gravar" action="#{certificacaoBean.gravar}" icon="fa fa-fw fa-save"
process="#this certificacao" update="#form certificacao" />
<br/>
</h:panelGrid>
</p:fieldset>
<p:dataTable
value="#{certificacaoBean.certificacoes}"
var="certificacao"
id="tabelaCertificacoes"
emptyMessage="Nenhuma certificação cadastrada"
editable="true"
style="margin-bottom:0px"
filteredValue="#{certificacaoBean.certificacaoSelecionada}"
widgetVar="tabelaCertificacoes">
<p:ajax event="rowEdit" listener="#{certificacaoBean.onRowEdit}" update=":certificacao:messages"/>
<p:ajax event="rowEditCancel" listener="#{certificacaoBean.onRowCancel}" update=":certificacao:messages" />
<p:column
headerText="Certificação"
filterBy="#{certificacao.nomeCertificacao}"
filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:outputText value="#{certificacao.nomeCertificacao}" />
</div>
</f:facet>
<f:facet name="input">
<p:inputText value="#{certificacao.nomeCertificacao}" style="width:100%" label="Certificação"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Descrição" filterBy="#{certificacao.descCertificacao}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{certificacao.descCertificacao}" /></f:facet>
<f:facet name="input"><p:inputText value="#{certificacao.descCertificacao}" style="width:100%" label="Descrição"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:3px">
<p:rowEditor />
</p:column>
<p:column style="width:3px">
<f:facet name="header">
<h:outputText value="" style="width:3px"/>
</f:facet>
<p:commandButton
action="#{certificacaoBean.removeCertificacao(certificacao)}"
icon="ui-icon-close"
title="Remover Certificação"
update="tabelaCertificacoes"
process="#this" >
<f:setPropertyActionListener
target="#{certificacaoBean.certificacaoSelecionada}"
value="#{certificacao}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
The bean part:
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import br.com.dao.DAO;
import br.com.model.Certificacao;
#ManagedBean(name="certificacaoBean")
#ViewScoped
public class CertificacaoBean implements Serializable {
private static final long serialVersionUID = 1L;
private Certificacao certificacao = new Certificacao();
public void setCertificacao(Certificacao certificacao) {
this.certificacao = certificacao;
}
private Certificacao certificacaoSelecionada;
public Certificacao getCertificacao() {
return certificacao;
}
public Certificacao getCertificacaoSelecionada() {
return certificacaoSelecionada;
}
public void setCertificacaoSelecionada(Certificacao certificacaoSelecionada) {
this.certificacaoSelecionada = certificacaoSelecionada;
}
public void removeCertificacao(Certificacao certificacao) {
new DAO<Certificacao>(Certificacao.class).remove(certificacaoSelecionada);
FacesMessage msg = new FacesMessage("Certificação excluída","");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Certificacao> getCertificacoes() {
return new DAO<Certificacao>(Certificacao.class).listaTodos();
}
public void gravar() {
System.out.println("Gravando Certificação " + this.certificacao.getNomeCertificacao());
if (certificacao.getNomeCertificacao().isEmpty()) {
FacesContext.getCurrentInstance().addMessage ("nomeCertificacao",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"O nome da certificação deve ser preenchido.", "O nome da certificação deve ser preenchido."));
return;
}
new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
this.certificacao = new Certificacao();
}
// Inicio Editor na Tabela
public void onRowEdit(RowEditEvent event) {
System.out.println("Passando no DAO retorno event Cod: " + ((((Certificacao) event.getObject()).getCodigoCertificacao())));
System.out.println("Passando no DAO retorno event Name: " + ((((Certificacao) event.getObject()).getNomeCertificacao())));
System.out.println("Passando no DAO retorno object: " + ((((Certificacao) event.getObject()))));
System.out.println("DAO evento " + event);
//new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
//Problema AQUI
new DAO<Certificacao>(Certificacao.class).atualiza((((Certificacao) event.getObject())));
this.certificacao = new Certificacao();
FacesMessage msg = new FacesMessage("Certificação editada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edição cancelada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
And the dao:
package br.com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
public class DAO<T> {
private final Class<T> classe;
public DAO(Class<T> classe) {
this.classe = classe;
}
public void adiciona(T t) {
// consegue a entity manager
EntityManager em = new JPAUtil().getEntityManager();
// abre transacao
em.getTransaction().begin();
// persiste o objeto
em.persist(t);
// commita a transacao
em.getTransaction().commit();
// fecha a entity manager
em.close();
}
public void remove(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.remove(em.merge(t));
em.getTransaction().commit();
em.close();
}
public void atualiza(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.merge(t);
em.getTransaction().commit();
em.close();
}
public List<T> listaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).getResultList();
em.close();
return lista;
}
public T buscaPorId(Integer id) {
EntityManager em = new JPAUtil().getEntityManager();
T instancia = em.find(classe, id);
em.close();
return instancia;
}
public int contaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
long result = (Long) em.createQuery("select count(n) from certificacao n")
.getSingleResult();
em.close();
return (int) result;
}
public List<T> listaTodosPaginada(int firstResult, int maxResults) {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).setFirstResult(firstResult)
.setMaxResults(maxResults).getResultList();
em.close();
return lista;
}
}
In your code, You only update the message'id not the datatable's id. Try to update the form in the "update" attribute of ajax when edit the row.

Not Able to Save/Update details from richfaces popup panel

I am working on richfaces4,
when i am trying to edit details from a popup panel,i am not able to save/update the edited details into my database.can anybody help me to solve this.
My XHTML Page is as follows:
<!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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
</h:head>
<h:body>
<h:form id="dboperatorform">
<t:saveState value="#{dBOperator.empList}"></t:saveState>
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<t:saveState value="#{dBOperator.employee}"></t:saveState>
<rich:panel style="width:1345px">
<f:facet name="header">
<h:outputText value="Search Panel" />
</f:facet>
<h:panelGrid id="searchPanel" columns="6">
<h:column>
<h:outputLabel value="First Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.first_Name}" />
</h:column>
<h:column>
<h:outputLabel value="Last Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.last_name}" />
</h:column>
<h:column>
<a4j:commandButton value="Search" action="#{dBOperator.search}"
render="richtable">
</a4j:commandButton>
</h:column>
<h:column>
</h:column>
</h:panelGrid>
</rich:panel>
<br />
<a4j:commandButton value="Add" action="#{dBOperator.editdetails}"
execute="#this" style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="false"></f:setPropertyActionListener>
</a4j:commandButton>
<p></p>
<rich:dataTable value="#{dBOperator.employees}" var="emp"
id="richtable" cellpadding="0" cellspacing="0" style="width:1349px"
reRender="richtable" iterationStatusVar="it"
noDataLabel="No Records Found!" rows="5">
<rich:column>
<f:facet name="header">#</f:facet>
<h:outputText value="#{it.index}" />
</rich:column>
<rich:column>
<f:facet name="header">
<a4j:commandLink value="First Name"
action="#{dBOperator.sortByFirstName}" render="richtable"></a4j:commandLink>
</f:facet>
<h:outputText value="#{emp.first_Name}" />
</rich:column>
<rich:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{emp.last_name}" />
</rich:column>
<rich:column>
<f:facet name="header">Edit</f:facet>
<a4j:commandButton image="images/edit.png"
action="#{dBOperator.editdetails}" execute="#this"
style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}"
value="#{it.index}"></f:setPropertyActionListener>
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="true"></f:setPropertyActionListener>
</a4j:commandButton>
</rich:column>
<f:facet name="footer">
<rich:dataScroller for="richtable" align="right"
status="ajaxProcessIcon" renderIfSinglePage="false" fastStep="5"
fastControls="auto" />
</f:facet>
</rich:dataTable>
<rich:popupPanel id="popup1" minHeight="300"
minWidth="300">
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink
onclick="#{rich:component('popup1')}.hide(); return false;"
reRender="richtable">X</h:outputLink>
</f:facet>
<rich:toolbar itemSeparator="line" width="100%" id="qawq">
<rich:toolbarGroup location="left">
<h:outputText
value="#{dBOperator.edit?'Employee Edit':'Employee Add'}" />
</rich:toolbarGroup>
</rich:toolbar>
<h:panelGrid id="CancelGrid" columns="2" width="100%">
<rich:column width="30%" style="border:none;">
<h:outputText value="First Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.first_Name}"
style="width:100%" id="abbr" />
</rich:column>
<rich:column width="30%" style="border:none;">
<h:outputText value="Last Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.last_name}"
style="width:100%" id="abbr1" />
</rich:column>
</h:panelGrid>
<a4j:commandButton value="#{dBOperator.edit?'Edit':'Save'}"
action="#{dBOperator.savedetails}"
oncomplete="#{rich:component('popup1')}.hide();"
onclick="validateFields();"></a4j:commandButton>
</rich:popupPanel>
<script type="text/javascript">
function validateFields() {
alert('came inside validateFields');
var fn=document.getElementById('dboperatorform:abbr');
alert('fn '+fn.value);
var ln=document.getElementById('dboperatorform:abbr1');
alert('ln '+ln.value);
}
</script>
</h:form>
</h:body>
</html>
My Bean Class is as follows
package com.richfaces.db;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.management.MBeanServer;
import javax.swing.SortOrder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.comparator.NameComparator;
import com.comparator.NameCompartor1;
import com.richfaces.Employee;
public class DBOperator {
String id;
String first_Name;
String last_name;
String fName;
String lName;
Employee employee;
int rowNum;
boolean edit;
Boolean search=Boolean.FALSE;
Boolean status = Boolean.FALSE;
List<Employee> list = new ArrayList<Employee>();
List<Employee> empList = new ArrayList<Employee>();
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public List<Employee> getEmployees() {
System.out.println("hghhghhhhh");
String sql2="";
Query query = null;
String sql1 = "from Employee as emp where id is not null ";
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
if(status==false && search==false) {
System.out.println("Normal Query +++++++++++++++++++++++ " + sql1);
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==true) {
System.out.println("came inside when search and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==false && search==true) {
System.out.println("came inside when search is true and status is false");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==false) {
System.out.println("came inside when search is false and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}
list = query.list();
/*if (status) {
Collections.sort(list, new NameComparator());
} else {
Collections.sort(list, new NameCompartor1());
}*/
System.out.println(list.size());
this.empList = list;
return list;
}
public String createCriteriaQuery(String query) {
StringBuffer sb = new StringBuffer(query);
if (getFirst_Name() != null && !(getFirst_Name().equals(""))) {
sb.append(" and emp.first_Name='" + first_Name + "'");
}
if (getLast_name() != null && !(getLast_name().equals(""))) {
sb.append(" and emp.last_name='" + last_name + "'");
}
if(this.status) {
sb.append(" order by emp.first_Name desc");
}else {
sb.append(" order by emp.first_Name");
}
System.out.println(sb.toString());
return sb.toString();
}
public void editdetails() {
if (edit) {
System.out.println("rownum is " + rowNum);
System.out.println(empList.size());
employee = (Employee) empList.get((rowNum));
System.out.println(employee.getFirst_Name() + "\t"
+ employee.getLast_name() + "\t" + employee.getId());
System.out.println("end of edit details method");
} else {
employee = new Employee();
}
}
public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public void savedetails() {
System.out.println("came into savedetails");
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
if(this.edit) {
System.out.println("EMPLOYEE DETAILS in IF "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
System.out.println("came inside if when edit is true");
sess.update(employee);
}else {
System.out.println("came inside else when edit is false");
System.out.println("EMPLOYEE DETAILS in ELSE "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
sess.save(employee);
}
}
public void search() {
System.out.println("came into search method");
search = true;
}
public void refreshData(ActionEvent ae) {
System.out.println("came into refreshdata");
getEmployees();
}
public void sortByFirstName() {
System.out.println("came inside sortByFirstName");
if (!status) {
status = Boolean.TRUE;
} else {
status = Boolean.FALSE;
}
//status=Boolean.TRUE;
getEmployees();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
My Entity class is as follows:
package com.richfaces;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String id;
String first_Name;
String last_name;
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
System.out.println("came inside setter method of firstname");
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
System.out.println("came inside setter method of lastname");
this.last_name = last_name;
}
}
if your exact problem is not seeing #{dBOperator.savedetails} action triggered:
i couldn't figure out the root cause yet, but this problem should be fixed by adding modal="true" to the rich:popupPanel attributes and moving validateFields() function into the popup panel. i faced this problem many times and saw it working properly on different popup components, including this one.

Not able to get data in popup panel in richfaces

I am not able to get the required data in rich popup panel when I click on edit link. Can anybody help me in resolving it.
When I am trying to edit row details, I am not able to get the required data in their respective fields for the first time, but surprisingly when i refresh my page and do the same procedure, I got the data in their respective fields.
I want to get the required data on click of edit link for the first time.
So, can anybody help me to resolve it.
My xhtml page
<!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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
</h:head>
<h:body>
<h:form id="dboperatorform">
<t:saveState value="#{dBOperator.empList}"></t:saveState>
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<t:saveState value="#{dBOperator.employee}"></t:saveState>
<rich:panel style="width:1345px">
<f:facet name="header">
<h:outputText value="Search Panel" />
</f:facet>
<h:panelGrid id="searchPanel" columns="6">
<h:column>
<h:outputLabel value="First Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.first_Name}" />
</h:column>
<h:column>
<h:outputLabel value="Last Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.last_name}" />
</h:column>
<h:column>
<a4j:commandButton value="Search" action="#{dBOperator.search}"
render="richtable">
</a4j:commandButton>
</h:column>
<h:column>
</h:column>
</h:panelGrid>
</rich:panel>
<br />
<a4j:commandButton value="Add" action="#{dBOperator.editdetails}"
execute="#this" style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="false"></f:setPropertyActionListener>
</a4j:commandButton>
<p></p>
<rich:dataTable value="#{dBOperator.employees}" var="emp"
id="richtable" cellpadding="0" cellspacing="0" style="width:1349px"
reRender="richtable" iterationStatusVar="it"
noDataLabel="No Records Found!" rows="5">
<rich:column>
<f:facet name="header">#</f:facet>
<h:outputText value="#{it.index}" />
</rich:column>
<rich:column>
<f:facet name="header">
<a4j:commandLink value="First Name"
action="#{dBOperator.sortByFirstName}" render="richtable"></a4j:commandLink>
</f:facet>
<h:outputText value="#{emp.first_Name}" />
</rich:column>
<rich:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{emp.last_name}" />
</rich:column>
<rich:column>
<f:facet name="header">Edit</f:facet>
<a4j:commandButton image="images/edit.png"
action="#{dBOperator.editdetails}" execute="#this"
style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}"
value="#{it.index}"></f:setPropertyActionListener>
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="true"></f:setPropertyActionListener>
</a4j:commandButton>
</rich:column>
<f:facet name="footer">
<rich:dataScroller for="richtable" align="right"
status="ajaxProcessIcon" renderIfSinglePage="false" fastStep="5"
fastControls="auto" />
</f:facet>
</rich:dataTable>
<rich:popupPanel id="popup1" minHeight="300"
minWidth="300">
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink
onclick="#{rich:component('popup1')}.hide(); return false;"
reRender="richtable">X</h:outputLink>
</f:facet>
<rich:toolbar itemSeparator="line" width="100%" id="qawq">
<rich:toolbarGroup location="left">
<h:outputText
value="#{dBOperator.edit?'Employee Edit':'Employee Add'}" />
</rich:toolbarGroup>
</rich:toolbar>
<h:panelGrid id="CancelGrid" columns="2" width="100%">
<rich:column width="30%" style="border:none;">
<h:outputText value="First Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.first_Name}"
style="width:100%" id="abbr" />
</rich:column>
<rich:column width="30%" style="border:none;">
<h:outputText value="Last Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.last_name}"
style="width:100%" id="abbr1" />
</rich:column>
</h:panelGrid>
<a4j:commandButton value="#{dBOperator.edit?'Edit':'Save'}"
action="#{dBOperator.savedetails}"
oncomplete="#{rich:component('popup1')}.hide();"
onclick="validateFields();"></a4j:commandButton>
</rich:popupPanel>
<script type="text/javascript">
function validateFields() {
alert('came inside validateFields');
var fn=document.getElementById('dboperatorform:abbr');
alert('fn '+fn.value);
var ln=document.getElementById('dboperatorform:abbr1');
alert('ln '+ln.value);
}
</script>
</h:form>
</h:body>
</html>
My Bean Class code
package com.richfaces.db;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.management.MBeanServer;
import javax.swing.SortOrder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.comparator.NameComparator;
import com.comparator.NameCompartor1;
import com.richfaces.Employee;
public class DBOperator {
String id;
String first_Name;
String last_name;
String fName;
String lName;
Employee employee;
int rowNum;
boolean edit;
Boolean search=Boolean.FALSE;
Boolean status = Boolean.FALSE;
List<Employee> list = new ArrayList<Employee>();
List<Employee> empList = new ArrayList<Employee>();
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public List<Employee> getEmployees() {
System.out.println("hghhghhhhh");
String sql2="";
Query query = null;
String sql1 = "from Employee as emp where id is not null ";
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
if(status==false && search==false) {
System.out.println("Normal Query +++++++++++++++++++++++ " + sql1);
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==true) {
System.out.println("came inside when search and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==false && search==true) {
System.out.println("came inside when search is true and status is false");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==false) {
System.out.println("came inside when search is false and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}
list = query.list();
/*if (status) {
Collections.sort(list, new NameComparator());
} else {
Collections.sort(list, new NameCompartor1());
}*/
System.out.println(list.size());
this.empList = list;
return list;
}
public String createCriteriaQuery(String query) {
StringBuffer sb = new StringBuffer(query);
if (getFirst_Name() != null && !(getFirst_Name().equals(""))) {
sb.append(" and emp.first_Name='" + first_Name + "'");
}
if (getLast_name() != null && !(getLast_name().equals(""))) {
sb.append(" and emp.last_name='" + last_name + "'");
}
if(this.status) {
sb.append(" order by emp.first_Name desc");
}else {
sb.append(" order by emp.first_Name");
}
System.out.println(sb.toString());
return sb.toString();
}
public void editdetails() {
if (edit) {
System.out.println("rownum is " + rowNum);
System.out.println(empList.size());
employee = (Employee) empList.get((rowNum));
System.out.println(employee.getFirst_Name() + "\t"
+ employee.getLast_name() + "\t" + employee.getId());
System.out.println("end of edit details method");
} else {
employee = new Employee();
}
}
public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public void savedetails() {
System.out.println("came into savedetails");
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
if(this.edit) {
System.out.println("EMPLOYEE DETAILS in IF "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
System.out.println("came inside if when edit is true");
sess.update(employee);
}else {
System.out.println("came inside else when edit is false");
System.out.println("EMPLOYEE DETAILS in ELSE "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
sess.save(employee);
}
}
public void search() {
System.out.println("came into search method");
search = true;
}
public void refreshData(ActionEvent ae) {
System.out.println("came into refreshdata");
getEmployees();
}
public void sortByFirstName() {
System.out.println("came inside sortByFirstName");
if (!status) {
status = Boolean.TRUE;
} else {
status = Boolean.FALSE;
}
//status=Boolean.TRUE;
getEmployees();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
My Entity class code as follows:
package com.richfaces;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String id;
String first_Name;
String last_name;
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
}
Change a4j:commandButton attributes
<a4j:commandButton value="Edit" action="#{dBOperator.editdetails}" execute="#this"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable, popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}" value="#{it.index}" />
</a4j:commandButton>

<h:commandButton> does not initiate a postback

I am using JSF 2.1.7 and Myfaces CODI 1.0.5 on JBoss AS 7.1.1. My <h:commandButton> is not working. I have read the requirements and have through examples in many blogs all to no avail. My facelets code is as follows
<ui:define name="pagecontent">
<h1 class="title ui-widget-header ui-corner-all">Upload Bulk Contact File</h1>
<div class="entry">
<h:form enctype="multipart/form-data" id="upload">
<p:panel closable="false" collapsed="false" header="Excel Contact Uploader"
id="pnlupload" rendered="true" toggleable="false" visible="true" widgetVar="pnlupload">
<p:growl id="msg" showDetail="true" life="3000" showSummary="true"/>
<p:fileUpload auto="true"
allowTypes="/(\.|\/)(xls)$/"
sizeLimit="1024000"
mode="advanced"
multiple="true" invalidFileMessage="Invalid file type" invalidSizeMessage="File too
large" dragDropSupport="true"
fileUploadListener="#{excelFileController.handleFileUpload}" showButtons="true"
update="msg, tblcontacts" required="false"/>
<p:scrollPanel rendered="true" style="height:200px;">
<p:dataTable draggableColumns="false" editable="false" emptyMessage="No
Contacts Uploaded" id="tblcontacts" rendered="true" rows="8"
selection="#{excelFileController.contactsSelected}"
value="#{excelFileController.contactDataModel}" var="contact" style="width:50pc;">
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="File Name">
#{contact.groupName}
</p:column>
<p:column headerText="Number of Contacts">
#{contact.numberofentries}
</p:column>
<p:column>
<h:button outcome="blkedit?faces-redirect=true" rendered="true" value="Edit">
<f:param name="contact" value="#{contact.contactId}"/>
</h:button>
</p:column>
</p:dataTable>
</p:scrollPanel>
<br />
</p:panel>
<h:commandButton value="Delete" id="btndelete"
action="#{excelFileController.removeContact}" type="button" immediate="true"
disabled="false" rendered="true"/>
<h:message for="btndelete" />
</h:form>
</div>
</ui:define>
The code for ExcelFileController is as follows:
#Named
#ViewAccessScoped
public class ExcelFileController implements Serializable, IFileController {
/**
*
*/
private static final long serialVersionUID = -8117258104485487921L;
#Inject
PhoneNumberFormatter formatter;
#Inject
#Authenticated
UserProfile profile;
public PhoneNumberFormatter getFormatter() {
return formatter;
}
public void setFormatter(PhoneNumberFormatter formatter) {
this.formatter = formatter;
}
#EJB
BulkContactDeleter deleter;
#Inject
Logger logger;
#Inject
#CurrentContext
FacesContext context;
#Inject
BulkSMSContactListProducer listProducer;
#Inject
ConfigurationListProducer producer;
private BulkSMSContacts[] contactsSelected;
private BulkContactDataModel contactDataModel;
public BulkSMSContacts[] getContactsSelected() {
return contactsSelected;
}
public void setContactsSelected(BulkSMSContacts[] contactsSelected) {
this.contactsSelected = contactsSelected;
}
public BulkContactDataModel getContactDataModel() {
return contactDataModel;
}
#PostConstruct
public void init() {
logger.log(Level.INFO, "Entering excel file controller");
contactDataModel = new BulkContactDataModel(
listProducer.getBulkSMSContacts());
}
/*
* (non-Javadoc)
*
* #see
* org.jboss.tools.examples.controller.IFileController#handleFileUpload(
* org.primefaces.event.FileUploadEvent)
*/
#Override
public void handleFileUpload(FileUploadEvent event) {
StringBuffer buffer = new StringBuffer();
// create a new file input stream with the input file specified
// at the command line
InputStream fin = null;
try {
fin = event.getFile().getInputstream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = null;
try {
poifs = new POIFSFileSystem(fin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(poifs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int numberofsheets = wb.getNumberOfSheets();
for (int i = 0; i < numberofsheets; i++) {
HSSFSheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING :
if (!cell.getStringCellValue().isEmpty())
buffer.append(formatter.formatPhoneNumber(cell
.getStringCellValue()));
buffer.append(producer.getConfiguration(
SettingsName.SMS_PHONENUMBERDELIMITER
.toString()).getValue());
break;
case Cell.CELL_TYPE_NUMERIC :
if (cell.getNumericCellValue() != 0) {
buffer.append(formatter
.formatPhoneNumber(String.valueOf(cell
.getNumericCellValue())));
buffer.append(producer.getConfiguration(
SettingsName.SMS_PHONENUMBERDELIMITER
.toString()).getValue());
break;
}
default :
break;
}
}
}
}
BulkSMSContacts contacts = new BulkSMSContacts();
contacts.setAccount(profile.getSmsAccount());
int number = formatter.splitPhoneNumbers(buffer.toString()).length;
contacts.setContacts(buffer.toString());
String filenameString = event.getFile().getFileName();
int index = filenameString.indexOf(".");
filenameString = filenameString.substring(0, index);
contacts.setGroupName(filenameString);
contacts.setNumberofentries(number);
try {
deleter.addContact(contacts);
List<BulkSMSContacts> temp = listProducer.getBulkSMSContacts();
contactDataModel.setWrappedData(temp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Success", number
+ " entries processed. Please refresh page to view"));
}
/*
* (non-Javadoc)
*
* #see org.jboss.tools.examples.controller.IFileController#removeContact()
*/
#Override
public String removeContact() {
int contactsdeleted = 0;
if (contactsSelected != null) {
for (BulkSMSContacts contacts : contactsSelected) {
if (contacts != null) {
deleter.deleteContact(contacts);
contactsdeleted += 1;
}
}
List<BulkSMSContacts> temp = listProducer.getBulkSMSContacts();
contactDataModel.setWrappedData(temp);
logger.log(Level.INFO, "Deleted " + contactsdeleted + " Contacts");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Success", contactsdeleted
+ " entries where deleted successfully"));
} else {
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error",
"No contact file was selected!"));
}
return null;
}
}
All the methods work fine except for the last one "removeContact" where the CommandButton concerned does not even initiate a postback.
How is this caused and how can I solve it?
You need to remove type="button" from the <h:commandButton>. It should have been type="submit", which is the default already.
The type="button" makes it an <input type="button"> instead of <input type="submit"> which is only useful for client side handlers which you usually attach using onclick and so on.

primefaces subtable checkbox not updated

I have a datatable with a few colums of data and 1 column with a checkbox. When checking some checkboxes and afterwards submitting the whole form. The model in my bean is updated and I can see what checkbox (row) is checked.
But I had to change the design and now I'm using subtables. (so I can group some info). Now the model is not updated when I submit the form. So when looping the datatable values, all checkboxes are false, while I did checked some on the page. How can I solve this?
I'm using primefaces 3
I fill superlist inside loadreports. And when clicking button I call downloadZip and I loop over the superlist to see if checkbox is checked and then I can add a document to a zip file.
Here is my bean
public ArrayList<HashMap<String, Object>> getSuperList() throws MWSException {
getLog().debug("getSuperList()");
if (superList == null) {
loadReports();
}
return superList;
}
private void loadReports() throws MWSException {
DocumentManager dm = new DocumentManager(getWA().getMwsProxy());
IMWSDocument[] list = dm.getDocumentHistory(getWS().getUser(), getWS().getUser().getCustomerPartnerId(),
WebConstants.BUSINESSPARTNER, WebConstants.PUBLISHSTRATEGYENUMIDS, dateFrom, dateTo, null, null, template);
ArrayList<Object> typeObject = new ArrayList<Object>();
superList = new ArrayList<HashMap<String, Object>>();
Set<Integer> setType = new HashSet<Integer>();
HashMap<String, Object> tempType = new HashMap<String, Object>();
String tempTypeName = "";
Integer tempTypeId = null;
for (IMWSDocument d : list) {
if (type == null || d.getTypeId().equals(type)) {
if (!setType.contains(d.getTypeId())) {
if (setType.size() > 0) {
tempType = new HashMap<String, Object>();
tempType.put("typeName", tempTypeName);
tempType.put("typeId", tempTypeId);
tempType.put("typeObject", typeObject);
superList.add(tempType);
typeObject = new ArrayList<Object>();
}
setType.add((Integer) d.getTypeId());
tempTypeName = d.getType();
tempTypeId = d.getTypeId();
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("checked", false);
temp.put("id", d.getId());
temp.put("name", d.getName());
temp.put("dateCreated", d.getDateCreated());
temp.put("fileName",
d.getDirPath().substring(d.getDirPath().lastIndexOf("/") + 1, d.getDirPath().length()));
temp.put("typeId", d.getTypeId());
temp.put("type", d.getType());
temp.put("templateId", d.getTemplateId());
temp.put("template", d.getTemplate());
typeObject.add(temp);
} else {
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("checked", false);
temp.put("id", d.getId());
temp.put("name", d.getName());
temp.put("dateCreated", d.getDateCreated());
temp.put("fileName",
d.getDirPath().substring(d.getDirPath().lastIndexOf("/") + 1, d.getDirPath().length()));
temp.put("typeId", d.getTypeId());
temp.put("type", d.getType());
temp.put("templateId", d.getTemplateId());
temp.put("template", d.getTemplate());
typeObject.add(temp);
}
}
}
tempType = new HashMap<String, Object>();
tempType.put("typeName", tempTypeName);
tempType.put("typeId", tempTypeId);
tempType.put("typeObject", typeObject);
superList.add(tempType);
rowCount = superList.size();
}
public void DownloadZip(ActionEvent event) throws IOException, MWSException {
int BUFSIZE = 4096;
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
String tempPath = SiteConfig.getInstance().get("file.dir.temp");
// RFC says 'attachment'. Unfortunately, IE has a typo so we set "attachement"
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"reports.zip\"");
DocumentManager dm = new DocumentManager(getWA().getMwsProxy());
// Stream to the requester.
byte[] buf = new byte[BUFSIZE];
File tempdir = new File(tempPath + File.separator + getWS().getUser().getSignOn() + "_" + new Date().getTime());
tempdir.mkdir();
File tempFile = new File(tempdir.getPath() + File.separator + "reports_temp.zip");
ServletOutputStream sos = response.getOutputStream();
FileOutputStream fos = new FileOutputStream(tempFile);
ZipOutputStream out = new ZipOutputStream(fos);
InputStream is = new FileInputStream(tempFile);
try {
// Create the ZIP file
// String outFilename = "outfile.zip";
// Compress the files
for (HashMap<String, Object> item : superList) {
for (Object reportItem : ((ArrayList<Object>) item.get("typeObject"))) {
HashMap<String, Object> report = ((HashMap<String, Object>) reportItem);
if ((Boolean) report.get("checked")) {
//this is always false.
....
And here is the jsf page
<p:dataTable id="reportlisttable" var="listItem" value="#{reportList.superList}" cellpadding="0" cellspacing="0"
rowClasses="row1,row2" styleClass="data" headerClass="header" columnClasses="col" width="100%"
emptyMessage="#{msg.all_lists_no_records_found}" paginator="true" rows="10" rowsPerPageTemplate="5,10,20,50,100"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} #{msg.all_lists_numberOfRowsDisplayed_label} {RowsPerPageDropdown}">
<p:subTable var="report" value="#{listItem.typeObject}">
<f:facet name="header">
#{listItem.typeName}
</f:facet>
<p:column id="column_select" >
<f:facet name="header">
<h:outputText value="" />
</f:facet>
<h:selectBooleanCheckbox name="selectColumn" value="#{report.checked}" />
</p:column>
<p:column id="id" sortBy="#{report.id}">
<f:facet name="header">
<h:outputText value="#{msg.reportlist_id}" />
</f:facet>
<h:outputText value="#{report.id}"/>
</p:column>
<p:column id="date" sortBy="#{report.dateCreated}" parser="date">
<f:facet name="header">
<h:outputText value="#{msg.reportlist_date}" />
</f:facet>
<h:outputText value="#{report.dateCreated}">
<mw:convertDateTime />
</h:outputText>
</p:column>
<p:column id="name" sortBy="#{report.name}" >
<f:facet name="header">
<h:outputText value="#{msg.reportlist_reportname}" />
</f:facet>
<h:outputText value="#{report.name}"/>
</p:column>
</p:subTable>
</p:dataTable>
<t:div id="download">
<h:panelGrid columns="2" >
<t:graphicImage url="${path.staticRootUrl}images/arrow_compare.gif" hspace="15"/>
<p:commandButton value="${msg.reportlist_download}" actionListener="#{reportList.DownloadZip}" styleClass="button" ajax="false"/>
</h:panelGrid>
</t:div>

Resources