I have this following error when I try to crop an image using primefaces cropper, but nothing is selected on the image (the selection is not there ) :
Mar 17, 2013 5:10:46 PM com.sun.faces.lifecycle.ProcessValidationsPhase execute
WARNING: negative or zero width
java.awt.image.RasterFormatException: negative or zero width
at java.awt.image.Raster.<init>(Raster.java:1108)
at java.awt.image.WritableRaster.<init>(WritableRaster.java:129)
at sun.awt.image.SunWritableRaster.<init>(SunWritableRaster.java:129)
at sun.awt.image.ByteComponentRaster.<init>(ByteComponentRaster.java:154)
at sun.awt.image.ByteInterleavedRaster.<init>(ByteInterleavedRaster.java:191)
at sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1261)
at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1173)
at org.primefaces.component.imagecropper.ImageCropperRenderer.getConvertedValue(ImageCropperRenderer.java:146)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:510)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIForm.visitTree(UIForm.java:362)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:378)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:253)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1171)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.FacesExceptionFilter.doFilter(FacesExceptionFilter.java:56)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.GzipResponseFilter.doFilter(GzipResponseFilter.java:148)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:115)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Mar 17, 2013 5:10:46 PM com.sun.faces.renderkit.html_basic.OutcomeTargetRenderer getNavigationCase
WARNING: JSF1090: Navigation case not resolved for component j_idt74.
I really don't know how to solve this because it seems that the error doesn't occur in the process of cropping..
Can you please help me to solve this problem ? I really don't know what to do.
I am using Primefaces 3.5 and Myfaces 2.1.17.
Thank you very much.
UPDATE :
The cropper bean :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.primefaces.model.CroppedImage;
import com.meinanliegen.backingbean.User;
import com.meinanliegen.handlers.filters.Configurations;
#ManagedBean
#ViewScoped
public class ImageCropperBean implements Serializable {
private static final long serialVersionUID = -7835902358418363820L;
private static final Logger LOGGER = Logger.getLogger(ImageCropperBean.class);
private CroppedImage croppedImage;
private String photoCropped;
// This only contains the relative path to the temp image : /temp/croppedImage
private String relativeImagePhotoCropped;
private String originalUploadedPhotoFileName;
#ManagedProperty(value = "#{user}")
private User user;
public CroppedImage getCroppedImage() {
return croppedImage;
}
public void setCroppedImage(CroppedImage croppedImage) {
this.croppedImage = croppedImage;
}
public String getPhotoCropped() {
return photoCropped;
}
public void setPhotoCropped(String photoCropped) {
this.photoCropped = photoCropped;
}
public String getRelativeImagePhotoCropped() {
return relativeImagePhotoCropped;
}
public void setRelativeImagePhotoCropped(String relativeImagePhotoCropped) {
this.relativeImagePhotoCropped = relativeImagePhotoCropped;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String crop() {
if (croppedImage == null) {
LOGGER.error("The cropped image is null");
}
else {
manageTheCrop();
}
return null;
}
private void manageTheCrop() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
String originalFilePhotoName = croppedImage.getOriginalFilename();
String tempLocationForCroppedFile = servletContext.getRealPath(Configurations.UPLOAD_TEMP_FILE_PATH);
String prefix = FilenameUtils.getBaseName(originalFilePhotoName);
String suffix = FilenameUtils.getExtension(originalFilePhotoName);
// First time we need to save the original photo name
if (originalUploadedPhotoFileName == null) {
originalUploadedPhotoFileName = prefix + "." + suffix;
}
try {
// We will keep the same name for cropped photo, until the user decides
File photoCroppedFile = File.createTempFile(prefix, "." + suffix, new File(tempLocationForCroppedFile));
photoCropped = photoCroppedFile.getPath();
cropImageAddContentTo(photoCropped);
String prefixCroppedPhoto = FilenameUtils.getBaseName(photoCropped);
String suffixCroppedPhoto = FilenameUtils.getExtension(photoCropped);
String photoCroppedFileName = prefixCroppedPhoto + "." + suffixCroppedPhoto;
relativeImagePhotoCropped = Configurations.UPLOAD_TEMP_FILE_PATH + photoCroppedFileName;
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Bitte versuchen Sie es noch einmal.",
"Fehler beim Zuschneiden Ihres Fotos");
}
}
public void saveCroppedImageAsPrimaryUserImage() {
if (photoCropped != null) {
String profilePhotoChosenFilePrefix = String.format("%s_%s_%s", user.getFirstName(), user.getLastName(),
originalUploadedPhotoFileName);
try {
// We will save the last cropped image as profile
File finalPhotoLocation = new File(Configurations.UPLOAD_FILE_PATH, profilePhotoChosenFilePrefix);
OutputStream output = null;
output = new FileOutputStream(finalPhotoLocation);
IOUtils.copy(new FileInputStream(photoCropped), output);
user.setTempProfilePictureSrc(relativeImagePhotoCropped);
user.setProfilePictureSrc("../uploads/" + finalPhotoLocation.getName());
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Bitte versuchen Sie es noch einmal.", "Fehlermeldung");
}
}
}
public void cropImageAddContentTo(String croppedImagePath) {
try {
cropImage(croppedImagePath);
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Fehlermeldung",
"Es ist eiin Fehler aufgetreten. Bitte versuchen Sie es noch einmal.");
}
}
public void cropImage(String imageFileName) throws IOException {
FileImageOutputStream imageFileOutput = null;
imageFileOutput = new FileImageOutputStream(new File(imageFileName));
imageFileOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
imageFileOutput.close();
}
}
and the JSF part :
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:row>
<p:column style="height:120px; width 120px;">
<p:panelGrid columns="2">
<p:row>
<p:column>
<div class="photo">
<p:graphicImage id="standardUploadedImage" value="#{user.tempProfilePictureSrc}" />
</div>
</p:column>
</p:row>
<p:row>
<h:panelGroup id="adjustImage">
<p:column style="width:150px">
<p:panelGrid>
<p:row>
<p:column>
<h:outputText value="Bild innerhalb des Rahmens positionieren"
rendered="#{uploadPhotoHandler.userImageUploaded == true}" />
</p:column>
</p:row>
<p:row>
<p:column>
<p:commandButton value="Bild anpassen" oncomplete="cropWidget.show()"
update=":growl cropDialog" immediate="true"
rendered="#{uploadPhotoHandler.userImageUploaded == true}"
styleClass="css3button" />
</p:column>
</p:row>
</p:panelGrid>
</p:column>
</h:panelGroup>
</p:row>
</p:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column>
<p:fileUpload fileUploadListener="#{uploadPhotoHandler.handleFileUpload}" mode="advanced"
label="Portraitfoto hochladen" sizeLimit="5242880" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="Datei darf maximal 5 MB groß sein"
invalidFileMessage="Bitte prüfen Sie das Format. Es können nur jpg, gif, png Dateien verwendet werden."
update=":growl standardUploadedImage uploadedImage imageCropper adjustImage" auto="true"
required="false" />
</p:column>
</p:row>
<p:row>
<p:column>
<p:confirmDialog id="cropDialog" header="Bild anpassen" severity="alert" showEffect="fade" closeOnEscape="true"
closable="true" hideEffect="fade" widgetVar="cropWidget">
<p:panelGrid>
<p:row>
<p:column colspan="2">
<p:panelGrid columns="3" style="height:50px">
<p:row>
<p:column>
<p:commandButton id="cancel" value="Löschen" onclick="cropWidget.hide()"
type="button"
update=":growl imageCropper uploadedImage standardUploadedImage"
immediate="true" styleClass="css3button" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:panelGrid id="cropBtnPanel">
<p:commandButton id="crop" value="Zuschneiden"
action="#{imageCropperBean.crop}"
update=":growl imageCropper uploadedImage standardUploadedImage cropFinished crop cropBtnPanel ApplyBtnPanel"
process="crop imageCropper" styleClass="css3button"
rendered="#{imageCropperBean.showCrop}" />
</h:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column>
<h:panelGrid id="ApplyBtnPanel">
<p:commandButton id="cropFinished" value="Übernehmen"
actionListener="#{imageCropperBean.saveCroppedImageAsPrimaryUserImage}"
oncomplete="cropWidget.hide()"
update=":growl imageCropper uploadedImage standardUploadedImage crop cropFinished cropBtnPanel ApplyBtnPanel"
process="cropFinished imageCropper" styleClass="css3button"
rendered="#{imageCropperBean.showApply}" />
</h:panelGrid>
</p:column>
</p:row>
</p:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column headerText="Original">
<div class="photoToBeCropped">
<p:imageCropper id="imageCropper"
value="#{imageCropperBean.croppedImage}"
image="#{user.tempProfilePictureSrc}"
initialCoords="225,75,300,125"
aspectRatio="1.0"
rendered="#{uploadPhotoHandler.userImageUploaded == true}"
minSize="170"
required="true" />
</div>
</p:column>
<p:column headerText="Cropped">
<div class="photoToBeCropped">
<p:graphicImage id="uploadedImage" value="#{imageCropperBean.relativeImagePhotoCropped}" />
</div>
</p:column>
</p:row>
</p:panelGrid>
</p:confirmDialog>
</p:column>
</p:row>
It is worth to be mentioned that this entire crop module is embedded in one wizard primefaces step.
I can reproduce it on their own showcase. When I deselect the image and click Crop, then I see the unhandled exception in the ajax response:
(it'd been nice if they installed a decent ajax exception handler, so that this was immediately visible to the enduser)
Well, this is really a bug in their own code. This is 4 days ago already been reported as issue 5349 which is currently unscheduled.
If you really can't wait for them to fix it, then your best is to override the renderer to skip the job in getConvertedValue():
public class MyImageCropperRenderer extends ImageCropperRenderer {
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue == null || ((String) submittedValue).endsWith("_0_0")) {
return null;
}
return super.getConvertedValue(context, component, submittedValue);
}
}
The submitted value is in the format x_y_w_h wherein the _w_h would be _0_0 when nothing is selected. In that case, the above custom renderer will thus return immediately null instead of continuing the conversion job which would throw that exception.
To get this renderer to run, register it as follows in faces-config.xml wherein the <renderer-class> is the FQN of the custom renderer:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.ImageCropperRenderer</renderer-type>
<renderer-class>com.example.MyImageCropperRenderer</renderer-class>
</renderer>
</render-kit>
I used the solution posted for BalusC. But sporadically I get the value "_2_0" or something like that. In these cases, the error happens again. Then I resolved so:
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue != null ){
String[] submittedValueArray = ((String) submittedValue).split("_");
if (!"0".equals(submittedValueArray[2]) && !"0".equals(submittedValueArray[3])) {
return super.getConvertedValue(context, component, submittedValue);
}
}
return null;
}
catch (RasterFormatException e) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "This crop size is not supported", null);
throw new ErrorImageSizeException(message); }
Creates ErrorImageSizeException extending ConverterException with constructor
public ErrorImageSizeException(FacesMessage mensagem) {
super(mensagem);
}
I get java.lang.NumberFormatException: For input string: "NaN" when I pressed the button before changing the crop area.
<h:form id="editUserPhotoForm" >
<p:messages showDetail="true" autoUpdate="false" closable="true" />
<h:panelGrid columns="2" rendered="#{not empty adminView.editUser}">
<p:imageCropper value="#{adminView.croppedImage}" image="#{adminView.userImagePath}" initialCoords="0,0,200,260" aspectRatio="0.77" minSize="200,260"/>
<p:graphicImage value="#{adminView.imageUser}" width="200" cache="false" />
</h:panelGrid>
<p:commandButton value="crop" action="#{adminView.crop}" ignoreAutoUpdate="true" process="#form" update="#form" icon="ui-icon-scissors"/>
</h:form>
I used the solution posted by #BalusC but added the condition:
if (submittedValue == null || ((String) submittedValue).endsWith("_0_0") || ((String)submittedValue).contains("NaN"))
Following the solution posted by #BalusC, I have implemented my own and I save the whole picture when there is no selection:
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue != null ){
String[] submittedValueArray = ((String) submittedValue).split("_");
if (!"0".equals(submittedValueArray[2]) && !"0".equals(submittedValueArray[3])) {
return super.getConvertedValue(context, component, submittedValue);
}
}
try {
return super.getConvertedValue(context, component, buildDefaultSubmittedValue(context, component));
} catch (IOException e) {
throw new ConverterException("Error cropping the whole image");
}
}
private String buildDefaultSubmittedValue(FacesContext context, UIComponent component) throws IOException {
ImageCropper cropper = (ImageCropper) component;
//remove query string
String imagePath = cropper.getImage();
int queryStringIndex = imagePath.indexOf("?");
if(queryStringIndex != -1 ) {
imagePath = imagePath.substring(0, queryStringIndex);
}
BufferedImage outputImage = getSourceImage(context, imagePath);
return "0_0_" + outputImage.getWidth() + "_" + outputImage.getHeight();
}
private BufferedImage getSourceImage(FacesContext context, String imagePath) throws IOException {
BufferedImage outputImage = null;
boolean isExternal = imagePath.startsWith("http");
if(isExternal) {
URL url = new URL(imagePath);
outputImage = ImageIO.read(url);
}
else {
ExternalContext externalContext = context.getExternalContext();
outputImage = ImageIO.read(new File(externalContext.getRealPath("") + imagePath));
}
return outputImage;
}
Related
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.
I want to change the language on click one of the images. There are two image and one of them is turkish the other one is english. If I click to the english language is english. Another one is turkish with onclick.Here is my managed bean and xhtml;
public class DilSecimBean {
private boolean isTurkey = true;
private final Locale TR = new Locale("tr");
private final Locale EN = Locale.ENGLISH;
public Locale getLocale() {
if (isTurkey) {
return TR;
} else {
return EN;
}
}
public void swapLocale() {
System.out.println("SWAP LOCALE");
switchLocale();
}
private void switchLocale() {
isTurkey = !isTurkey;
Locale newLocale;
if (isTurkey) {
newLocale = TR;
} else {
newLocale = EN;
}
FacesContext.getCurrentInstance().getViewRoot().setLocale(newLocale);
}
}
Here is my xhtml;
<h:panelGrid columns="3" border="0">
<h:outputText value="Dil seçimi : " />
<h:graphicImage alt="JSF"
url="/resimler/tb.png"
width="20" height="20">
<f:ajax event="click" execute="#{dilSecimBean.swapLocale()}"/>
</h:graphicImage>
<h:graphicImage alt="JSFS"
url="/resimler/ib.png"
width="20" height="20">
<f:ajax event="click" execute="#{dilSecimBean.swapLocale()}"/>
</h:graphicImage>
</h:panelGrid>
When I click to the image there is no change on the language.How can I change the language with image click event?
first you should have a form to submit
second: why are yusing ajax here?
any way here is a working example
<h:form>
<h:commandLink action="#{localeChanger.turkishAction}">
<h:graphicImage library="images" name="de_flag.gif"
style="border: 0px; margin-right: 1em;"/>
</h:commandLink>
<h:commandLink action="#{localeChanger.englishAction}">
<h:graphicImage library="images"
name="en_flag.gif" style="border: 0px"/>
</h:commandLink>
</h:form>
for the managed bean:
import java.io.Serializable;
import java.util.Locale;
import javax.inject.Named;
// or import javax.faces.bean.ManagedBean;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#Named // or #ManagedBean
#SessionScoped
public class LocaleChanger implements Serializable {
public String TurkishAction() {
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(new Locale("tr"));
return null;
}
public String englishAction() {
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(Locale.ENGLISH);
return null;
}
}
I am trying to fetch the checkbox selected values selectedCars from primefaces datatable to my managed bean named TableBean.I am getting null pointer exception at the point where I am trying to fetch the values in the function getSelection() please help me with this
My JSF page:
<h:form id="form">
<p:dataTable id="multiCars" var="car"
value="#{tableBean.mediumCarsModel}" paginator="true" rows="10"
selection="#{tableBean.selectedCars}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Model" style="width:25%">
#{car.model}
</p:column>
<p:column headerText="Year" style="width:25%">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" style="width:24%">
#{car.manufacturer}
</p:column>
<p:column headerText="Color" style="width:24%">
#{car.color}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View"
icon="ui-icon-search" update=":form:displayMulti"
oncomplete="multiCarDialog.show()" />
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail"
widgetVar="multiCarDialog" height="300" showEffect="fade"
hideEffect="explode">
<p:dataList id="displayMulti" value="#{tableBean.selectedCars}"
var="selectedCar">
Model: #{selectedCar.model}, Year: #{selectedCar.year}
</p:dataList>
</p:dialog>
</h:form>
My managed bean
#SessionScoped
#ManagedBean
public class TableBean implements Serializable {
private List<Car> cars;
private Car[] selectedCars;
private CarDataModel mediumCarsModel;
Connection connection;
Statement stmt;
ResultSet rs;
public TableBean() {
cars = new ArrayList<Car>();
getCars();
getSelection();
mediumCarsModel = new CarDataModel(cars);
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
public void getCars() {
int i = 0;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://cvgapp106I/dev2_LPSR");
System.out.println("connected to the database");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select * from test");
while(rs.next()) {
cars.add(i,new Car(rs.getString("Model"),rs.getInt("Year"),rs.getString("Manufacturer"),rs.getString("Color")));
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void getSelection() {
System.out.println(selectedCars[0].getModel());
}
public CarDataModel getMediumCarsModel() {
return mediumCarsModel;
}
public void setMediumCarsModel(CarDataModel mediumCarsModel) {
this.mediumCarsModel = mediumCarsModel;
}
}
public void getSelection() {
System.out.println(selectedCars[0].getModel());
}
This will throw NullPointerException if the list is empty.
If you really want to use this then you should try check if the list not null
if(selectedCars!=null && !selectedCars.isEmpty()){
System.out.println(selectedCars[0].getModel());
}
Do not call getSelection() in your constructor. There selectedCars will be always null
i am new on prime faces .I have a user with some attribute i have shown the table of user data . Now the requirement is that, on click of particular user row the data associated with that user must be shown on same window under the table please tell the way to do this i m trying to use layout but the problem is how i can get the data on same window .Give me learing site link if possible doing the same thing or tell me the procedure thanks
package com.poc.faces;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
#ViewScoped
public class UserManagedBean {
UserService service = new UserService();
private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSearchUser() {
return searchUser;
}
public void setSearchUser(String searchUser) {
this.searchUser = searchUser;
}
public Collection<User> getSearchUsersResults() {
return searchUsersResults = service.getAllUser();
}
public void setSearchUsersResults(Collection<User> searchUsersResults) {
this.searchUsersResults = searchUsersResults;
}
public User getSelectedUser() {
return selectedUser;
}
public String login() {
if ("sas".equalsIgnoreCase(getUsername())
&& "sas".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("User Selected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This home.xhtml
where i am getting the tabledata
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
</h:head>
<h:body>
<p:layout style="min-width:400px;min-height:200px;" id="layout">
<p:layoutUnit position="center">
<h:form prependId="false">
<h:panelGroup layout="block" id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.searchUsersResults}"
var="user" pagination="true" rows="5" styleClass="userTable"
headerClass="userTableHeader"
rowClasses="userTableOddRow,userTableEvenRow"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<!-- <p:ajax event="rowSelect" listener="#{userManagedBean.onRowSelect}"
update=":form:display :form:growl" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{userManagedBean.onRowUnselect}" update=":form:growl" /> -->
<p:column>
<f:facet name="header">UserId</f:facet>
<h:outputText value="#{user.userId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Username</f:facet>
<h:outputText value="#{user.username}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">EmailId</f:facet>
<h:outputText value=" #{user.emailId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Phone</f:facet>
<h:outputText value=" #{user.phone}"></h:outputText>
</p:column>
</p:dataTable>
</center>
</h:panelGroup>
</h:form>
<p:layoutUnit position="west" resizable="true" size="100"
minSize="40" maxSize="200">
West
</p:layoutUnit>
</p:layout>
</h:body>
</html>
I don't think there is a component of PF called layoutUnit. are you sure it's not layout?
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)