setPropertyActionListener not working properly [duplicate] - jsf-2

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 :)

Related

p:dataTable RowEdit keeping old values

I'm trying to update a value of a line edited on the datatable (editable = true, row edition). But I always keep getting the old value through the listener. Can you pls tell me where's my mistake? tks..
Here is the code:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="_template.xhtml">
<ui:define name="conteudo">
<h:form id="certificacao" >
<p:messages globalOnly="false" showSummary="true" showDetail="true" />
<p:growl id="messages" autoUpdate = "true"/>
<p:fieldset legend="Dados da Certificação">
<h:panelGrid columns="3" >
<p:outputLabel value="Nome da Certificação:" for="nomeCertificacao" style="font-weight:bold"/>
<p:inputText id="nomeCertificacao" value="#{certificacaoBean.certificacao.nomeCertificacao}"
required="true" requiredMessage="Nome da certificação não preenchido" >
</p:inputText>
<br/>
<h:outputLabel value="Descrição da Certificação:" for="descCertificacao" style="font-weight:bold"/>
<p:inputText id="descCertificacao" value="#{certificacaoBean.certificacao.descCertificacao}">
</p:inputText>
<br/>
<p:commandButton value="Gravar" action="#{certificacaoBean.gravar}" icon="fa fa-fw fa-save"
process="#this certificacao" update="#form certificacao" />
<br/>
</h:panelGrid>
</p:fieldset>
<p:dataTable
value="#{certificacaoBean.certificacoes}"
var="certificacao"
id="tabelaCertificacoes"
emptyMessage="Nenhuma certificação cadastrada"
editable="true"
style="margin-bottom:0px"
filteredValue="#{certificacaoBean.certificacaoSelecionada}"
widgetVar="tabelaCertificacoes">
<p:ajax event="rowEdit" listener="#{certificacaoBean.onRowEdit}" update=":certificacao:messages"/>
<p:ajax event="rowEditCancel" listener="#{certificacaoBean.onRowCancel}" update=":certificacao:messages" />
<p:column
headerText="Certificação"
filterBy="#{certificacao.nomeCertificacao}"
filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:outputText value="#{certificacao.nomeCertificacao}" />
</div>
</f:facet>
<f:facet name="input">
<p:inputText value="#{certificacao.nomeCertificacao}" style="width:100%" label="Certificação"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Descrição" filterBy="#{certificacao.descCertificacao}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{certificacao.descCertificacao}" /></f:facet>
<f:facet name="input"><p:inputText value="#{certificacao.descCertificacao}" style="width:100%" label="Descrição"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:3px">
<p:rowEditor />
</p:column>
<p:column style="width:3px">
<f:facet name="header">
<h:outputText value="" style="width:3px"/>
</f:facet>
<p:commandButton
action="#{certificacaoBean.removeCertificacao(certificacao)}"
icon="ui-icon-close"
title="Remover Certificação"
update="tabelaCertificacoes"
process="#this" >
<f:setPropertyActionListener
target="#{certificacaoBean.certificacaoSelecionada}"
value="#{certificacao}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
The bean part:
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import br.com.dao.DAO;
import br.com.model.Certificacao;
#ManagedBean(name="certificacaoBean")
#ViewScoped
public class CertificacaoBean implements Serializable {
private static final long serialVersionUID = 1L;
private Certificacao certificacao = new Certificacao();
public void setCertificacao(Certificacao certificacao) {
this.certificacao = certificacao;
}
private Certificacao certificacaoSelecionada;
public Certificacao getCertificacao() {
return certificacao;
}
public Certificacao getCertificacaoSelecionada() {
return certificacaoSelecionada;
}
public void setCertificacaoSelecionada(Certificacao certificacaoSelecionada) {
this.certificacaoSelecionada = certificacaoSelecionada;
}
public void removeCertificacao(Certificacao certificacao) {
new DAO<Certificacao>(Certificacao.class).remove(certificacaoSelecionada);
FacesMessage msg = new FacesMessage("Certificação excluída","");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Certificacao> getCertificacoes() {
return new DAO<Certificacao>(Certificacao.class).listaTodos();
}
public void gravar() {
System.out.println("Gravando Certificação " + this.certificacao.getNomeCertificacao());
if (certificacao.getNomeCertificacao().isEmpty()) {
FacesContext.getCurrentInstance().addMessage ("nomeCertificacao",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"O nome da certificação deve ser preenchido.", "O nome da certificação deve ser preenchido."));
return;
}
new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
this.certificacao = new Certificacao();
}
// Inicio Editor na Tabela
public void onRowEdit(RowEditEvent event) {
System.out.println("Passando no DAO retorno event Cod: " + ((((Certificacao) event.getObject()).getCodigoCertificacao())));
System.out.println("Passando no DAO retorno event Name: " + ((((Certificacao) event.getObject()).getNomeCertificacao())));
System.out.println("Passando no DAO retorno object: " + ((((Certificacao) event.getObject()))));
System.out.println("DAO evento " + event);
//new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
//Problema AQUI
new DAO<Certificacao>(Certificacao.class).atualiza((((Certificacao) event.getObject())));
this.certificacao = new Certificacao();
FacesMessage msg = new FacesMessage("Certificação editada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edição cancelada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
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);
}
}
}
And the dao:
package br.com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
public class DAO<T> {
private final Class<T> classe;
public DAO(Class<T> classe) {
this.classe = classe;
}
public void adiciona(T t) {
// consegue a entity manager
EntityManager em = new JPAUtil().getEntityManager();
// abre transacao
em.getTransaction().begin();
// persiste o objeto
em.persist(t);
// commita a transacao
em.getTransaction().commit();
// fecha a entity manager
em.close();
}
public void remove(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.remove(em.merge(t));
em.getTransaction().commit();
em.close();
}
public void atualiza(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.merge(t);
em.getTransaction().commit();
em.close();
}
public List<T> listaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).getResultList();
em.close();
return lista;
}
public T buscaPorId(Integer id) {
EntityManager em = new JPAUtil().getEntityManager();
T instancia = em.find(classe, id);
em.close();
return instancia;
}
public int contaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
long result = (Long) em.createQuery("select count(n) from certificacao n")
.getSingleResult();
em.close();
return (int) result;
}
public List<T> listaTodosPaginada(int firstResult, int maxResults) {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).setFirstResult(firstResult)
.setMaxResults(maxResults).getResultList();
em.close();
return lista;
}
}
In your code, You only update the message'id not the datatable's id. Try to update the form in the "update" attribute of ajax when edit the row.

Primefaces datatable is not updated when deleting element

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.

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.

getting the data on same browser window on click of row using primefaces or jsf

i am new on prime faces .I have a user with some attribute i have shown the table of user data . Now the requirement is that, on click of particular user row the data associated with that user must be shown on same window under the table please tell the way to do this i m trying to use layout but the problem is how i can get the data on same window .Give me learing site link if possible doing the same thing or tell me the procedure thanks
package com.poc.faces;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
#ViewScoped
public class UserManagedBean {
UserService service = new UserService();
private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSearchUser() {
return searchUser;
}
public void setSearchUser(String searchUser) {
this.searchUser = searchUser;
}
public Collection<User> getSearchUsersResults() {
return searchUsersResults = service.getAllUser();
}
public void setSearchUsersResults(Collection<User> searchUsersResults) {
this.searchUsersResults = searchUsersResults;
}
public User getSelectedUser() {
return selectedUser;
}
public String login() {
if ("sas".equalsIgnoreCase(getUsername())
&& "sas".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
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("Car Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This home.xhtml
where i am getting the tabledata
<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>
<p:layout style="min-width:400px;min-height:200px;" id="layout">
<p:layoutUnit position="center">
<h:form prependId="false">
<h:panelGroup layout="block" id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.searchUsersResults}"
var="user" pagination="true" rows="5" styleClass="userTable"
headerClass="userTableHeader"
rowClasses="userTableOddRow,userTableEvenRow"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<!-- <p:ajax event="rowSelect" listener="#{userManagedBean.onRowSelect}"
update=":form:display :form:growl" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{userManagedBean.onRowUnselect}" update=":form:growl" /> -->
<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>
</h:panelGroup>
</h:form>
<p:layoutUnit position="west" resizable="true" size="100"
minSize="40" maxSize="200">
West
</p:layoutUnit>
</p:layout>
</h:body>
</html>
I don't think there is a component of PF called layoutUnit. are you sure it's not layout?

checkbox datatable primefaces doesn't working

the checkbox datatable of primefaces library doesn't work for me, I tried to make the same code as the showcase of primefaces but when I check some rows and I click on the view button the selectedCars[] contains 0 rows :
here is my xhtml page :
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>TODO supply a title</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="multiCars" var="car" value="#{fortest.mediumCarsModel}" paginator="true" rows="10"
selection="#{fortest.selectedCars}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="id">
#{car.id}
</p:column>
<p:column headerText="date envoi">
#{car.dateEnvoi}
</p:column>
<p:column headerText="decision" >
#{car.decision}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{fortest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.dateEnvoi}
</p:dataList>
</p:dialog>
</h:form>
</h:body>
</html>
and here is my managed-Bean :
#ManagedBean
#SessionScoped
public class fortest implements Serializable {
private Commande[] selectedCars;
private dortestDataModel mediumCarsModel;
utilisateursHelper uh;
/**
* Creates a new instance of fortest
*/
public fortest() {
uh = new utilisateursHelper();
mediumCarsModel = new dortestDataModel(uh.getAllCommandes());
}
public void setSelectedCars(Commande[] selectedCars) {
System.out.println("alors je suis donc la size : "+selectedCars.length);
this.selectedCars = selectedCars;
}
public Commande[] getSelectedCars() {
return selectedCars;
}
public dortestDataModel getMediumCarsModel() {
return mediumCarsModel;
}
}
and here is my dataModel :
public class dortestDataModel extends ListDataModel<Commande> implements SelectableDataModel<Commande> {
utilisateursHelper uh;
public dortestDataModel() {
}
public dortestDataModel(List<Commande> data) {
super(data);
uh = new utilisateursHelper();
}
#Override
public Commande getRowData(String rowKey) {
//In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data
List<Commande> cars = (List<Commande>) uh.getAllCommandes();
for(Commande car : cars) {
if(car.getId().equals(rowKey))
return car;
}
return null;
}
#Override
public Object getRowKey(Commande car) {
return car.getId();
}
}
do you have any idea, thank you in advance
you forgot to attach rowCheckListener to your datatable like this
<p:ajax event="rowSelectCheckbox" listener="#{forTest.check}" />
below code is working for me. i am able to see the id and decision on the dialog.
XHTML:
i dint implement selectableDataModel, i just used rowKey attribute of datatable, you could use that as well
<h:form id="form">
<p:dataTable id="multiCars" var="car" value="#{forTest.carList}" paginator="true" rows="10"
rowKey ="#{car.id}" selection="#{forTest.selectedCars}" >
<p:ajax event="rowSelectCheckbox" listener="#{forTest.check}" />
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="id">
#{car.id}
</p:column>
<p:column headerText="decision" >
#{car.decision}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{forTest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.decision}
</p:dataList>
</p:dialog>
</h:form>
ManagedBean:
package managedbeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.jws.Oneway;
import org.primefaces.event.SelectEvent;
import beans.Car;
#ManagedBean(name="forTest")
#SessionScoped
public class forTest implements Serializable {
private List<Car> carList = new ArrayList<Car>();
private Car selectedCars[];
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car selectedCars[]) {
this.selectedCars = selectedCars;
}
public List<Car> getCarList() {
if(carList.size()==0) {
setCarList();
}
return carList;
}
public void setCarList() {
this.carList.add(new Car(1, "car1"));
this.carList.add(new Car(2, "car2"));
this.carList.add(new Car(3, "car3"));
}
public void check(SelectEvent event) {
System.out.println("in check");
}
}
Remove this:
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{forTest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.decision}
</p:dataList>
</p:dialog>

Resources