I have a page where some users are displayed through datatable.I have a option to add new user. when the add window is in the same page then the users are added to the datatable through ajax. But if I transfer the add option to primeface dialog the ajax functionality is not working and the datatable is not refreshed.
Here are my codes:
Code1: Here we have used the add user window in the same page -- this one works
<h:form>
<h:panelGrid id="grid" cellpadding="5" columns="2"
style="margin-bottom:10px">
<f:facet name="header">
<p:messages id="msgs" />
</f:facet>
<p:outputLabel for="firstname" value="Firstname:" />
<p:inputText id="firstname" value="#{userView.firstname}" />
<p:outputLabel for="surname" value="Surname:" />
<p:inputText id="surname" value="#{userView.lastname}"
required="true" requiredMessage="Surname is required." />
</h:panelGrid>
<h:panelGrid id="grid2">
<p:dataTable var="user" value="#{userView.getUsers()}">
<p:column headerText="FirstName">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column headerText="LastName">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="All" id="btnAll" process="#all" update="grid2"
actionListener="#{userView.save}" />
</h:panelGrid>
</h:form>
and my managed Bean is
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
#ManagedBean
public class UserView {
private String firstname;
private String lastname;
public List<User> dataUser;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public UserView()
{
dataUser = new ArrayList<User>();
dataUser.add(new User("AA", "LA"));
dataUser.add(new User("AB", "LB"));
dataUser.add(new User("AC", "LC"));
dataUser.add(new User("AD", "LD"));
dataUser.add(new User("AE", "LE"));
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<User> getUsers()
{
return dataUser;
}
public void save() {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Welcome " + firstname + " " + lastname));
dataUser.add(new User(firstname, lastname));
}
public class User{
public String firstname;
public String lastname;
public User(String fn, String ln)
{
this.firstname= fn;
this.lastname= ln;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
}
Code 2: if I use the add user in the pdialog then the page is not getting refreshed. The above managed bean remains same
<h:form>
<h:panelGrid id="grid2">
<p:dataTable var="user" value="#{userView.getUsers()}">
<p:column headerText="FirstName">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column headerText="LastName">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="AllPopup" id="btnAllPopup" process="#all"
update="grid2" onclick="PF('dlg1').show();" />
</h:panelGrid>
<p:dialog header="Basic Dialog" widgetVar="dlg1" minHeight="40">
<h:panelGrid id="gridpopup" cellpadding="5" columns="2"
style="margin-bottom:10px">
<p:outputLabel for="firstname1" value="Firstname:" />
<p:inputText id="firstname1" value="#{userView.firstname}" />
<p:outputLabel for="surname1" value="Surname:" />
<p:inputText id="surname1" value="#{userView.lastname}"
required="true" requiredMessage="Surname is required." />
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="Alladd" id="btnAlladd" process="#all"
update="grid2" actionListener="#{userView.save}" />
</h:panelGrid>
</p:dialog>
</h:form>
Please help in understanding where the issue is
in following code commandbutton not properly work for the datatable.
<p:dataTable id="invoiceTable" var="ipsDetail"
value="#{invoiceBean.ipsDetails}" border="1">
<p:column headerText="Sr. No.">
<h:inputText id="serialN7umber" value="#{ipsDetail.serialNumber}"
size="3" />
</p:column>
<p:column headerText="Description of Goods">
<p:inputText value="#{ipsDetail.descriptionOfGoodsOrService}" />
</p:column>
<p:column headerText="HSN Code">
<p:inputText value="#{ipsDetail.hsnCode}" styleClass="Alingment" />
</p:column>
<p:column headerText="Quantity">
<p:inputText value="#{ipsDetail.quantity}" styleClass="Alingment" />
</p:column>
<p:column headerText="Rate">
<p:inputText value="#{ipsDetail.rate}" styleClass="Alingment" />
</p:column>
<p:column headerText="Percentage Discount">
<p:inputText value="hello" rendered="#{ipsDetail.percentDiscount}"
styleClass="Alingment" />
</p:column>
<p:column headerText="Amount">
<p:inputText value="#{invoiceBean.amount}" styleClass="Alingment" />
</p:column>
<f:facet name="footer">
<p:commandButton value="Add New Row" action="#{invoiceBean.addRow}" update=":form:invoiceTable">
<!-- <f:ajax execute=":form:invoiceTable" render=":invoiceTable:addColumn" /> -->
</p:commandButton>
</f:facet>
</p:dataTable>
</h:form>
I want To add dynamic row with inputtext using primefaces commandbutton in java. it work but re-render not possible.
public class InvoiceBean implements Serializable {
public List getInvoices() {
InvoiceDao invoiceDao = new InvoiceDao();
invoices = invoiceDao.getInvoiceData();
return invoices;
}
public void setInvoices(List<Invoice> invoices) {
if (invoices != null) {
this.invoices.add(new Invoice());
}
}
public void getInvoiceData() {
InvoiceDao invoiceDao = new InvoiceDao();
ipsDetail = new InvoiceProductsServicesDetail();
if ( ipsDetail != null) {
ipsDetail
.setDescriptionOfGoodsOrService(descriptionOfGoodsOrService);
ipsDetail.setHsnCode(hsnCode);
ipsDetail.setInvoiceId(invoice.getId());
ipsDetail.setPercentDiscount(percentDiscount);
ipsDetail.setQuantity(quantity);
ipsDetail.setRate(rate);
ipsDetail.setSerialNumber(serialNumber);
ipsDetail.setServiceTax((float) 12.5);
ipsDetail.setVat(5);
System.out.println("InvoiceBean.insertInvoice");
}
invoiceDao.insertInvoice(invoice, ipsDetail);
}
public Row addRow() {
Row row = new Row();
InputText inputText = new InputText();
inputText.setSubmittedValue("Hello");
Column column = new Column();
row.setParent(inputText);
column.setHeader(inputText);
column.setHeaderText("Hardik");
return row;
}
}
This Is code for add row or column with inputtext
Since you are using Primefaces you can also Update any component from ManagedBean itself using org.primefaces.context.RequestContext object.
For example:
Facelet:
<h:form id="form1">
<p:dataTable id="myTab">
...
</p:dataTable>
</h:form>
ManagedBean:
RequestContext reqCtx = Requestcontext.getCurrentInstance();
req.Ctx.update("form1:myTab");
You can't update the table from inside the table. You can do the following:
<p:dataTable id="invoiceTable" var="ipsDetail" value="#{invoiceBean.ipsDetails}"
border="1">
...
<f:facet name="footer">
<p:commandButton value="Add New Row" onclick="updateTable();">
</p:commandButton>
</f:facet>
</p:dataTable>
...
<p:remoteCommand name="updateTable" update=":form:invoiceTable"
actionListener="#{invoiceBean.addRow}" />
Thank For Your Response and Solution regarding my question is below edit addRow().
public void addRow() {
ipsDetail = new InvoiceProductsServicesDetail();
if (descriptionOfGoodsOrService != null
&& hsnCode != null && quantity != 0 && rate != 0) {
ipsDetail.setSerialNumber(serialNumber);
ipsDetail
.setDescriptionOfGoodsOrService(descriptionOfGoodsOrService);
ipsDetail.setHsnCode(hsnCode);
ipsDetail.setPercentDiscount(percentDiscount);
ipsDetail.setQuantity(quantity);
ipsDetail.setRate(rate);
ipsDetails.add(ipsDetail);
}
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
DataTable table = (DataTable) facesContext.getViewRoot()
.findComponent("form:invoiceTable");
UIComponent uiTable = ComponentUtils.findParentForm(facesContext,
table);
final AjaxBehavior behavior = new AjaxBehavior();
RowEditEvent rowEditEvent = new RowEditEvent(uiTable, behavior,
table.getRowData());
rowEditEvent.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
table.broadcast(rowEditEvent);
} catch (AbortProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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;
}
}
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>
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