Update in datatable after updating data - java

I'm having a problem updating a column in my datatable after an edit.
I use a dialog to edit the data you want. You are saving everything in the database, the problem
Rezide in updating the table, the fields are being updated with the new values,
Only one that is not updating, just a selectOneMenu that is in the dialog.
The field that is not updating is from the Lotação, the rest is working.
My table..
<h:head>
</h:head>
<h:body>
<ui:composition template="/WEB-INF/template/template.xhtml">
<ui:define name="TituloCorpo">Alterar Impressora</ui:define>
<ui:define name="Corpo">
<div align="center">
<h:form id="form">
<!-- BOTÕES QUE GERA RELATÓRIOS EM PDF E CSV -->
<div style="width:2958px">
<h:commandLink>
<h:graphicImage value="/resources/img/icon_pdf.png" width="35" title="Relatório em PDF"/>
<p:dataExporter type="pdf" target="tab" fileName="impressoras" pageOnly="true"/>
</h:commandLink>
<h:commandLink>
<h:graphicImage value="/resources/img/icon_csv.png" width="35" title="Relatório em CSV"/>
<p:dataExporter type="csv" target="tab" fileName="impressoras" pageOnly="true" />
</h:commandLink>
</div>
<!-- SCRIPT QUE CRIA UMA TABELA -->
<p:dataTable id="tab" var="impressora" widgetVar="tab" value="#{impressoraMB.impressoras}" editable="true" reflow="true" style="width:1100px">
<p:column id="fabricante" headerText="Fabricante" filterBy="#{impressora.fabricante}" filterMatchMode="contains" style="width:170px">
<h:outputLabel value="#{impressora.fabricante}"/>
</p:column>
<p:column id="modelo" headerText="Modelo" filterBy="#{impressora.modelo}" filterMatchMode="contains" style="width:170px">
<h:outputLabel value="#{impressora.modelo}"/>
</p:column>
<p:column id="modeloCartucho" headerText="Modelo do Cartucho" filterBy="#{impressora.modeloCartucho}" filterMatchMode="contains" style="width:180px">
<h:outputLabel value="#{impressora.modeloCartucho}"/>
</p:column>
<p:column id="patrimonio" headerText="Patrimonio" filterBy="#{impressora.patrimonio}" filterMatchMode="contains" style="width:120px">
<h:outputLabel value="#{impressora.patrimonio}"/>
</p:column>
<p:column id="lotacao" headerText="Lotação" filterBy="#{impressora.nome}" filterMatchMode="contains" style="width:110px">
<h:outputLabel value="#{impressora.nome}"/>
</p:column>
<p:column headerText="Alterar" style="width:70px" exportable="false">
<p:commandButton update=":formAlterar:panelAlterar" icon="ui-icon-pencil" title="Alterar" style="height:35px;width:35px"
oncomplete="PF('alterarImpre').show()" ajax="true">
<f:setPropertyActionListener value="#{impressora}" target="#{impressoraMB.impressora}"/>
</p:commandButton>
</p:column>
<p:column headerText="Remover" style="width:90px" exportable="false">
<p:commandButton update=":formExcluir:panelExcluir" oncomplete="PF('excluirImpre').show()" icon="ui-icon-trash"
styleClass="btn btn-small" style="height:35px;width:35px" title="Excluir">
<f:setPropertyActionListener value="#{impressora}" target="#{impressoraMB.impressora}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</div>
<!-- PAGINA COM A CAIXA DE DIALOGO -->
<ui:include src="/panel.xhtml"/>
</ui:define>
</ui:composition>
</h:body>
My dialog..
<p:dialog id="editar" header="Altere os dados desejados" widgetVar="alterarImpre" width="600" location="center"
draggable="true" modal="true" responcive="true" showEffect="fade" hideEffect="fade">
<h:form id="formAlterar">
<h6 align="center"><i>*Para abrir o campo de edição, clique em cima do valor</i></h6>
<br/>
<h:panelGrid id="panelAlterar" columns="2" cellpadding="5" width="75%">
<h:outputLabel for="fabricante" value="Fabricante:"/>
<p:inplace id="fabricante" editor="true" emptyLabel="Me edite">
<p:inputText value="#{impressoraMB.impressora.fabricante}" required="true" label="text"/>
</p:inplace>
<h:outputLabel for="modelo" value="Modelo:"/>
<p:inplace id="modelo" editor="true" emptyLabel="Me edite">
<p:inputText value="#{impressoraMB.impressora.modelo}" required="true" label="text"/>
</p:inplace>
<h:outputLabel for="modeloCartucho" value="Modelo do Cartucho: "/>
<p:inplace id="modeloCartucho" editor="true" emptyLabel="Me edite">
<h:inputText value="#{impressoraMB.impressora.modeloCartucho}" required="true" label="text"/>
</p:inplace>
<h:outputLabel for="patrimonio" value="Patrimonio"/>
<p:inplace id="patrimonio" editor="true" emptyLabel="Me edite">
<p:inputText value="#{impressoraMB.impressora.patrimonio}" required="true" label="text"/>
</p:inplace>
<h:outputLabel for="lotacoes" value="Lotações:"/>
<h:panelGroup>
<h:selectOneMenu id="lotacoes" value="#{impressoraMB.impressora.id_Lotacoes}" effect="fold" required="true"
immediate="true" style="width:100%">
<f:selectItems value="#{lotacoesMB.listLotacoes}" var="item"
itemLabel="#{item.nome}" itemValue="#{item.id}"/>
<f:ajax execute="#this"/>
</h:selectOneMenu>
</h:panelGroup>
</h:panelGrid>
<br/>
<div align="center">
<h:panelGrid>
<h:panelGroup>
<p:commandButton id="btnAlterar" value="Alterar" action="#{impressoraMB.alterar}" onclick="PF('alterarImpre').hide()"
oncomplete="PF('form').hide(); #{impressoraMB.impressora}" ajax="true" process="#form" title="Alterar">
<f:ajax execute="#all" render=":form:tab"/>
</p:commandButton>
<p:commandButton id="btnCancelar" value="Cancelar" onclick="PF('alterarImpre').hide()" title="Cancelar"/>
</h:panelGroup>
</h:panelGrid>
</div>
</h:form>
</p:dialog>
MY Bean..
public class ImpressoraMB {
private Impressora impressora;
private ImpressoraDAO dao;
private List<Impressora> impressoras;
public ImpressoraMB() {
impressora = new Impressora();
impressoras = new ArrayList<Impressora>();
dao = new ImpressoraDAO();
}
public List<Impressora> getImpressoras() {
if (impressoras.size() == 0) {
impressoras = dao.getImpressoras();
}
return impressoras;
}
public void adicionar() {
dao.adicionar(impressora);
impressora = new Impressora();
}
public void remover() {
dao.remover(impressora);
impressoras.remove(impressora);
impressora = new Impressora();
}
public void alterar() {
dao.alterar(impressora);
impressora = new Impressora();
}
public void showMsgAdicionar() {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Impressora adicionada", "com sucesso!");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public Impressora getImpressora() {
return impressora;
}
public void setImpressora(Impressora impressora) {
this.impressora = impressora;
}
}
Thank you very much in advance.

In your dialog you have
<h:selectOneMenu id="lotacoes" value="#{impressoraMB.impressora.id_Lotacoes}" effect="fold"
required="true" immediate="true" style="width:100%">
while your DataTable uses
<p:column id="lotacao" headerText="Lotação" filterBy="#{impressora.nome}"
filterMatchMode="contains" style="width:110px">
<h:outputLabel value="#{impressora.nome}"/>
</p:column>
If you change the value in one of the two different .xhtml files you should have the expected result

You have to use the update attribute in your command button or in your ajax call.
<p:commandButton id="btnAlterar" value="Alterar" action="#{impressoraMB.alterar}" update=":form:tab" onclick="PF('alterarImpre').hide()"
oncomplete="PF('form').hide(); #{impressoraMB.impressora}" ajax="true" process="#form" title="Alterar">
or
<f:ajax execute="#all" update=":form:tab" render=":form:tab"/>
Make sure that the object is updated in the backed bean

Related

Primefaces datatable with selection attribute - dynamic tables

First some explain:
I create dynamically an accordeonpanel and in each Tab i create a p:datatable ( also dynamically).
I now have to edit the lines of the tables but my method in the "selection" is not called.
I think it's because of the above explained dynamism.
the method is: evaluationController.deleteIndicator()
Does anyone have an idea how to fix that?
Here the code:
XHTML:
<!-- **************************************** ACCORDEON **************************************** -->
<p:panel id="mainAccordeonHeader" header="Capacités et dégrés de maîtrise" styleClass="panelSearch">
<h:form id="evalAccordionForm" styleClass="orgForm">
<p:accordionPanel id="evalAccordion"
styleClass="orgAccordion"
value="#{evaluationController.availableCapacitys}"
var="capListItem">
<p:tab id="evalAccordTitle">
<f:facet name="title">
<h:panelGrid columns="4">
<h:outputText value="#{capListItem.name}"/>
<h:outputText value="#{capListItem.isThresholdOfSuccess ? 'Capacité Déterminante' : 'Degré de Maitrise'}" />
<h:outputText value="Nr Indicateurs: #{evaluationController.findNumberOfIndicators(capListItem)}"/>
<h:outputText value="Pondération: #{evaluationController.findCapacityPonderation(capListItem)}"/>
</h:panelGrid>
</f:facet>
<!-- CAPACITY DETAIL-->
<table border="0" >
<thead>
<tr>
<th>
<p>Description</p>
</th>
<th>
<p style="float: right">Pondération</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p:inputTextarea id="capDescTextArea" rows="3" cols="113" value="#{capListItem.description}" readonly="true"/>
</td>
<td>
<p:inputTextarea style="float: right" id="capPonderationTextArea" rows="1" cols="1" readonly="true" value="#{evaluationController.findCapacityPonderation(capListItem)}"/>
</td>
</tr>
</tbody>
</table>
<p:separator />
<!-- INDICATORS-->
<h:form>
<p:contextMenu for="indicatorTable">
<p:menuitem value="Modifier" update="indicatorTable" icon="ui-icon-wrench" actionListener="#{evaluationcontroller.updateIndicator()}"/>
<p:menuitem value="Supprimer" update="indicatorTable" icon="ui-icon-trash" actionListener="#{evaluationController.deleteIndicator()}"/>
<p:menuitem value="Ajouter" update="indicatorTable" icon="ui-icon-plus" actionListener="#{evaluationController.addIndicator()}"/>
<p:separator/>
<p:menuitem value="Annuler action"/>
</p:contextMenu>
<p:dataTable
id="indicatorTable"
value="#{evaluationController.findIndicatorsByCapacity(capListItem)}"
var="indicator"
editable="true"
tableStyle="indicatorTableStyle"
rowKey="#{indicator.id}"
selection="#{evaluationcontroller.selectedIndicatorRow}" selectionMode="single"
>
<f:facet name="header">Les Indicateurs ( #{evaluationController.findNumberOfIndicators(capListItem)})
</f:facet>
<p:column headerText="Org Ut" >
<h:outputText value ="#{indicator.organizedUt.id}"/>
</p:column>
<p:column headerText="Date">
<h:outputText value ="#{indicator.organizedUt.toString()}"/>
</p:column>
<p:column headerText="Nom">
<h:outputText value ="#{indicator.name}"/>
</p:column>
<p:column headerText="Description" toggleable="false" width="450">
<p:outputLabel value ="#{indicator.description}" />
</p:column>
<p:column headerText="Max" toggleable="false" width="30">
<p:inputTextarea style="float: none" rows="1" cols="1" readonly="true" value="#{indicator.maxPossible}"/>
</p:column>
</p:dataTable>
<p:commandButton styleClass="addButtonStyle" icon="ui-icon-plus" value="Ajouter un indicateur"/>
<p:commandButton styleClass="deleteAllButtonStyle" icon="ui-icon-trash" value="Supprimer tous les indicateurs" actionListener="#{evaluationController.deleteIndicator()}"/>
</h:form>
</p:tab>
</p:accordionPanel>
</h:form>
</p:panel>
CONTROLER:
Here is the problem : the Getter Setter are not called when i select a row!
public Indicator getSelectedIndicatorRow() {
System.out.println("GETTER - selectedIndicatorRow");
return selectedIndicatorRow;
}
public void setSelectedIndicatorRow(Indicator selectedIndicatorRow) {
this.selectedIndicatorRow = selectedIndicatorRow;
System.out.println("SETTER - selectedIndicatorRow");
}
public void deleteIndicator(){
System.out.println("Function: deleteIndicator");
try {
System.out.println("TRY TO DELETE INDICATOR");
indicatorFacade.remove(selectedIndicatorRow);
List<Indicator> tempIndicatorsList = actualGridHM.get(selectedIndicatorRow.getCapacity());
actualGridHM.remove(selectedIndicatorRow.getCapacity());
tempIndicatorsList.remove(selectedIndicatorRow);
actualGridHM.put(selectedIndicatorRow.getCapacity(), tempIndicatorsList);
System.out.println("INDICATOR DELETED!");
}
catch (Exception e) {
System.out.println("ERROR - DELETE OF INDICATOR NOT WORKED!");
}
Does anyone have a solution? Maybe an another way to edit this dynamic table ( placed in a dynamic accordeon)??
First obvious problem with your code is that you have two <h:form>. You have to delete the inner <h:form> and test again.
Try this way below;
put your command buttons in facets at the bottom of your datatable like
<p:dataTable>
...
<f:facet>
<p:commandButton styleClass="addButtonStyle" icon="ui-icon-plus" value="Ajouter un indicateur"/>
<p:commandButton styleClass="deleteAllButtonStyle" icon="ui-icon-trash" value="Supprimer tous les indicateurs" action="#{evaluationController.deleteIndicator}"/>
</f:facet>
</p:dataTable>
and use "action" attribute instead of "actionListener" without '()' at the end of your action method in your command button or add ActionEvent parameter to your action method.

Forward variable on the next page

I have a Users table. Added, view and delete work. But I have problem to edit.
My list page:
<h:form id="form">
<p:dataTable styleClass="table" value="#{userMB.allAdmins}" var="admin" paginator="true" rows="15" rowKey="#{admin.id}" selection="#{userMB.user}" selectionMode="single">
<f:facet name="header">
Lista administratorów
</f:facet>
<p:column headerText="#{msg.firstName}">
<h:outputText value="#{admin.firstName}" />
</p:column>
<p:column headerText="#{msg.lastName}">
<h:outputText value="#{admin.lastName}" />
</p:column>
<p:column headerText="#{msg.personalId}">
<h:outputText value="#{admin.personalId}" />
</p:column>
<f:facet name="footer">
<p:commandButton id="viewButton" value="#{msg.info}" icon="ui-icon-search"
update=":form:display" oncomplete="userDialog.show()"/>
<p:commandButton action="#{userMB.createStart()}" value="#{msg.add}" icon="ui-icon-plus" />
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}" >
<f:setPropertyActionListener target="#{userMB.user}" value="#{userMB.user}" />
</p:commandButton>
<p:commandButton action="#{userMB.deleteUser()}" value="#{msg.delete}" icon="ui-icon-close"/>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Administrator" widgetVar="userDialog" resizable="false"
width="300" showEffect="clip" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<f:facet name="header">
<p:graphicImage value="./../../images/person4.png" width="150" height="150"/>
</f:facet>
<h:outputText value="#{msg.firstName}" />
<h:outputText value="#{userMB.user.firstName}" />
<h:outputText value="#{msg.lastName}" />
<h:outputText value="#{userMB.user.lastName}" />
<h:outputText value="#{msg.personalId}" />
<h:outputText value="#{userMB.user.personalId}" />
</h:panelGrid>
</p:dialog>
</h:form>
I want to send the selected user on the next page:
I use aciontListener:
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}" >
<f:setPropertyActionListener target="#{userMB.user}" value="#{userMB.user}" />
</p:commandButton>
My edit page where I want to send user:
<h:form>
<div id="userPanel">
<h:inputHidden value="#{userMB.user}" />
<p:panel id="panelUser" header="Edytuj administratora" >
<div id="panelImage">
<img src="./../../images/person4.png" alt="person" width="150px" height="130px"/>
</div>
<h:panelGrid columns="3">
<p:outputLabel for="firstName" value="#{msg.firstName}"></p:outputLabel>
<p:inputText id="firstName" value="#{userMB.user.firstName}" label="#{msg.firstName}" required="true">
<f:validator validatorId="nameValidator" />
<p:ajax update="msgFristName" event="keyup" />
</p:inputText>
<p:message for="firstName" id="msgFristName"/>
<p:outputLabel for="lastName" value="#{msg.lastName}"></p:outputLabel>
<p:inputText id="lastName" value="#{userMB.user.lastName}" label="#{msg.lastName}" required="true">
<f:validator validatorId="nameValidator" />
<p:ajax update="msgLastName" event="keyup" />
</p:inputText>
<p:message for="lastName" id="msgLastName"/>
<p:outputLabel for="personalId" value="#{msg.personalId}"></p:outputLabel>
<p:inputText id="personalId" value="#{userMB.user.personalId}" label="#{msg.personalId}" required="true">
<f:validator validatorId="personalIdValidator" />
<p:ajax update="msgPersonalId" event="keyup" />
</p:inputText>
<p:message for="personalId" id="msgPersonalId"/>
<p:outputLabel for="password" value="#{msg.password}"></p:outputLabel>
</p:panel>
</div>
</h:form>
I added: <h:inputHidden value="#{userMB.user}" /> but I do not see data user, only empty field. How do I send this person? I used once this method in other project, a little different without primefaces and it worked. Why now does not work?
Method editStart:
public String editStart() {
return "editStart";
}
faces-config:
<navigation-case>
<from-outcome>editStart</from-outcome>
<to-view-id>/protected/admin/adminEdit.xhtml</to-view-id>
<redirect/>
</navigation-case>
When I'm on the side adminEdit I edited the pool and do editUser method:
public String editUser() {
FacesContext context = FacesContext.getCurrentInstance();
Map requestParameterMap = (Map) context.getExternalContext().getRequestParameterMap();
try {
String userRole = requestParameterMap.get("userRole").toString();
String active = requestParameterMap.get("active").toString();
Boolean act = Boolean.parseBoolean(active);
user.setRole(userRole);
user.setActive(act);
userDao.update(user);
} catch (EJBException e) {
sendErrorMessageToUser("Edit error");
return null;
}
sendInfoMessageToUser("Account edited");
return user.getRole() + "List";
}
My method editStart use only for navigation.
You can either consider Przemek's answer or use one of the 4 ways of passing a parameter to a backing bean.
1. Method expression
2. f:param
3. f:atribute
4. f:setPropertyActionListener
For very well explained full explanation refer to this
It has easy to understand examples. Take a look and pick what fits your needs.
Or simply:
In the actual managed bean...
public String navigationButtonListener(User parameter) {
FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
.put("parameterAttribute", parameter);
return "my-destination-page";
}
In the destination managed bean...
#PostConstruct
public void init(){
myAttribute= (User) FacesContext.getCurrentInstance()
.getExternalContext().getRequestMap().get("parameterAttribute");
}
Good Luck!
You can pass your userid through the session.
Add a parameter to your commandLink
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}>
<f:param name="userId" value="#{userMB.user.id}" />
</p:commandButton>
In your backing bean do this
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest myRequest = (HttpServletRequest)context.getExternalContext().getRequest();
HttpSession mySession = myRequest.getSession();
Integer userId = Integer.parseInt(myRequest.getParameter("userId"));
After that you can reload the user you want to edit with the Id you got

How to update jsf datatable from back bean

I have a form that user should enter some values to get some info from a web service. Firstly user fulfills the form and then as he clicks the request button webservice is called. Until here everything works nicely. But as the webservice returns the info, I have to re-render the datatable with the new data. Here is my page:
<h:body>
<h:form id="formCus">
<h:outputLabel value="Müşteri Tipi: *"/>
<p:selectOneMenu id="customerType" value="#{customerService.musteriTipi}" style="width: 39%">
<f:selectItem itemLabel="" itemValue=" " />
<f:selectItem itemLabel="Bireysel" itemValue="BIREYSEL" />
<f:selectItem itemLabel="Tüzel" itemValue="TUZEL" />
<f:selectItem itemLabel="Yabancı" itemValue="YABANCI" />
<p:ajax event="change" update="#{customerService.musteriTipi}"/>
</p:selectOneMenu>
<h:outputLabel value="Ad/Firma Adı: *" for="customerName" />
<p:inputText id="customerName" value="#{customerService.adFirmaAdi}" title="Müşteri adı." >
<p:ajax event="change" update="#{customerService.adFirmaAdi}" />
</p:inputText>
<h:outputLabel value="Soyad/Ünvan: *" for="customerSurname" />
<p:inputText id="customerSurname" value="#{customerService.soyadUnvan}" title="Müşteriye ait soyad/ünvan." >
<p:ajax event="change" update="#{customerService.soyadUnvan}" />
</p:inputText>
<h:outputLabel value="TC Kimlik No: *" />
<p:inputText id="customerTC" value="#{customerService.tcKimlikNo}" title="TC Kimlik numarasını buraya girin.TC numarası sadece sayılardan oluşmalıdır." >
<p:ajax event="change" update="#{customerService.tcKimlikNo}" partialSubmit="true" process="#this"/>
</p:inputText>
<h:outputLabel value="Vergi No:" />
<p:inputText id="customerVergi" value="#{customerService.vergiNo}" title="TC Kimlik numarasını buraya girin.TC numarası sadece sayılardan oluşmalıdır." >
<p:ajax event="change" update="#{customerService.vergiNo}" partialSubmit="true"/>
</p:inputText>
<h:outputLabel value="Müdürlük Kodu: *" />
<p:inputText id="departmantId" value="#{customerService.mudurlukKodu}" title="Müdürlük kodunu buraya girin.Müdürlük kodu sadece sayılardan oluşmalıdır." >
<p:ajax event="change" update="#{customerService.mudurlukKodu}" partialSubmit="true"/>
</p:inputText>
<h:outputLabel value="Müşteri Kodu: " />
<p:inputText id="customerId" value="#{customerService.musteriKodu}" title="Müdürlük kodunu buraya girin.Müdürlük kodu sadece sayılardan oluşmalıdır." >
<p:ajax event="change" update="#{customerService.musteriKodu}" />
</p:inputText>
<h:outputLabel value="E-Posta Adresi: " />
<p:inputText id="customerMail" value="#{customerService.mail}" title="Müşteriye ait e-mail adresini buraya girin." >
<p:ajax event="change" update="#{customerService.mail}" partialSubmit="true"/>
</p:inputText>
<h:outputText value=" "/>
<p:commandButton id="query" value="Müşteri Sorgula" actionListener="#{customerService.request}" async="true" onsuccess="panelwv.show()">
<f:ajax execute="#form" render=":personList" ></f:ajax>
</p:commandButton>
</h:form>
<h:panelGrid columns="5">
<h:outputText value=""/>
<h:outputText value=""/>
<p:panel widgetVar="panelwv" visible="false" closable="true" header="Sorgu Yapılıyor...">
<p:graphicImage value="/resources/images/ajaxloadingbar.gif" />
</p:panel>
<h:outputText value=""/>
<h:outputText value=""/>
</h:panelGrid>
<h:outputText value="Bulunan Müşterilere Ait Bilgiler:" />
<h:form id="personList" rendered="#{not empty customerService.musteriKodu}">
<p:dataTable value="#{customerService.customer}" var="item" id="persontable" emptyMessage="Henüz müşteri eklemediniz.">
<p:column headerText="Müşteri/Firma ID">
#{item.customerId}
</p:column>
<p:column headerText="Ad/Firma Adı">
#{item.customerName}
</p:column>
<p:column headerText="Soyad/Ünvan" >
#{item.customerSurname}
</p:column>
<p:column headerText="Müşteri Tipi" >
#{item.customerType}
</p:column>
<p:column headerText="Telefon" >
#{item.customerTel}
</p:column>
<p:column headerText="Adres">
#{item.customerAddress}
</p:column>
<p:column headerText="E-Posta">
#{item.customerMail}
</p:column>
</p:dataTable>
</h:form>
</h:body>
And here is my back bean:
//some getter and setters
List<Customers> customer = new ArrayList<Customers>();
public List<Customers> getCustomer() {
return customer;
}
public void setCustomer(List<Customers> customer) {
this.customer = customer;
}
public String request() {
final RequestContext context = RequestContext.getCurrentInstance();
//System.out.println("Progress...");
//musteriSorgula(musteriSorgulaKriter());
new Thread(new Runnable() {
public void run() {
try {
musteriKodu = String.valueOf(musteriSorgula(musteriSorgulaKriter()).getMusteriBilgisi().getMusteriKodu());
List<TelefonBilgisi> tel_result = telefonSorgula(telefonSorgulaKriter(musteriKodu)).getMusteriTelefonListesi();
//telefon = tel_result.getMusteriTelefonListesi().get(0).getTelefonNo();
if (tel_result.size() > 0) {
for (TelefonBilgisi t : tel_result) {
telefon = t.getTelefonNo();
}
} else {
telefon = "No telephone.";
}
List<UavtAdresBilgisi> uavt_result = uavtAdresSorgula(uavtAdresSorgulaKriter(musteriKodu)).getMusteriUavtAdresListesi();
if (uavt_result.size() > 0) {
for (UavtAdresBilgisi u : uavt_result) {
adres = String.valueOf(u.getSehir()) + ", " + String.valueOf(u.getBucak()) + ", " + String.valueOf(u.getKasaba());
}
} else {
adres = "No address.";
}
Customers cust = new Customers(musteriTipi, BigInteger.valueOf(Long.valueOf(musteriKodu)), adFirmaAdi, soyadUnvan, telefon, adres, mail, projectId);
if (!customer.contains(cust)) {
customer.add(cust);
System.out.println("Customer has been added.");
} else {
System.out.println("Customer is still in the list.");
}
} catch (Exception ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
context.execute("alert('Try again.')");
}
}
}).start();
context.execute("panelwv.close()");
return "";
}
The back bean could connect to webservice and gether the info, I can see that in the logs. In the beginning my datatable is empty. What I want is to show the new data as the webservice responses. context.update("personList") doesn't work when I place it below:
customer.add(cust);
If someone could help me I would be greatly appriciated.
<f:ajax execute="#form" render=":personList" ></f:ajax>
Make a change as
<f:ajax execute="#form" update="persontable" render=":personList" ></f:ajax>
Ok so what you want to do is to force the client to update the data table from your server. Take a look at comet and push technology and also (if you don't need to support older browsers) WebSocket.
If you google around you'll find tutorials on how to do it using JSF. And as you are using Primefaces, not that this library has comet support: checkout p:push and atmosphere support.
This problem is easy to solve if you use RichFaces
I would prefer using RemoteCommand component as #Ömer said.
Try use it at the end of the thread(inside the thread braces) with context.execute("updater();");

Partially rendering datatable

After I save the components of a form I show it in a datatable. Interestingly if I don't refresh the page my datatable partially renders the values.
Here is the service class:
public EBSResponse uyeTeminatKaydet(UyeTeminat uyeTeminat, Kullanici sessionUser, String ipAdresi ){
Session session = null;
Transaction tx = null;
EBSException EE = new EBSException();
EBSResponse ER = new EBSResponse();
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("saved", false);
Date tarih = new Date();
if (uyeTeminat.getTarih()!= null)
tarih = uyeTeminat.getTarih();
else
uyeTeminat.setTarih(tarih);
uyeTeminat.setDurum(Boolean.TRUE);
BigDecimal teminatDegeri=null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
teminatDegeri=calculateTeminatDegeri(uyeTeminat,tarih, session);
uyeTeminat.setTeminatDegeri(teminatDegeri);
session.save(uyeTeminat);
session.flush();
tx.commit();
List<UyeTeminat> uyeTeminatList = getTumUyeTeminatlari(session);
ER.setStringValue("teminatIslemleriBean.uyeTeminatKaydet.info1");
ER.setObjectValue(uyeTeminatList);
context.addCallbackParam("saved", true);
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null) {
tx.rollback();
}
EE.setHataTipi(EBSConstants.HATA_TIPI_ERROR);
EE.setHataMesaji("teminatIslemleriBean.uyeTeminatKaydet.err1");
ER.setExceptionValue(EE);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return ER;
}
Here is the backing bean:
public void uyeTeminatKaydet() {
EBSResponse er = uyeServisi.uyeTeminatKaydet(uyeTeminat, sessionUser, ipAdresi);
if (er.getExceptionValue() == null) {
this.uyeTeminatList = (List<UyeTeminat>) er.getObjectValue();
FacesUtil.addMessage(FacesMessage.SEVERITY_INFO, LocaleBean.lang.getString(er.getStringValue()));
uyeTeminat = new UyeTeminat();
} else {
FacesUtil.addMessage(EBSUtils.getHataTipi(er.getExceptionValue().getHataTipi()), LocaleBean.lang.getString(er.getExceptionValue().getHataMesaji()));
}
}
Does anyone have any idea about this?
EDIT:
xhtml:
<h:outputText value="#{lang.teminatTuruAdi}: *" />
<h:selectOneMenu id="TeminatTuru" required="true" converter="teminatTurConverter" value="#{teminatTanimlamaIslemleriBean.teminat.teminatTur}">
<f:selectItem itemLabel="#{lang.seciniz}" />
<f:selectItems value="#{teminatTanimlamaIslemleriBean.teminatTurleriMenu}" />
</h:selectOneMenu>
<h:outputText value="#{lang.teminatKodu}: *" />
<p:inputText size="50" maxlength="50" required="true" value="#{teminatTanimlamaIslemleriBean.teminat.teminatKodu}"/>
<h:outputText value="#{lang.teminatAdi}: *" />
<p:inputText size="50" maxlength="50" required="true" value="#{teminatTanimlamaIslemleriBean.teminat.teminatAdi}"/>
<h:outputText value="#{lang.birimFiyat}: *" />
<p:inputText id="BirimFiyat" size="30" maxlength="50" value="#{teminatTanimlamaIslemleriBean.teminat.birimFiyati}"
style="text-align:right" onkeypress="return isNumberAndComma(event); isMaxLength(this, 14, event);" onkeyup="this.value=numberFormat(this.value,6);">
<f:converter converterId="ondalikAltiHaneConverter" />
</p:inputText>
<h:outputText value="#{lang.fiyatTipi}: *" />
<h:selectOneMenu id="FiyatTipi" required="true" value="#{teminatTanimlamaIslemleriBean.teminat.fiyatTuru}">
<f:selectItem itemLabel="#{lang.seciniz}" />
<f:selectItems value="#{genelBilgiBean.fiyatTipiListesi}" />
</h:selectOneMenu>
</h:panelGrid>
<br/>
<p:commandButton value="#{lang.kaydetButton}" onclick="confirmationKaydet.show()"/>
<br/><br/>
<p:dialog showEffect="explode" hideEffect="explode" resizable="false"
header="#{lang.uyari}" widgetVar="confirmationKaydet" appendToBody="true" modal="true">
<h:outputText value="#{lang.kayitOnayMesaji}"/>
<br/><br/>
<p:commandButton value="#{lang.evetButton}" actionListener="#{teminatTanimlamaIslemleriBean.teminatKaydet}"
update="sysMsg, dTable"
process="mf:formPanel"
onstart="waitDialog.show(),confirmationKaydet.hide()"
oncomplete="waitDialog.hide();handleComplete(xhr, status, args);" />
<p:commandButton value="#{lang.hayirButton}" onclick="confirmationKaydet.hide()" type="button" />
</p:dialog>
</p:panel>
<p:panel id="dtPanel" style="width: 80%">
<p:dataTable style="width: 100%;" id="dTable" var="tt" value="#{teminatTanimlamaIslemleriBean.teminatList}" paginator="true" rows="20"
selection="#{teminatTanimlamaIslemleriBean.selectedTeminat}" selectionMode="single" emptyMessage="#{lang.kayitBulunamadi}"
onRowSelectUpdate="mf:tabcontent" onRowSelectComplete="tvl();">
<f:facet name="header">
#{lang.menu_teminat}
</f:facet>
<p:column filterBy="#{tt.teminatId}" sortBy="#{tt.teminatId}">
<f:facet name="header">
<h:outputText value="#{lang.teminatId}" />
</f:facet>
<h:outputText value="#{tt.teminatId}" />
</p:column>
<p:column filterBy="#{tt.teminatTur.teminatTuruAdi}" sortBy="#{tt.teminatTur.teminatTuruAdi}">
<f:facet name="header">
<h:outputText value="#{lang.teminatTuruAdi}" />
</f:facet>
<h:outputText value="#{tt.teminatTur.teminatTuruAdi}" />
</p:column>
<p:column filterBy="#{tt.teminatKodu}" sortBy="#{tt.teminatKodu}">
<f:facet name="header">
<h:outputText value="#{lang.teminatKodu}" />
</f:facet>
<h:outputText value="#{tt.teminatKodu}" />
</p:column>
<p:column filterBy="#{tt.teminatAdi}" sortBy="#{tt.teminatAdi}">
<f:facet name="header">
<h:outputText value="#{lang.teminatAdi}" />
</f:facet>
<h:outputText value="#{tt.teminatAdi}" />
</p:column>
<p:column filterBy="#{tt.birimFiyati}" sortBy="#{tt.birimFiyati}" style="text-align:right">
<f:facet name="header">
<h:outputText value="#{lang.birimFiyat}" />
</f:facet>
<h:outputText value="#{tt.birimFiyati}" style="text-align:right">
<f:converter converterId="ondalikAltiHaneConverter" />
</h:outputText>
</p:column>
<p:column filterBy="#{tt.fiyatTuru}" sortBy="#{tt.fiyatTuru}">
<f:facet name="header">
<h:outputText value="#{lang.fiyatTipi}" />
</f:facet>
<h:outputText value="#{tt.fiyatTuru}" />
</p:column>
<p:column filterBy="#{tt.durum == true ? lang.kullanimda : lang.kullanimDisi}" sortBy="#{tt.durum == true ? lang.kullanimda : lang.kullanimDisi}">
<f:facet name="header">
<h:outputText value="#{lang.durum}" />
</f:facet>
<h:outputText value="#{tt.durum == true ? lang.kullanimda : lang.kullanimDisi}" />
</p:column>
<f:facet name="footer">
#{lang.toplamKayit}: #{fn:length(teminatTanimlamaIslemleriBean.teminatList)}
</f:facet>
</p:dataTable>
</p:panel>
there were two problems:
corresponding converters in Uye and Teminat did not include the necessary fields.
the correct xhtml for the same fields should have been:
d
<h:selectOneMenu id="uyeAdi" required="true" converter="uyeConverter" value="#{teminatTanimlamaIslemleriBean.uyeTeminat.uye}">
<h:selectOneMenu id="teminatTuruAdi" required="true" converter="teminatTurConverter" value="#{teminatTanimlamaIslemleriBean.uyeTeminat.teminat.teminatTur}">

h:commandButton not working within PrimeFaces p:dataTable

I have a PrimeFaces datatable. For each row in this table, I want to allow the user to update/delete the row entry (a user).
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css" />
</h:head>
<h:body>
<center>
<h:form>
<p:panel id="viewUsersPanel" header="View Users">
<p:dataTable var="user" value="#{uController.users}"
emptyMessage="No Users Found.">
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.name}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="Postal Address" />
</f:facet>
<h:outputText value="#{user.address}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="Phone Number" />
</f:facet>
<h:outputText value="#{user.phone}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="Email Address" />
</f:facet>
<h:outputText value="#{user.email}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="DOB" />
</f:facet>
<h:outputText value="#{user.dob}">
<f:convertDateTime pattern="dd-MMM-yyyy" />
</h:outputText>
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="No. Memberships" />
</f:facet>
<h:outputText value="#{user.numberOfMemberships}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="Actions" />
</f:facet>
<h:commandButton value="Update" action="#{uController.update}" />
<h:commandButton value="Delete" action="#{uController.delete}" />
</p:column>
</p:dataTable>
<h:panelGrid columns="2" cellpadding="2" id="footerPanelGrid"
border="0">
<h:commandButton action="#{uController.home}" value="Home Page" />
</h:panelGrid>
</p:panel>
</h:form>
</center>
</h:body>
</html>
However, neither of the buttons work. Instead they appear to simply refresh the view page. I have ran the app in debug and neither update or delete method is hit.
I suspect this may be due to using h:commandButton within a p:dataTable. However, I have also tried p:commandButton but to no avail.
For reference, here is a snippet of the UserController class:
#ManagedBean(name="uController")
public class UserController extends AbstractController {
private Collection<User> users;
...
public String update() {
System.out.println("Ready for update");
return "update-user";
}
public String delete() {
System.out.println("Ready for delete");
return "delete-user";
}
...
}
I have found the solution using a ViewScoped bean. The article that I came across for this:
Learning JSF2: Managed beans
I changed my h:commandButton to:
<h:commandButton value="Delete" action="#{userList.delete}">
<f:setPropertyActionListener target="#{userList.selectedUser}"
value="#{user}" />
I also re-designed my UserController class and it became UserList:
import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="userList")
#ViewScoped
public class UserList {
private Collection<User> users;
private User selectedUser;
#ManagedProperty(value="#{userService}")
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
#PostConstruct
public void populateList() {
users = userService.getUsers();
}
public void delete() {
// TODO remove from DB
users.remove(selectedUser);
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public Collection<User> getUsers() {
return users;
}
}
Thanks for your responses Zenzen.

Categories

Resources