How to reset <p:selectOneMenu> to default inside a <p:dialog> [duplicate] - jsf

This question already has answers here:
How to show details of current row from p:dataTable in a p:dialog and update after save
(1 answer)
p:resetInput does not reset the p:dialog when it is reopened
(1 answer)
Closed 2 years ago.
I have a problem with resetting the values of a <p: selectOneMenu> component that is housed within a <p: dialog> component, it turns out that I have declared the <p: dialog> on the same page where I show it with a < p: commandButton> and I want that when I finish editing the data and press the button again, the component <p: selectOneMenu> comes out with the initial values, and this is not happening, instead it keeps the selection I made previously. Thank you very much for the help you can give me. this is the code of the page. I don't think it is necessary to put the code for the backing beans but they do need it without problem.
<?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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<body class="areaContenido">
<ui:composition template="../resources/template/tgeneral.xhtml">
<ui:define name="content" class="areaContenido">
<h:form id="guser">
<p:growl id="msgs" showDetail="true" />
<p:dataTable var="usermio" value="#{userBean.lazyModel}" paginator="true" rows="10" class="FuentTable" rowKey="#{usermio.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="userTable" lazy="true">
<f:facet name="header">
<p:outputLabel value="Gestión de usuarios del sistema" style="font-weight: bold; text-align: center;"/>
</f:facet>
<p:column headerText="Id" width="5%">
<h:outputText value="#{usermio.id}" />
</p:column>
<p:column headerText="Usuario" width="15%" >
<h:outputText value="#{usermio.usuario}" />
</p:column>
<p:column headerText="Nombre" width="20%">
<h:outputText value="#{usermio.nombre}"/>
</p:column>
<p:column headerText="Apellidos" width="25%">
<h:outputText value="#{usermio.apellidos}" />
</p:column>
<p:column headerText="Rol" width="15%">
<h:outputText value="#{usermio.rol.rol}" />
</p:column>
<p:column headerText="Opt" width="15%">
<p:commandButton value="" update=":guser:userEdit" onclick="PF('userDial').show()" icon="ui-icon-pencil" ajax="true" >
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
<p:commandButton value="" update=":guser:userEdit" onclick="PF('cd').show()" icon="ui-icon-key" ajax="true">
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
<p:commandButton value="" update=":guser:userEdit" onclick="PF('cd').show()" icon="ui-icon-cancel" ajax="true">
<f:setPropertyActionListener value="#{usermio}" target="#{userBean.selecteduser}" />
</p:commandButton>
</p:column>
<f:facet name="footer">
<p:button icon="ui-icon-plus" id="nuevo" value="Nuevo" href="/glitic/adm/register.xhtml" title="Nuevo usuario" />
</f:facet>
</p:dataTable>
<p:dialog header="Edición de datos" widgetVar="userDial" modal="true" showEffect="bounce" hideEffect="fade" resizable="false" class="Fuent" responsive="true" >
<p:outputPanel id="userEdit" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty userBean.selecteduser}" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{userBean.selecteduser.id}" />
<h:outputText value="Usuario" />
<p:inputText value="#{userBean.selecteduser.usuario}" id="username" required="true" requiredMessage="Se necesita el usuario"/>
<h:outputText value="Nombres" />
<p:inputText value="#{userBean.selecteduser.nombre}" id="nombre" required="true" requiredMessage="Se necesita el nombre"/>
<h:outputText value="Apellidos" />
<p:inputText value="#{userBean.selecteduser.apellidos}" id="apellidos" required="true" requiredMessage="Se necesita los apellidos"/>
<h:outputText value="Rol" />
<p:selectOneMenu id="sroles" value="#{userBean.selectedrol}" style="width:160px" effect="fold" >
<f:selectItem itemLabel="Escoja un rol para el usuario" itemValue="" />
<f:selectItems value="#{userBean.roles}" var="xroles" itemLabel="#{xroles.rol}" itemValue="#{xroles.id}" />
</p:selectOneMenu>
<h:outputText value="Guardar cambios:" />
<p:commandButton value="Guardar" action="#{cttobean.NVenta()}" ajax="false"/>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>

Related

Error sending property object from .xhtml to bean

I have this .xhtml file. It's a data table page with three buttons (one for creating users, one for editing them and one for deleting them). Creating and deleting users are working but updating not. When I call the method actionListener="#{usuariosBean.actualizarUsuario}", I get all parameters well but not the Id, I'm getting 0 instead of the real Id of the user.
I have tried to do it in different .xhtml and it work good so I think that the problem is about the .xhtml file but... I don't know. Could anybody help me? Thanks a lot!!!
<?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:ui="http://xmlns.jcp.org/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="./../template.xhtml">
<ui:define name="content">
<p:growl id="msgs" showDetail="true" />
<h:form>
<p:commandButton update=":formCrear" icon="ui-icon-document"
title="Crear Usuario" value="Crear Usuario"
oncomplete="PF('usuarioDialogCrear').show();">
</p:commandButton>
</h:form>
<h:form id="form">
<p:dataTable var="usuario" value="#{usuariosBean.usuarios}"
paginator="true" rows="10">
<p:column headerText="Id">
<h:outputText value="#{usuario.id}" />
</p:column>
<p:column headerText="Nombre de Usuario">
<h:outputText value="#{usuario.nombreDeUsuario}" />
</p:column>
<p:column headerText="Contraseña">
<h:outputText value="#{usuario.contrasenya}" />
</p:column>
<p:column headerText="Rol">
<h:outputText value="#{usuario.rol}" />
</p:column>
<p:column headerText="" style="text-align:center; width:4%">
<p:commandButton update=":form:usuarioActualizar" id="Actualizar"
icon="ui-icon-pencil" title="Actualizar"
oncomplete="PF('usuarioDialogActualizar').show();">
<f:setPropertyActionListener value="#{usuario}"
target="#{usuariosBean.usuarioSeleccionado}" />
</p:commandButton>
</p:column>
<p:column headerText="" style="text-align:center; width:4%">
<p:commandButton update=":form:usuarioEliminar" id="Eliminar"
icon="ui-icon-close" title="Eliminar"
oncomplete="PF('confirmacion').show();">
<f:setPropertyActionListener value="#{usuario}"
target="#{usuariosBean.usuarioSeleccionado}" />
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Actualizar Usuario"
widgetVar="usuarioDialogActualizar" modal="true" showEffect="fade"
hideEffect="explode" resizable="false" width="400">
<p:outputPanel id="usuarioActualizar" style="text-align:center;"
layout="block">
<p:panelGrid columns="2">
<h:outputText value="Id " />
<p:inputText
value="#{usuariosBean.usuarioSeleccionado.id}"
style="font-weight:bold" size="37" />
<h:outputText value="Usuario: " />
<p:inputText
value="#{usuariosBean.usuarioSeleccionado.nombreDeUsuario}"
style="font-weight:bold" size="37" />
<h:outputText value="Contraseña: " />
<p:inputText
value="#{usuariosBean.usuarioSeleccionado.contrasenya}"
style="font-weight:bold" size="37" />
<h:outputText value="Rol " />
<p:inputText value="#{usuariosBean.usuarioSeleccionado.rol}"
style="font-weight:bold" size="37" />
</p:panelGrid>
</p:outputPanel>
<f:facet name="footer">
<p:commandButton update=":form, :msgs" id="btnActualizarAceptar"
icon="ui-icon-disk" title="Guardar Usuario"
value="Actualizar Usuario"
actionListener="#{usuariosBean.actualizarUsuario}"
oncomplete="PF('usuarioDialogActualizar').hide()">
</p:commandButton>
<p:commandButton id="btnActualizarCancelar" icon="ui-icon-close"
title="Cancelar" value="Cancelar" type="button"
onclick="PF('usuarioDialogActualizar').hide()">
</p:commandButton>
</f:facet>
</p:dialog>
<p:confirmDialog
message="¿Está seguro que desea eliminar el usuario?"
showEffect="bounce" hideEffect="explode" header="Eliminar Usuario"
severity="alert" widgetVar="confirmacion">
<p:outputPanel id="usuarioEliminar" style="text-align:center;"
layout="block">
<h:inputHidden value="#{usuariosBean.usuarioSeleccionado.id}" />
</p:outputPanel>
<p:commandButton id="confirmarDialogo" value="Aceptar"
icon="ui-icon-check" update=":form, :msgs"
oncomplete="PF('confirmacion').hide()"
actionListener="#{usuariosBean.eliminarUsuario}" />
<p:commandButton id="cancelarDialogo" icon="ui-icon-close"
title="Cancelar" value="Cancelar"
oncomplete="PF('confirmacion').hide()">
</p:commandButton>
</p:confirmDialog>
</h:form>
<h:form id="formCrear">
<p:dialog header="Crear Usuario" widgetVar="usuarioDialogCrear"
modal="true" showEffect="fade" hideEffect="explode"
resizable="false" width="400">
<p:outputPanel id="usuarioCrear" style="text-align:center;"
layout="block">
<p:panelGrid columns="2">
<h:outputText value="Usuario: " />
<p:inputText value="#{usuariosBean.nombreDeUsuario}"
required="true" size="37" />
<h:outputText value="Contraseña: " />
<p:inputText value="#{usuariosBean.contrasenya}" required="true"
size="37" />
<h:outputText value="Rol " />
<p:inputText value="#{usuariosBean.rol}" required="true"
size="37" />
</p:panelGrid>
</p:outputPanel>
<f:facet name="footer">
<p:commandButton update=":form, :msgs" id="btnCrearAceptar"
icon="ui-icon-disk" title="Guardar Usuario"
value="Guardar Usuario" action="#{usuariosBean.guardarUsuario}"
oncomplete="PF('usuarioDialogCrear').hide()">
</p:commandButton>
<p:commandButton id="btnCrearCancelar" icon="ui-icon-close"
title="Cancelar" value="Cancelar"
oncomplete="PF('usuarioDialogCrear').hide()">
</p:commandButton>
</f:facet>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>

Primefaces, right way to use form tag

I have an xhtml in which I wrap two model dialogs in one form ( I wrap the whole body ). As a result when I try to submit the content on one dialog, I get validation errors from the other dialog.
When I seperate the forms for each dialog, I get warnings regarding I should wrap the whole content under one form ( or so I have interpreted ).
What is the correct way to use form tag both under this example and in general ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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:p="http://primefaces.org/ui">
<f:view>
<h:head>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf8"/>
</h:head>
<h:body id="templateBody">
<h:form id="userForm" prependId="false">
<p:messages id="mymessages" autoUpdate="true" showDetail="true"/>
<h:panelGrid columns="4" id="operationBtnsGrid">
<p:commandButton value="New" icon="ui-icon-plusthick" onclick="newDialog.show();"/>
<p:commandButton value="Update" update="dataTable" icon="ui-icon-pencil"
disabled="#{userController.userModels.selectedUser.id==null}"
onclick="updateDialog.show();"/>
<p:commandButton id="Delete" value="Delete" update="dataTable" onclick="confirmation.show()"
icon="ui-icon-trash" disabled="#{userController.userModels.selectedUser.id==null}"/>
</h:panelGrid>
<p:dataTable id="dataTable"
var="user"
value="#{userController.findAll()}"
rowKey="#{user.id}"
selectionMode="single"
selection="#{userController.userModels.selectedUser}">
<f:facet name="header">
<h:outputText value="User List"/>
</f:facet>
<p:ajax event="rowSelect" update="#(form)"/>
<p:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{user.name}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Lastname"/>
</f:facet>
<h:outputText value="#{user.lastname}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Phone Number"/>
</f:facet>
<h:outputText value="#{user.phoneNumber}"/>
</p:column>
</p:dataTable>
<p:dialog header="Add New User" widgetVar="newDialog" modal="true">
<p:panelGrid columns="2">
<h:outputLabel for="new_name" value="Name: "/>
<p:inputText id="new_name" required="true" value="#{userController.userModels.newUser.name}"/>
<h:outputLabel for="new_lastname" value="Lastname: "/>
<p:inputText id="new_lastname" required="true" value="#{userController.userModels.newUser.lastname}"/>
<h:outputLabel for="new_phoneNumber" value="Phone number: "/>
<p:inputMask id="new_phoneNumber" value="#{userController.userModels.newUser.phoneNumber}" mask="(999) 999-9999"/>
</p:panelGrid>
<p:panelGrid columns="1">
<p:captcha label="Captcha" language="en" theme="white"/>
</p:panelGrid>
<p:commandButton id="saveNewButton" actionListener="#{userController.addNewUser}"
oncomplete="confirmation.hide()" update="#(form), #(#mymessages)" value="Save"
ajax = "false" icon="ui-icon-check"/>
</p:dialog>
<p:dialog header="Update User" widgetVar="updateDialog" modal="true">
<p:panelGrid columns="2">
<h:outputLabel for="update_name" value="Name: "/>
<p:inputText id="update_name" required="true" value="#{userController.userModels.selectedUser.name}"/>
<h:outputLabel for="update_lastname" value="Lastname: "/>
<p:inputText id="update_lastname" required="true" value="#{userController.userModels.selectedUser.lastname}"/>
<h:outputLabel for="update_phoneNumber" value="Phone number: "/>
<p:inputMask id="update_phoneNumber" value="#{userController.userModels.selectedUser.phoneNumber}" mask="(999) 999-9999"/>
</p:panelGrid>
<p:commandButton id="updateSelectedButton" actionListener="#{userController.updateUser}"
oncomplete="confirmation.hide()" update="#(form), #(#mymessages)" value="Save"
ajax = "false" icon="ui-icon-check"/>
</p:dialog>
<p:confirmDialog id="confirmDialog" message="Silmek istediğinizden emin misiniz ?"
header="Silmek için onayınız gerekiyor" severity="alert" widgetVar="confirmation">
<p:commandButton id="confirm" value="Evet" oncomplete="confirmation.hide()"
actionListener="#{userController.deleteUser}"
ajax = "false" update="#(form), #(#mymessages)"/>
<p:commandButton id="decline" value="Hayır" onclick="confirmation.hide()" type="button"/>
</p:confirmDialog>
</h:form>
<p:ajaxStatus style="width:64px;height:64px;position:fixed;right:5px;bottom:5px">
<f:facet name="start">
<p:graphicImage value="/images/ajax-loader.gif" />
</f:facet>
<f:facet name="complete">
<h:outputText value="" />
</f:facet>
</p:ajaxStatus>
</h:body>
</f:view>
</html>
When you do a form submit it submits the whole form and all ids, you have them all on the page so they fail validations.
You can either:
A) Use 'rendered' on your div blocks to hide them from the dom based on conditions, but not likely due to you wanting to have an update/new - its kind of difficult.
B) use PPR (Partial Tree Processing)
http://www.primefaces.org/showcase/ui/pprPartialTree.jsf
On your commandbutton - add 'process="update_name, update_lastname, update_phoneNumber"'
This will only submit those fields to be updated, or if you wrap them in a block with an id you can just do process="blockToUpdate"

datatable selection is not updated when open dialog

i have an issue. I have one form and a dialog with another form inside. The second form has a datatable with radiobutton selection. When i open the dialog by first time, the selection is shown fine. I close the dialog. But when i try with another element, the selection on the datatable don't be updated.
The configuration that i use is:
Mojarra 2.2.4
Primefaces 4.0
But, if i use the Primefaces 3.5 version, it works.
I attach the xhtml files.
First file
<h:form id="formPlanificarCursos">
<p:outputPanel styleClass="pnlDeclaracionMessages">
<p:messages showSummary="true" />
</p:outputPanel>
<p:panel id="pnlPlanHorarioCurso" styleClass="pnlPlanHorarioCurso non-borders">
<components:titleSeparator title="Horarios de Curso" />
<!-- Toolbar -->
<p:outputPanel layout="block" styleClass="toolbar">
<p:commandLink id="btnAgregar" update="#(.dlgHorarioCurso)"
oncomplete="jQuery('.dlgHorarioCurso .ui-dialog-title').text('#{plan_msgs['planCurso.registrar.titulo']}'); dlgHorarioCurso.show();">
<h:graphicImage value="/resources/images/document_add.png" />
</p:commandLink>
<p:tooltip for="btnAgregar" value="Agregar Horario" />
</p:outputPanel>
<p:schedule id="scheduleCurso" minTime="6" value="#{detallePlanCursoBean.scheduleModel}" styleClass="scheduleCurso schedule-without-days"
allDaySlot="false" showHeader="false" view="agendaWeek" axisFormat="HH:mm" timeFormat="H:mm{ - H:mm}" aspectRatio="4" locale="es"
widgetVar="scheduleCurso">
<p:ajax event="eventSelect" listener="#{detallePlanCursoBean.onEventSelect}" update="#(.dlgHorarioCurso)"
oncomplete="jQuery('.dlgHorarioCurso .ui-dialog-title').text('#{plan_msgs['horarioCurso.modificar.titulo']}'); dlgHorarioCurso.show();" />
</p:schedule>
<f:facet name="footer">
<div class="div-botonera">
<p:commandButton id="btnAceptar" value="Aceptar" action="#{detallePlanCursoBean.registrarDetallePlanCurso}" />
<p:commandButton id="btnCancelar" value="Cancelar" action="#{detallePlanCursoBean.irConsultarPlanCurso}" immediate="true" />
</div>
</f:facet>
</p:panel>
</h:form>
<!-- Agregar Disponibilidad Horaria -->
<p:dialog widgetVar="dlgHorarioCurso" styleClass="dlgHorarioCurso" modal="true" resizable="false" closable="false">
<p:ajax event="close" listener="#{detallePlanCursoBean.cancelarHorarioCurso}" />
<ui:include src="/planificacion/horarioCurso.xhtml" />
</p:dialog>
Second file
<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:o="http://omnifaces.org/ui"
xmlns:components="http://java.sun.com/jsf/composite/components">
<h:form id="frmHorarioCurso">
<p:panel styleClass="pnlHorarioCurso non-borders">
<p:messages id="messagesfrmHorarioCurso" />
<components:titleSeparator title="Aula" />
<p:outputPanel id="pnlAulas" styleClass="pnlAulas" style="border-width:0px;">
<p:dataTable emptyMessage="No hay aulas para seleccionar." var="aula" id="grdAulas" styleClass="grdAulas"
value="#{detallePlanCursoBean.aulaModel}" selection="#{detallePlanCursoBean.detallePlanCursoDTO.aula}" rows="3" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
currentPageReportTemplate="({currentPage} de {totalPages})" paginatorPosition="bottom" paginatorAlwaysVisible="false" widgetVar="grdAulas">
<p:column selectionMode="single" style="width:15px;" />
<p:column headerText="Nombre">
<h:outputText value="#{aula.nombre}" />
</p:column>
<p:column headerText="Ubicación">
<h:outputText value="#{aula.locacion.nombre}" />
</p:column>
<p:column headerText="Capacidad" style="text-align:center;width:100px;">
<h:outputText value="#{aula.capacidad}" />
</p:column>
<p:column headerText="Accesibilidad" style="width:10%; text-align:center;">
<p:selectBooleanCheckbox value="#{aula.accesible}" disabled="true" />
</p:column>
</p:dataTable>
</p:outputPanel>
<f:facet name="footer">
<div class="div-botonera">
<p:commandButton value="Aceptar" action="#{detallePlanCursoBean.agregarHorarioCurso}" update="#(.pnlHorarioCurso)"
oncomplete="if(!args.validationFailed) HorarioCurso.handleComplete(xhr, status, args);" />
<p:commandButton value="Cancelar" oncomplete="scheduleCurso.update(); dlgHorarioCurso.hide();" update="#(.pnlHorarioCurso)" immediate="true"
action="#{detallePlanCursoBean.cancelarHorarioCurso}" />
</div>
</f:facet>
</p:panel>
</h:form>
I appreciate your help.
I was having a problem similar to this. I had a dialog which was being opened with information based on a pre-selected dataTable row, but the content of this dialog was not being updated after the first time it was opened.
I solved my problem by adding the attribute "process=#form" to my commandLink and in your case i think the update attribute should be update=":dlgHorarioCurso"

My p:dialog is never called

Well, my problem is that no dialog inside my main page is called. I.E: I have a commandButton should call "varDialogFindPacientes" but don't work. I don't know what can i do to fix it.
Look my main page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns: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">
<h:head>
</h:head>
<h:body>
<ui:composition>
<p:dialog id="dialogCadastrar" width="900px" height="500px"
header="Cadastrar Orçamento" widgetVar="varDialogCadastrar"
modal="true" showEffect="fade" hideEffect="fade">
<h:form id="formCadastrar">
<p:panelGrid id="panelGridCadastar" styleClass="semBorda"
columns="2">
<h:outputText value="Data Emissão: " />
<p:inputText id="dataEmissao"
value="#{orcamentoMB.orcamento.dataEmissao}" readonly="true">
<f:convertDateTime pattern="dd/MM/yyyy" />
</p:inputText>
<h:outputText value="Data Validade: " />
<p:inputText id="dataValidade"
value="#{orcamentoMB.orcamento.dataValidade}" readonly="true">
<f:convertDateTime pattern="dd/MM/yyyy" />
</p:inputText>
<h:outputText value="Situação " />
<p:inputText id="situacao"
value="#{orcamentoMB.orcamento.situacao.descricao}"
readonly="true" />
<h:outputText value="Desconto (%): " />
<p:panelGrid columns="2" styleClass="semBorda">
<pe:inputNumber value="#{orcamentoMB.orcamento.desconto}"
id="desconto" symbol=" %" symbolPosition="suffix"
validatorMessage="O desconto não pode ser maior que #{orcamentoMB.maxDesconto} %">
<f:validateDoubleRange maximum="#{orcamentoMB.maxDesconto}" />
</pe:inputNumber>
<p:commandButton value="Recalcular" process="desconto"
icon="ui-icon-refresh"
update=":formCadastrar:totalGeral, :formCadastrar:totalGeralComDesconto" />
</p:panelGrid>
<h:outputText value="Observação: " />
<p:inputTextarea value="#{orcamentoMB.orcamento.observacoes}"
rows="5" cols="30" />
<h:outputText value="Dentista: *" />
<p:panel style="border:1px solid #e5e5e5;">
<p:inputText required="true"
requiredMessage="Selecione um dentista"
value="#{orcamentoMB.orcamento.dentistaOrcou.pessoaFisica.nome}"
readonly="true" size="30" id="dentistaOrcou" />
<p:commandButton icon="ui-icon-search" type="button"
onclick="varDialogFindDentistas.show()" />
</p:panel>
<h:outputText value="Paciente *" />
<p:panel style="border:1px solid #e5e5e5;">
<p:inputText required="true"
requiredMessage="Selecione um paciente"
value="#{orcamentoMB.orcamento.paciente.pessoaFisica.nome}"
readonly="true" size="30" id="paciente" />
<p:commandButton icon="ui-icon-search" type="button"
onclick="varDialogFindPacientes.show()" />
</p:panel>
</p:panelGrid>
<p:toolbar>
<p:toolbarGroup align="left">
<p:commandButton value="Add" icon="ui-icon-plus"
onclick="varDialogFindItensTabela.show()" type="button"
update=":formCadastrar:dataTableItens, :formCadastrar:salvarAceitando,:formCadastrar:salvarSemAceitar, :formCadastrar:totalGeral,
:formCadastrar:totalGeralComDesconto" />
<p:commandButton value="Del" icon="ui-icon-minus"
disabled="#{orcamentoMB.selectedItemOrcamento == null}"
actionListener="#{orcamentoMB.delItemOrcamento}"
update=":formCadastrar:dataTableItens, :formCadastrar:totalGeral,
:formCadastrar:totalGeralComDesconto, :formCadastrar:salvarAceitando,:formCadastrar:salvarSemAceitar" />
</p:toolbarGroup>
</p:toolbar>
<p:dataTable rowKey="#{item}" var="item"
value="#{orcamentoMB.itens}"
emptyMessage="Não foi encontrado nenhum registro"
id="dataTableItens"
selection="#{orcamentoMB.selectedItemOrcamento}"
selectionMode="single" rowIndexVar="rowIndex"
rowStyleClass="#{(rowIndex mod 2) eq 0 ? 'first-row' : 'second-row'}">
<p:column headerText="Nome"
sortBy="#{item.itemTabelaProcedimento.procedimento.nome}"
id="nome">
<h:outputText
value="#{item.itemTabelaProcedimento.procedimento.nome}" />
</p:column>
<p:column headerText="Valor"
sortBy="#{item.itemTabelaProcedimento.valor}" id="valor">
<h:outputText value="#{item.itemTabelaProcedimento.valor}">
<f:convertNumber currencySymbol="R$ " type="currency" />
</h:outputText>
</p:column>
<p:column headerText="Local Aplicação"
sortBy="#{item.localAplicacao.descricao}" id="localAplicacao">
<h:outputText value="#{item.localAplicacao.descricao}" />
</p:column>
<p:column headerText="Dente" sortBy="#{item.dente.descricao}"
id="dente">
<h:outputText value="#{item.dente.descricao}" />
</p:column>
<p:column headerText="Face"
sortBy="#{item.faceAplicacao.descricao}" id="face">
<h:outputText value="#{item.faceAplicacao.descricao}" />
</p:column>
</p:dataTable>
<p:panelGrid columns="2">
<h:outputText value="Total Geral: " />
<h:outputText value="#{orcamentoMB.totalGeral}" id="totalGeral">
<f:convertNumber currencySymbol="R$ " type="currency" />
</h:outputText>
<h:outputText value="Total Com Desconto: " />
<h:outputText value="#{orcamentoMB.totalGeralComDesconto}"
id="totalGeralComDesconto">
<f:convertNumber currencySymbol="R$ " type="currency" />
</h:outputText>
</p:panelGrid>
<p:toolbar>
<p:toolbarGroup align="left">
<p:commandButton icon="ui-icon-disk" value="Salvar Sem Aceitar"
id="salvarSemAceitar" disabled="#{orcamentoMB.itens.size() == 0}"
actionListener="#{orcamentoMB.salvar}"
oncomplete="if (!args.validationFailed){ varDialogCadastrar.hide() }"
update=":formOrcamentos:dataTableOrcamentos">
<f:attribute name="salvarAceitando" value="false" />
</p:commandButton>
<p:commandButton icon="ui-icon-disk" value="Salvar Aceitando"
id="salvarAceitando" disabled="#{orcamentoMB.itens.size() == 0}"
actionListener="#{orcamentoMB.salvar}"
oncomplete="if (!args.validationFailed){ varDialogCadastrar.hide() }"
update=":formOrcamentos:dataTableOrcamentos">
<f:attribute name="salvarAceitando" value="true" />
</p:commandButton>
<p:commandButton value="Cancelar" icon="ui-icon-close"
onclick="varDialogCadastrar.hide()" type="button" />
</p:toolbarGroup>
</p:toolbar>
</h:form>
</p:dialog>
</ui:composition>
</h:body>
</html>
So, i'll show a page the is called for "varDialogFindPacientes"
<!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">
<h:head>
</h:head>
<h:body>
<ui:composition>
<p:dialog id="dialogFindPacientes" width="600px" height="auto"
header="Pesquisar Pacientes" widgetVar="varDialogFindPacientes"
modal="true" showEffect="fade" hideEffect="fade">
<h:form id="formFindPacientes">
<p:dataTable rowKey="#{paciente.id}" var="paciente"
value="#{orcamentoMB.pacientes}" paginator="true"
emptyMessage="Não foi encontrado nenhum registro" rows="20"
id="dataTablePacientes" selection="#{orcamentoMB.selectedPaciente}"
selectionMode="single" rowIndexVar="rowIndex"
rowStyleClass="#{(rowIndex mod 2) eq 0 ? 'first-row' : 'second-row'}"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}">
<p:ajax event="rowDblselect" process="dataTablePacientes"
listener="#{orcamentoMB.updatePacienteFromFind}"
oncomplete="dialogFindPacientes.hide()"
update=":formCadastrar:paciente" />
<p:column headerText="Nome" sortBy="#{paciente.pessoaFisica.nome}"
filterBy="#{paciente.pessoaFisica.nome}" id="nome"
filterMatchMode="contains">
<h:outputText value="#{paciente.pessoaFisica.nome}" />
</p:column>
</p:dataTable>
</h:form>
</p:dialog>
</ui:composition>
</h:body>
</html>
EDIT 1:
I have another problem yet, the #PostConstruct from my ManagedBean is called every ajax call.

p:dataTable never refreshes after a delete, update or insert

Well, I have a p:dialog that inserts a new Entity, but after this entity is saved into database the p:dataTable remains the same, the new row doesn't appear.
Look at my p:dialog:
<!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">
<h:head>
</h:head>
<h:body>
<ui:composition>
<h:form id="formCadastrar">
<p:dialog width="900px" height="500px" header="Cadastrar Dentista"
widgetVar="dialogCadastrar" modal="true">
<p:panelGrid columns="2" styleClass="semBorda">
<p:commandButton icon="ui-icon-disk" value="Salvar"
actionListener="#{dentistaMB.salvar}"
update=":formDentistas:dataTableDentistas" />
<p:commandButton value="Cancelar" icon="ui-icon-close"
onclick="confirmCancelar.show()" type="button" />
</p:panelGrid>
<p:panelGrid id="panelGridCadastar" styleClass="semBorda"
columns="2">
<h:outputText value="Nome: *" />
<p:inputText id="nome"
value="#{dentistaMB.dentista.pessoaFisica.nome}" size="40"
required="true" requiredMessage="O Nome do Dentista é obrigatório">
</p:inputText>
<h:outputText value="CRO *" />
<p:inputText id="cro" value="#{dentistaMB.dentista.cro}" size="10"
required="true" requiredMessage="O Número do CRO é obrigatório" />
</p:panelGrid>
<p:panelGrid columns="2" styleClass="semBorda">
<p:commandButton icon="ui-icon-disk" value="Salvar"
actionListener="#{dentistaMB.salvar}"
update=":formDentistas:dataTableDentistas" />
<p:commandButton value="Cancelar" icon="ui-icon-close"
onclick="confirmCancelar.show()" />
</p:panelGrid>
<p:confirmDialog id="confirmCancelar" message="Deseja cancelar ?"
showEffect="fade" hideEffect="fade" header="Cancelar"
severity="alert" widgetVar="confirmCancelar" appendToBody="true">
<p:commandButton value="Sim" oncomplete="confirmCancelar.hide()"
actionListener="#{dentistaMB.cancelar}" />
<p:commandButton value="Não" onclick="confirmCancelar.hide()"
type="button" />
</p:confirmDialog>
</p:dialog>
</h:form>
</ui:composition>
</h:body>
</html>
And look at my p:dataTable
<h:form id="formDentistas">
<p:growl autoUpdate="true" id="growlmessages" />
<p:dataTable rowKey="#{dentista.id}" var="dentista" value="#{dentistaMB.dentistas}"
paginator="true" emptyMessage="Não foi encontrado nenhum registro"
rows="10" id="dataTableDentistas"
selection="#{dentistaMB.selectedDentista}" selectionMode="single">
<f:facet name="header">Lista de Dentistas</f:facet>
<p:column headerText="Nome" sortBy="nome" filterBy="nome" id="nome"
width="200px">
#{dentista.pessoaFisica.nome}
</p:column>
<p:column headerText="Data Nascimento" sortBy="dataNascimento"
filterBy="dataNascimento" id="dataNascimento" width="60px">
#{dentista.pessoaFisica.dataNascimento}
</p:column>
<p:column headerText="CRO" sortBy="cro" filterBy="cro" id="cro"
width="60px">
#{dentista.cro}
</p:column>
<f:facet name="footer">
<div class="align_text_left">
<p:commandButton icon="ui-icon-plus" value="Novo" id="cadastrar"
oncomplete="dialogCadastrar.show()" />
<p:column headerText="Ações" style="width:50px;">
<p:commandButton value="Alterar" icon="ui-icon-pencil" />
<p:commandButton value="Remover" icon="ui-icon-trash"
action="#{dentistaMB.deletar}"
update=":formDentistas:dataTableDentistas" />
</p:column>
</div>
</f:facet>
</p:dataTable>
</h:form>
So, what's the correct form to update the p:dataTable after a change in an entity? This example above is about an insert, but remove doesn't work either. I used the following code:
<p:commandButton value="Remover" icon="ui-icon-trash"
action="#{dentistaMB.deletar}"
update=":formDentistas:dataTableDentistas" />
in your dialog you must add an ajax event to fire update of form like:
<p:ajax event="close" listener="#{dentistaMB.load}"
update=":formDentistas" immediate="true" global="false" />
this will allow you to reload your table feed lists.
in your load method you need to update (refetch data from db) dentistas list. If you are using filtering do not forget to update your filtering list as well.
In managedbean load function you can use:
public void load(){
dentistas.clear();
filteredDentistas.clear();
dentistas.addAll(getDentistService().getDentists());
filteredDentistas.addAll(getDentistService().getDentists());
}

Resources