Primefaces datatable is not updated when deleting element - jsf-2

I have a p: datatable using rowedit and works fine, but when you delete an item datatable not updated.
#Named(value = "localesMB")
#SessionScoped
public class LocalesMB implements Serializable {
/**
* Creates a new instance of Activos
*/
public LocalesMB() {
}
private List<entidades.Locales> localesAll = new ArrayList<>();
private entidades.Locales selected = new Locales();
public Locales getSelected() {
return selected;
}
public void setSelected(Locales selected) {
this.selected = selected;
}
public List<Locales> getLocalesAll() {
return localesAll;
}
public void setLocalesAll(List<Locales> localesAll) {
this.localesAll = localesAll;
}
public void deleteSelect(Locales locales) {
this.selected = locales;
}
public void obtenerLocalesAll() {
try {
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: obtenerActivosAll() " + e.getMessage());
}
}
public void eliminarLocal() {
try {
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
cn.getInterfaces().eliminarLocal(this.selected);
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: eliminarLocal() " + e.getMessage());
}
}
public void onRowEdit(RowEditEvent event) {
try {
Locales ps = (Locales) event.getObject();
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
cn.getInterfaces().modificarLocal(ps);
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
JsfUtil.addSuccessMessage("Se ha cambiado el valor correctamente.");
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: onRowEdit() " + e.getMessage());
}
}
}
xhtml
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./../resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./../resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>Activos</title>
<script language="javascript">
window.onload = function() {
PF('tb1').clearFilters();
};
</script>
</h:head>
<h:body>
<h:form id="frm1">
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:panel header="Locales e Instalaciones" id="pn1">
<p:dataTable emptyMessage="No se encontraron elementos" editable="true" rowKey="#{item.idLocales}"
id="tabla_listado" var="item" paginator="true" widgetVar="tb1"
rows="25" value="#{localesMB.localesAll}">
<f:facet name="header">
<h:outputText value="Locales e Instalaciones: #{localesMB.localesAll.size()}"/>
</f:facet>
<p:ajax event="rowEdit" listener="#{localesMB.onRowEdit}"/>
<p:column headerText="Descripción">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.descripcion}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.descripcion}" style="width:95%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Ubicación">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.ubicacion}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.ubicacion}" style="width:95%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:20px">
<p:rowEditor/>
</p:column>
<p:column style="width:20px">
<p:commandButton id="selectButton256" oncomplete="PF('confirmation').show()" process="#this, tabla_listado" actionListener="#{localesMB.deleteSelect(item)}"
icon="ui-icon-trash" title="Eliminar" update=":frm1:confirmDialog">
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
<p:confirmDialog appendTo="#(body)" id="confirmDialog" message="Confirma que desea eliminar a: #{localesMB.selected.descripcion}"
header="Mensaje de Confirmación" severity="alert" widgetVar="confirmation" closeOnEscape="true">
<p:commandButton id="confirm" value="Sí" update=":frm1" oncomplete="PF('confirmation').hide()"
actionListener="#{localesMB.eliminarLocal}" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"/>
<p:commandButton id="decline" value="No" onclick="PF('confirmation').hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:form>

that the problem, this code active the filter, but datatable dont have filterValue:
<script language="javascript">
window.onload = function() {
PF('tb1').clearFilters();
};
</script>
DataTable frm1:tabla_listado has filtering enabled but no filteredValue model reference is defined, for backward compatibility falling back to page viewstate method to keep filteredValue. It is highly suggested to use filtering with a filteredValue model reference as viewstate method is deprecated and will be removed in future.
Solution: remove script.

Related

reinitialize session bean (a bean in sessionScopped) in JSF2

I am using JSF 2.0 , I have a bean opcD (#SessionScoped). since I have defined the bean in SessionScoped after submitting the form and returning to the page the data remains inside the fields that is logic! But I would like to reinitialize my bean if I return again inside it.
But I do not want to destroy the session!
#ManagedBean(name="opcD")
#SessionScoped
public class NewOPCDetailBean implements Serializable {
Please find in below a part of my cod. I go from page (newopcheadpage.xhtml) relevant to opc managedBean to page (newopcdetailpage.xhtml)relevant to managedBean opcD. After submiting page(newopcdetailpage.xhtml) if I want to return to page (newopcheadpage.xhtml), I would like to see the fields blank(beans become reinitialized ).
#ManagedBean(name="opc",eager = true) #SessionScoped
public class NewOPCHeadBean implements Serializable {
private long partID;
private String partDesc;
private String taskDesc;
private Date date;
private String opcDesc;
private List<Part> partList;
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public String getPartDesc() {
return partDesc;
}
public void setPartDesc(String partDesc) {
this.partDesc = partDesc;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public Date getDate() {
return new Date();
}
public void setDate(Date date) {
this.date = new Date();
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void showPartDesc()
{
HibernateDA hDA = new HibernateDA();
partDesc = hDA.showPartDescription(partID);
setPartDesc(partDesc);
}
public String submit()
{
return "/pages/admin/newopcdetailpage";
}
public void resetBean()
{
opcDesc="";
partID=0;
partDesc="";
}
}
#ManagedBean(name="opcD") #ViewScoped
public class NewOPCDetailBean implements Serializable {
private long partID;
private String taskDesc;
private long partNumber;
private Part part;
private Date date;
private String opcDesc;
private long task_opc_number;
private long task_nominal_time;
private OPCDetail opcDetail;
private List<Part> partList;
private static final ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
//private static ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
public ArrayList<OPCDetail> getOpcDetailList() {
return opcDetailList;
}
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public long getPartNumber() {
return partNumber;
}
public void setPartNumber(long partNumber) {
this.partNumber = partNumber;
}
public Part getPart() {
return part;
}
public void setPart(Part part) {
this.part = part;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public long getTask_nominal_time() {
return task_nominal_time;
}
public long getTask_opc_number() {
return task_opc_number;
}
public void setTask_opc_number(long task_opc_number) {
this.task_opc_number = task_opc_number;
}
public void setTask_nominal_time(long task_nominal_time) {
this.task_nominal_time = task_nominal_time;
}
public OPCDetail getOpcDetail() {
return opcDetail;
}
public void setOpcDetail(OPCDetail opcDetail) {
this.opcDetail = opcDetail;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void takePartNumber(ActionEvent e) throws Exception
{
Map m = e.getComponent().getAttributes();
partID = (Long)m.get("pID");
HibernateDA hDA = new HibernateDA();
part = hDA.takePart(partID);
partNumber = part.getPart_number();
opcDesc = (String) m.get("opcDesc");
date = (Date) m.get("opcDate");
}
public void addAction()
{
OPCDetail opcDetail1 = new OPCDetail(this.task_nominal_time,this.taskDesc);
int i = 0;
int j=0;
if (opcDetailList != null){
while (i < opcDetailList.size())
{
String tDesk = this.taskDesc.toLowerCase();
if (opcDetailList.get(i).getTask_desc().equals(tDesk))
{
j = 1;
break;
}
i++;
}
if(j == 0)
{
opcDetailList.add(opcDetail1);
}
}
taskDesc = "";
task_nominal_time = 0;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Edited",((OPCDetail) event.getObject()).getTask_desc());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
opcDetailList.remove((OPCDetail) event.getObject());
}
public void resetBean()
{
taskDesc = "";
task_nominal_time=0;
}
public String submitNewOPC()
{
int i = 0;
List<OPCDetail> opcDetailList1 = new ArrayList<OPCDetail>();
if (opcDetailList != null && opcDetailList.size() != 0){
while (i < opcDetailList.size())
{
OPCDetail opcDetail1 = new OPCDetail(i+1,opcDetailList.get(i).getTask_nominal_time(),opcDetailList.get(i).getTask_desc());
opcDetailList1.add(opcDetail1);
i++;
}
HibernateDA hDA = new HibernateDA();
OPC opc1 = new OPC();
opc1.setOpc_date(date);
opc1.setOpc_desc(opcDesc);
opc1.setPart(part);
opc1.setListOfTasks(opcDetailList1);
hDA.addNewOPC(opc1);
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opcD}");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opc}");
return "/index?faces-redirect=true";
}
}
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="2" cellpadding="5">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description"/>
<p:message for="opcDesc" />
<h:outputText value="" />
<h:outputText value="Part Number " style="font-weight:bold; font-size: .8em" />
<p:selectOneMenu value="#{opc.partID}" required="true">
<p:ajax listener="#{opc.showPartDesc()}" update="partdesc" />
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{opc.partList}" var="parts" itemLabel="#{parts.part_number}" itemValue="#{parts.id}"/>
</p:selectOneMenu>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<h:outputText id="partdesc" value="#{opc.partDesc}" label="Part Description:"/>
<p:message for="partdesc" />
<h:outputText value="" />
</h:panelGrid>
</p:panel>
<p:commandButton value="Register" action="#{opc.submit()}" actionListener="#{opcD.takePartNumber}" ajax="false" icon="ui-icon-check" validateClient="true" style="margin-right:10px">
<f:attribute name="pID" value="#{opc.partID}"/>
<f:attribute name="opcDate" value="#{opc.date}"/>
<f:attribute name="opcDesc" value="#{opc.opcDesc}"/>
</p:commandButton>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
</h:form>
</div>
</div>
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="4" cellpadding="5">
<p:row>
<p:column colspan="10">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description :" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description" disabled="true"/>
<p:message for="opcDesc" />
<h:outputText value="" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="partnum" value="Part Number:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partnum" value="#{opcD.partNumber}" required="true" label="Part Number" disabled="true"/>
</p:column>
<p:column>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partdesc" value="#{opc.partDesc}" required="true" label="Part Description" disabled="true"/>
</p:column>
</p:row>
</h:panelGrid>
</p:panel>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
<p:commandButton value="Submit" action="#{opcD.submitNewOPC}" ajax="false" icon="ui-icon-wrench">
<f:actionListener binding="#{opc.resetBean()}"/>
</p:commandButton>
</h:form>
</div>
</div>
<div>
<h:form id="form1">
<p:growl id="messages" showDetail="true"/>
<p:panel header="OPC Detail" style="width: 400px;font-size: .6em">
<p:panelGrid columns="2">
<h:outputLabel for="taskDesk" value="Task Description: " />
<p:inputText id="taskDesk" value="#{opcD.taskDesc}"/>
<h:outputLabel for="tasknumTime" value="Task Numinal Time: " />
<p:inputText id="tasknumTime" value="#{opcD.task_nominal_time}"/>
<f:facet name="footer">
<h:commandButton value="Register Item" action="#{opcD.addAction()}"/>
</f:facet>
</p:panelGrid>
<p:spacer height="30px;"/>
<p:dataTable value="#{opcD.opcDetailList}" var="o" widgetVar="50" style="font-size: .3em" editable="true">
<f:facet name="header">
OPC Detail List
</f:facet>
<p:ajax event="rowEdit" listener="#{opcD.onEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{opcD.onCancel}" update=":form1:messages" />
<p:column>
<f:facet name="header">
<h:outputText value="Task Desc" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_desc}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_desc}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Numinal Time" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_nominal_time}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_nominal_time}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</div>
I don't fully understand what are you trying to achieve ....
But I would like to reinitialize my bean if I return again inside it.
You mean, when you navigate away from page that is driven by the bean, and than when you navigate back to it, to reinitialize the bean again?
That is what #javax.faces.ViewScoped bean is for. It keeps the data of the fields in memory as long as you are on the view. When you navigate away from it, the data is no longer available. So turn you bean into #ViewScoped.
It seems you're structuring your beans in the wrong way. For your case, you should create another backing bean for the form using #RequestScoped. Then you can inject your #SessionScoped into the #RequestScoped bean to store whatever you need into the session.

Pagination on Primefaces datatable doesn't work

I am currently developing an application with JPA2, Spring 3, MyFaces 2.1 and Primefaces 4.0 RC1.
I developed a simple page with one datatable using pagination feature of primefaces, but when I click on page number (bottom or header), it simply doesn't work. No exception or javascript error is shown.
I've tested both in Chrome and Firefox. Same problem.
Here my code:
#ManagedBean
#ViewScoped
public class MeusCelularesTitularMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 5446365969371398743L;
private static final Logger logger = LogManager.getLogger(MeusCelularesTitularMB.class);
private CadastroGeral loggedUser;
private List<LinhaCelularTitular> listaCelularesTitular;
#PostConstruct
public void init() {
try {
this.loggedUser = getCadastroGeralService().loadUser(getAuthenticatedUser());
this.listarMeusCelularesTitular();
} catch (ServiceException e) {
logger.error("Erro ao consultar banco de dados", e);
throw new RuntimeException(e);
}
}
private void listarMeusCelularesTitular() {
try {
this.listaCelularesTitular = getLinhaCelularTitularSevice().getLinhasCelularesPorReponsavel(this.loggedUser.getMatricula());
} catch (ServiceException e) {
logger.error("Erro ao consultar banco de dados", e);
throw new RuntimeException(e);
}
}
private static CadastroGeralService getCadastroGeralService() {
return Faces.evaluateExpressionGet("#{cadastroGeralService}");
}
private static LinhaCelularTitularService getLinhaCelularTitularSevice() {
return Faces.evaluateExpressionGet("#{linhaCelularTitularService}");
}
public List<LinhaCelularTitular> getListaCelularesTitular() {
return listaCelularesTitular;
}
public void setListaCelularesTitular(List<LinhaCelularTitular> listaCelularesTitular) {
this.listaCelularesTitular = listaCelularesTitular;
}
}
And the XHTML:
<?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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="../../templates/template.xhtml">
<ui:define name="content">
<h:outputStylesheet library="css" name="meusCelulares.css" />
<h:form id="meusCelularesTitulares">
<p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/>
<h2>Celulares - Titular</h2>
<p:dataTable id="tblLinhaCelularesTitulares"
var="celTitular"
widgetVar="wdgLinhaCelularesTitulares"
value="#{meusCelularesTitularMB.listaCelularesTitular}"
rowKey="#{celTitular.id}"
paginator="true"
rows="10"
rowsPerPageTemplate="5,10,15"
emptyMessage="Nenhum celular encontrado na Base de Dados">
<p:column>
<f:facet name="header">
<h:outputText value="Ações" />
</f:facet>
<h:outputText value="A B C" />
</p:column>
<p:column styleClass="colunaCentralizada">
<f:facet name="header">
<h:outputText value="Código DDD" />
</f:facet>
<h:outputText value="#{celTitular.codigoDDD}" />
</p:column>
<p:column styleClass="colunaCentralizada">
<f:facet name="header">
<h:outputText value="Número" />
</f:facet>
<h:outputText value="#{celTitular.numeroLinha}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Nome" />
</f:facet>
<h:outputText value="#{celTitular.responsavel.nome}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
If you need some more information, please let me know.
Found the solution! Thanks to #XtremeBiker for the hints.
The <p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/> is referencing a dialog box that I forgot to add in the XHTML. So I added the code below and it worked.
<p:dialog modal="true"
widgetVar="statusDialog"
header="Aguarde..."
draggable="false"
closable="false"
resizable="false"
width="245"
height="25" >
<div align="center">
<p:graphicImage value="/resources/images/ajax-loader.gif" />
</div>
</p:dialog>
I use this code to block screen when a ajax request is processing.
Thanks again.

row editable data table column with dialog in jsf

I am new to JSF. I am using row editable data table in JSF primefaces. In row editable datatable input text column it have two ajax calls.one is blur and another one is Commandbuuton. I want to get value from this input text column from backing bean.
Here is my Code:
<h:form id="frm1">
<p:dataTable var="fert" value="#{fertilizerEntryBean.fertList}" id="fertList" editable="true" scrollable="true" scrollWidth="900" scrollHeight="250" >
<p:ajax event="rowEdit" listener="#{fertilizerEntryBean.onEdit}" update=":frm1:messages :frm1:ha_amount" />
<p:ajax event="rowEditCancel" listener="#{fertilizerEntryBean.onCancel}" update=":frm1:messages :frm1:ha_amount" />
<p:column headerText="...." width="15">
<p:rowEditor />
</p:column>
<p:column headerText="Receiver Plot No." width="150">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{fert.receiverPlot}" /></f:facet>
<f:facet name="input">
<p:inputText id="receiverPlot" value="#{fert.receiverPlot}" size="15">
<p:ajax event="blur" listener="#{fertilizerEntryBean.loadReceiverDetails(fert)}" update="receiverCode,receiverName"/>
</p:inputText>
<p:commandButton icon="ui-icon-search" style="height: 25px;position: absolute;" onclick="receiver_dialog.show();"/>
</f:facet>
</p:cellEditor>
</p:column>
</p:datatable>
</h:form>
<h:form id="receiverForm">
<p:dialog widgetVar="receiver_dialog" id="receiver_dialog">
<p:dataTable id="receiver_table" value="#{fertilizerEntryBean.mediumFertModel}" selection="#{fertilizerEntryBean.selectedList}" selectionMode="single" var="fert" rows="10" liveScroll="true" paginator="true" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,20">
<p:ajax event="rowSelect" listener="#{fertilizerEntryBean.onRowSelect}" update=':frm1:fertList:receiverPlot'/>
<p:column id="state_id_column" headerText="Receiver Code">
<h:outputText value="#{fert.receiverPlot}"/>
</p:column>
</p:dataTable>
<p:commandButton style="alignment-adjust: central;" value='OK' onclick="receiver_dialog.hide();"/>
</p:dialog>
</h:form>
And my Bean Class:
public class FertilizerEntryBean implements Serializable{
private List<FertModel> fertList=null;
private FertDataModel mediumFertModel;
private FertModel selectedList;
public List<FertModel> getFertList() {
return fertList;
}
public void setFertList(List<FertModel> fertList) {
this.fertList = fertList;
}
public FertDataModel getMediumFertModel() {
getReceiverCode();
return mediumFertModel;
}
public void setMediumFertModel(FertDataModel mediumFertModel) {
this.mediumFertModel = mediumFertModel;
}
public FertModel getSelectedList() {
return selectedList;
}
public void setSelectedList(FertModel selectedList) {
this.selectedList = selectedList;
}
public List<FertModel> getReceiverCode(){
Session session=HibernateUtil.getSessionFactory().openSession();
try{
List<DosVendormaster> vendorList=session.createCriteria(DosVendormaster.class).add(Restrictions.eq("vendortype", "CGRV")).add(Restrictions.eq("block", "X")).list();
if(vendorList.size()>0){
for (Iterator<DosVendormaster> it = vendorList.iterator(); it.hasNext();) {
DosVendormaster dosVendormaster = it.next();
fertList.add(new FertModel(dosVendormaster.getSapVendorcode()));
}
mediumFertModel=new FertDataModel(fertList);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return fertList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage(" Selected", ((FertModel) event.getObject()).getReceiverPlot());
FacesContext.getCurrentInstance().addMessage(null, msg);
FertModel fert=new FertModel();
fert.setReceiverPlot(((FertModel) event.getObject()).getReceiverPlot());
}
}
You can try this: FacesContext.getCurrentInstance().getViewRoot().findComponent(id) where id is something like frm1:fert:(rowIndex):receiverPlot. That's how you can find component and use getValue for that component. You can take rowIndex by setting rowIndexVar attributte to your datatable

Not getting value on selection of row using prime faces

i am having problem on getting the value on selection of row under the table field using prime faces.
Requirement is that as i select row the associated data and relevant information must be shown on same page here like i want to show only gender and address of particular user under the table .
I am using jsf 2.0 and prime faces 3.5
here is my code please check it where i have mistaking
package com.poc.faces;
all imports
.............
..............
#ManagedBean
#SessionScoped
public class UserManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<User> list = new ArrayList<User>();
static {
list.add(new User(3, "ankurjadiya", "jadiyaankur#gmail.com",
"88849113", new Date(), "M", "sare ga ma pa"));
list.add(new User(1, "Administrator", "admin#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
list.add(new User(2, "Guest", "guest#gmail.com", "9247469543",
new Date(), "M", "Hyderabad"));
list.add(new User(3, "John", "John#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
list.add(new User(4, "Paul", "Paul#gmail.com", "9247469543",
new Date(), "M", "Hyderabad"));
list.add(new User(5, "raju", "raju#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
}
private String username;
private String password;
private String searchUser;
private User selectedUser;
private UserDataModel dataModel;
public UserManagedBean() {
this.dataModel = new UserDataModel(list);
}
setter and getter of fields
..............
...............
public String login() {
if ("ankur".equalsIgnoreCase(getUsername())
&& "ankur".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
User data model class
public class UserDataModel extends ListDataModel<User> implements Serializable,
SelectableDataModel<User> {
public UserDataModel() {
}
public UserDataModel(List<User> users) {
super(users);
}
public User getRowData(String username) {
List<User> list = (List<User>) getWrappedData();
for (User user : list) {
if (user.getUsername().equals(username))
return user;
}
return null;
}
public Object getRowKey(User user) {
// TODO Auto-generated method stub
return user.getUsername();
}
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("User Selected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("User Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This is home.xtml where i retrieving the value
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
</h:head>
<h:body>
<h:form prependId="false" id="form">
<p:layout style="min-width:400px;min-height:200px;" id="layout"
fullPage="true">
<p:layoutUnit position="west" header="Menu" collapsible="true">
<p:menu>
<p:submenu label="Resources">
<p:menuitem value="Option1"
action="#{userManagedBean.getSearchUsersResults()}"
update="left_column" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<p:panel id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.dataModel}" var="user"
pagination="true" rows="5" selection="#{userManagedBean.selectedUser}" selectionMode="single" >
<p:column>
<f:facet name="header">UserId</f:facet>
<h:outputText value="#{user.userId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Username</f:facet>
<h:outputText value="#{user.username}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">EmailId</f:facet>
<h:outputText value=" #{user.emailId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Phone</f:facet>
<h:outputText value="#{user.phone}"></h:outputText>
</p:column>
</p:dataTable>
</center>
</p:panel>
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Gender:" />
<h:inputText value="#{userManagedBean.selectedUser.gender}" />
<h:outputText value="Address:" />
<h:inputText value="#{userManagedBean.selectedUser.address}" />
</h:panelGrid>
` </p:layoutUnit>
<p:layoutUnit position="south" footer="bottom">
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
</html>
You need to set the rowKey attribute on the <p:dataTable/> to properly enable row selection. The rowKey attribute should be set to a unique identifier for the entity in your datatable, like the primary key attribute. From your sample, it'll look something like:
<p:dataTable value="#{userManagedBean.dataModel}" rowKey="#{user.userId}" var="user" pagination="true" rows="5" selection="#{userManagedBean.selectedUser}" selectionMode="single">

setPropertyActionListener not working properly [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)

Resources