JQuery loaded JSF page doesn't update parent page (Primefaces) - jsf

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;
}
}

Related

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

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>

Refresh dialog in primefaces

I am building an application where it is necessary to register a user, more precisely a picture for a user besides his name, username and some other information, when the registration window is show, a default user image is load, then when they select a new image the default image dissapear and the selected one is displayed on the window, and a new button is displayed as well, this button allows the user to remove the selected picture, so the default image must be display again, but I still can't display again the default picture in case de button is clicked to return to the default picture and remove the selected one
View where users are listed and the modal window is displayed
<?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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="/sesionAdmin/_admintmp.xhtml">
<ui:define name="body">
<h:head>
<h:outputScript library="js" name ="Calendario.js"/>
</h:head>
<h:body>
<h:form>
<p:commandButton id="createButton" value="Registrar usuario"
onclick="PF('UsuarioCreateDialog').show()">
</p:commandButton>
</h:form>
<p:separator/>
<h:form id="UsuarioListForm">
<p:panelGrid columns="2" styleClass="panelgrid">
<p:outputLabel style="font-weight: bold;" value="Buscar usuario:" />
<p:inputText placeholder="Digite nombres, apellidos, nombre de usuario o email"
style="width: 350px;" value="#{usuarioController.datoBusqueda}" >
<p:ajax event="keyup" update="datalist" listener="#{usuarioController.buscarUsuario()}" />
</p:inputText>
</p:panelGrid>
<p:dataTable id="datalist" value="#{usuarioController.items}" var="item"
paginator="true" widgetVar="tablaUsuarios"
rows="10"
rowsPerPageTemplate="10,20"
>
<f:facet name="header">
</f:facet>
<p:column >
<f:facet name="header">
<h:outputText value="Nombres"/>
</f:facet>
<h:outputText value="#{item.usunombres}"/>
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="Apellidos"/>
</f:facet>
<h:outputText value="#{item.usuapellidos}"/>
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="Nombre de usuario"/>
</f:facet>
<h:outputText value="#{item.usunombreusuario}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Email"/>
</f:facet>
<h:outputText value="#{item.usuemail}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Cargo"/>
</f:facet>
<h:outputText value="#{item.carid.carnombre}"/>
</p:column>
<p:column width="70" style="text-align: center">
<f:facet name="header">
<h:outputText value="Foto" />
</f:facet>
<p:graphicImage id="imgUsuario" value="#{usuarioController.imagenFlujo}" width="50" height="50" >
<f:param name="id" value="#{item.usuid}" />
</p:graphicImage>
</p:column>
<p:column style="width: 90px">
<f:facet name="header">
<p:outputLabel value="Acciones"/>
</f:facet>
<p:commandButton id="viewButton" icon="ui-icon-search" action="#{usuarioController.seleccionarUsuarioVer(item)}" update=":UsuarioViewForm, :formfotoView" oncomplete="PF('UsuarioViewDialog').show()" />
<p:commandButton id="editButton" icon="ui-icon-pencil" action="#{usuarioController.seleccionarUsuarioEditar(item)}" update=":UsuarioEditForm, :formEditarfoto" oncomplete="PF('UsuarioEditDialog').show()" />
</p:column>
</p:dataTable>
</h:form>
<ui:include src="RegistrarUsuario.xhtml"/>
<ui:include src="EditarUsuario.xhtml"/>
<ui:include src="VerInfoUsuario.xhtml"/>
<p:dialog header="Información" modal="true" position="center" widgetVar="mensajeRegistroExitoso" closable="false">
<p:messages style="font-size: 15px;" showDetail="true" autoUpdate="true"/>
<h:form>
<p:commandButton value="Aceptar" style="font-weight: normal;"
onclick="PF('mensajeRegistroExitoso').hide()"/>
</h:form>
</p:dialog>
</h:body>
</ui:define>
</ui:composition>
</html>
User dialog window
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:composition>
<p:dialog id="UsuarioCreateDlg" widgetVar="UsuarioCreateDialog" modal="true" resizable="false"
appendTo="#(body)" header="Registrar usuario">
<h:outputStylesheet name="css/appearUploadFile.css" />
<p:ajax event="close" listener="#{usuarioController.cancelarRegistroUsuario()}"/>
<p:outputLabel style="float: right;" value="  Campos obligatorios" />
<p:outputLabel style="float: right; font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
<br/>
<!--h:form id="formfoto" enctype="multipart/form-data"-->
<center>
<p:outputLabel style="font-weight:bold;" value="Foto de perfil" />
</center>
<center>
<br/>
<p:graphicImage rendered="#{usuarioController.miImagen ==null}"
style="height:100px; width:100px;"
value="#{usuarioController.imagenDefecto}"/>
<p:graphicImage rendered="#{usuarioController.miImagen !=null}"
id="img"
style="height:100px; width:100px;"
value="#{usuarioController.miImagen}"
cache="false"/>
<p:fileUpload mode="advanced" auto="true" fileUploadListener="#{usuarioController.convertirImagenABytes}"
allowTypes="/(\.|\/)(jpe?g|png)$/" sizeLimit="10000000" invalidFileMessage="El archivo no está en el formato válido"
required="true"
update="#form" multiple="false" label="Subir imagen">
</p:fileUpload>
<h:commandLink rendered="#{usuarioController.miImagen !=null}"
value="Imagen por defecto"
actionListener="#{usuarioController.establecerFotoPorDefecto()}"
>
<f:ajax execute="#all" render="#form"/>
<p:ajax update="UsuarioCreateDlg"/>
</h:commandLink>
</center>
<br/>
<!--/h:form-->
<h:form id="UsuarioCreateForm">
<p:panelGrid styleClass="panelgrid" id="panel2">
<p:row>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Nombres:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:inputText id="usunombres" value="#{usuarioController.selected.usunombres}"
title="#{bundleAdmin.CreateUsuarioTitle_usunombres}" required="true"
requiredMessage="Campo obligatorio">
<f:validator validatorId="ValidarCampo75Caracteres"/>
<p:ajax event="keyup" update="msgCaracteresNombre"/>
</p:inputText>
</p:column>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Apellidos:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:inputText id="usuapellidos" value="#{usuarioController.selected.usuapellidos}"
title="#{bundleAdmin.CreateUsuarioTitle_usuapellidos}" required="true"
requiredMessage="Campo obligatorio">
<f:validator validatorId="ValidarCampo75Caracteres"/>
<p:ajax event="keyup" update="msgCaracteresApellido"/>
</p:inputText>
</p:column>
</p:row>
<p:row>
<p:column>
</p:column>
<p:column>
<p:message id="msgCaracteresNombre" for="usunombres"/>
</p:column>
<p:column>
</p:column>
<p:column>
<p:message id="msgCaracteresApellido" for="usuapellidos"/>
</p:column>
</p:row>
<p:row>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Genero:" />
</p:column>
<p:column>
<p:selectOneRadio value="#{usuarioController.selected.usugenero}">
<f:selectItem itemLabel="Masculino" itemValue="M" />
<f:selectItem itemLabel="Femenino" itemValue="F" />
</p:selectOneRadio>
</p:column>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Fecha de nacimiento:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:calendar id="usufechanacimiento"
placeholder="dd/mm/aaaa" pattern="dd/MM/yyyy"
value="#{usuarioController.selected.usufechanacimiento}"
title="#{bundleAdmin.EditUsuarioTitle_usufechanacimiento}"
required="true"
readonlyInput="true"
requiredMessage="Campo obligatorio"
showOn="button"
navigator = "true"
locale="es"
maxdate="#{usuarioController.fechaHoy}">
<p:ajax event="keyup" update="msgUsuFechaNacimiento"/>
<p:ajax event="dateSelect" update="msgUsuFechaNacimiento"/> </p:calendar>
</p:column>
</p:row>
<p:row>
<p:column>
</p:column>
<p:column>
</p:column>
<p:column>
</p:column>
<p:column>
<p:message id="msgUsuFechaNacimiento" for="usufechanacimiento"/>
</p:column>
</p:row>
<p:row>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Email:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:inputText id="usuemail" value="#{usuarioController.selected.usuemail}"
title="#{bundleAdmin.CreateUsuarioTitle_usuemail}"
required="true" requiredMessage="Campo obligatorio">
<f:validator validatorId="ValidarCampoCorreoElectronico"/>
<p:ajax event="keyup" update="msgCaracteresEMail"/>
</p:inputText>
</p:column>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Cargo:" />
</p:column>
<p:column>
<p:selectOneMenu id="carid" value="#{usuarioController.cargo}" >
<f:selectItems value="#{cargoController.itemsAvailableSelectOne}"
var="caridItem"
itemValue="#{caridItem}"
itemLabel="#{caridItem.carnombre}"
/>
<f:validator validatorId="ValidarCamposSeleccionar"/>
</p:selectOneMenu>
</p:column>
</p:row>
<p:row>
<p:column>
</p:column>
<p:column>
<p:message id="msgCaracteresEMail" for="usuemail"/>
</p:column>
<p:column>
</p:column>
<p:column>
<p:message for="carid"/>
</p:column>
</p:row>
<p:row>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Tipo de usuario:" />
</p:column>
<p:column>
<p:selectOneMenu id="grupoId" value="#{usuarioController.grupo.gruid}" >
<p:ajax event="change" update="grupoId"/>
<f:selectItems value="#{grupoController.itemsAvailableSelectOne}"
var="grupo"
itemValue="#{grupo.gruid}"
itemLabel="#{grupo.grudescripcion}"
>
</f:selectItems>
<f:validator validatorId="ValidarCamposSeleccionar"/>
</p:selectOneMenu>
</p:column>
</p:row>
<p:row>
<p:column>
</p:column>
<p:column>
<p:message for="grupoId"/>
</p:column>
</p:row>
<p:row>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Nombre de usuario:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:inputText id="usunombreusuario" value="#{usuarioController.selected.usunombreusuario}"
title="#{bundleAdmin.CreateUsuarioTitle_usunombreusuario}" required="true"
requiredMessage="Campo obligatorio">
<f:validator validatorId="ValidarCampoNombreUsuario"/>
<p:ajax event="keyup" update="msgCaracteresNombreUsuario"/>
</p:inputText>
</p:column>
<p:column>
<p:outputLabel style="font-weight:bold;" value="Contraseña:" />
<p:outputLabel style="font-style: italic; font-size: 16px; text-align: left; color: red;" value="* " />
</p:column>
<p:column>
<p:password id="usucontrasena" value="#{usuarioController.selected.usucontrasena}"
title="#{bundleAdmin.CreateUsuarioTitle_usucontrasena}"
required="true" requiredMessage="Campo obligatorio"/>
</p:column>
</p:row>
<p:row>
<p:column>
</p:column>
<p:column>
<p:message id="msgCaracteresNombreUsuario" for="usunombreusuario"/>
</p:column>
<p:column>
</p:column>
<p:column>
<p:message for="usucontrasena"/>
</p:column>
</p:row>
</p:panelGrid>
<p:separator/>
<center>
<p:commandButton action="#{usuarioController.registrarUsuario()}"
value="Registrar" update=":UsuarioListForm:datalist, panel2"
/>
</center>
</h:form>
</p:dialog>
</ui:composition>
</html>
User controller
public class UsuarioController implements Serializable {
#EJB
private com.unicauca.coordinacionpis.sessionbean.UsuarioFacade ejbUsuario;
#EJB
private UsuariogrupoFacade ejbUsuarioGrupo;
private List<Usuario> items = null;
private Cargo cargo;
private Grupo grupo;
private List<Usuario> filtroBusqueda;
private boolean campoFoto;
private boolean campoContrasena;
private String contrasena;
private String datoBusqueda;
private Usuario usuario;
private UploadedFile file;
private SimpleDateFormat formatoFecha;
private byte[] imagen;
private DefaultStreamedContent miImagen;
private UploadedFile uploadedFile;
public StreamedContent getImagenDefecto(){
return Utilidades.getImagenPorDefecto("foto");
}
public StreamedContent getImagen(Usuario usuario) {
RequestContext requestContext = RequestContext.getCurrentInstance();
FacesContext context = FacesContext.getCurrentInstance();
String id = context.getExternalContext().getRequestParameterMap().get("idUsu");
if (usuario.getUsufoto() == null) {
return Utilidades.getImagenPorDefecto("foto");
} else {
return new DefaultStreamedContent(new ByteArrayInputStream(usuario.getUsufoto()));
}
}
public void establecerFotoPorDefecto()
{
System.out.println("Hallo");
this.miImagen = null;
RequestContext requestContext = RequestContext.getCurrentInstance();
//requestContext.execute("PF('UsuarioCreateDialog').hide()");
//requestContext.execute("PF('UsuarioCreateDialog').show()");
//this.imagenPorDefecto();
}
public DefaultStreamedContent getMiImagen() {
convertirBytesAImagen();
/*if(miImagen==null)
miImagen = Utilidades.getImagenPorDefecto("foto");*/
return miImagen;
}
public void convertirBytesAImagen()
{
if(imagen != null)
{
InputStream is = new ByteArrayInputStream((byte[]) imagen);
miImagen = new DefaultStreamedContent(is, "image/png");
}
}
}
The method I am calling to set the default picture is establecerFotoPorDefecto()

Calling two dialog and save in two methods in JSF

I have two buttons and two dialog, each button calls a dialog, each dialog has a save button, you send two different methods in the Bean. The problem is that it only works sending a dialog and not the other.
xhtml
<h:form id='form1'>
<p:panel id="basic" header="#{usuarioBean.nompagina}" footer="" style="margin-bottom:20px">
<p:panelGrid columns="3" style="width: 100%">
<p:commandButton value="Nuevo" icon="ui-icon-document" actionListener="#{menuBean.setAccion('Registrar')}" type="button" onclick="PF('dlg').show();" update=":dialog"/>
</p:panelGrid>
.......
<p:column headerText="Acción">
<p:commandButton value="Asignar Rol" actionListener="#{usuarioBean.leerUsuario(rowusu)}" oncomplete="PF('wdatosvar').show()" update=":wdatosid" icon="ui-icon-person"/>
</p:column>
</p:dataTable>
</p:panel>
</h:form>
<p:dialog position="center top" styleClass="ui-widget-container" id="dialog" header="Usuarios" widgetVar="dlg" dynamic="true" modal="true" width="400">
<h:form>
<p:panelGrid columns="2">
...
<p:commandButton value="Guardar" actionListener="#{usuarioBean.inUsuario()}" oncomplete="handleDialogSubmit2(args)" update=":form1:listusuario" icon="ui-icon-check" />
<p:commandButton value="Cancelar" immediate="true" onclick="PF('dlg').hide();" icon="ui-icon-cancel" />
<p:outputLabel id="refresc" />
</p:panelGrid>
</h:form>
</p:dialog>
<p:dialog header="Datos" position="center top" widgetVar="wdatosvar" id="wdatosid" modal="true" showEffect="explode" hideEffect="explode">
<h:form>
<h:panelGrid columns="2">
...
<p:commandButton value="Guardar" actionListener="#{usuarioBean.saveUsuario()}" oncomplete="handleDialogSubmit(xhr, status, args)" update=":form1:listusuario,#form,refrescar" icon="ui-icon-check" />
<p:commandButton value="Cancelar" immediate="true" onclick="PF('wdatosvar').hide();" icon="ui-icon-cancel" />
<p:outputLabel id="refrescar" />
</h:panelGrid>
</h:form>
</p:dialog>
And usuarioBean.java
#ManagedBean
#SessionScoped
public class usuarioBean {
public void saveUsuario() throws Exception {
usuariohistorialDAO dao = new usuariohistorialDAO();
try {
dao.insertCredencial(usuariohis,value1);
this.listarUsuarios(palabra);
} catch (Exception e) {
throw e;
}
}
public void inUsuario() throws Exception{
usuariohistorialDAO dao = new usuariohistorialDAO();
try {
dao.insertarUsuario(usuariohis);
this.listarUsuarios(palabra);
} catch (Exception e) {
throw e;
}
}
}
inUsuario does no work.
Do not know exactly why but this form solves my problem
<h:form id='form1'>
<p:panel id="basic" header="Lista de Usuarios" footer="" style="margin-bottom:20px">
<p:panelGrid columns="3" style="width: 100%">
<p:commandButton value="Nuevo" icon="ui-icon-document" oncomplete="PF('dlg').show()" update=":dialog"/>
</p:panelGrid>
<p:inputText value="#{usuarioBean.palabra}" id="search" class="inputmediano"/>
<p:commandButton value="Buscar" icon="ui-icon-refresh" actionListener="#{usuarioBean.bucarUsuario()}" update="listusuario"/>
<p:dataTable tableStyleClass="ui-table-columntoggle" var="rowusu" value="#{usuarioBean.arrayusu}" paginator="true" paginatorPosition="bottom" rows="30" id="listusuario" style="width: 100%;margin-top: 10px" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">
<p:column headerText="Id" style="width: 25px">
<h:outputText value="#{rowusu.ush_id}"/>
</p:column>
<p:column headerText="Usuario" >
<h:outputText value="#{rowusu.usu_nombre}"/>
</p:column>
<p:column headerText="Sexo" >
<h:outputText value="#{rowusu.usu_sexo}"/>
</p:column>
<p:column headerText="Nick">
<h:outputText value="#{rowusu.ush_correo}" />
</p:column>
<p:column headerText="Rol">
<h:outputText value="#{rowusu.nomrol}"/>
</p:column>
<p:column headerText="Cargo">
<h:outputText value="#{rowusu.nomcargo}"/>
</p:column>
<p:column headerText="Acción">
<p:commandButton value="Asignar Rol" actionListener="#{usuarioBean.leerUsuario(rowusu)}" oncomplete="PF('wdatosvar').show()" update=":wdatosid" icon="ui-icon-person"/>
<p:commandButton value="Modificar" actionListener="#{usuarioBean.leerUsuario(rowusu)}" oncomplete="PF('dlg').show()" update=":dialog" icon="ui-icon-person"/>
</p:column>
</p:dataTable>
</p:panel>
</h:form>

Avoid refresh the whole page after submit

in the code below there is a form with the name of FormData where every time I submit the data, it updates the entire page. I wish this did not happen when submit the data, it would execute the action q without refreshing the whole page. This behavior is normal or I'm doing something wrong?
My code:
<ui:decorate template="/resources/Template.xhtml">
<ui:define id="content" name="content">
<p:growl id="war"/>
<style type="text/css">
.ok{
color: #336600
}
.erro{
color: #D20005;
}
</style>
<div style="width: 90%; margin-left: auto; margin-right: auto; ">
<br/>
<br/>
<p:panel>
<f:facet name="header">
Lista de Arquivos Armazenados
</f:facet>
<h:form id="pesquisar">
<p:toolbar style="width: 100%;">
<p:toolbarGroup align="left" >
<h:panelGrid columns="1" cellpadding="0">
</h:panelGrid>
</p:toolbarGroup>
<p:toolbarGroup align="right">
<h:panelGrid columns="5" cellpadding="0">
<h:outputLabel value="De: "/>
<p:inputMask mask="99/99/9999" value="#{arquivoBean.dataInicial}" size="10"/>
<h:outputLabel value="Até: "/>
<p:inputMask mask="99/99/9999" value="#{arquivoBean.datafinal}" size="10"/>
<p:commandButton value="Buscar" action="#{arquivoBean.listar()}" ajax="false"/>
<br/>
<p:selectBooleanCheckbox id="check" value="#{arquivoBean.pendente}"
itemLabel="Pendente">
<p:ajax process="#this" event="change" listener="#{arquivoBean.listarPendente()}" />
</p:selectBooleanCheckbox>
</h:panelGrid>
</p:toolbarGroup>
</p:toolbar>
</h:form>
</p:panel>
<br/>
<p:dataTable id="dataTable"
var="Arquivo"
paginator="true"
paginatorPosition="bottom"
rowsPerPageTemplate="100"
rows="100"
sortBy="#{Arquivo.id}"
value="#{arquivoBean.dataModelArquivo}"
rowStyleClass="#{Arquivo.pendente eq 1 ? 'ok' : 'erro'}"
emptyMessage="Você ainda não ativou uma empresa ou não existe postagem para esta Empresa">
<p:column headerText="ID">
#{Arquivo.id}
</p:column>
<p:column headerText="Nome">
#{Arquivo.nomeMury}
</p:column>
<p:column headerText="Envio">
#{Arquivo.dataEnvio}
</p:column>
<p:column headerText="Produto" width="10px;">
<h:form id="formProduto">
<p:commandButton icon="ui-icon-circle-zoomout" value=""
action="#{arquivoBean.listarProdutoPorArquivo()}"
oncomplete="prodDialog.show()"
onclick="listarProd([{name: 'ArquivoId', value:#{Arquivo.id}}]);">
<f:setPropertyActionListener value="#{Arquivo}" target="#{arquivoBean.arquivo}"/>
</p:commandButton>
<p:remoteCommand name="listarProd" action="#{arquivoBean.listarProdutoPorArquivo()}" update=":formDataTable:dataTableProd">
<f:setPropertyActionListener value="#{Arquivo}" target="#{arquivoBean.arquivo}"/>
</p:remoteCommand>
</h:form>
</p:column>
<p:column headerText="Data" width="10px;">
<h:form id="formData">
<p:inputMask id="entrada#{cc.clientId}" mask="99/99/9999" value="#{Arquivo.dataEntrada}"
onkeypress="if (event.keyCode === 13) {
test([{name: 'rowIndex', value:#{Arquivo.id}}]);
return;
}"
size="8">
<f:convertDateTime pattern="dd/MM/yyyy" type="date" timeZone="GMT-03:00"/>
</p:inputMask>
<p:remoteCommand name="test" action="#{arquivoBean.inserirDataNota()}">
<f:setPropertyActionListener value="#{Arquivo}" target="#{arquivoBean.arquivo}"/>
</p:remoteCommand>
</h:form>
</p:column>
</p:dataTable>
<h:form id="formDataTable">
<p:dialog closeOnEscape="true"
widgetVar="prodDialog"
modal="true"
header="Lista de Produtos da NF-e"
style="width: 300; height: 500"
position="center">
<p:dataTable
id="dataTableProd"
var="XmlItens"
paginator="true"
paginatorPosition="bottom"
rowsPerPageTemplate="10"
rows="10"
value="#{arquivoBean.listaProd}">
<p:column headerText="ID">
#{XmlItens.id}
</p:column>
<p:column headerText="Nome">
#{XmlItens.descricaoProd}
</p:column>
<p:column headerText="Envio">
#{XmlItens.chaveNfe}
</p:column>
</p:dataTable>
</p:dialog>
</h:form>
</div>
</ui:define>
</ui:decorate>
First: The method on your managedBean must be void or return a String null
Second: you must write which ones components do you want to update after de action works.
Like primefaces example:
https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml

PrimeFaces dataTable not updating after Ajax request

I'm currently working with a PrimeFaces dataTable and am trying endlessly to append a new to the dataTable immediately after the user adds it. Server-side, everything is working -- data is saved to both the database and hard disk. I'd like to see a partial-page update following the successful request, and I just can't seem to get it to work. Here is my XHTML code:
<div class="content">
<div id="mainContent">
<div class="topNav">
<h:form id="navForm">
<p:commandButton value="Upload"/>
<p:commandButton value="New Folder" onclick="createDlg.show();" />
<p:commandButton value="Delete Folder" action="#" />
</h:form>
</div>
<div id="filePanel">
<h:form id="dataTable" prependId="false">
<p:dialog header="Create" widgetVar="createDlg" modal="true" height="200">
<p:panel header="New Folder">
<h:panelGrid columns="2">
<h:outputLabel value="Name:" for="txt_name"></h:outputLabel>
<p:inputText id="txt_name" value="#{directoryController.newDir.name}" required="true" />
<p:commandButton value="Create" actionListener="#{directoryController.createNew}" update="dGrid" oncomplete="createDlg.hide();"/>
<p:ajaxStatus style="width:16px; height:16px;">
<f:facet name="start">
<h:outputText value="Saving..." />
</f:facet>
<f:facet name="">
<h:outputText value="Complete." />
</f:facet>
</p:ajaxStatus>
</h:panelGrid>
</p:panel>
</p:dialog>
<p:dataTable id="dGrid" value="#{directoryController.itemsByOwner}" var="dir">
<p:column selectionMode="multiple"/>
<p:column sortBy="#{dir.name}">
<f:facet name="header">
File Name
</f:facet>
<h:outputText value="#{dir.name}" />
</p:column>
<p:column>
<f:facet name="header">
File Size
</f:facet>
</p:column>
</p:dataTable>
</h:form>
</div>
</div>
</div>
And finally, here is my backing bean.
public String createNew(){
newDir.setDateCreated(new Date());
newDir.setDateModified(new Date());
newDir.setId(BigDecimal.ZERO);
newDir.setLocation(ROOT_DIRECTORY + currentUser.getUsername() + "/");
newDir.setFilesCollection(f);
newDir.setDescription("");
newDir.setOwner(currentUser);
current = newDir;
create();
persistDirectoryFromObject(newDir);
newDir = new Directory();
RequestContext.getCurrentInstance().addPartialUpdateTarget("dGrid");
return null;
}
If you are using 3.0.M4 you could do:
...
...
<p:outputPanel autoUpdate="true">
<p:dataTable id="dGrid" value="#{directoryController.itemsByOwner}" var="dir">
<p:column selectionMode="multiple"/>
<p:column sortBy="#{dir.name}">
<f:facet name="header">
File Name
</f:facet>
<h:outputText value="#{dir.name}" />
</p:column>
<p:column>
<f:facet name="header">
File Size
</f:facet>
</p:column>
</p:dataTable>
</p:outputPanel>
or you could simply:
<p:commandButton value="Create" action="#{directoryController.createNew}" oncomplete="createDlg.hide();" ajax="false" />

Resources