command button doesn't work on primefaces and ui:define - spring

So, I have a problem with primefaces, I'm trying have a button that reset a panel but that button just don't work, here's the code.
<?xml version="1.0" encoding="utf-8" ?>
<ui:composition template="templatePortal.xhtml" 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:a="http://www.ambientinformatica.com.br/jsf2" xmlns:p="http://primefaces.org/ui">
<ui:define name="head">
<style>
.col1 {
width: 10%;
}
.col2 {
width: 90%;
}
</style>
</ui:define>
<ui:define name="corpo">
<a:field label="Ficha: ">
<p:inputText id="ficha" label="ficha">
</p:inputText>
</a:field>
<a:field label="Dotação: ">
<p:inputMask id="dotacao" mask="99.99.9999.999.999.999" />
</a:field>
<a:field>
</a:field>
<a:newLine />
<p:panel id="panel" header="Orçamento">
<a:field label="Exercício">
<p:inputText id="exercicio"></p:inputText>
</a:field>
<a:newLine />
<a:field label="Unidade:">
<p:inputText id="unidade" value="#{ElaboracaoOrcamentariaControl.unidade.codigo}" label="unidade">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeUnidade" value="#{ElaboracaoOrcamentariaControl.unidade.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="Orgão:">
<p:inputText id="orgao" value="#{ElaboracaoOrcamentariaControl.orgao.codigo}">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeOrgao" value="#{ElaboracaoOrcamentariaControl.orgao.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="Função:">
<p:inputText id="funcao" value="#{ElaboracaoOrcamentariaControl.funcao.id}" label="funcao">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeFuncao" value="#{ElaboracaoOrcamentariaControl.funcao.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="SubFunção:">
<p:inputText id="subfuncao" value="#{ElaboracaoOrcamentariaControl.subFuncao.id}" label="subfuncao">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeSubfuncao" value="#{ElaboracaoOrcamentariaControl.subFuncao.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="Programa:">
<p:inputText id="programa" value="#{ElaboracaoOrcamentariaControl.programa.codigo}" label="programa">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomePrograma" value="#{ElaboracaoOrcamentariaControl.programa.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="Ação:">
<p:inputText id="acao" value="#{ElaboracaoOrcamentariaControl.acao.nroProjAtiv}" label="acao">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeAcao" value="#{ElaboracaoOrcamentariaControl.acao.descricaoReduzida}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:field label="elemento Despesa:">
<p:inputText id="elementoDespesa" value="#{ElaboracaoOrcamentariaControl.elementoDespesa.codigo}" label="elementoDespesa">
<p:ajax event="blur" listener="#{ElaboracaoOrcamentariaControl.validar}" update=":formCorpo:panel" />
</p:inputText>
</a:field>
<a:field>
<p:inputText id="nomeElementoDespesa" value="#{ElaboracaoOrcamentariaControl.elementoDespesa.descricao}" style="width:550px;"></p:inputText>
</a:field>
<a:newLine />
<a:newLine />
<a:newLine />
<p:commandButton process="#this" immediate="true">
<p:resetInput target=":formCorpo"/>
</p:commandButton>
<p:dataTable id="dataTable" var="fonte" value="#{ElaboracaoOrcamentariaControl.dotacao.fontes}">
<p:column headerText="Fonte">
<h:outputText value="#{fonte.fonte.codigo}" />
</p:column>
<p:column headerText="Descrição da fonte de recurso">
<h:outputText value="#{fonte.fonte.descricao}" />
</p:column>
<p:column headerText="Valor">
<h:outputText value="#{fonte.valor}" />
</p:column>
<p:column headerText="Excluir">
<p:commandButton id="selectButton" update=":form:display" immediate="true" icon="ui-icon-search" title="View" process="#this">
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
</ui:define>
and the back bean:
package br.com.webgoverno.contabilidade.controle;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import br.com.ambientinformatica.ambientjsf.util.UtilFaces;
import br.com.ambientinformatica.jpa.exception.PersistenciaException;
import br.com.webgoverno.contabilidade.persistencia.AcaoDao;
import br.com.webgoverno.contabilidade.persistencia.DotacaoDao;
import br.com.webgoverno.contabilidade.persistencia.ElementoDespesaDao;
import br.com.webgoverno.contabilidade.persistencia.FuncaoDao;
import br.com.webgoverno.contabilidade.persistencia.SubFuncaoDao;
import br.com.webgoverno.orcamento.entidade.Acao;
import br.com.webgoverno.orcamento.entidade.Dotacao;
import br.com.webgoverno.orcamento.entidade.ElementoDespesa;
import br.com.webgoverno.orcamento.entidade.FonteDotacao;
import br.com.webgoverno.orcamento.entidade.Funcao;
import br.com.webgoverno.orcamento.entidade.OrcamentoException;
import br.com.webgoverno.orcamento.entidade.Orgao;
import br.com.webgoverno.orcamento.entidade.Programa;
import br.com.webgoverno.orcamento.entidade.SubFuncao;
import br.com.webgoverno.orcamento.entidade.UnidadeOrcamentaria;
import br.com.webgoverno.orcamento.persistencia.OrgaoDao;
import br.com.webgoverno.orcamento.persistencia.ProgramaDao;
#Controller("ElaboracaoOrcamentariaControl")
#Scope("conversation")
public class ElaboracaoOrcamentariaControl extends ControleContabilidade {
private Dotacao dotacao = new Dotacao();
// campos da tela
private UnidadeOrcamentaria unidade;
private Orgao orgao;
private Funcao funcao;
private SubFuncao subFuncao;
private Programa programa;
private Acao acao;
private ElementoDespesa elementoDespesa;
// fim campos da tela
List<FonteDotacao> fonteDotacoes = new ArrayList<FonteDotacao>();
private List<Dotacao> dotacoes = new ArrayList<Dotacao>();
#Autowired
private DotacaoDao dotacaoDao;
#Autowired
private OrgaoDao orgaoDao;
#Autowired
private FuncaoDao funcaoDao;
#Autowired
private SubFuncaoDao subFuncaoDao;
#Autowired
private ProgramaDao programaDao;
#Autowired
private AcaoDao acaoDao;
#Autowired
private ElementoDespesaDao elementoDespesaDao;
#PostConstruct
public void inicializar() {
unidade = new UnidadeOrcamentaria();
orgao = new Orgao();
funcao = new Funcao();
subFuncao = new SubFuncao();
programa = new Programa();
acao = new Acao();
elementoDespesa = new ElementoDespesa();
}
public Dotacao getDotacao() {
return dotacao;
}
public void setDotacao(Dotacao dotacao) {
this.dotacao = dotacao;
}
public UnidadeOrcamentaria getUnidade() {
return unidade;
}
public void setUnidade(UnidadeOrcamentaria unidade) {
this.unidade = unidade;
}
public Orgao getOrgao() {
return orgao;
}
public void setOrgao(Orgao orgao) {
this.orgao = orgao;
}
public Funcao getFuncao() {
return funcao;
}
public void setFuncao(Funcao funcao) {
this.funcao = funcao;
}
public SubFuncao getSubFuncao() {
return subFuncao;
}
public void setSubFuncao(SubFuncao subFuncao) {
this.subFuncao = subFuncao;
}
public Programa getPrograma() {
return programa;
}
public void setPrograma(Programa programa) {
this.programa = programa;
}
public Acao getAcao() {
return acao;
}
public void setAcao(Acao acao) {
this.acao = acao;
}
public ElementoDespesa getElementoDespesa() {
return elementoDespesa;
}
public void setElementoDespesa(ElementoDespesa elementoDespesa) {
this.elementoDespesa = elementoDespesa;
}
public List<Dotacao> getDotacoes() {
return dotacoes;
}
public void setDotacoes(List<Dotacao> dotacoes) {
this.dotacoes = dotacoes;
}
public DotacaoDao getDotacaoDao() {
return dotacaoDao;
}
public void setDotacaoDao(DotacaoDao dotacaoDao) {
this.dotacaoDao = dotacaoDao;
}
public void confirmar(ActionEvent evt) {
unidade.setOrgao(orgao);
programa.getAcoes().add(acao);
dotacao.setUnidade(unidade);
dotacao.setPrograma(programa);
try {
dotacaoDao.alterar(dotacao);
UtilFaces.addMensagemFaces("Salvo com sucesso");
} catch (Exception e) {
UtilFaces.addMensagemFaces(e);
}
}
public List<Dotacao> listarDotacoes() {
try {
this.dotacoes = dotacaoDao.listar();
} catch (PersistenciaException e) {
UtilFaces.addMensagemFaces(e);
}
return dotacoes;
}
public void pesquisaDotacao() {
try {
this.dotacao = dotacaoDao.consultar(this.dotacao);
} catch (PersistenciaException e) {
UtilFaces.addMensagemFaces(e);
}
}
public void validar(AjaxBehaviorEvent event) {
try {
/*
* if (unidade.getCodigo() != null &&
* unidade.consultarPorCodigo(unidade).size() > 0) { orgao =
* orgaoDao.consultarPorCodigo(orgao).get(0); }
*/
if (orgao.getCodigo() != null && orgaoDao.consultarPorCodigo(orgao).size() > 0) {
orgao = orgaoDao.consultarPorCodigo(orgao).get(0);
} else orgao = new Orgao();
if (funcao != null && (funcao.getId() != null) && (funcaoDao.consultar(funcao.getId()) != null)) {
funcao = funcaoDao.consultar(funcao.getId());
} else funcao = new Funcao();
if (subFuncao != null && (subFuncao.getId() != null) && (subFuncaoDao.consultar(subFuncao.getId()) != null)) {
subFuncao = subFuncaoDao.consultar(subFuncao.getId());
} else subFuncao = new SubFuncao();
if (programa.getCodigo() != null && programaDao.consultarPorCodigo(programa).size() > 0) {
programa = programaDao.consultarPorCodigo(programa).get(0);
} else programa = new Programa();
if (acao.getNroProjAtiv() != null && acaoDao.consultarPorCodigo(acao).size() > 0) {
acao = acaoDao.consultarPorCodigo(acao).get(0);
} else acao = new Acao();
if (elementoDespesa.getCodigo() != null && elementoDespesaDao.consultarPorCodigo(elementoDespesa).size() > 0) {
elementoDespesa = elementoDespesaDao.consultarPorCodigo(elementoDespesa).get(0);
} else elementoDespesa = new ElementoDespesa();
} catch (OrcamentoException e) {
UtilFaces.addMensagemFaces(e);
e.printStackTrace();
} catch (PersistenciaException e) {
UtilFaces.addMensagemFaces(e);
e.printStackTrace();
}
}
public void adicionaFonte(FonteDotacao fonteDotacao) {
fonteDotacoes.add(fonteDotacao);
}
}
The parent template has a form defyned in it.
I'm stuck in it so any tip will help, thank.

The most common reasons for an UICommand to not work are explained here: commandButton/commandLink/ajax action/listener method not invoked or input value not updated
From your given code, your case seems to fall in case 1: the components may not be inside a <h:form> component. Make sure in your template file you have a structure like this:
<h:form>
<ui:insert name="corpo" />
</h:form>
But note that this is not a good approach because is like having a god form in your page. It will be better if in your template file you have the <ui:insert name="corpo" /> without being inside any form and start defining the <h:form> inside your page. To give an example (based on your posted Facelets code):
<h:form>
<p:dataTable id="dataTable" var="fonte" value="#{ElaboracaoOrcamentariaControl.dotacao.fontes}">
<p:column headerText="Fonte">
<h:outputText value="#{fonte.fonte.codigo}" />
</p:column>
<p:column headerText="Descrição da fonte de recurso">
<h:outputText value="#{fonte.fonte.descricao}" />
</p:column>
<p:column headerText="Valor">
<h:outputText value="#{fonte.valor}" />
</p:column>
<p:column headerText="Excluir">
<p:commandButton id="selectButton" update=":form:display" immediate="true" icon="ui-icon-search" title="View" process="#this">
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>

Related

primefaces cascade selectonemenu

I have 3 dropdowns, the second has to be loaded based on the selected option of the first. And the third based on the selected option of the second.
This is the page:
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Empresa:" for="selectCompany" />
<p:selectOneMenu id="selectCompany" value="#{dropdownBean.company}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="company">
<p:ajax process="#this" event="change"
update="selectBranch, selectVendor" />
<f:selectItems value="#{dropdownBean.companies}" var="companyItem"
itemLabel="#{companyItem.corporateName}" itemValue="#{companyItem}" />
<p:column>
<h:outputText value="#{company.corporateName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Surcursal:" for="#selectBranch" />
<p:selectOneMenu id="#selectBranch" value="#{dropdownBean.branch}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="branch">
<p:ajax process="#this" event="change" update="#selectVendor" />
<f:selectItem itemLabel="SELECCIONE SUCURSAL" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownBean.branches}" var="branchItem"
itemLabel="#{branchItem.branchName}" itemValue="#{branchItem}" />
<p:column>
<h:outputText value="#{branch.branchName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Vendedor: " for="#selectVendor" />
<p:selectOneMenu id="#selectVendor" value="#{dropdownBean.vendor}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="vendor">
<f:selectItem itemLabel="SELECCIONE VENDEDOR" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownBean.vendors}" var="vendorItem"
itemLabel="#{vendorItem.vendorName}" itemValue="#{vendorItem}" />
<p:column>
<h:outputText value="#{vendor.vendorName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
And the backbean:
#ManagedBean
public class DropdownBean {
#Inject
private CompanyBC companyBC;
#Inject
private BranchBC branchBC;
#Inject
private VendorBC vendorBC;
private V_Companies company;
private V_Branches branch;
private V_Vendors vendor;
private List<V_Companies> companies;
private List<V_Branches> branches;
private List<V_Vendors> vendors;
#PostConstruct
public void allCompanies() {
companies = companyBC.allCompanies();
}
public List<V_Companies> getCompanies() {
return companies;
}
public void setCompanies(List<V_Companies> companies) {
this.companies = companies;
}
public List<V_Branches> getBranches() {
if(company!=null)
branches = branchBC.allCompanyBranches(company.getCompanyId());
return branches;
}
public void setBranches(List<V_Branches> branches) {
this.branches = branches;
}
public List<V_Vendors> getVendors() {
if(company!=null && branch!=null)
vendors = vendorBC.allBranchVendors(company.getCompanyId(), branch.getBranchId());
return vendors;
}
public void setVendors(List<V_Vendors> vendors) {
this.vendors = vendors;
}
public V_Companies getCompany() {
return company;
}
public void setCompany(V_Companies company) {
this.company = company;
}
public V_Branches getBranch() {
return branch;
}
public void setBranch(V_Branches branch) {
this.branch = branch;
}
public V_Vendors getVendor() {
return vendor;
}
public void setVendor(V_Vendors vendor) {
this.vendor = vendor;
}
}
The first two dropdowns work great but the last one does not. Apparently cannot be more than one p:ajax for the same event or something like that. Any suggestions please?
adding a listener worked:
<p:ajax process="#this" listener="#{userEditMB.onBranchChange}" event="change" update="selectVendor" />
public void onBranchChange(AjaxBehaviorEvent event) {
setBranch((V_Branches) ((UIOutput) event.getSource()).getValue());
vendors = vendorBC.allBranchVendors(getBranch().getCompanyId(),
getBranch().getBranchId());
}
I tried listener before but passing the Id's as parameters. Passing AjaxBehaviorEvent and casting to the object was the answer for me. I hope helps someone
Thanks!

capture selected text from inputTextArea primefaces jsf

I want to capture selected text from inputTextArea on ajax dblclick or select event.How can I do this ?
The code below selects everything in the text area (which I don't want). Thank you very much.
<h:form id="form">
<p:panel header="Select Text">
<h:panelGrid columns="3" cellpadding="5">
<h:outputText value="Text: " />
<p:inputTextarea id="textarea"
value="#{selectedTextBean.selectedText}">
<p:ajax event="select" update="selectedText" />
</p:inputTextarea>
<h:outputText id="selectedText"
value="#{selectedTextBean.selectedText}" />
</h:panelGrid>
</p:panel>
</h:form>
Here is SelectedTextBean
#ManagedBean
#ViewScoped
public class SelectedTextBean {
public SelectedTextBean() {
}
private String selectedText;
public String getSelectedText() {
return selectedText;
}
public void setSelectedText(String selectedText) {
this.selectedText = selectedText;
}
}
You can use this plugin jquery-textrange.
xhtml
<p:inputTextarea onselect="setSelectedText()" />
<p:remoteCommand name="setSelectedTextCommand"
actionListener="#{mainBean.setSelectedText()}"
update="currentSelectedText" />
Selected Text is:
<h:outputText value="#{mainBean.selectedTextInArea}"
id="currentSelectedText" />
<h:outputScript library="js" name="jquery-textrange.js" />
<script>
function setSelectedText() {
var range = $('.ui-inputtextarea').textrange();// general selector
setSelectedTextCommand([{name: 'selectedText', value: range.text}]);
}
</script>
Bean
private String selectedTextInArea;
public void setSelectedText() {
FacesContext context = FacesContext.getCurrentInstance();
Map map = context.getExternalContext().getRequestParameterMap();
selectedTextInArea = (String) map.get("selectedText");
}
public String getSelectedTextInArea() {
return selectedTextInArea;
}
public void setSelectedTextInArea(String selectedTextInArea) {
this.selectedTextInArea = selectedTextInArea;
}
And Here's a live demo on Primefaces TextArea Selection, and on github.
You can do that sending a parameter to a remote command as follows:
The View
<h:form id="form">
<p:panel header="Select Text">
<h:panelGrid columns="3" cellpadding="5">
<h:outputText value="Text: " />
<h:panelGroup>
<p:inputTextarea id="textarea"
value="#{selectedTextBean.selectedText}" onselect="processSelection();" />
<p:remoteCommand name="sendSelection" actionListener="#{selectedTextBean.onSelect}" update="selectedText" process="#this" />
</h:panelGroup>
<h:outputText id="selectedText"
value="#{selectedTextBean.selectedText}" />
</h:panelGrid>
</p:panel>
</h:form>
<script>
function processSelection() {
var selectedText = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
sendSelection([{name: 'selectedText', value: selectedText}]);
}
</script>
Note that the text selection changes depending on the browser.
The Bean
import java.io.Serializable;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ViewScoped
public class SelectedTextBean implements Serializable {
public SelectedTextBean() {
}
private String selectedText;
public void onSelect() {
FacesContext context = FacesContext.getCurrentInstance();
Map map = context.getExternalContext().getRequestParameterMap();
selectedText = (String) map.get("selectedText");
}
public String getSelectedText() {
return selectedText;
}
public void setSelectedText(String selectedText) {
this.selectedText = selectedText;
}
}

Two ajax updates with h:selectOneMenu f:ajax

In short, if a component has been updated by Ajax, it can not launch new events Ajax
I have three h:selectOneMenu: A, B and C.
When I fire change event in A, then update the B h:selectOneMenu.
When I fire change event in B, then update the C h:selectOneMenu.
The problem is that when the content of B h:selectOneMenu is updated, the ajax in B don't work and C never can't be updated.
<h:selectOneMenu id="A" value="#{paqueteBean.mes}" label="a">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItem itemLabel="Enero" itemValue="ENERO" />
<f:selectItem itemLabel="Febrero" itemValue="FEBRERO" />
<f:ajax listener="#{paqueteBean.changeMes}" render="B" />
</h:selectOneMenu>
<h:selectOneMenu id="B" value="#{paqueteBean.origen}" label="b">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.origenes}" />
<f:ajax listener="#{paqueteBean.changeOrigen}" render="C"/>
</h:selectOneMenu>
<h:selectOneMenu id="C" value="#{paqueteBean.zona}" label="c">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.zonas}" />
</h:selectOneMenu>
The ajax response is good, but simply don't work after the update:
<?xml version='1.0' encoding='UTF-8'?>
<partial-response id="j_id1"><changes><update id="B"><![CDATA[<select id="B" name="b" size="1" onchange="mojarra.ab(this,event,'valueChange','#this','C')"> <option value="">Seleccione...</option>
<option value="BUE">Ezeiza o Aeroparque</option>
</select>]]></update><update id="j_id1:javax.faces.ViewState:0"><![CDATA[-2984590031183218074:6198891110668113457]]></update></changes></partial-response>
UPDATE!
With PrimeFaces I have the same behavior:
<h:form id="filtro">
<p:selectOneMenu id="A" value="#{paqueteBean.mes}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItem itemLabel="Enero" itemValue="ENERO" />
<f:selectItem itemLabel="Febrero" itemValue="FEBRERO" />
<f:selectItem itemLabel="Marzo" itemValue="MARZO" />
<p:ajax listener="#{paqueteBean.changeMes}" update="B" />
</p:selectOneMenu>
<p:selectOneMenu id="B" value="#{paqueteBean.origen}"
disabled="#{empty paqueteBean.mes}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.origenes}" />
<p:ajax listener="#{paqueteBean.changeOrigen}" update="C"
process="origen mesSalida" />
</p:selectOneMenu>
<p:selectOneMenu id="C" value="#{paqueteBean.zona}"
disabled="#{empty paqueteBean.mes or empty paqueteBean.origen}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.zonas}" />
</p:selectOneMenu>
When I change some A values, the method in backing bean is fired, but when I change some B value, the method in backing bean is not fired.
The most strange is that for items that existed in B before the ajax update, the backing bean is called.
Backing Bean, nothing special:
public void changeMes(){
logger.debug("en changeMes el Mes es: " + this.mes);
this.origenes = new HashMap<String, String>();
this.origenes.put("Ezeiza o Aeroparque", "BUE");
}
public void changeOrigen(){
logger.debug("Mes: " + this.mes);
logger.debug("Origen" + this.origen);
this.zonas = new HashMap<String, String>();
this.zonas.put("Argentina", "AR");
this.zonas.put("Brasil", "BR");
}
public void changeZona(){
logger.debug("Mes: " + this.mes);
logger.debug("Origen" + this.origen);
logger.debug("Zona" + this.zona);
this.destinos = new HashMap<>();
this.destinos.put("Mar del Plata", "MDQ");
this.destinos.put("Punta Lara", "LTA");
}
UPDATE:
here is a working example:
Bean:
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.SelectItem;
#ManagedBean(name="myBean")
#SessionScoped
public class MyBean {
private boolean bDisabled;
private boolean cDisabled;
private String selectedA;
private String selectedB;
private String selectedC;
private ArrayList<SelectItem> aItems;
private ArrayList<SelectItem> bItems;
private ArrayList<SelectItem> cItems;
public MyBean() {
}
#PostConstruct
public void init(){
try{
this.bDisabled = new Boolean(true);
this.cDisabled = new Boolean(true);
this.aItems = new ArrayList<SelectItem>();
this.bItems = new ArrayList<SelectItem>();
this.cItems = new ArrayList<SelectItem>();
this.aItems.add(new SelectItem("NONE", "---?"));
this.aItems.add(new SelectItem("A1", "A 1"));
this.aItems.add(new SelectItem("A1", "A 1"));
this.aItems.add(new SelectItem("A1", "A 1"));
this.bItems.add(new SelectItem("NONE", "---?"));
this.cItems.add(new SelectItem("NONE", "---?"));
}catch(Exception e){
e.printStackTrace();
}
}
public final void selectA(final AjaxBehaviorEvent event){
try{
System.out.println(this.selectedA);
this.bItems.clear();
this.bItems.add(new SelectItem("NONE", "---?"));
if(this.selectedA.equals("NONE") ){
this.setbDisabled(true);
return;
}
this.bItems.add(new SelectItem("B1","B 1"));
this.setbDisabled(false);
}catch(Exception ex){
ex.printStackTrace();
}
}
public final void selectB(final AjaxBehaviorEvent event){
try{
System.out.println(this.selectedB);
this.cItems.clear();
this.cItems.add(new SelectItem("NONE", "---?"));
if(this.selectedB.equals("NONE") ){
this.setcDisabled(true);
return;
}
this.cItems.add(new SelectItem("C1","C 1"));
this.setcDisabled(false);
}catch(Exception ex){
ex.printStackTrace();
}
}
public final void selectC(final AjaxBehaviorEvent event){
try{
System.out.println(this.selectedC);
}catch(Exception ex){
ex.printStackTrace();
}
}
public String getSelectedA() {
return selectedA;
}
public void setSelectedA(String selectedA) {
this.selectedA = selectedA;
}
public String getSelectedB() {
return selectedB;
}
public void setSelectedB(String selectedB) {
this.selectedB = selectedB;
}
public String getSelectedC() {
return selectedC;
}
public void setSelectedC(String selectedC) {
this.selectedC = selectedC;
}
public ArrayList<SelectItem> getaItems() {
return aItems;
}
public void setaItems(ArrayList<SelectItem> aItems) {
this.aItems = aItems;
}
public ArrayList<SelectItem> getbItems() {
return bItems;
}
public void setbItems(ArrayList<SelectItem> bItems) {
this.bItems = bItems;
}
public ArrayList<SelectItem> getcItems() {
return cItems;
}
public void setcItems(ArrayList<SelectItem> cItems) {
this.cItems = cItems;
}
public boolean isbDisabled() {
return bDisabled;
}
public void setbDisabled(boolean bDisabled) {
this.bDisabled = bDisabled;
}
public boolean iscDisabled() {
return cDisabled;
}
public void setcDisabled(boolean cDisabled) {
this.cDisabled = cDisabled;
}
}
XHTML:
<!DOCTYPE html>
<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"
>
<h:head>
<meta charset="UTF-8" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Test</title>
</h:head>
<body>
<f:view>
<h:form id="dataForm">
<h:selectOneMenu value="#{myBean.selectedA}" style="width: 100%;">
<f:selectItems value="#{myBean.aItems}" />
<f:ajax execute="#form" render="#form" listener="#{myBean.selectA}" />
</h:selectOneMenu>
<h:selectOneMenu disabled="#{myBean.bDisabled}" value="#{myBean.selectedB}" style="width: 100%;">
<f:selectItems value="#{myBean.bItems}" />
<f:ajax execute="#form" render="#form" listener="#{myBean.selectB}" />
</h:selectOneMenu>
<h:selectOneMenu disabled="#{myBean.cDisabled}" value="#{myBean.selectedC}" style="width: 100%;">
<f:selectItems value="#{myBean.cItems}" />
<f:ajax execute="#form" render="#form" listener="#{myBean.selectC}" />
</h:selectOneMenu>
</h:form>
</f:view>
</body>
</html>
Instead of using <f:ajax/> you can also use the PrimeFaces-Ajax-Element <p:ajax> which offers you a update-attribute:
<p:ajax update="elementID"/>
Another possibility I can recommend: Have you tried to put your SelectOneMenus in a <h:form>-Element? It looks like you didn't use a form. Do so, then you can always update the form in order to make the menues change. Worked good for me at my projects.
I had the same mistake.
For the second selectonemenu i miss a setter.
In your code it was the setter for myBean.selectedB.
Check all your getter and setter. Maybe there is the problem

PrimeFaces PropertyNotFoundException Target Unreachable, 'null' returned null

I am having problems with the site I am creating. I am new to Faces 2.0 and was only using JSP and now shifting to Faces 2.0. I have a page that adds and deletes a location Zip Code. The edit part works but the add part, I am having an error:
PropertyNotFoundException, Target Unreachable, 'null' returned null.
on following value:
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
I dont know why it does not work because the edit part works and they use the same ManagedBean.
I am using Spring 3.1.3 With Hibernate and PrimeFaces 3.5. I hope someone answers my question as I dont know how to solve this.
I suspect that whenever I click the button, a new object is being created as I am using a #RequestScoped annotation.
I tried to from instantiating the entity class on #PostConstruct Method, even instantiating the entity on the declaration and setting an empty string on description and nothing works.
It doesnt get to call save() method and seems to get stuck on the Update Model Values Phase
Below is my xhtml page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition template="/WEB-INF/views/template.xhtml">
<ui:define name="content">
<table border="0" width="100%">
<tr align="center">
<td><c:if test="${not empty param.login_error}">
<div class="error"
style="font-family: serif; font-size: medium; color: red;">
#{msg['label.login.invalidlogon']}<br />
#{sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
</div>
</c:if> <c:if test="">
<div class="message"
style="font-family: serif; font-size: medium; color: red;">
${sessionScope.messageVariable}</div>
</c:if> </td>
</tr>
</table>
<p:panelGrid columns="3">
<h:form id="form">
<f:facet name="header">
<p:row>
<p:column colspan="3">#{msg['usrmnt.header']}</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="userSearch" value="Search ZipCode/Description" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="userSearch"
value="#{zipCodeMaintennanceBean.searchString}">
</p:inputText>
</p:column>
<p:column>
<p:commandButton value="#{msg['usrmnt.searchbutton']}"
actionListener="#{zipCodeMaintennanceBean.search}"
update="panel,dataTable" process="#form" />
<p:commandButton value="Add"
actionListener="#{zipCodeMaintennanceBean.triggerAdd}"
update="panel,:#{p:component('displayadd')}"
oncomplete="addDialog.show()" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3" styleClass="ui-widget-header">
<p:spacer height="0" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
<p:outputPanel id="panel">
<p:dataTable id="dataTable" var="zip"
value="#{zipCodeMaintennanceBean.zipCodes}" paginator="true"
rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15"
rendered="#{zipCodeMaintennanceBean.hasSearchResult}"
selectionMode="single"
selection="#{zipCodeMaintennanceBean.selectedZipCode}"
rowKey="#{zip.zipcode}">
<p:ajax event="rowSelect"
listener="#{zipCodeMaintennanceBean.onRowSelect}"
oncomplete="editDialog.show()"
update=":#{p:component('display')}" />
<p:ajax event="rowUnselect"
listener="#{zipCodeMaintennanceBean.onRowUnselect}" />
<f:facet name="header">
Users
</f:facet>
<p:column>
<f:facet name="header">
<h:outputText value="Zip Code" />
</f:facet>
<h:outputText value="#{zip.zipcode}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{zip.description}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:column>
</p:row>
<p:dialog header="Add ZipCode" widgetVar="addDialog" id="addDialog"
modal="true" showEffect="clip" hideEffect="fold" dynamic="true">
<p:outputPanel autoUpdate="true">
<p:panelGrid cellpadding="4" id="displayadd"
rendered="#{zipCodeMaintennanceBean.addMode}"
styleClass="maintennancePanelGrid">
<f:facet name="header">
<p:row>
<p:column colspan="3">
<h:outputText value="Add Zip Code" />
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="zipcodeAdd" value="Zip Code:" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="zipcodeAdd"
value="#{zipCodeMaintennanceBean.selectedZipCode.zipcode}"
label="Zip Code" required="true">
<f:validateLength for="userName" minimum="4" maximum="6"></f:validateLength>
</p:inputText>
</p:column>
<p:column>
<p:message for="zipcodeAdd"></p:message>
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="descriptionAdd" value="Description: " />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="descriptionAdd"
required="true"
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
label="Description"></p:inputText>
</p:column>
<p:column>
<p:message for="descriptionAdd"></p:message>
</p:column>
</p:row>
<f:facet name="footer">
<p:row>
<p:column styleClass="text-align:center" colspan="3">
<p:commandButton value="Submit"
update=":#{p:component('displayadd')}"
action="#{zipCodeMaintennanceBean.add}"
oncomplete="if (!args.validationFailed) addDialog.hide()" process="#form" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
</p:column>
</p:row>
</f:facet>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dialog header="Edit ZipCode" resizable="false" id="editDialog"
widgetVar="editDialog" modal="true" showEffect="clip"
hideEffect="fold" closeOnEscape="true" dynamic="true">
<p:outputPanel autoUpdate="true">
<p:panelGrid cellpadding="4" id="display"
rendered="#{zipCodeMaintennanceBean.hasSelectedZipCode}"
styleClass="maintennancePanelGrid">
<f:facet name="header">
<p:row>
<p:column colspan="3">
<h:outputText value="Edit Zip Code" />
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="zipcode" value="Zip Code:" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="zipcode"
value="#{zipCodeMaintennanceBean.selectedZipCode.zipcode}"
label="Zip Code" disabled="true">
<f:validateLength for="userName" minimum="4" maximum="6"></f:validateLength>
</p:inputText>
</p:column>
<p:column>
<p:message for="zipcode"></p:message>
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="descripton" value="Description: " />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="description"
required="true"
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
label="Description"></p:inputText>
</p:column>
<p:column>
<p:message for="description"></p:message>
</p:column>
</p:row>
<f:facet name="footer">
<p:row>
<p:column styleClass="text-align:center" colspan="3">
<p:commandButton value="Submit"
update="panel,:#{p:component('display')}"
action="#{zipCodeMaintennanceBean.save}"
oncomplete="if (!args.validationFailed) editDialog.hide()" />
<p:commandButton value="Delete"
update="panel,:#{p:component('display')}"
action="#{zipCodeMaintennanceBean.delete}"
oncomplete="if (!args.validationFailed) editDialog.hide()"
process="#this">
</p:commandButton>
<p:confirmDialog global="true" showEffect="fade"
hideEffect="explode">
<p:commandButton value="Yes" type="button"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
<p:commandButton value="No" type="button"
styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
</p:confirmDialog>
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
</p:column>
</p:row>
</f:facet>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</p:panelGrid>
</ui:define>
</ui:composition>
</html>
Below is my Backing Bean:
package com.siteam.web.bean;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.siteam.web.invsys.dao.ZipCodeDao;
import com.siteam.web.invsys.entities.TblZipcodes;
#ManagedBean(name = "zipCodeMaintennanceBean")
#RequestScoped
#Service
public class ZipCodeMaintennanceBean {
private TblZipcodes selectedZipCode = new TblZipcodes();
private boolean hasSelectedZipCode = false;
private List<TblZipcodes> zipCodes = new ArrayList<TblZipcodes>();
private ZipCodeDao zipCodeDao;
private boolean hasSearchResult = false;
private String searchString;
private boolean addMode;
public void triggerAdd() {
init();
this.addMode = true;
}
public String add() {
try {
this.selectedZipCode.setDateupdated(Calendar.getInstance()
.getTime());
this.zipCodeDao.add(this.selectedZipCode);
this.zipCodeDao.refresh(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Saved. ",
"Saved Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
init();
this.addMode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
public String save() {
try {
this.selectedZipCode.setDateupdated(Calendar.getInstance()
.getTime());
this.zipCodeDao.update(this.selectedZipCode);
this.zipCodeDao.refresh(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
init();
// RequestContext.getCurrentInstance().execute("editDialog.hide()");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Saved. ",
"Saved Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
hasSearchResult = false;
this.hasSelectedZipCode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
public String delete() {
try {
this.zipCodeDao.delete(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
init();
// RequestContext.getCurrentInstance().execute("editDialog.hide()");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Deleted. ",
"Deleted Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
hasSearchResult = false;
this.hasSelectedZipCode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
#PostConstruct
public void init() {
this.hasSelectedZipCode = false;
this.hasSearchResult = false;
this.addMode = false;
this.selectedZipCode = new TblZipcodes();
this.selectedZipCode.setDescription("");
this.zipCodes.clear();
}
public void search() {
hasSearchResult = false;
TblZipcodes zipCode = new TblZipcodes();
zipCode.setZipcode(searchString);
this.zipCodes = zipCodeDao.findZipCodes(zipCode);
if (zipCodes.size() > 0) {
hasSearchResult = true;
}
}
public TblZipcodes getSelectedZipCode() {
return selectedZipCode;
}
public void setSelectedZipCode(TblZipcodes selectedZipCode) {
this.selectedZipCode = selectedZipCode;
}
public boolean isHasSelectedZipCode() {
return hasSelectedZipCode;
}
public void setHasSelectedZipCode(boolean hasSelectedZipCode) {
this.hasSelectedZipCode = hasSelectedZipCode;
}
public List<TblZipcodes> getZipCodes() {
return zipCodes;
}
public void setZipCodes(List<TblZipcodes> zipCodes) {
this.zipCodes = zipCodes;
}
public ZipCodeDao getZipCodeDao() {
return zipCodeDao;
}
#Autowired
public void setZipCodeDao(ZipCodeDao zipCodeDao) {
this.zipCodeDao = zipCodeDao;
}
public boolean isHasSearchResult() {
return hasSearchResult;
}
public void setHasSearchResult(boolean hasSearchResult) {
this.hasSearchResult = hasSearchResult;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public void onRowSelect(SelectEvent event) {
this.selectedZipCode = (TblZipcodes) event.getObject();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Selected Zip Code", "Zip Code Selected: "
+ selectedZipCode.getZipcode());
zipCodeDao.refresh(this.selectedZipCode);
FacesContext.getCurrentInstance().addMessage(null, msg);
this.hasSelectedZipCode = true;
}
public void onRowUnselect(UnselectEvent event) {
// FacesMessage msg = new FacesMessage("Car Unselected", ((Car)
// event.getObject()).getModel());
this.selectedZipCode = new TblZipcodes();
this.hasSelectedZipCode = false;
}
public boolean isAddMode() {
return addMode;
}
public void setAddMode(boolean addMode) {
this.addMode = addMode;
}
}
Below is my Zip Code Entity Code
package com.siteam.web.invsys.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "TBL_ZIPCODES", schema = "INVSYS")
public class TblZipcodes implements java.io.Serializable {
private String zipcode;
private String description = "";
private Date dateupdated;
private Set<TblCustomer> tblCustomers = new HashSet<TblCustomer>(0);
public TblZipcodes() {
}
public TblZipcodes(String zipcode) {
this.zipcode = zipcode;
}
public TblZipcodes(String zipcode, String description, Date dateupdated,
Set tblCustomers) {
this.zipcode = zipcode;
this.description = description;
this.dateupdated = dateupdated;
this.tblCustomers = tblCustomers;
}
#Id
#Column(name = "ZIPCODE", unique = true, nullable = false, length = 5)
public String getZipcode() {
return this.zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
#Column(name = "DESCRIPTION", length = 50)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Temporal(TemporalType.DATE)
#Column(name = "DATEUPDATED", length = 7)
public Date getDateupdated() {
return this.dateupdated;
}
public void setDateupdated(Date dateupdated) {
this.dateupdated = dateupdated;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "tblZipcodes")
public Set<TblCustomer> getTblCustomers() {
return this.tblCustomers;
}
public void setTblCustomers(Set<TblCustomer> tblCustomers) {
this.tblCustomers = tblCustomers;
}
#Override
public boolean equals(Object newObject) {
return newObject instanceof TblZipcodes;
}
// This must return the same hashcode for every Foo object with the same key.
public int hashCode() {
return this.getClass().hashCode();
}
}
Thank you in advance.
In your dataTable you are using the same variable for row selection.
selectionMode="single" selection="#{zipCodeMaintennanceBean.selectedZipCode}"
When no row is selected the selectedZipCode attribute will be null and you will continue to get an Exception.
You could simply use another instance of TblZipcodes for the addDialog.
PS: Some time ago someone reported a bug when giving the same name to id and widgetVar as you did in addDialog, check if this is a problem in version 3.5.

JSF/Primefaces Action Listener not invoked from p:commandButton

I am migrating an JSP/Servlets website to JSF and am having difficulty in implementing some of the more interesting abilities of JSF. The current problem that I have attempted to resolve for several days is deleting one or more rows from a <p:dataTable>. The following code snippet defines the table:
<ui:composition template="/templates/RescueDBAdminTemplate.xhtml" ... >
<ui:define name="body">
<div id="mainContent">
<h1> Pet Information Edit </h1>
<p>
This page allows the detailed information for an animal to be inserted or edited.
</p>
<br />
<!--
~~~~ The first row contains the AIF number, and two optional hyperlinks to the History and Cage Card
~~~~ pages. Since we have at most three entries, and a layout of 4 columns, we will need a sub-table
~~~~ to evenly space out these objects.
~~~~ -->
<table class="w100pct">
<tr>
<!--
~~~~ Display the AIF_NO for the animal at the top of the page. For Reference Only.
~~~~ -->
<td class="label" align="left" >
AIF Number: #{animals.aifNo}
</td>
<td align="center"> Display History </td>
<td align="right"> Display Cage Card </td>
</tr>
</table>
<p:accordionPanel id="profile" multiple="true" activeIndex="0,1,2,3,4,5,6,7">
<p:tab title="Cage Card Information">
<h:form id="cageCardForm">
<p:panelGrid styleClass="rdbGrid w100pct">
<p:row>
<p:column styleClass="block"> Child Friendly: </p:column>
<p:column>
<p:selectOneMenu id="childFriendly" value="#{animals.isChildFriendly}">
<f:selectItem itemValue="Y" itemLabel="Yes" />
<f:selectItem itemValue="N" itemLabel="No" />
<f:selectItem itemValue="U" itemLabel="Unknown" />
<f:selectItem itemValue="O" itemLabel="Older Children Only" />
</p:selectOneMenu>
</p:column>
<p:column styleClass="block"> Dog Friendly: </p:column>
<p:column>
<p:selectOneMenu id="dogFriendly" value="#{animals.isDogFriendly}">
<f:selectItem itemValue="Y" itemLabel="Yes" />
<f:selectItem itemValue="N" itemLabel="No" />
<f:selectItem itemValue="U" itemLabel="Unknown" />
<f:selectItem itemValue="T" itemLabel="Tolerates" />
<f:selectItem itemValue="S" itemLabel="Some" />
</p:selectOneMenu>
</p:column>
</p:row>
<p:row>
<p:column styleClass="block"> Cat Friendly: </p:column>
<p:column>
<p:selectOneMenu id="catFriendly" value="#{animals.isCatFriendly}">
<f:selectItem itemValue="Y" itemLabel="Yes" />
<f:selectItem itemValue="N" itemLabel="No" />
<f:selectItem itemValue="U" itemLabel="Unknown" />
<f:selectItem itemValue="T" itemLabel="Tolerates" />
<f:selectItem itemValue="S" itemLabel="Some" />
</p:selectOneMenu>
</p:column>
<p:column styleClass="block"> Housebroken: </p:column>
<p:column>
<p:selectOneMenu id="housebroken" value="#{animals.isHousebroken}">
<f:selectItem itemValue="Y" itemLabel="Yes" />
<f:selectItem itemValue="N" itemLabel="No" />
<f:selectItem itemValue="U" itemLabel="Unknown" />
</p:selectOneMenu>
</p:column>
</p:row>
<p:row>
<p:column styleClass="block" style="text-align:top;"> Cage Card Comments: </p:column>
<p:column> <p:inputTextarea name="previousOwner" rows="11" cols="40" value="#{animals.cageCardComment}" /> </p:column>
<p:column styleClass="block" style="text-align:top;"> Lifestyle Needs: </p:column>
<p:column> <p:inputTextarea name="reasonObtained" rows="11" cols="40" value="#{animals.lifestyleNeeds}" /> </p:column>
</p:row>
</p:panelGrid>
</h:form>
</p:tab>
<p:tab title="Fees and Expenditures">
<h:form id="feesForm">
<p:panelGrid styleClass="rdbGrid w100pct">
<p:row>
<p:column styleClass="block"> Adoption Fee: </p:column>
<p:column>
<p:inputText size="16" value="#{animals.adoptionFee}" maxlength="64" />
</p:column>
<p:column styleClass="block"> Normal Costs: </p:column>
<p:column>
<p:inputText size="16" value="#{animals.costRegular}" maxlength="64" />
</p:column>
</p:row>
<p:row>
<p:column styleClass="block"> Extra Costs: </p:column>
<p:column>
<p:inputText size="16" value="${aifBean.costNonRegular}" maxlength="64" />
</p:column>
<p:column styleClass="block"> Extra Cost Description </p:column>
<p:column>
<p:inputTextarea rows="4" cols="40" value="#{animals.nonRegularDesc}" />
</p:column>
</p:row>
<p:row>
<p:column styleClass="block"> Comments </p:column>
<p:column colspan="3">
<p:inputTextarea rows="2" cols="80" value="#{animals.comments}" />
</p:column>
</p:row>
</p:panelGrid>
</h:form>
</p:tab>
<p:tab title="Medical History">
<p:dataTable styleClass="w100pct" var="current" value="#{medical.getMedHistoryByAifNo(param.AIF_NO)}">
<p:column headerText="Delete">
Delete
</p:column>
<p:column headerText="Procedure Name">
#{current.shortName}
</p:column>
<p:column headerText="Date">
#{current.treatmentDate}
</p:column>
<p:column headerText="Vet Information">
#{current.vetName} #{current.vetClinic}
</p:column>
<p:column headerText="Comments">
#{current.comments}
</p:column>
</p:dataTable>
</p:tab>
<p:tab title="Documents">
<h:form id="docListForm">
<p:dataTable id="docListTable" styleClass="w100pct" var="current" value="#{documents.currentDocList}"
paginator="true" rows="10" selection="#{documents.selectedDocs}">
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Date">
<h:outputText value="#{current.treatmentDate}" />
</p:column>
<p:column headerText="Document Type">
<h:outputText value="#{current.group}" converter="com.rescuedb.DocGroupName" />
</p:column>
<p:column headerText="Description">
#{current.description}
</p:column>
<f:facet name="footer">
<p:commandButton id="docListDelete" value="Delete Selected Records"
icon="ui-icon-search"
update=":#{p:component('docListTable')}"
actionListener="#{documents.deleteReference}" >
<f:param name="docNo" value="#{current.docNo}" />
<f:param name="refNo" value="#{animals.aifNo}" />
<f:param name="group" value="#{current.group}" />
</p:commandButton>
</f:facet>
</p:dataTable>
</h:form>
</p:tab>
</p:accordionPanel>
</div>
</ui:define>
</ui:composition>
The managed bean that backs this page is as follows (this is fairly preliminary code, as I am still experimenting with PrimeFaces and JSF):
package com.rescuedb.beans.managed;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.apache.log4j.Logger;
import com.rescuedb.Beans.DocMasterBean;
import com.rescuedb.Beans.DAO.DocMaster;
import com.rescuedb.Beans.DAO.DocXref;
import com.rescuedb.Beans.Models.DocMasterDataModel;
import com.rescuedb.Core.RescueException;
#ManagedBean(name="documents")
#ViewScoped
public class DocumentManagedBean implements Serializable
{
static final long serialVersionUID = 5L;
static Logger logger = Logger.getLogger(DocumentManagedBean.class);
private transient DocMaster docInfo; // Document Master accessor object
private transient DocXref xrfInfo; // Document Master accessor object
private String currentAifNo;
private String refNo;
private String docNo;
/**
* Contains a list of document records, wrapped in a DataModel, for the currently
* active foster animal.
*/
private DocMasterDataModel currentDocList = null;
private DocMasterBean[] selectedDocs;
public DocumentManagedBean()
{
logger.trace ("DocumentManagedBean.constructor");
try {
//
// Retrieve the URL parameter from the context.
//
FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> paramMap = context.getExternalContext().getRequestParameterMap();
String paramAifNo = paramMap.get("AIF_NO");
if (paramAifNo != null) {
if (!paramAifNo.isEmpty()) {
currentAifNo = paramAifNo;
loadCurrentDocList();
}
}
} catch (Exception e) {
logger.error ("Exception caught in DocumentManagedBean() constructor :: " + e.getMessage(), e);
}
}
/**
* Initialize the bean from the database.
*/
#PostConstruct
public void initialize ()
{
logger.trace ("DocumentManagedBean.initialize");
try {
docInfo = new DocMaster();
xrfInfo = new DocXref();
} catch (Exception e) {
logger.error ("Exception in DocumentsManagedBean.initialize() : " + e.getMessage(), e);
}
}
public List<DocMasterBean> getDocList()
{
logger.trace ("DocumentManagedBean.getDocList");
return docInfo.getRecordList();
}
/**
* Retrieve the list of documents that are associated wit a specific foster animal.
* <p>
* #param aifNo
* #return
*/
public DocMasterDataModel getCurrentDocList()
{
logger.trace ("DocumentManagedBean.getCurrentDocList");
return currentDocList;
}
/**
* Load the document list for the currently active foster animal.
*/
private void loadCurrentDocList()
{
DocMaster docMaster = null;
logger.info ("DocumentManagedBean.loadCurrentDocList");
try {
docMaster = new DocMaster();
if (currentAifNo != null) {
if (!currentAifNo.isEmpty()) {
docMaster.queryByRefNo (Integer.parseInt(currentAifNo));
currentDocList = new DocMasterDataModel (docMaster.getRecordList());
logger.info ("DocumentManagedBean.loadCurrentDocList :: currentDocList reloaded, length = " + docMaster.getRecordCount());
} else {
logger.info ("DocumentManagedBean.loadCurrentDocList :: currentAifNo is empty, no records loaded.");
}
} else {
logger.info ("DocumentManagedBean.loadCurrentDocList :: currentAifNo is null, no records loaded.");
}
} catch (Exception e) {
logger.error ("Exception in DocumentsManagedBean.loadCurrentDocList() : " + e.getMessage(), e);
}
}
public void deleteReference(ActionEvent event)
{
boolean status; // Status of the update.
int refNo = 0;
int docNo = 0;
logger.info ("DocumentManagedBean.deleteReference");
try {
//
// Retrieve the parameter of the request.
//
FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> paramMap = context.getExternalContext().getRequestParameterMap();
String paramDocNo = paramMap.get("docNo");
String paramRefNo = paramMap.get("refNo");
logger.info (String.format("DocumentManagedBean.deleteReference :: paramDocNo = [%s]", paramDocNo));
logger.info (String.format("DocumentManagedBean.deleteReference :: paramRefNo = [%s]", paramRefNo));
//
// Retrieve the items necessary to delete the proper records.
// The refNo parameter will only be specified when a specific cross-referenced
// record is to be deleted. If this value is missing, then the master document
// is to be deleted.
//
if (paramRefNo != null) {
try {
refNo = Integer.parseInt (paramRefNo);
this.refNo = paramRefNo;
} catch (NumberFormatException e) {
refNo = 0;
}
}
//
// The docNo has to be present. If the refNo is zero, then we will delete the
// master document. If a refNo is present, then we will delete a cross reference.
//
if (paramDocNo != null) {
try {
docNo = Integer.parseInt (paramDocNo);
this.docNo = paramDocNo;
} catch (NumberFormatException e) {
docNo = 0;
String message = String.format ("Illegal value for docNo (%d)", docNo);
logger.error(String.format("DocumentManagedBean.deleteReference :: Exception Message [%s]", message));
throw new RescueException ("DS000091", message, "DocumentsManagedBean", "deleteReference");
}
} else {
logger.error("DocumentManagedBean.deleteReference :: paramDocNo is null");
}
//
// Delete the cross reference record.
//
if (refNo != 0) {
xrfInfo = new DocXref();
status = xrfInfo.queryByCrossRef (docNo, refNo);
if (status != true) {
String message = String.format ("Error querying DOC_xref for refNo = %d, docNo = %d", refNo, docNo);
logger.error(String.format("DocumentManagedBean.deleteReference :: Exception Message [%s]", message));
throw new RescueException ("DS000092", message, "DocumentsManagedBean", "deleteReference");
} else {
status = xrfInfo.delete();
logger.warn("DocumentManagedBean.deleteReference :: Document XRef deleted");
// logger.warn("DocumentManagedBean.deleteReference :: TEST TEST TEST Document XRef not actually deleted");
if (status != true) {
String message = String.format ("Error deleting DOC_xref for refNo = %d, docNo = %d", refNo, docNo);
logger.error(String.format("DocumentManagedBean.deleteReference :: Exception Message [%s]", message));
throw new RescueException ("DS000093", message, "DocumentsManagedBean", "deleteReference");
} else {
loadCurrentDocList();
logger.error("DocumentManagedBean.deleteReference :: currentDocList reloaded");
}
}
} else {
logger.error("DocumentManagedBean.deleteReference :: refNo is 0. No Records were deleted.");
}
} catch (RescueException e) {
logger.error ("RescueException in DocumentsManagedBean.deleteReference() :: " + e.getMessage(), e);
} catch (Exception e) {
logger.error ("Exception in DocumentsManagedBean.deleteReference()", e);
}
}
public DocMaster getDocInfo()
{
logger.info ("DocumentManagedBean.getDocInfo");
return docInfo;
}
public void setDocInfo(DocMaster docInfo)
{
logger.info ("DocumentManagedBean.setDocInfo");
this.docInfo = docInfo;
}
public String getRefNo()
{
logger.info ("DocumentManagedBean.getRefNo");
return refNo;
}
public void setRefNo(String refNo)
{
logger.info ("DocumentManagedBean.setRefNo");
this.refNo = refNo;
}
public String getDocNo()
{
logger.info ("DocumentManagedBean.getDocNo");
return docNo;
}
public void setDocNo(String docNo)
{
logger.info ("DocumentManagedBean.setDocNo");
this.docNo = docNo;
}
public DocMasterBean[] getSelectedDocs()
{
logger.info ("DocumentManagedBean.getSelectedDocs");
return selectedDocs;
}
public void setSelectedDocs(DocMasterBean[] selectedDocs)
{
logger.info ("DocumentManagedBean.setSelectedDocs");
this.selectedDocs = selectedDocs;
}
}
I have tried a number of different strategies, and have read a fair number of very detailed explanations of this process in other StackOverflow threads (Thank you, BalusC!), but have still been unable to actually invoke the action listener.
My Environment is as follows:
Java 1.6
Eclipse Kepler (originally Juno)
GlassFish 3.1.2
PrimeFaces 3.5.0
From a presentation perspective, the XHTML displays correctly. The <p:dataTable> element is rendered just like the documentation and examples indicate, but when I attempt to delete a a row, the listener is never invoked.
I have tried changing the update name several times. Currently, the value of the update parameter is profile:docListForm:docListTable.
Other posts seem to indicate that there was a problem with <p:commandButton> from within a <p:accordianPanel>, but that was for a previous version of PrimeFaces (3.2).
I have tried moving the <p:commandButton> outside the <p:dataTable> and also on each row, yet the behavior does not change.
If your Listener does not trigger try this, it work fine in p:tables
<p:column id="delete" headerText="Action" width="65">
<h:commandLink value="Delete"
action="#{documents.deleteReference(current.docNo,animals.aifNo,current.group)}" ajax="false" />
</p:column>
And in your documents bean:
public void deleteReference(String docNo, String aifNo, String group)
You can actually pass the 2 string that you eventually cast as int but as Integer wrapper in the method not the primitive.
Cheers,
Thierry
Try to add ajax="false" attribute in commandbutton ,Something like this.
<p:commandButton value="Non-Ajax Submit" actionListener="#{pprBean.savePerson}"
ajax="false" />
Or use h:commandButton with ajax="false" here also .
In my application i got same issue plenty of time and i got answer few week back that issue with the page or code somewhere in the page or managed bean throwing exception or some logic going fail which is generating exception for JSF that is the main reason behind firing the event.It is JSF2 feature not to fire event if code or logic fail somewhere . May be this will help you

Resources