This question already has answers here:
Keep p:dialog open when a validation error occurs after submit
(6 answers)
Closed 6 years ago.
i have a dialog with two input fields and a commandButton, to add an object. If the user leaves a blank field a message growl is shown and the dialog stays open. But if the user completes all the fields and press the commandButton the object is added but the dialog doesn't close.
View.xhtml
<h:form id="allIncidenciasAux">
<div id="divBotonCrear">
<p:commandButton value="Añadir Incidencia" type="button" onclick="PF('dlg1').show();"/>
</div> <br/>
<p:tabView>
<p:tab title="All">
<ui:repeat value="#{incidenciaBean.allIncidencias}" var="aux" >
<p:panel id="basic" header="#{aux.titulo}" style="margin-bottom:20px" toggleable="true" collapsed="true" styleClass="#{ aux.solucionado eq 'false' ? 'incNS' : null}">
<h:panelGrid columns="2">
<h:panelGrid style="background-color: #B6C2DE; padding: 10px;">
<h:panelGrid columns="2">
<h:outputText value="Fecha de publicacion: " style="font-weight: bold"/>
<h:outputText value="#{aux.fecha_publicacion}"/>
</h:panelGrid>
<h:panelGrid columns="2">
<h:outputText value="Autor: " style="font-weight: bold"/>
<h:outputText value="#{aux.nombreCompleto}"/>
</h:panelGrid>
<h:panelGrid columns="2">
<h:outputText value="Solucionado: " style="font-weight: bold"/>
<h:outputText value="#{aux.solucionado ? 'Si' : 'No'}"/>
</h:panelGrid>
</h:panelGrid>
<h:panelGrid>
<h:outputText value="Descripción: " style="font-weight: bold"/>
<h:outputText value="#{aux.descripcion}"/>
</h:panelGrid>
</h:panelGrid> <br/>
</p:panel>
</ui:repeat>
</p:tab>
</p:tabView>
<p:growl id="growl" showDetail="true" sticky="false" life="8000"/>
</h:form>
<h:form id="dialogAddIncidencia">
<p:dialog id="newIncDialogo" header="Nueva Incidencia" widgetVar="dlg1" minHeight="40" resizable="false">
<p:ajax event="close" listener="#{incidenciaBean.handleClose}" update=":dialogAddIncidencia"/>
<p:outputLabel value="Título"/> <br/>
<p:inputTextarea id="tituloEdit" value="#{incidenciaBean.titulo}" rows="2" cols="50" counter="displayTA" maxlength="50" counterTemplate="{0} caracteres restantes" autoResize="true" required="true" requiredMessage="Título necesario"/> <br/>
<p:outputLabel id="displayTA"/> <br/> <br/>
<p:outputLabel value="Descripción: "/> <br/>
<p:inputTextarea id="descripcion" value="#{incidenciaBean.descripcion}" rows="10" cols="50" counter="displayDA" maxlength="200" counterTemplate="{0} caracteres restantes" autoResize="true" required="true" requiredMessage="Descripción necesaria"/> <br/>
<p:outputLabel id="displayDA"/> <br/> <br/>
<p:commandButton value="Guardar Incidencia" action="#{incidenciaBean.insertIncidencia()}" oncomplete="if (#{incidenciaBean.camposNoVacios()}) dlg1.hide()" update=":allIncidenciasAux :allIncidenciasAux:growl"/>
<p:messages for="titulo"/>
<p:messages for="descripcion"/>
</p:dialog>
</h:form>
Methods of incidenciaBean.java
public void insertIncidencia(){
HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
UsuarioBean usuarioHttp = (UsuarioBean) httpSession.getAttribute("usuarioSession");
this.idComunidad = usuarioHttp.idComunidad;
this.idUsuario = usuarioHttp.getIdUsuario();
this.solucionado = false;
this.fecha_solucion = null;
DateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY");
Date date = new Date();
this.fecha_publicacion = dateFormat.format(date);
if(ejb_incidencia.existIncidenciaTitulo(this.titulo, this.descripcion)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error:",
"Ya existe una incidencia con el mismo título y descripción."
+ "Por favor, compruebe que no se trata de la misma incidencia."));
} else{
ejb_incidencia.realizaRegistroIncidencia(this);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info:",
"La incidencia se ha registrado correctamente"));
initialStatusIncidencia();
}
}
public boolean camposNoVacios(){
return !(this.titulo == null || this.descripcion == null);
}
public void initialStatusIncidencia(){
this.titulo = null;
this.descripcion = null;
}
public void handleClose (CloseEvent event){
initialStatusIncidencia();
}
You are correct in using oncomplete; however, I don't think your if (#{incidenciaBean.camposNoVacios()}) statement ever evaluates true. The dialouge only hides if camposNoVacios() returns ture(if bothtitulo and descripcion aren't null). In insertIncidencia()'s else statement (which I assume is the success case) you set them to null with initialStatusIncidencia().
So your program sets titulo and descripcion, checks that they aren't null in insertIncidencia(), and then sets them to null before checking to see if they aren't null with camposNoVacios().
Related
(Sorry If bad english)
I got a page that displays a datatable and the records can be deleted, but I have a condition that if its ID kind it's the only one left it can't be delete. So when this happens I want to display a message in a <p:growl /> component, this happens okay, but if I click the delete button again, the page goes blank and it can't be refreshed or anything, I have to login again.
xhtml:
<p:dataTable id="respProdDT" widgetVar="respProdDT" var="resProd" value="#{caleFactBean.lstResponsablesProductos}"
reflow="true" styleClass="products-table" scrollable="true" scrollWidth="99%"
paginator="true" rows="10" paginatorPosition="bottom" >
<f:facet name="header">
<div align="center">
<h:outputText value="Responsables por Producto" style="font-size: large"/>
</div>
</f:facet>
<p:column headerText="Producto">
<h:outputText value="#{resProd.grupoProducto}" />
</p:column>
<p:column headerText="Rol Autorizador">
<h:outputText value="#{resProd.rolResponsable}" />
</p:column>
<p:column headerText="Tipo Autorizacion">
<h:outputText value="Nivel #{resProd.idNivel}" />
</p:column>
<p:column headerText="Estado Autorizacion">
<h:outputText value="#{resProd.estadoSolicitud}" rendered="#{resProd.isText()}"/>
<p:selectOneMenu value="#{resProd.idEstadoSolicitud}" rendered="#{resProd.isComboBox()}">
<f:selectItem var="car" itemLabel="Select one" itemValue="" />
<f:selectItems value="#{caleFactBean.combo}"/>
</p:selectOneMenu>
</p:column>
<p:column headerText="Fecha Inicio">
<h:outputText value="#{resProd.fechaInicio}" >
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column headerText="Fecha Fin">
<h:outputText value="#{resProd.fechaFin}" >
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column headerText="Accion">
<p:commandLink id="btnEditarRespProd"
rendered="#{resProd.isEditable()}"
styleClass="ui-icon-document"
oncomplete="PF('dlgEditarRespProd').show();"
update="acordionPanels:frmEditarRespProd"
action="#{caleFactBean.mapearRespProd()}">
<p:tooltip for="btnEditarRespProd" value="Editar" />
<f:setPropertyActionListener value="#{resProd}"
target="#{caleFactBean.respProdAEditar}" />
<p:graphicImage style="width:30px;"
value="/resources/static/images/edit-icon.png" />
</p:commandLink>
<p:commandLink id="btnBorrarRespProd" styleClass="ui-icon-document"
rendered="#{resProd.isRemovable()}"
oncomplete="PF('dlgEliminarRespProd').show();" update="#form">
<p:tooltip for="btnBorrarRespProd" value="Eliminar" />
<f:setPropertyActionListener value="#{resProd}"
target="#{caleFactBean.respProdAEliminar}" />
<p:graphicImage style="width:30px;"
value="/resources/static/images/borrar-icon.png" />
</p:commandLink>
</p:column>
</p:dataTable>
<h:form id="frmEliminarRespProd">
<p:dialog header="¿Eliminar responsable producto?" id="dlgEliminarRespProd" widgetVar="dlgEliminarRespProd" modal="true" resizable="false" closable="false">
<center>
<h:outputLabel value="¿Eliminar registro?" />
<br/><br/>
<p:commandButton value="Cancelar" onclick="PF('frmEliminarRespProd').hide();" />
<p:commandButton value="Aceptar" action="#{caleFactBean.eliminarRespProd}" onclick="PF('frmEliminarRespProd').hide();" style="margin-left: 10px;"/>
</center>
</p:dialog>
</h:form>
Method to delete:
public void eliminarRespProd() throws Exception {
logger.info("respProdAEliminar: " + respProdAEliminar);
//boolean hasMoreThanOne = false;
int countRespProdNivel = 0;
try {
for (ResponsableProdVo respProd : lstResponsablesProductos ) {
if(respProdAEliminar.getIdGrupoProducto() == respProd.getIdGrupoProducto())
countRespProdNivel++;
if(countRespProdNivel > 1) {
break;
}
}
if(countRespProdNivel > 1) {
responsablesProductoService.eliminarRespProd(respProdAEliminar);
FacesContext.getCurrentInstance().getExternalContext().redirect("factnueva-flow");
} else {
//TODO: mensaje "El registro no se puede eliminar al ser el único responsable del producto"
// FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR al eliminar","El registro no se puede eliminar al ser el único responsable del producto");
// FacesContext.getCurrentInstance().addMessage("respProdMssg", message);
// this.mensaje = "El registro no se puede eliminar al ser el único responsable del producto";
// RequestContext.getCurrentInstance().execute("PF('dlgMensajes').show();");
}
} catch (Exception e) {
logger.error("Ocurrio un error al eliminar el registro de Responsables Producto. " + e.getLocalizedMessage());
throw e;
}
}
Any ideas why this could happen?
I'm facing some problem updating my dataTable when I perform a filter operation with this:
<p:panel styleClass="card" header="Filtri">
<h:panelGrid columns="4" layout="grid"
styleClass="ui-panelgrid-blank form-group">
<h:panelGroup styleClass="md-inputfield">
<p:inputText id="orderMinFilter" label="N. bolla più basso"
value="#{productionOrdersView.orderNumberStartFilter}">
</p:inputText>
<p:outputLabel for="orderMinFilter" value="N. bolla più basso" />
</h:panelGroup>
<h:panelGroup styleClass="md-inputfield">
<p:inputText id="orderMaxFilter" label="N. bolla più alto"
value="#{productionOrdersView.orderNumberEndFilter}">
</p:inputText>
<p:outputLabel for="orderMaxFilter" value="N. bolla più alto" />
</h:panelGroup>
<p:commandButton value="Cancella filtri" icon="ui-icon-clear"
styleClass="red-btn flat"
actionListener="#{productionOrdersView.clearFilter()}"
style="width:auto;margin-bottom:10px; float:right;"
update="dtOrders" />
<p:commandButton value="Cerca" icon="ui-icon-search"
styleClass="primary-btn flat"
actionListener="#{productionOrdersView.filter()}"
update="dtOrders"
style="width:auto;margin-bottom:10px; float:right;" />
</h:panelGrid>
</p:panel>
This is my dataTable:
<p:dataTable id="dtOrders" var="productionOrder"
value="#{productionOrdersView.orders}" selectionMode="single"
reflow="true" selection="#{productionOrdersView.selected}"
filteredValue="#{productionOrdersView.filtered}"
widgetVar="ordersTable" rowKey="#{productionOrder.pk}"
emptyMessage="Nessun elemento oppure la ricerca è ancora attiva..."
paginator="true" rows="20">
And this is the method:
public void filter() {
if (orderNumberStartFilter != null && orderNumberEndFilter != null) {
this.orders = productionOrderController.findFromToOrderNumber(Integer.valueOf(orderNumberStartFilter),
Integer.valueOf(orderNumberEndFilter));
this.filtered = orders;
}
}
The filter() method is executed correctly and the list in the bean are correct (I search for 11 elements and I got it), but the dataTable is updated but not with these values; why? Where am I wrong?
You add form tag to update property of commandButton.
<p:commandButton value="Cerca" icon="ui-icon-search"
styleClass="primary-btn flat"
actionListener="#{productionOrdersView.filter()}"
update=":formName:dtOrders"
style="width:auto;margin-bottom:10px; float:right;" />
.
I have a little project, reading/searching data from database include pictures. I have added primefaces-5.3.jar to my project , And my problem is that, When I change users photo to another it does not shows me that change Immediately, whereas I can see other changes(updates) in users record And only when I refresh the web page I am able to see another picture. Please help me with this
here is my piece of code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
//....
<h:form id="searchform">
<!--1 Form for searching -->
<br/>
<br/>
<h:form id="searchform">
<p:outputLabel value="type the key"/>
<p:inputText value="#{personBean.searchinperson.searchAllUsingLikeOpSTRING}" required="true" requiredMessage="Please Enter the key"/>
<br/>
<p:commandButton value="Search by key" icon="ui-icon-search" action="#{personBean.displaySearchedPeopleList()}" update="searchform"/>
<p:dataTable id="searchdatatable_id" value="#{personBean.listofSeachedPeople}" var="person">
<p:column headerText="PersonId">
<p:outputLabel value="#{person.personid}"/>
</p:column>
<p:column headerText="FirstName">
<p:outputLabel value="#{person.firstname}"/>
</p:column>
<p:column headerText="LastName">
<p:outputLabel value="#{person.lastname}"/>
</p:column>
<p:column headerText="Age">
<p:outputLabel value="#{person.age}"/>
</p:column>
<p:column headerText="UserName">
<p:outputLabel value="#{person.username}"/>
</p:column>
<p:column headerText="Password" >
<p:outputLabel value="#{person.password}"/>
</p:column>
<p:column headerText="DataAddTime" >
<p:outputLabel value="#{person.dataaddtime}"/>
</p:column>
<p:column headerText="Person Photo">
<p:graphicImage value="#{personBeanApp.imageDisplay}" alt="no image" height="150" width="150">
<f:param value="#{person.personid}" name="image_id"/>
</p:graphicImage>
</p:column>
<p:column headerText="Modification">
<p:commandLink value="Modify" actionListener="#{personBean.readPersonID(person)}" oncomplete="PF('wdlgData').show();" update=":dlgDataform" />
</p:column>
<p:column headerText="Delete" style=" color: red;">
<p:commandLink value="Delete Person" actionListener="#{personBean.readPersonID(person)}" oncomplete="PF('wdlgconfirmation').show();" update=":dlgconfdelform" />
</p:column>
</p:dataTable>
</h:form>
<!-- Dialog for Modification column -->
<h:form id="dlgDataform">
<p:dialog header="Data" widgetVar="wdlgData" >
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="modifyDlgPersonid_id" value="PersonID"/>
<p:inputText id="modifyDlgPersonid_id" value="#{personBean.person.personid}" required="true" />
<p:outputLabel for="modifyDlgFirstname_id" value="FirstName"/>
<p:inputText id="modifyDlgFirstname_id" value="#{personBean.person.firstname}" required="true" />
<p:outputLabel for="modifyDlgLastname_id" value="LastName"/>
<p:inputText id="modifyDlgLastname_id" value="#{personBean.person.lastname}" required="true"/>
<p:outputLabel for="modifyDlgAge_id" value="Age"/>
<p:inputText id="modifyDlgAge_id" value="#{personBean.person.age}" required="true"/>
<p:outputLabel for="modifyDlgUsername_id" value="UserName"/>
<p:inputText id="modifyDlgUsername_id" value="#{personBean.person.username}" required="true"/>
<p:outputLabel for="modifyDlgPassword_id" value="Password"/>
<p:inputText id="modifyDlgPassword_id" value="#{personBean.person.password}" required="true"/>
</h:panelGrid>
<p:outputLabel value="add/alter Picture"/>
<p:fileUpload fileUploadListener="#{personBean.handleFileUploadForAdminModifyDlg}" mode="advanced" dragDropSupport="false"
update="adminModifyDlgUpload_msgs" sizeLimit="1000000" fileLimit="1" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:messages id="adminModifyDlgUpload_msgs" for="adminModifyDlgPicUpload" showDetail="true" autoUpdate="true" closable="true" />
<br/>
<br/>
<p:separator />
<p:messages for="dialogModAdmin" showDetail="true" autoUpdate="true" closable="true" />
<br/>
<p:commandButton value="Modify" actionListener="#{personBean.modificatePersonData()}" update=":searchform:searchdatatable_id" />
<h:outputText value=" " />
<p:commandButton value="Cancel/Close" immediate="true" oncomplete="PF('wdlgData').hide();"/>
</p:dialog>
</h:form>
PersonBean.java:
#ManagedBean
#SessionScoped
public class PersonBean {
private List<Person> listofSeachedPeople;
public List<Person> getListofSeachedPeople() {
return listofSeachedPeople;
}
public void setListofSeachedPeople(List<Person> listofSeachedPeople) {
this.listofSeachedPeople = listofSeachedPeople;
}
public void displaySearchedPeopleList() throws Exception
{
PersonDAO dao;
try{
dao=new PersonDAO();
listofSeachedPeople=dao.searchByAll(searchinperson);
}
catch(Exception ex){throw ex;}
}
public void readPersonID(Person per) throws Exception{
PersonDAO dao;
Person temp;
try{
dao=new PersonDAO();
temp=dao.readID(per);
if(temp!=null){ persId=temp.getPersonid();persPass=temp.getPassword();this.person=temp; }
}
catch(Exception ex){throw ex;}
}
public void modificatePersonData() throws Exception{
PersonDAO dao;
try{
dao=new PersonDAO();
if("personIdFree".equals(dao.IsPersonIdFreeExceptThis(person)) && "passwordFree".equals(dao.IsPasswordFreeExceptThis(person))){dao.modificate(person);FacesContext.getCurrentInstance().addMessage("dialogModAdmin", new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "The Data has been modified"));}
else {FacesContext.getCurrentInstance().addMessage("dialogModAdmin", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "PersonID or Password is already in use"));}
this.displaySearchedPeopleList();
}
catch(Exception ex){throw ex;}
}
public void handleFileUploadForAdminModifyDlg(FileUploadEvent event) throws Exception {
try{
if(event.getFile()!=null){
uplf.setUploadedFile(event.getFile());
person.setPersonimage(IOUtils.toByteArray(uplf.getUploadedFile().getInputstream()));
FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage("adminModifyDlgPicUpload", message);}
}
catch(Exception ex){throw ex;}
}
PersonDAO.java :
public void modificate(Person per) throws Exception {
PreparedStatement pst;
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss");
try {
this.connectDB();
pst = this.getConn().prepareStatement("UPDATE person SET personid=?,firstname=?, lastname=?, age=?, username=?, password=?,dataaddtime=?,personimage=? WHERE personid=? ");
pst.setInt(1, per.getPersonid());
pst.setString(2, per.getFirstname());
pst.setString(3, per.getLastname());
pst.setInt(4, per.getAge());
pst.setString(5, per.getUsername());
pst.setString(6, per.getPassword());
pst.setString(7, df.format(date));
pst.setBytes(8,per.getPersonimage());
pst.setInt(9,PersonBean.getPersId());
pst.executeUpdate();
} catch (Exception ex) {
throw ex;
} finally {
this.toClose();
}
}
public byte[] chosenPictureInBytes(int id) throws Exception{
PreparedStatement pst;
ResultSet rs;
byte[] byteArr =new byte[1048576];
try{
this.connectDB();
pst = this.getConn().prepareStatement("SELECT personimage FROM person WHERE personid=? ");
pst.setInt(1,id);
rs = pst.executeQuery();
while(rs.next()){
// byteArr=rs.getBytes("personimage");
Blob blobPic = rs.getBlob("personimage");
byteArr=blobPic.getBytes(1,(int) blobPic.length());
}
}
catch(Exception ex){throw ex;}
finally{this.toClose();}
return byteArr;
}
PersonBeanApp.java:
#ManagedBean
#ApplicationScoped
public class PersonBeanApp {
public StreamedContent getImageDisplay() throws Exception{
PersonDAO dao;
try{
dao=new PersonDAO();
FacesContext fc=FacesContext.getCurrentInstance();
String id=fc.getExternalContext().getRequestParameterMap().get("image_id");
if(fc.getCurrentPhaseId()==PhaseId.RENDER_RESPONSE){ return new DefaultStreamedContent(); }
byte[] imageInByteArray=dao.chosenPictureInBytes(Integer.parseInt(id));
return new DefaultStreamedContent(new ByteArrayInputStream(imageInByteArray));
}
catch(Exception ex){throw ex;}
}
}
Please help me...
In my case, i had to have an img tag in modal dialog and i updated #form on user clicking the submit button on the dialog.
<p:dialog widgetVar="dlg7" id="showImage" closable="true" modal="true" header="Edit Email Image" closeOnEscape="true" draggable="true" dynamic="true" >
<p:ajax event="close" listener="#{emailConfigurationEditAction.handleCloseEditImage}" update=":emailConfiguration" />
<h:form id="editImage">
<div id="editImageDiv" align="center">
<p:messages globalOnly="false" autoUpdate="true" id="messages"
rendered="true" closable="true">
<p:effect id="idar760" type="bounce" event="load" delay="500" />
</p:messages>
<h:panelGrid columns="2" width="500px;" id="editImageGrid" columnClasses="emailTemplatePadding,row1-padding">
<p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_NAME}" for="imageNameText" id="imageNameLable" />
<h:outputText value="#{emailConfigurationEditAction.editEmbeddedImage.cidname}" converter="upperCaseConverter" id="imageNameText" style="width:300px;" maxlength="20" validatorMessage="#{msg.EMAIL_INLINE_IMAGES_CIDNAME_VLDMSG}"/>
<p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_MIMETYPE}" for="imageMimeType" id="imagemimeLabel"/>
<p:selectOneMenu id="imageMimeType" value="#{emailConfigurationEditAction.editEmbeddedImage.mimeType}" style="width:310px">
<f:selectItem itemLabel="#{msg.DROP_SELECTONE }" itemValue="#{null}" />
<f:selectItems value="#{emailConfigurationEditAction.mimeTypeOptions}"/>
</p:selectOneMenu>
<p:outputLabel value="Uploaded Image:" id="imageUploadedLabel"/>
<img width="100" height="100" border="0" id="imageUploaded" src="data:image/jpg;base64,#{imageUtility.getImageAsString(emailConfigurationEditAction.editEmbeddedImage.imageByteArray)}" />
<!-- p:graphicImage value="#{emailImages.image}" id="imageUploaded" height="100px" width="100px" >
<f:param name="cidName" value="#{emailConfigurationEditAction.editEmbeddedImage.cidname}"/>
</p:graphicImage-->
<p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_UPLOAD}" for="imageUploader" id="imageUploaderLabel"/>
<p:fileUpload id="imageUploader" mode="advanced" dragDropSupport="true" fileLimit="1" update=":editImage" style="width:310px" label="#{msg.EMAIL_INLINE_UPLAOD_IMAGE}"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileUploadListener="#{emailConfigurationEditAction.imageEditListener}" fileLimitMessage="#{msg.EMAIL_INLINE_IMAGES_FILELIMIT_VLDMSG}"/>
</h:panelGrid>
<p:commandButton value="#{msg.BTN_SUBMIT}" id="submitNewImage" action="#{emailConfigurationEditAction.updateEmbeddedImage}" process=":editImage" ajax="true" update="#form"/>
<p:commandButton value="#{msg.BTN_CANCEL}" id="cancelEditImage" action="#{emailConfigurationEditAction.cancel}" immediate="true" ajax="true" process="#this"/>
</div>
</h:form>
</p:dialog>
And my datatable looked as follows:
<p:dataTable var="image" value="#{emailConfigurationEditAction.searchedImages}" id="dataTableImages" rendered="#{emailConfigurationEditAction.searchedImages!=null}"
paginator="true" rows="10" paginatorPosition="top"
rowStyleClass="#{index%2==0?'row1Data':'row2Data'}" style="width:600px;"
styleClass="ui-citi-datatable-paginator"
rowClasses="row1Data,row2Data"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
currentPageReportTemplate="{currentPage} #{msg.LBL_OF} {totalPages}"
emptyMessage="#{msg.INFO_SEARCH_RESULT_EMPTY}" >
<p:column id="col1" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_NAME}" styleClass="centered" style="width:175px;">
#{image.cidname}
</p:column>
<p:column id="col2" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_MIMETYPE}" styleClass="centered" style="width:120px;">
#{image.mimeType}
</p:column>
<p:column id="col3" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_IMAGE}" styleClass="centered" style="width:120px;">
<img width="100" height="100" border="0" id="graphicImage3"
src="data:image/jpg;base64,#{imageUtility.getImageAsString(image.imageByteArray)}" />
<!--p:graphicImage value="#{emailImages.image}" id="graphicImage3" height="100px" width="100px;">
<f:param name="cidName" value="#{image.cidname}"/>
</p:graphicImage-->
</p:column>
<p:column id="col4" headerText="" styleClass="centered" style="width:60px;">
<!-- h:commandButton image="/global/images/Delete_But_small.png" title="#{msg.LBL_EVENTEMAILMAPPING_DELETE_BUTTON}" immediate="true" value="#{msg.BTN_DELETE}" id="imgDelete"/>
<pe:tooltip for="imgDelete" value="#{msg.LBL_EVENTEMAILMAPPING_DELETE_BUTTON}" myPosition="left" atPosition="right"
showEffect="slideToggle" hideEffect="slideToggle" id="tooltip_delimg"/-->
<h:commandButton image="/global/images/Edit_But_small.png" title="#{msg.LBL_EVENTEMAILMAPPING_EDIT_BUTTON}" value="#{msg.BTN_EDIT}" id="imgEdit" action="#{emailConfigurationEditAction.editImage(image)}">
<p:ajax update=":editImage" oncomplete="PF('dlg7').show()" process="dataTableImages"/>
</h:commandButton>
<pe:tooltip for="imgEdit" value="#{msg.LBL_EVENTEMAILMAPPING_EDIT_BUTTON}" myPosition="left" atPosition="right"
showEffect="slideToggle" hideEffect="slideToggle" id="tooltip_edim"/>
</p:column>
</p:dataTable>
When i used grpahicImage instead, i understood that it will not work due to the way it is designed
I'm having problem with a commamd link that adds a row in a datatable and refreshes it. It was working fine, but when I added another table with multiple selection on the same form, It stopped work. Is there some incompatibility between them?
I'm using PrimeFaces 3.4, Mojarra 2.1.6 and Glassfish 3
Here is my form:
<h2>Projeto para Credenciamento Equipe de Saúde da Família</h2>
<hr />
<h:form id="formCredenciamentoEsf" prependId="false">
<p:fieldset legend="Caracterização Geral">
<p:panelGrid id="microareas" columns="2" cellspacing="8">
<p:dataTable
value="#{credenciamentoEsfMB.credenciamentoESF.projeto.caracterizacaoTerritorialDemograficaList}"
var="carac" emptyMessage="Adicione uma microárea.">
<p:column
headerText="Microáreas que compõem a área de abrangência da ESF">
<p:inputText value="#{carac.microarea}" size="50" />
</p:column>
<p:column
headerText="População Estimada por Microárea (nº de pessoas)">
<p:inputText value="#{carac.populacaoEstimadaMicroarea}"
size="50" />
</p:column>
<p:column>
<p:commandLink
actionListener="#{credenciamentoEsfMB.removerCaracteristica}"
update=":formCredenciamentoEsf:microareas">
<f:setPropertyActionListener value="#{carac}"
target="#{credenciamentoEsfMB.caracteristicaSelecionada}" />
<h:outputText value="Remover " />
</p:commandLink>
</p:column>
</p:dataTable>
</p:panelGrid>
<h:panelGrid columns="2">
<p:commandLink actionListener="#{credenciamentoEsfMB.addCaracteristicaTerritorialDemografica}"
update=":formCredenciamentoEsf:microareas">
<h:outputText value="Adicionar Microárea" />
</p:commandLink>
<h:outputLabel/>
<h:outputLabel
value="População total coberta pela ESF (nº de pessoas):"></h:outputLabel>
<p:inputText id="populacaoCoberta"
value="#{credenciamentoEsfMB.credenciamentoESF.populacaoTotalCoberta}" />
<h:outputLabel
value="Caracterização da população a ser coberta pelas ações da ESF:" />
<p:dataTable
value="#{credenciamentoEsfMB.populacaoCobertaDataModel}" var="pop"
id="dtCaracteristicaPopulacaoCoberta"
selection="#{credenciamentoEsfMB.populacaoCobertaSelecionadas}" >
<p:column selectionMode="multiple" />
<p:column headerText="População a ser atendida">
<h:outputLabel
value="#{pop.caracteristicaPopulacaoCoberta.descricao}" />
</p:column>
<p:column headerText="Nº de pessoas">
<p:inputText value="#{pop.numPessoas}" />
</p:column>
</p:dataTable>
</h:panelGrid>
</p:fieldset>
</h:form>
</ui:define>
The link "Adicionar Microárea" didn't work when I put the last datatable with multiple selection.
Here is my Managed bean:
#ManagedBean
#ViewScoped
public class CredenciamentoEsfMB {
....
public PopulacaoCobertaDataModel getPopulacaoCobertaDataModel() {
List<CaracteristicaPopulacaoCoberta> caracteristicas = caracteristicaPopulacaoCobertaEjb.buscarTodos();
populacaoCobertaEsf = new ArrayList<PopulacaoCobertaESFESB>();
for (CaracteristicaPopulacaoCoberta caracteristicaPopulacaoCoberta : caracteristicas) {
PopulacaoCobertaESFESB p = new PopulacaoCobertaESFESB();
p.setCaracteristicaPopulacaoCoberta(caracteristicaPopulacaoCoberta);
p.setCredenciamentoESFESB(credenciamentoESF);
populacaoCobertaEsf.add(p);
}
this.populacaoCobertaDataModel = new PopulacaoCobertaDataModel(this.populacaoCobertaEsf);
return this.populacaoCobertaDataModel;
}
public void removerCaracteristica() {
credenciamentoESF.getProjeto()
.getCaracterizacaoTerritorialDemograficaList().remove(caracteristicaSelecionada);
}
public void addCaracteristicaTerritorialDemografica(ActionEvent e) {
System.out.println("Adicionando microarea");
credenciamentoESF.getProjeto()
.getCaracterizacaoTerritorialDemograficaList()
.add(new CaracterizacaoTerritorialDemografica());
}
}
Does anyone know what is going on?
I am currently making a Facelets page with JSF2.0 and I am using Primefaces to make it look fancy :D. But I have a problem which I can't seem to solve. The idea behind my page is the following : I have a dashboard page which contains different accordion tabs and in each tab there is a primefaces datatable. In that datatable are some rows for a given user. But when I want to add a new row to my datatable I use the following method. I have a button "Add row" beneath my datatable and when I click it I load through JQuery a page into a div that's beneath my button. In that div is then my "addrow" page loaded with the validation and so on.
But here is the problem: when I click on my add button on the included page, I want to update my datatable in the "parent" page, so the page that includes my add page, and this is not working as the update attribute for my p:commandButton doesn't seem to find the datatable or any other component on my parent page.
So if someone could tell me how that I could update my component in my parent page ?
Here is the related code fragments :
Parent page (which includes the add page in the "content div")
<f:view contentType="text/html" beforePhase="#{userBean.retrievePersonalInformation}">
<h:outputText value="#{companyBean.companyName}" id="test2"/>
<h:form id="form" prependId="false">
<p:accordionPanel autoHeight="true" effect="bounceslide" id="accordion">
<p:tab title="Personal information">
<h:panelGrid columns="2" cellpadding="10">
<h:outputText
value="Welkom #{loginBean.username}"/><br/>
<h:outputText value="#{bundle.name}"/>
<h:outputText value="#{userBean.lastName}"/>
<h:outputText value="#{userBean.street}"/>
<h:outputText value="#{userBean.zipCode}"/>
<h:outputText value="#{userBean.city}"/>
<h:outputText value="#{userBean.cellPhone}"/>
<h:outputText value="#{userBean.phone}"/>
<h:outputText value="#{userBean.email}"/>
<h:outputText value="#{userBean.dateOfBirth}"/>
<h:outputText value="#{userBean.gender}"/>
<h:outputText value="training: #{userBean.trainingName}"/>
</h:panelGrid>
</p:tab>
<p:tab title="My studies">
<h:panelGrid columns="2" cellpadding="10">
<h:outputText value="My studies"/>
</h:panelGrid>
</p:tab>
<p:tab title="My job history">
<h:panelGrid columns="2" cellpadding="10">
<h:outputText value="My Job history"/>
</h:panelGrid>
</p:tab>
<p:tab title="My Technologies">
<h:panelGrid columns="2" cellpadding="10">
<h:outputText value="My Technologies"/>
</h:panelGrid>
</p:tab>
<p:tab title="My language skills">
<h:panelGrid columns="2" cellpadding="10">
</h:panelGrid>
</p:tab>
<p:tab title="My Certificates">
<h:panelGrid columns="2" cellpadding="10">
<input type="button" id="btnCertificate" value="show me"/>
</h:panelGrid>
</p:tab>
<p:tab title="My Trainings">
<h:panelGrid columns="2" cellpadding="10">
<p:dataTable var="training" value="#{trainingBean.trainingsByUser}" id="trainingTable"
emptyMessage="No trainings found with given criteria" paginator="true"
rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column headerText="Training name" sortBy="#{training.name}"
filterBy="#{training.name}" filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{training.name}"/>
</p:column>
<p:column headerText="Training date" sortBy="#{training.trainingDate}"
filterBy="#{training.trainingDate}" filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{training.trainingDate}"/>
</p:column>
<p:column headerText="Training description" sortBy="#{training.description}"
filterBy="#{training.description}" filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{training.description}"/>
</p:column>
</p:dataTable>
</h:panelGrid>
</p:tab>
<p:tab title="My Companies">
<p:dataTable value="#{companyBean.companiesByUser}" var="company" id="companyTable"
emptyMessage="No companies found for given user" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column headerText="name" sortBy="#{company.companyName}"
filterBy="#{company.companyName}"
filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{company.companyName}"/>
</p:column>
<p:column headerText="Start date" sortBy="#{company.startDate}"
filterBy="#{company.startDate}"
filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{company.startDate}">
<f:convertDateTime pattern="dd/MM/yyyy" type="date" timeZone="CET"/>
</h:outputText>
</p:column>
<p:column headerText="End date" sortBy="#{company.endDate}"
filterBy="#{company.endDate}"
filterMatchMode="contains"
style="width: 100px;">
<h:outputText value="#{company.endDate}">
<f:convertDateTime pattern="dd/MM/yyyy" type="date" timeZone="CET"/>
</h:outputText>
</p:column>
<p:column>
<p:commandButton id="btnEditCompany" value="Edit company" action="#{companyBean.navigateUser}" oncomplete="showCertificateEdit()">
<f:setPropertyActionListener value="#{company}" target="#{companyBean.selectedCompany}"/>
</p:commandButton>
</p:column>
</p:dataTable>
<input type="button" id="btnAddCompany" value="Add company"/>
</p:tab>
</p:accordionPanel>
</h:form>
<div id="content">
</div>
</f:view>
The add page
<f:view contentType="text/html">
<ui:composition>
<h:form id="companyForm" prependId="false">
<h:message for="name"/>
<h:message for="startdate"/>
<h:message for="enddate"/>
<h:outputText class="label" value="name: "/>
<h:inputText id="name" styleClass="inputtext validate[required]"
value="#{companyBean.companyName}"/>
<h:outputText class="label" value="start date: "/>
<h:inputText id="startdate" styleClass="inputtext validate[required]"
value="#{companyBean.startDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
<h:outputText class="label" value="end date: "/>
<h:inputText id="enddate" styleClass="inputtext validate[required]"
value="#{companyBean.endDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
<h:outputText class="label" value="type: "/>
<h:selectOneMenu styleClass="input" value="#{companyBean.type}">
<f:selectItem itemValue="0" itemLabel="Internal"/>
<f:selectItem itemValue="1" itemLabel="External"/>
</h:selectOneMenu>
<h:commandButton action="cancel" value="cancel" immediate="true"/>
<p:commandButton id="btnAddCompanyTest" actionListener="#{companyBean.addCompany}" value="Add company" ajax="false"/>
</h:form>
</ui:composition>
</f:view>
JQuery load method
jQuery("#btnAddCompany").click(function() {
jQuery("#content").load('/user/companyDetail.xhtml',function(){
jQuery("#companyForm").validationEngine('attach', {promptPosition : "topRight", scroll: false});
});
});
Backing bean add method
public String addCompany() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
companyService.addCompany(companyName, startDate, endDate, type);
loadCompanyList();
} catch (cvApplicationException e) {
facesContext.addMessage("companyForm", new FacesMessage(e.getMessage()));
}
return "../user/dashboard.xhtml?faces-redirect=true";
}
My backingBean is sessionscoped.
Thanks in advance
Heading
instead you are loading using jQuery(..).load()
why don't you using inside the div element.
<div id="content">
<p:outputPanel id="" rendered="#{companyBean.insertMode}">
<!-- put your add page here -->
</p:outputPanel>
</div>
You can just set isInsertMode() method to return either true or false.
So you will be in the same view page. Updating the datatable from your add page may work.
In this case please review this one
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://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.prime.com.tr/ui">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form id="form">
<p:accordionPanel autoHeight="true" effect="bounceslide" id="accordion">
<p:tab title="My Companies">
<p:dataTable value="#{companyBean.list}" var="company" id="companyTable">
<p:column headerText="name"
style="width: 100px;">
<h:outputText value="#{company.name}"/>
</p:column>
<p:column headerText="Start date"
style="width: 100px;">
<h:outputText value="#{company.startDate}">
<f:convertDateTime pattern="dd/MM/yyyy" type="date" timeZone="CET"/>
</h:outputText>
</p:column>
<p:column headerText="End date"
style="width: 100px;">
<h:outputText value="#{company.endDate}">
<f:convertDateTime pattern="dd/MM/yyyy" type="date" timeZone="CET"/>
</h:outputText>
</p:column>
</p:dataTable>
<p:commandButton id="btnAddCompany" value="Add company" update=":form:add_panel" action="#{companyBean.prepareAdd}" ajax="false"/>
</p:tab>
</p:accordionPanel>
<div id="content">
<p:outputPanel id="add_panel" rendered="#{companyBean.insertMode}">
<!-- put your add page here -->
<h:message for="name"/>
<h:message for="startdate"/>
<h:message for="enddate"/>
<h:outputText class="label" value="name: "/>
<h:inputText id="name" styleClass="inputtext validate[required]"
value="#{companyBean.company.name}"/>
<h:outputText class="label" value="start date: "/>
<h:inputText id="startdate" styleClass="inputtext validate[required]"
value="#{companyBean.company.startDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
<h:outputText class="label" value="end date: "/>
<h:inputText id="enddate" styleClass="inputtext validate[required]"
value="#{companyBean.company.endDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
<h:outputText class="label" value="type: "/>
<h:selectOneMenu styleClass="input" value="#{companyBean.company.type}">
<f:selectItem itemValue="0" itemLabel="Internal"/>
<f:selectItem itemValue="1" itemLabel="External"/>
</h:selectOneMenu>
<h:commandButton action="cancel" value="cancel" immediate="true"/>
<p:commandButton id="btnAddCompanyTest" actionListener="#{companyBean.addCompany}" value="Add company"
ajax="false"/>
</p:outputPanel>
</div>
</h:form>
</h:body>
</f:view>
also the Backing bean
public class CompanyBean {
private Company company;
private boolean insertMode;
private List<Company> list;
private TestController(){
list = new ArrayList<Company>();
//populate data, should be from database
list.add(new Company("A", new Date(), new Date(), "1"));
list.add(new Company("B", new Date(), new Date(), "0"));
list.add(new Company("C", new Date(), new Date(), "1"));
insertMode = false;
}
public String prepareAdd(){
company = new Company();
setInsertMode(true);
return "";
}
public String addCompany() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
//companyService.addCompany(companyName, startDate, endDate, type);
//loadCompanyList();
list.add(company); //change to add to database
//load company list here
setInsertMode(false);
} catch (Exception e) {
facesContext.addMessage("companyForm", new FacesMessage(e.getMessage()));
}
return "";
}
/**
* #return the list
*/
public List<Company> getList() {
return list;
}
/**
* #return the company
*/
public Company getCompany() {
return company;
}
/**
* #param company the company to set
*/
public void setCompany(Company company) {
this.company = company;
}
/**
* #return the insertMode
*/
public boolean isInsertMode() {
return insertMode;
}
/**
* #param insertMode the insertMode to set
*/
public void setInsertMode(boolean insertMode) {
this.insertMode = insertMode;
}
}