I´ve a data table with primefaces, that has a filter column. So when I access my xhtml it doesn´t show the populated data till I enter values in the filter. Or if I take out the filter it shows the populated data.
Here is my managed bean code:
#ManagedBean(name="estatusAdminMB")
#ViewScoped
public class EstatusAdminManagedBean implements Serializable {
private IEstatusService estatusService;
private List<MapeoEstatusDTO> mapeoEstatusList = new ArrayList<MapeoEstatusDTO>();
private List<MapeoEstatusDTO> filteredPorMapeoEstatusDTO = new ArrayList<MapeoEstatusDTO>();
private MapeoEstatusDTO selectedMapeoEstatus = new MapeoEstatusDTO();
/**
* Creates a new instance of EstatusAdminManagedBean
*/
public EstatusAdminManagedBean() {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
mensajeriasService = (IMensajeriasService) context.getBean("MensajeriasService");
originadoresService = (IOriginadoresService) context.getBean("OriginadoresService");
estatusService = (IEstatusService) context.getBean("EstatusService");
populateMapeo();
}
private void populateMapeo() {
try {
mapeoEstatusList.clear();
mapeoEstatusList.addAll(estatusService.getMapeoEstatus());
System.out.println(mapeoEstatusList.size());
} catch (ServiceException ex) {
Logger.getLogger(EstatusAdminManagedBean.class.getName()).log(Level.SEVERE, null, ex);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
"Ocurrió un error al cargar el mapeo."));
}
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Mapeo Seleccionado", ((MapeoEstatusDTO) event.getObject()).getCodigo().getDescripcion());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public IEstatusService getEstatusService() {
return estatusService;
}
public void setEstatusService(IEstatusService estatusService) {
this.estatusService = estatusService;
}
public MapeoEstatusDTO getSelectedMapeoEstatus() {
return selectedMapeoEstatus;
}
public void setSelectedMapeoEstatus(MapeoEstatusDTO selectedMapeoEstatus) {
this.selectedMapeoEstatus = selectedMapeoEstatus;
}
public List<MapeoEstatusDTO> getFilteredPorMapeoEstatusDTO() {
return filteredPorMapeoEstatusDTO;
}
public void setFilteredPorMapeoEstatusDTO(List<MapeoEstatusDTO> filteredPorMapeoEstatusDTO) {
this.filteredPorMapeoEstatusDTO = filteredPorMapeoEstatusDTO;
}
}
and here is my xhtml 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 lang="en-US"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:body>
<ui:composition template="../template/Layout.xhtml">
<ui:define name="content">
<div class="frame">
<h:form id="mapeoForm">
<p:growl id="growl" showDetail="true" />
<p:spacer> </p:spacer>
<div style="text-align:center">
<h:outputText value="Mapeo de Estatus" />
</div>
<p:spacer> </p:spacer>
<div align="center">
<p:dataTable id="mapeoTable" var="c" value="#{estatusAdminMB.mapeoEstatusList}" paginator="true" rows="10"
selection="#{estatusAdminMB.selectedMapeoEstatus}" selectionMode="single"
filteredValue="#{estatusAdminMB.filteredPorMapeoEstatusDTO}"
emptyMessage="No hay registros" rowKey="#{c.idMapeo}" rowIndexVar="rowIndex">
<p:ajax event="rowSelect" listener="#{estatusAdminMB.onRowSelect}"
update=":mapeoForm:dialogUpdate, :mapeoForm:growl"
oncomplete="dialogUpdateW.show()"/>
<f:facet name="header">
Haz clic sobre cualquier registro para editar
</f:facet>
<p:column id="originadorColumn" filterBy="#{c.originadorDTO.nombre}"
headerText="Originador" filterMatchMode="contains">
<h:outputText value="#{c.originadorDTO.nombre}" />
</p:column>
<p:column headerText="Descripción Estatus Folio">
#{c.estatus.descripcion}
</p:column>
<p:column headerText="Descripción Tipificación">
#{c.tipificacion.DESCRIPCION_TIPIFICACION}
</p:column>
<p:column headerText="Descripción Estatus Geotracking">
#{c.codigo.descripcion}
</p:column>
</p:dataTable>
<p:dialog maximizable="true" minHeight="400" minWidth="400" style="overflow-y:auto; top:5px; bottom:5px;"
id="dialogUpdate" header="Editar Mapeo" widgetVar="dialogUpdateW" resizable="false"
showEffect="fade" hideEffect="explode">
<h:form id="updateMapForm">
<table id="display">
</table>
</h:form>
</p:dialog>
</div>
</h:form>
</div>
</ui:define>
</ui:composition>
</h:body>
</html>
Why am I not getting the data from the very begging???
Thanks for the help.
Related
I have problem to display StreamedContent PDF in DocumentViewer from Primefaces Extensions (6.2.9) with PrimeFaces 6.2 and MyFaces 2.2.12. I read the same question, but it's an other situation.
Message: Missing PDF in PrimeFaces Extensions DocumentViewer
This is my xhtml code
<p:commandButton icon="fa fa-print" actionListener="#{bean.onPrerender}" />
Dialog code
<p:dialog id="dvDialog" widgetVar="dv_dialog" dynamic="true" header="Document" width="1200px" height="700px" modal="true">
<pe:documentViewer cache="true" height="500" value="#{bean.content}" download="report.pdf" />
</p:dialog>
This is my java code
private StreamedContent content;
public void onPrerender(ActionEvent actionEvent) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
for (int i = 0; i < 50; i++) {
document.add(
new Paragraph("All work and no play makes Jack a dull boy"));
}
document.close();
// content = new DefaultStreamedContent(
// new ByteArrayInputStream(out.toByteArray()), "application/pdf");
content = new ByteArrayContent(out.toByteArray(), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
PrimeFaces.current().executeScript("PF('dv_dialog').show()");
}
public StreamedContent getContent() {
return content;
}
public void setContent(StreamedContent content) {
this.content = content;
}
The error message
PDF.js v1.10.88 (build: c62a1938)
Message: Missing PDF "http://localhost:8080/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=1a55ef4c9448951fae5f493579cf80e1&pfdrt=sc&pfdrid_c=true&download=report.pdf".
have anyone clue, what is wrong with my code? it is actually the code in demo showcase Primeface-Extensions with modification.
My project use iframe and the documentviewer will display in a popup dialog. I also tried with #SessionScoped and #ViewScoped, but have no luck.
If I try it in stand alone project, it works (without iframe). May be someone can give clues, how to debug to find the problem.
Please help.... Thank you.
I get error message
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581 GET http://localhost:8081/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=3c954d24c76c30714a581092c23e1489&pfdrt=sc&pfdrid_c=true&download=report.pdf 404
PDFFetchStreamReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581
getFullReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17527
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:4388
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1002
resolveCall # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1001
_createStreamSink # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1266
MessageHandler._onComObjOnMessage # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1094
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633 Uncaught (in promise) Error: Missing PDF file.
at pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633
I tried this using:
Java EE 7
GlassFish 4.1.2
PrimeFaces 6.2
PrimeFaces-Extensions 6.2.9
At the bean (class) code:
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
The scope is #ApplicationScoped. I have a private StreamedContent attribute. And two main public methods:
First method: It's called from actionListener attribute of a p:commandButton. The method receive a parameter (in my case).
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
Second method: It's used from a pe:documentViewer inside a dialog component, like this:
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
Note: The 2nd method works like a property (getter and setter). THAT'S THE TRICK.
The final code from my project is:
# Bean (DocumentViewerController.java):
package com.epmrpsd.certificado.consulta.controladores;
import com.epmrpsd.certificado.consulta.controladores.util.JsfUtil;
import com.epmrpsd.certificado.consulta.entidades.Tramite;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
/**
*
* #author pbonilla
*/
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
private StreamedContent content;
private Integer numeroTramite;
private Integer contrato;
private Tramite tramiteSelected;
// Path where the file exists
private String pdfPathDirectory = "C:\\Users\\<user>\\certificados\\";
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
public StreamedContent getCertificado() {
InputStream stream = null;
try {
File file = new File(pdfPathDirectory + numeroTramite + "_" + contrato + ".pdf");
if (file.exists()) {
stream = new FileInputStream(file);
} else {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo");
}
this.content = new DefaultStreamedContent(stream, "application/pdf");
} catch (FileNotFoundException fnfex) {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo. Error: " + fnfex.getMessage());
fnfex.printStackTrace();
} catch (Exception e) {
JsfUtil.addErrorMessage("Error", "Se ha generado un error al cargar el certificado. Error: " + e.getMessage());
e.printStackTrace();
}
return content;
}
public void setCertificado(StreamedContent contenido) {
content = contenido;
}
public Tramite getTramiteSelected() {
return tramiteSelected;
}
public void setTramiteSelected(Tramite tramiteSelected) {
this.tramiteSelected = tramiteSelected;
}
public Integer getNumero() {
return numeroTramite;
}
public void setNumero(Integer numeroTramite) {
this.numeroTramite = numeroTramite;
}
public Integer getContrato() {
return contrato;
}
public void setContrato(Integer contrato) {
this.contrato = contrato;
}
}
# View (index.xhtml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pe="http://primefaces.org/ui/extensions">
<h:head>
<title>Consulta de Certificados Digitales</title>
<h:outputStylesheet library="css" name="epmrpsd.css" />
<h:outputStylesheet library="webjars" name="font-awesome/5.5.0/css/all-jsf.css" />
<h:outputStylesheet library="css" name="jsfcrud.css"/>
<h:outputScript library="js" name="jsfcrud.js"/>
<link rel="shortcut icon" type="image/png" href="#{resource['images/logo.png']}"/>
</h:head>
<h:body>
<div id="background" style="position: fixed;">
<h:form id="formCertificados">
<div class="ui-g" style="margin-top: 25px;">
<div class="ui-g-1"></div>
<div class="ui-g-10">
<p:growl id="mensajes" />
<Extra code> ...
<p:outputPanel id="pnlCertificado">
<p:dataTable id="tramitesTable"
value="#{tramiteController.items}"
var="tramite"
rowKey="#{tramite.id}"
selectionMode="single"
selection="#{tramiteController.selected}"
emptyMessage="No se encontraron trámites con los criterios dados"
rows="10"
rowsPerPageTemplate="10,20,30,40,50">
<p:column headerText="Número Trámite" >
<h:outputText value="#{tramite.numero}" />
</p:column>
<p:column headerText="Descripción" >
<h:outputText value="#{tramite.tipo.descripcion}" />
</p:column>
<p:column headerText="Número Contrato" >
<h:outputText value="#{tramite.contrato}" />
</p:column>
<p:column style="text-align: center" headerText="Acción" >
<center>
<p:commandButton id="viewCertificado"
styleClass="ui-priority-primary"
value="Ver certificado"
actionListener="#{documentViewerController.onPrerender(tramite)}"
update=":ViewCertificadoForm"
oncomplete="PF('ViewCertificadoDialog').show()" />
</center>
</p:column>
</p:dataTable>
</p:outputPanel>
</div>
<div class="ui-g-1"></div>
</div>
</h:form>
<ui:include src="ViewCertificado.xhtml"/>
</div>
</h:body>
</html>
And the final component for the view is (ViewCertificado.xhtml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<ui:composition>
<p:dialog id="ViewCertificadoDlg"
widgetVar="ViewCertificadoDialog"
modal="true"
resizable="false"
appendTo="#(body)"
header="Certificado #{documentViewerController.contrato}">
<h:form id="ViewCertificadoForm">
<h:panelGroup id="display">
<p:panelGrid columns="1" rendered="#{documentViewerController.tramiteSelected != null}">
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
</p:panelGrid>
<p:commandButton value="Cerrar" onclick="ViewCertificadoDialog.hide()"/>
</h:panelGroup>
</h:form>
</p:dialog>
</ui:composition>
</html>
The following is my code snippet in my abc.xhtml page :
<p:panelGrid id="pnlGrd_numOfLbl"
style="align:center; width:100%;" cellpadding="5">
<c:forEach var="i" begin="1" end="${specificationMB.numOfLbl}" >
<p:row>
<p:column width="50%">
<p:outputLabel value="Label ${i}" />
</p:column>
<p:column width="50%">
<p:inputText id="inputTxt_${i}" style="width:150px;" />
</p:column>
</p:row>
</c:forEach>
</panelGrid>
This is my panelGrid I am generating inputText dynamically depending
numOfLable. After generation say 2 will be generate user will add some
text to each inputText so my Question is How can I get value of dyanamically
generated inputbox.
Thanks.
This can easily be done with basics of JSF and primefaces. Here is full working Example:
XHTML File (I am using p:panel and ui:repeater)
<!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">
<f:view contentType="text/html">
<h:head>
<link rel=" stylesheet" type="text/css" href="css/style.css"></link>
</h:head>
<h:body>
<h:form>
<p:panel header="Panel">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.lbl} :" />
</p:column>
<p:column width="50%">
<p:inputText value="#{lbl.value}" />
</p:column>
</p:row>
</ui:repeat>
</p:panel>
<p:commandButton actionListener="#{tBean.submit}" value="Subtmi" update="values"></p:commandButton>
<p:outputPanel id="values">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.value} :" />
</p:column>
</p:row>
</ui:repeat>
</p:outputPanel>
</h:form>
</h:body>
</f:view>
<body>
</body>
</html>
Managed Bean
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
#ManagedBean(name = "tBean")
#ViewScoped
public class TestBean {
private List<LabelClass> lblClassess;
public TestBean() {
lblClassess = new ArrayList<LabelClass>();
lblClassess.add(new LabelClass("First Label", ""));
lblClassess.add(new LabelClass("Second Label", ""));
lblClassess.add(new LabelClass("Third Label", ""));
}
public void submit(ActionEvent e) {
for (LabelClass lbl : lblClassess) {
System.out.println(lbl.getValue());
}
}
public List<LabelClass> getLblClassess() {
return lblClassess;
}
public void setLblClassess(List<LabelClass> lblClassess) {
this.lblClassess = lblClassess;
}
}
Label Class
public class LabelClass {
private String lbl;
private String value;
public LabelClass(String lbl, String value) {
super();
this.lbl = lbl;
this.value = value;
}
public String getLbl() {
return lbl;
}
public void setLbl(String lbl) {
this.lbl = lbl;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Output
In order to get the values of your dynamically generated inputTexts. You may do something like this.
<input type="text" id="inputTxt_${i}" name="inputTxt_${i}" style="width:150px;" />
Then retrieve the text value by using this code in servlet
String inputText1 = request.getParameter("nameOfFirstInputText");
You can bind the value into the bean value object:
<input type="text" id="inputTxt_${i}" value="${specificationMB.getValue(i).value}" />
I have an issue with primefaces datagrid.I am following this example1, trying to update the dialog box with the selected values on click of p:commandLink. The Dialog doesnt work, doesnt show. I am using primefaces-4.0 on GlassFish Server 4.0. I've replaced the bean and its methods with my bean.
This is what i did.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<body>
<ui:composition template="./plantilla/plantillaPrincipal.xhtml">
<ui:define name="content">
<h:form id="form" class="well">
<h1>#{accionesController.tipo}</h1>
<p:dataGrid var="r" value="#{accionesController.lista}" columns="3"
rows="3" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="3,6,9">
<p:panel header="#{r.title}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<p:graphicImage value="/img/libros/#{r.ubicacion}.jpg"/>
<h:outputText value="#{r.author}" />
<p:commandLink update=":form:carDetail" oncomplete="PF('carDialog').show()" title="View Detail">
<h:outputText styleClass="ui-icon ui-icon-search" style="margin:0 auto;" />
<f:setPropertyActionListener value="#{r}"
target="#{r.libroseleccionado}" />
</p:commandLink>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<p:dialog header="Car Detail" id="carDialog" widgetVar="carDialog" modal="true">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:graphicImage value="/img/libros/#{r.libroseleccionado.ubicacion}.jpg"/>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="modelNo" value="Model No: " />
<h:outputText id="modelNo" value="#{r.libroseleccionado.author}" />
<h:outputLabel for="year" value="Year: " />
<h:outputText id="year" value="#{r.libroseleccionado.title}" />
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
My bean
#Component()
#ManagedBean
#RequestScoped
#ComponentScan("pe.egcc.eureka.app.layer.service")
public class AccionesController {
#Autowired
private AccionesService accionesService;
private List<Map<String, Object>> lista;
private String tipo;
private Books libroseleccionado;
public void setLibroseleccionado(Books libroseleccionado) {
this.libroseleccionado = libroseleccionado;
}
public Books getLibroseleccionado() {
return libroseleccionado;
}
public String getTipo() {
return tipo;
}
public List<Map<String, Object>> getLista() {
if (lista == null) {
lista = new ArrayList<Map<String, Object>>();
}
return lista;
}
public String consultarLibros() {
String destino;
lista = accionesService.listarLibros();
tipo="Todos los Libros";
destino = "listarLibros";
return destino;
}
public String consultarLibrosLiteratura() {
String destino;
tipo="Libros de Literatura";
lista = accionesService.listarLibrosLiteratura();
destino = "listarLibros";
return destino;
}
public String consultarLibrosInformatica() {
String destino;
tipo="Libros de Informática";
lista = accionesService.listarLibrosInformatica();
destino = "listarLibros";
return destino;
}
public String consultarArticulos() {
String destino;
tipo="Artículos Diversos";
lista = accionesService.listarArticulos();
destino = "listarLibros";
return destino;
}
}
If anyone can point me in the right direction that'd be great. Sorry for the huge post, it needed a bit of explaining to make it coherent. Hopefully it makes sense. Thanks.
I discovered some compatibility problems between primefaces and twitter bootstrap, so I replaced the primefaces modal with a boostrap modal but keeping the outputPanel in order to get updated the data and changed from r.libroelegito to accionesController.libroelegido. Here is the code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:k="http://xmlns.jcp.org/jsf/passthrough">
<h:body>
<ui:composition template="./plantilla/plantillaPrincipal.xhtml">
<ui:define name="content">
<h:form id="form">
<h1>#{accionesController.tipo}</h1>
<p:dataGrid var="r" value="#{accionesController.lista}" columns="3"
rows="3" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="3,6,9">
<p:panel header="#{r.title}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<p:graphicImage value="/img/libros/#{r.ubicacion}.jpg"/>
<h:outputText value="#{r.book_id}" />
<h:outputText value="#{r.author}" />
<p:commandButton icon="ui-icon-search" update=":form:carDetail" title="View Detail" k:data-toggle="modal" k:data-target="#vermasinformacion">
<f:setPropertyActionListener value="#{r}" target="#{accionesController.libroelegido}" />
</p:commandButton>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<!--</p:dialog>-->
<div class="modal fade" id="vermasinformacion" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="panel panel-default">
<div class="panel-body">
<p:outputPanel id="carDetail" style="text-align:center;">
<legend>#{accionesController.libroelegido.title}</legend>
<p:graphicImage value="/img/libros/#{accionesController.libroelegido.ubicacion}.jpg"/>
<h:panelGrid columns="2" cellpadding="5" style="text-align: left">
<h:outputLabel for="idbook" value="Registro ISBN: " />
<h:outputText id="idbook" value="#{accionesController.libroelegido.book_id}002014" />
<h:outputLabel for="autorlibro" value="Autor :" />
<h:outputText id="autorlibro" value="#{accionesController.libroelegido.author}" />
<h:outputLabel for="preciolibro" value="Precio :" />
<h:outputText id="preciolibro" value="$ #{accionesController.libroelegido.price}" />
<h:commandButton value="Comprar" class="btn btn-primary"/>
<h:commandButton value="Agregar al carrito" class="btn btn-default"/>
</h:panelGrid>
</p:outputPanel>
</div>
</div>
</div>
</div>
</div>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
I am trying to set up 2 chained select boxes using JSF and PrimeFaces. I have created them as in the example on the official site, however:
When i enter the page using the new button(no existing record to be displayed) the change event will return a 500 error from the controller
When i enter the page using the edit button(there is an existing record) the change event will not return a 500 error, however the id from the select is not mapped to the record.
Any help would be appreciated.
Relevant code bits below:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:o="http://omnifaces.org/ui"
template="/WEB-INF/templates/page.xhtml">
<f:metadata>
<o:viewParam name="userUploadedWorkId" value="#{userUploadedWorkController.userUploadedWork}"
converter="#{userUploadedWorkConverter}"
converterMessage="Solicitare eronata. Va rugam sa navigati in aceasta pagina dintr-o lista de lucrari"/>
</f:metadata>
<ui:define name="bread-crumb">
<p:menuitem value="Lucrarile mele" outcome="user-uploaded-work-list?faces-redirect=true"/>
<p:menuitem
value="#{userUploadedWorkController.userUploadedWork.id eq null ? 'Lucrare noua' : userUploadedWorkController.userUploadedWork.title}"
url="#"/>
</ui:define>
<ui:define name="page-content">
<h:form>
<p:panelGrid columns="2" columnClasses="right-aligned,raw" id="user-uploaded-work-details">
<f:facet name="header">Detalii lucrare</f:facet>
<p:outputLabel value="Titlu" for="uuwTitle"/>
<p:inputText id="uuwTitle" value="#{userUploadedWorkController.userUploadedWork.title}" required="true"
style="width: 400px"/>
<p:outputLabel value="Capitol" for="chapter"/>
<p:selectOneMenu style="width: 400px" required="true" id="chapter" value="#{userUploadedWorkController.userUploadedWork.criterion eq null?'':userUploadedWorkController.userUploadedWork.criterion.chapter.id}" effect="fade">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{chapters}" var="ch" itemLabel="#{ch.name}" itemValue="#{ch.id}"/>
<p:ajax update="uuwCriterion" listener="#{userUploadedWorkController.chapterChange}"/>
</p:selectOneMenu>
<p:outputLabel value="Criteriu" for="uuwCriterion"/>
<p:selectOneMenu style="width: 400px" required="true" id="uuwCriterion" value="#{userUploadedWorkController.userUploadedWork.criterion eq null?'':userUploadedWorkController.userUploadedWork.criterion.id}" effect="fade">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{userUploadedWorkController.criteria}" var="criterion" itemLabel="#{criterion.name}" itemValue="#{criterion.id}"/>
</p:selectOneMenu>
<f:facet name="footer">
<p:message for="uuwTitle"/>
<p:message for="uuwCriterion"/>
<p:message for="uuwChapter"/>
<p:commandButton action="#{userUploadedWorkController.save}" value="Salveaza atribute" process="#form"
update="#form :messages" icon="ui-icon-disk"/>
<p:button outcome="user-uploaded-work-list?faces-redirect=true" value="Lista lucrari"
icon="ui-icon-arrowreturnthick-1-e"/>
</f:facet>
</p:panelGrid>
</h:form>
</ui:define>
The managed bean:
#Named
#ViewScoped
public class UserUploadedWorkController implements Serializable {
private static final long serialVersionUID = -4736897416993974840L;
#Inject
private OrganizationalChartService service;
private UserUploadedWork userUploadedWork = new UserUploadedWork();
private List<Criterion> criteria;
public UserUploadedWork getUserUploadedWork() {
return userUploadedWork;
}
public void setUserUploadedWork(UserUploadedWork userUploadedWork) {
this.userUploadedWork = userUploadedWork;
}
#PostConstruct
public void init() {
criteria = service.findAllCriteria();
}
public List<Criterion> getCriteria() {
return criteria;
}
public void setCriteria(List<Criterion> criteria) {
this.criteria = criteria;
}
public String save() {
userUploadedWork.setCriterion(service.findById(Criterion.class, userUploadedWork.getCriterion().getId()));
userUploadedWork.setUser(service.findBySimpleProperty(User.class, "email", LoginController.getRequest().getUserPrincipal().getName()));
userUploadedWork = service.merge(userUploadedWork);
Messages.addFlashGlobalInfo("Salvare efectuata cu succes");
return "user-uploaded-work-list?faces-redirect=true";
}
public void chapterChange() {
if (userUploadedWork.getChapter() != null
&& userUploadedWork.getChapter().getId() != null) {
criteria = service.findCriteriaByChapter(userUploadedWork.getChapter().getId());
} else {
criteria = new ArrayList<Criterion>();
}
}
}
I have a managed bean placed in view scope. Here is the bean:
#ManagedBean(name = "adminController")
#ViewScoped
public class AdminController extends BaseWebController implements Serializable {
private static final long serialVersionUID = 1019716974557397635L;
private transient CustomerDTO customerDTO;
#PostConstruct
public void init() {
customerDTO = new CustomerDTO();
}
public void saveCustomer(ActionEvent event) {
System.out.println(customerDTO.isActive());
try {
getServiceProvider().getCustomerService().addNewCustomer(customerDTO);
getFacesContext().addMessage(null, FacesMessageUtils.getMessageForCustomerAddSuccess(getFacesContext()));
} catch (Throwable throwable) {
getFacesContext().addMessage(null, FacesMessageUtils.getMessageForCustomerAddError(getFacesContext()));
printStackTrace(throwable);
}
}
public CustomerDTO getCustomerDTO() {
return customerDTO;
}
public void setCustomerDTO(CustomerDTO customerDTO) {
this.customerDTO = customerDTO;
}
}
The view is:
<ui:composition 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"
xmlns:pe="http://primefaces.org/ui/extensions">
<p:panel header="#{adbBundle['admin.addCustomerPanel.header']}"
id="addCustomerPanel" toggleable="true">
<p:panelGrid columns="2" id="addCustomerTable"
styleClass="addCustomerTable">
<f:facet name="header">
<p:outputLabel id="header"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.header']}" />
</f:facet>
<p:outputLabel for="customerName"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName']}" />
<h:panelGroup layout="block">
<p:inputText id="customerName" styleClass="customerName"
autocomplete="off"
label="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName']}"
value="#{adminController.customerDTO.customerName}" required="true" />
<pe:tooltip for="customerName"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName.tooltip']}"
showEffect="slideToggle" hideEffect="slideToggle" showDelay="0"
myPosition="left center" atPosition="right center" />
</h:panelGroup>
<p:outputLabel for="customerId"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId']}" />
<h:panelGroup layout="block">
<p:inputText id="customerId" autocomplete="off"
label="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId']}"
value="#{adminController.customerDTO.customerId}" required="true">
<f:validator validatorId="customerIDValidator" />
</p:inputText>
<pe:tooltip for="customerId"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId.tooltip']}"
showEffect="slideToggle" hideEffect="slideToggle" showDelay="0"
myPosition="left center" atPosition="right center" />
</h:panelGroup>
<p:outputLabel for="activeStatus"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.activeStatus']}" />
<h:panelGroup layout="block">
<p:selectBooleanCheckbox id="activeStatus" value="#{adminController.customerDTO.active}" />
</h:panelGroup>
<f:facet name="footer">
<p:commandButton value="#{adbBundle['saveButton']}"
actionListener="#{adminController.saveCustomer}"
icon="ui-icon-check" update=":growl, #form" />
</f:facet>
</p:panelGrid>
</p:panel>
</ui:composition>
The problem that I am facing is, after the actionListener successfully executed the input fields are holding the values.
The h:form is not visible in the aforementioned xhtml, it is placed in the parent page as:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/templates/globalTemplate.xhtml">
<ui:define name="title">#{adbBundle['home']}</ui:define>
<ui:define name="content">
<p:growl id="growl" showDetail="true" />
<h:form id="form">
<ui:include src="/WEB-INF/includes/addCustomer.xhtml" />
</h:form>
</ui:define>
</ui:composition>
However if I add customerDTO = new CustomerDTO(); at the end of the actionListener saveCustomer, the inputs are reset.
Is it the way to clear the form? Or there is a better way to achieve this?
To clear form data using ActionEvent on button
public void clear(){
customerDTO = new CustomerDTO();
}