AJAX creates 15 queries in db - primefaces

I have a simple datatable with cell editing in primefaces. It works, but, first, does not create JavaScript message, second, it creates 15 identically queries to db. (i can see that in hibernate console)
Code is token from official site:
<h:form id="form">
<p:growl id="messages" showDetail="true"/>
<p:contextMenu for="clients" widgetVar="cMenu">
<p:menuitem value="Edit Cell" icon="ui-icon-search" onclick="clientsTable.showCellEditor();return false;"/>
<p:menuitem value="Hide Menu" icon="ui-icon-close" onclick="cMenu.hide()"/>
</p:contextMenu>
<p:dataTable id="clients" var="client" value="#{clientsBean.clients}" paginator="true" rows="5"
editable="true" editMode="cell" widgetVar="clientsTable">
<p:ajax event="cellEdit" listener="#{clientsBean.onCellEdit}" update=":form:messages"/>
<p:column headerText="Name" style="width:25%">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{client.name}"/></f:facet>
<f:facet name="input"><p:inputText id="nameInput" value="#{client.name}"
style="width:96%"/></f:facet>
</p:cellEditor>
</p:column>
So, when i edit some info and press Enter, it creates 15 queries and does not show JS message.
Bean's getClients() is a simple hibernate query (works fine), and onCellEdit() looks like
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Also new strange bug apperead : oldValue and newValue in that bean are always same.

Related

How to set null value selectone menu jsf

I am using PrimeFaces 5.1 , I have a field Cumulative indicator which is a select drop down wit Y/N/select, when I update the value to Y/N the edit/update is happening fine, but when I chose select as the drop down value it does not update it to null. I am able to set the value to null from the backend. When I chose select as the drop down value it should update to null instead it shows the previous value(Y/N) that is saved in the database. The below is my code xhtml, java bean and the update query. Please advice why its not updating the value to null value.
I tried putting the drop down value itemValue="#{null}" but that didn't work as mentioned in this post How to save Null value with selectone dropdown
Below is my xhtml:
<p:column headerText="Cumulative Indicator" width="60">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#
{AcctRefRecord.cumIndicator}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{AcctRefRecord.cumIndicator}"
label="Cumulative Indicator">
<f:selectItem
itemLabel="--Select--" itemValue="" />
<f:selectItem
itemValue="Y" />
<f:selectItem
itemValue="N" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:dataTable id="dtable" var="AcctRefRecord"value="#
{AcctRefMBean.
AcctRefRecords}" editable="true"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink}
{PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}
{RowsPerPageDropdown}" >
<p:ajax event="rowEdit" listener="#
{AcctRefMBean.onRowEdit}" update=":dtableform:msgs" resetValues="true"/>
<p:ajax event="rowEditCancel" listener="#
{AcctRefMBean.onRowCancel}" update=":dtableform:msgs"/>
Below is my javaBean:
//retrive the record/row of type
AcctRefTo on which edit even occurred
AcctRefTo to = (AcctRefTo)
event.getObject();
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
facesContext.getExternalContext().getSession(false);
String userId = (String)
session.getAttribute(WebAppConstants.CURRENT_USER_ID);
if (userId == null) {
userId = WebAppConstants.DEFAULT_CURRENT_USER_ID;
}
to.setUpdatedByUserID(userId);
updateRecord(to);
FacesMessage msg = new FacesMessage("Reference Data Updated for Account#"
+ to.getAcctNbr());
FacesContext.getCurrentInstance
().addMessage("null", msg);
}
/**
* #param to
* updates the given to in DB accordingly
*/
public void updateRecord(AcctRefTo to) {
jetSessionFacadebean.updateAccntRef(to);
}
Below is my updateQuery:
<key><value>updateAcctgRef</value></key>
<value>
update acct_ref set
cd_val=?,
dt_eff_end=?,
ind_bal=?,
ind_bal_acct_type=?,
ind_cum=?,
ind_net=?,
ind_net__bal_type=?,
ind__rcn=?,
ind_b=?,
nbr_gl_acct_yeb_offst=?,
nbr_gl_acct_net_unam_bal=?,
cd_fee_cat_type=?,
id_lst_updt=?,

commandlink primefaces with href

i'm trying to open a popup mailto by using two different codes:
(1)- <p:link href="mailto:#{classManagedBean.sendEmails}" />
(2)- <p:commandlink actionListener="#{candidatManagedBean.sendEmails()}" />
the "senEmails" is a method declared in the classManagedBean in order to get all the selected emails when a submit of the form done.
The issus that i encountred that when:
working with the code (1) the selected mails came to the managedBean with null values and a popup of the mail interface open with empty mails (as destination)
with the code (2) the selected mails came with the correct values but the popup didn't appear (beacause there is no href attribut!! in the commandLink)
My question is how can i use a
<p:link> with a submit form
<p:commandLink> with href attribut
The Xhtml:
<h:form id="form">
<p:link href="#{candidatManagedBean.createmaito()}">
<p:graphicImage width="25" value="ecrire.png" height="25" alt="envoyer"/>
</p:link>
</h:form>
<p:dataTable id="listCandidat"
value="#{candidatManagedBean.listCandidat}"
emptyMessage="0 candidat trouvé"
var="item"
paginator="true" rows="15" paginatorPosition="bottom"
rowKey="#{item.idCandidat}"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
lazy="true"
selection="#{candidatManagedBean.selectedCandidates}"
>
<p:ajax event="rowSelect" listener="#{candidatManagedBean.onRowSelect}" />
<p:column exportable="false" selectionMode="multiple" style="width:16px;text-align:center"/>
{<p:column>...</p:column>}
</p:dataTable>
The managedBean:
public String createmaito() { // private List<Candidat> selectedCandidates;
System.out.println(selectedCandidates);//here i got a null value of selectedCandidates
if (selectedCandidates != null && !selectedCandidates.isEmpty()) {
for (Candidat cand : selectedCandidates) {
lsEmail = lsEmail.concat(cand.getEmail1());
lsEmail = lsEmail.concat(",");
}
lsEmail= lsEmail.substring(0, lsEmail.length()-1);
result = lsEmail;
}
else {
result = "";
}
return result;
}
I got the solution as follows:
-In XHTML:
<p:commandLink actionListener="#{ManagedBean.getListeOfEmailContacts()}">
<p:graphicImage value="/mail.png" />
</p:commandLink>
-In managed bean:
public void getListeOfEmailContacts() {
/* instruction to get the ListOfContacts ...*/
RequestContext.getCurrentInstance().execute("window.open(href ='mailto:" + ListOfContacts + "')");
}

Save checkbox state After ReLoadThe Page in JSF Primefaces

Im using a "DataTable - Selection",(http://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml) in primefaces 5 to check the selected rows, but when I reload the page, the checkboxes are unchecked, How can i keep the state of the checkboxes in session?
**
*********DataTable****************
**
<p:dataTable var="var" value="#{vistaBean.listaFichero}" rowKey="#{var.nombre}" paginator="true" rows="10"
selection="#{vistaBean.selectFichero}">
<f:facet name="header">
Votar ProductBox
</f:facet>
<p:column headerText="Votar" selectionMode="multiple"/>
<p:column headerText="Nombre del Fichero">
<h:outputText value="#{var.nombre}" />
</p:column>
<p:column headerText="Ver/Descargar">
<h:commandLink id="pdf" action="#{vistaBean.downLoad}">
<f:setPropertyActionListener target="#{vistaBean.ruta}" value="#{var.ruta}" />
<h:graphicImage library="images" name="pdf.png" />
</h:commandLink>
</p:column>
</p:dataTable>
<p:commandButton value="Guardar Votos" action="#{vistaBean.addVoto()}" update="msgs"/>
<p:commandButton value="Ver Votos" update="display" oncomplete="PF('dlg').show()" icon="ui-icon-check" inmediate="true"/>
<p:dialog header="Product Box Seleccionados" modal="true" showEffect="clip" widgetVar="dlg" resizable="false">
<p:outputPanel id="display">
<p:dataList value="#{vistaBean.selectFichero}" var="v">
#{v.nombre}
</p:dataList>
</p:outputPanel>
</p:dialog>
I solve the issue by installing a newer version of Primefaces, 5.2, i had the 5.1 and it had that bug.
This is how you set a session variable:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("foo", "bar");
This is how you can get session variables:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements())
{
String attr = (String)e.nextElement();
System.err.println(" attr = "+ attr);
Object value = session.getValue(attr);
System.err.println(" value = "+ value);
}
Your only task is to save the state of your checkboxes into the session and then load it.

Primefaces dialog fields not filled after click in CommandLink

I am using Primefaces 3.5 with Weblogic 11. I have a page where a dialog to edit a 'profile' entity ('perfil' in Portuguese) which is called from two places. First from a commandButton to insert a new profile. The second from a dataTable to edit a specific profile. Below, I show the code:
Snippet of XHTML page
<p:fieldset legend="Pesquisa de Perfil">
<p:panelGrid columns="2">
<f:facet name="footer">
<p:commandButton id="btnPesquisar"
actionListener="#{perfilAcessoMB.pesquisar}" value="Pesquisar"
immediate="true" update="pnlPerfis" styleClass="ui-icon-search" />
<p:spacer width="20"></p:spacer>
<!-- OPEN DIALOG TO CREATE A NEW PROFILE -->
<p:commandButton id="btnIncluir" value="Incluir"
update="dlgPerfil" immediate="true"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(null)}"
oncomplete="dlgPerfil.show();">
</p:commandButton>
</f:facet>
</p:panelGrid>
</p:fieldset>
<br />
<p:outputPanel id="pnlPerfis" layout="block">
<p:fieldset id="resultadoPesquisa" legend="Resultado da Pesquisa"
rendered="#{not empty perfilAcessoMB.perfis}">
<p:dataTable id="tblPerfis" value="#{perfilAcessoMB.perfis}"
var="perfil" emptyMessage="Nenhum perfil encontrado.">
<p:column headerText="Nome do Perfil">
<h:outputText value="#{perfil.nome}"></h:outputText>
</p:column>
<p:column headerText="Descrição do Perfil">
<h:outputText value="#{perfil.descricao}"></h:outputText>
</p:column>
<p:column headerText="Situação do Perfil"
style="text-align: center; width: 100px;">
<h:outputText value="Ativo" rendered="#{perfil.situacao}" />
<h:outputText value="Inativo" rendered="#{not perfil.situacao}" />
</p:column>
<p:column headerText="Editar"
style="text-align: center; width: 50px;">
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="Editar Perfil" update=":formPrincipal:dlgPerfil :formPrincipal:pnlPerfilEdicao"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(perfil)}"
oncomplete="dlgPerfil.show();">
<h:outputText value="Editar" />
</p:commandLink>
</p:column>
<p:column headerText="Excluir"
style="text-align: center; width: 50px;">
</p:column>
</p:dataTable>
</p:fieldset>
</p:outputPanel>
<p:dialog id="dlgPerfil" widgetVar="dlgPerfil" resizable="false"
closable="true" modal="true" closeOnEscape="true"
header="#{(empty perfilAcessoMB.perfil)? 'Incluir': 'Editar'} Perfil">
<h:outputText value="#{perfilAcessoMB.perfil}"></h:outputText>
<h:panelGroup id="pnlPerfilEdicao" layout="block">
<p:fieldset legend="Dados do Perfil">
<p:panelGrid columns="2">
<h:outputLabel id="lblNomePerfilEdicao" value="Nome do Perfil"
for="txtNomePerfilEdicao" />
<p:inputText id="txtNomePerfilEdicao" required="true"
requiredMessage="É obrigatório preencher o campo Nome do Perfil."
value="#{perfilAcessoMB.perfil.nome}" maxlength="20" size="20"></p:inputText>
<h:outputLabel id="lblDescricaoPerfilEdicao"
value="Descrição do Perfil" for="txtDescricaoPerfilEdicao" />
<p:inputText id="txtDescricaoPerfilEdicao" required="true"
requiredMessage="É obrigatório preencher o campo Descrição do Perfil."
value="#{perfilAcessoMB.perfil.descricao}" maxlength="20"
size="20"></p:inputText>
<h:outputLabel id="lblSituacaoPerfilEdicao" value="Situação"
for="selSituacaoPerfilEdicao" />
<p:selectOneMenu id="selSituacaoPerfilEdicao"
value="#{perfilAcessoMB.perfil.situacao}">
<f:selectItems value="#{perfilAcessoMB.situacoesEdicao}" />
</p:selectOneMenu>
</p:panelGrid>
</p:fieldset>
<br />
<p:fieldset legend="Permissões">
<p:pickList id="pickFuncoes" value="#{perfilAcessoMB.funcoes}"
var="funcao" itemValue="#{funcao}"
itemLabel="#{funcao.descricao}" required="true"
requiredMessage="É obrigatório associar ao menos uma funcionalidade ao perfil."
converter="funcaoConverter" />
<p:column>#{funcao.descricao}</p:column>
</p:fieldset>
<p:panelGrid columns="2">
<p:commandButton id="btnSalvarPerfil" value="Salvar"
actionListener="#{perfilAcessoMB.salvar}"
oncomplete="if(args && !args.validationFailed) dlgPerfil.hide();" />
<p:commandButton id="btnCancelarPerfil" value="Cancelar"
immediate="true" onclick="dlgPerfil.hide();" />
</p:panelGrid>
</h:panelGroup>
</p:dialog>
MangedBean (perfilAcessoMB)
#ManagedBean
#ViewScoped
public class PerfilAcessoMB extends BaseMB {
private PerfilAcessoORM perfil;
private List<PerfilAcessoORM> perfis;
private String nomePerfil;
private Boolean situacao;
private DualListModel<FuncaoORM> funcoes;
private SelectItem[] situacoesPesquisa = new SelectItem[] {
new SelectItem(null, "Todos"), SELECT_ITEM_ATIVO,
SELECT_ITEM_INATIVO };
private SelectItem[] situacoesEdicao = new SelectItem[] {
SELECT_ITEM_ATIVO, SELECT_ITEM_INATIVO };
private FuncaoORM funcaoA = new FuncaoORM(1L, "FUNÇÃO A"), //
funcaoB = new FuncaoORM(2L, "B Function"), //
funcaoC = new FuncaoORM(10L, "Se Funssaum");
public void abrirDialogoEdicao(PerfilAcessoORM p) {
this.perfil = (p == null)? new PerfilAcessoORM(): p;
System.out.println("PerfilAcessoMB.onAbrirDialogoEdicao(): "
+ this.perfil);
List<FuncaoORM> funcoesDisponiveis = new ArrayList<FuncaoORM>(
Arrays.asList(funcaoA, funcaoB, funcaoC));
// Remove from funcoesDisponiveis those whose are present in perfil.
if (this.perfil.getFuncoes() == null) {
this.funcoes = new DualListModel<FuncaoORM>(funcoesDisponiveis,
Lists.<FuncaoORM> newArrayList());
} else {
funcoesDisponiveis.removeAll(this.perfil.getFuncoes());
this.funcoes = new DualListModel<FuncaoORM>(funcoesDisponiveis,
this.perfil.getFuncoes());
}
}
// Getters & Setters
}
PerfilAcessoORM (Profile) Entity
public class PerfilAcessoORM {
private Long id;
private String nome;
private String descricao;
private Boolean situacao = null;
private List<FuncaoORM> funcoes;
// Getters & Setters
}
FuncaoORM Entity:
public class FuncaoORM {
private Long id;
public String descricao;
// Getters & Setters
}
What is my problem? Apparently, when I want insert a new Profile, all seems OK. However, when I click to edit an existent profile to open the dialog, although the outputText and pickList are correctly filled, the inputText's and selectOneMenu are not.
Looking for solutions, I found here a suggestion to use appendToBody="true" in dialog. When I tried, the inputText's and selectOneMenu are correctly filled. However, the validation is not working as waited. When I click to save it is showed a message indicating that pickList is not filled, even if it is really filled. Actually, even if inputText's are not filled, there is no message about these inputTexts although they are required.
Another alternative would be use <f:setPropertyActionListener> inside commandLink:
<!-- OPEN DIALOG TO CREATE A NEW PROFILE -->
<p:commandButton id="btnIncluir" value="Incluir"
update="dlgPerfil" immediate="true"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao}"
oncomplete="dlgPerfil.show();">
<f:setPropertyActionListener target="#{perfilAcessoMB.perfil}" value="#{null}"/>
</p:commandButton>
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="Editar Perfil" update=":formPrincipal:dlgPerfil :formPrincipal:pnlPerfilEdicao"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao}"
oncomplete="dlgPerfil.show();">
<f:setPropertyActionListener target="#{perfilAcessoMB.perfil}" value="#{perfil}"/>
<h:outputText value="Editar" />
</p:commandLink>
The actionListener method would changed to:
public void abrirDialogoEdicao() {
if(this.perfil == null) {
this.perfil = new PerfilAcessoORM();
}
System.out.println("PerfilAcessoMB.onAbrirDialogoEdicao(): "
+ this.perfil);
// The rest remains the same ...
}
Now, when I click to create a new perfil, although in actionListener method the perfil attribute is filled, I got a NullPointerException when the dialog is renderized. It is like first is called perfilAcessoMB.setPerfil(), after the dialog is opened and finally actionListener method. On the other hand, if I click to edit an existent profile, I return to initial situation.
Therefore, I am lost, without idea how to solve this issue.
Thanks,
Rafael Afonso
The solution was incredible simple: just added process="#this" to both commandButtons.
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="#{msg['titulo.edicao']}" process="#this"
update=":formPrincipal:dlgPerfil"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(perfil)}"
oncomplete="dlgPerfil.show();">
<h:outputText value="#{msg['titulo.edicao']}" />
</p:commandLink>

How to use jsf to edit some data in a database

i have an app that displays some data entered in a databse, this should allow a user to delete or edit this information, so far i have managed to get it to delete, but i am wondering, what is the best method for editting the data, what i would like if possible is to click on an edit button on a page already populated with the data and this to take the user to a webpage that has only that selected records pre populating textboxs and then allow the user to edit these, how would i do this ?
this is how i am deleting a row from the database
<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
User ID
</f:facet>
#{u.userID}
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
#{u.name}
</p:column>
<p:column>
<f:facet name="header">
Email
</f:facet>
#{u.email}
</p:column>
<p:column>
<f:facet name="header">
Address
</f:facet>
#{u.address}
</p:column>
<p:column>
<f:facet name="header">
Created Date
</f:facet>
#{u.created_date}
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
</p:column>
<p:column>
<f:facet name="header">
Edit
</f:facet>
<h:commandButton value="Edit" action="{user.delete(u.userID)}" />
</p:column>
</p:dataTable>
and this is the backing bean allowing me to delete
public void delete(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "DELETE FROM user1 WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row deleted successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks
EDIT
i have figured out how to update the data, my question is now simply, how do i get the data from a row and populate a new page with input boxes with the selected data Or even better would be to edit the data live in the table, is this possilbe
instead of taking the user to a second page to edit the data, you can make use of primfaces DataTable - Row Editing see this
http://www.primefaces.org/showcase/ui/datatableRowEditing.jsf
send user object only with editdata method
<h:commandButton value="Edit" action="{user.editData(u)}" />
then you can use prepared statement with update like shown below
String sql = "UPDATE user1 set name = '"+name+"', email = '"+ email +"', address = '"+address+"' WHERE userId=" + userID;
I will suggest try hibernate.