Good afternoon people! I'm trying to do an update through the datatable edit the Primefaces, but does not send the value of inputText upgraded to the bean. The process occurs almost correctly, the value is sent and updated, but the old value already loaded into datatable.
can anyone help me on this :)
Forgive my English. I do not speak or write very well ....
listaProduto.xhtml
<!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">
<ui:composition template= "template.xhtml">
<ui:define name="conteudo" >
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:dataTable var="prod" value="#{pBean.listaproduto}" editable="true" style="margin-bottom:20px" id="listaproduto1" >
<p:ajax event="rowEditInit" listener="#{pBean.onRowEdit}" update=":form:msgs" immediate="true" />
<p:ajax event="rowEditCancel" listener="#{pBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Id">
<h:outputText value="#{prod.id}"/>
</p:column>
<p:column headerText="Nome">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.nome}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.nome}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Preço">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.preco}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.preco}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fornecedor">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.fornecedor}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.fornecedor}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Categoria">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.categoria}"/> </f:facet>
<f:facet name="input"><p:inputText id="cate" value="#{prod.categoria}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
ProdutoBean
package manager;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;
import br.com.estoque.model.Produto;
import br.com.estoque.persistence.ProdutoDao;
#ManagedBean(name = "pBean")
#ViewScoped
public class ProdutoBean {
private Produto produto;
private List<Produto> listaproduto;
public ProdutoBean() {
produto = new Produto();
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public List<Produto> getListaproduto() {
try {
listaproduto = new ProdutoDao().listar();
} catch (Exception e) {
e.printStackTrace();
}
return listaproduto;
}
public void setListaproduto(List<Produto> listaproduto) {
this.listaproduto = listaproduto;
}
public String cadastrar() {
FacesContext fc = FacesContext.getCurrentInstance();
try {
new ProdutoDao().cadastrar(produto);
fc.addMessage("formproduto", new FacesMessage(produto.getNome() + "produto cadastrado com sucesso"));
produto = new Produto();
} catch (Exception e) {
e.printStackTrace();
fc.addMessage("formproduto", new FacesMessage(produto.getNome() + "Não cadastrado"));
}
return null;
}
public void onRowEdit(RowEditEvent event) {
System.out.println(produto);
produto = ((Produto) event.getObject());
System.out.println(produto);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I think you should use other type of event, because rowEditInit is executing when you click pencil icon, and after edition when you click save icon is executing event rowEdit. Therefore try:
<p:ajax event="rowEdit" listener="#{pBean.onRowEdit}" update=":form:msgs"/>
Also forgive my English :)
Staff managed to solve. in fact the problem was in my listaprodutos get ... after entering an if and else, testing whether the product list was null, functioned normally.
The cool thing is, as a friend pointed out, always check the values passed by the network browser.
Hugs
Related
This question already has an answer here:
How and when should I load the model from database for JSF dataTable
(1 answer)
Closed 1 year ago.
I have a bean that brings the list of products from the database, I can change it in onRowEdit normally, but when I do a search for the part method in the beanProd.searchProd () form it populates the datatable with related products and when I change some of them event.getObject () takes the object with an incorrect id and update incorrect product. Please HELP-ME
<!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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:outputStylesheet name="a.css" library="css" />
</h:head>
<h:body>
<div id="go">
<p:panel id="basic" header="Adicionar Produto"
style="margin-bottom:20px; width:400px">
<p:panelGrid columns="4" style="margin:10px 0"/>
<h:form id="form1" >
<p:outputLabel value="Marca:" />
<td> </td>
<p:inputText id="marcacomp" value="#{beanProd.marcaProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}" />
<p:message for="marcacomp" />
<br/>
<p:outputLabel value="Nome:" />
<td> </td>
<p:inputText id="nome" value="#{beanProd.nomeProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}" />
<p:message for="nome" />
<br/>
<p:outputLabel value="Tamanho:" />
<td></td>
<p:inputText id="tamanho" value="#{beanProd.tamanhoProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}"/>
<p:message for="tamanho" />
<br/>
<p:commandButton id="button" value="Adicionar" ajax="false"
actionListener="#{beanProd.addUser()}" update="datatable"/>
<p:messages id="messages" showDetail="true" closable="true" />
<td></td>
<td></td>
<td></td>
<br/>
</h:form>
</p:panel>
<p:panel id="basic5" header="Buscar Produtos"
style="margin-bottom:20px; width:380px">
<p:panelGrid columns="1" />
<h:form id="form10">
<p:outputLabel value="Digite a busca:" />
<br></br>
<p:inputText id="buscaprod" value="#{beanProd.busca}"
size="25" requiredMessage="#{beanMsgs.campovazio}" />
<p:commandButton id="button3" value="Buscar" ajax="false"
actionListener="#{beanProd.searchProd()}" update="datatable" />
</h:form>
</p:panel>
<h:form>
<p:commandButton id="button5" value="INVERTER TODOS MOSTRAR" ajax="false"
actionListener="#{beanProd.alterarTodos()}" update="datatable" />
</h:form>
</div>
<div id="direita">
<h:form id="form3">
<p:dataTable id="datatable" value="#{beanProd.produtos}" var="p"
editable="true" sortOrder="ascending" sortBy="#{p.id}"
paginator="true" rows="10">
<f:facet name="header">
Lista de Produtos
</f:facet>
<p:ajax event="rowEdit" listener="#{beanProd.onRowEdit}" update="datatable"/>
<p:ajax event="rowEditCancel" listener="#{beanProd.onRowCancel}" update="datatable"/>
<p:column headerText="Marca"
style="width:70px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.marcaProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput2" value="#{p.marcaProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Nome"
style="width:110px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.nomeProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput3" value="#{p.nomeProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Tamanho"
style="width:70px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.tamanhoProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput5" value="#{p.tamanhoProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Mostrar"
style="width:50px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="Não" rendered="#{p.mostrar == 0}" />
<h:outputText value="Sim" rendered="#{p.mostrar == 1}" />
</f:facet>
<f:facet name="input">
<p:selectOneMenu id="mastrar2"
value="#{beanProd.mostrar2}"
style="height:30px; width:70px" required="false">
<f:param name="mostrar2" value="#{beanProd.mostrar2}" />
<f:selectItem itemLabel="Sim" itemValue="Sim" />
<f:selectItem itemLabel="Nao" itemValue="Nao" />
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Acao" style="width:30px; text-align: center;">
<p:rowEditor editTitle="Editar" saveTitle="Salvar"
cancelTitle="Cancelar" />
<h:outputLabel id="editRow2">
<p:commandButton id="button" jax="false"
icon="ui-icon-circle-close" title="Excluir"
action="#{beanProd.deleteFromDB(p)}" update="datatable"
process="#this">
<p:confirm header="Confirmação" message="Tem certeza que deseja excluir este usuario?"
icon="pi pi-exclamation-triangle" />
</p:commandButton>
<p:confirmDialog global="true" showEffect="fade" hideEffect="fade">
<p:commandButton value="SIM" type="button"
styleClass="ui-confirmdialog-yes" />
<p:commandButton value="NÃO" type="button"
styleClass="ui-confirmdialog-no" />
</p:confirmDialog>
<p:message for="button" />
</h:outputLabel>
<p:tooltip for="editRow2" value="Excluir" showEffect="fade"
hideEffect="fade" />
</p:column>
</p:dataTable>
</h:form>
</div>
</h:body>
</html>
package Bean;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
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.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import DAO.DaoFactory;
import DAO.PredictDAO;
import Model.Produto;
import Model.Usuario;
#ManagedBean(name="beanProd")
#RequestScoped
public class BeanProd implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Produto produto = new Produto();
private ArrayList<Produto> produtos;
private String marcaProd;
private String nomeProd;
private String tamanhoProd;
private String busca;
private String mostrar2;
private boolean ativo;
public BeanProd() {
}
#PostConstruct
public void init() {
buscarTodosProd();
}
public ArrayList<Produto> buscarTodosProd() {
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.buscaProdutos();
factory.fecharConexao();
return produtos;
}
public ArrayList<Produto> searchProd() {
produtos.clear();
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.buscarUmProduto(busca);
System.out.println(busca);
factory.fecharConexao();
return produtos;
}
public ArrayList<Produto> alterarTodos() {
produtos.clear();
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.alterarTodosProdutos();
factory.fecharConexao();
return produtos;
}
public void addUser() {
Produto produto = new Produto();
produto.setMarcaProd(marcaProd);
produto.setNomeProd(nomeProd);
produto.setTamanhoProd(tamanhoProd);
produto.setMostrar(1);
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
dao.adicionarProduto(produto);
factory.fecharConexao();
produtos.add(produto);
marcaProd = "";
nomeProd = "";
tamanhoProd = "";
}
public void deleteFromDB(Produto produto) {
// FacesContext context = FacesContext.getCurrentInstance();
int id;
// int id = (Integer) event.getComponent().getAttributes().get("id2");
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
// id =
// Integer.parseInt(context.getExternalContext().getRequestParameterMap().get("idhidden"));
try {
// Map m = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
// System.out.println(m.toString());
dao.excluirProduto(produto.getId());
produtos.remove(produto);
FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage("Produto Excluido com Sucesso!"));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.fecharConexao();
}
public void onRowEdit(RowEditEvent<Produto> event) {
Produto promocao2 = new Produto();
promocao2 = (Produto) event.getObject();
System.out.println(promocao2.getId());
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
dao.atualizarProduto(promocao2);
factory.fecharConexao();
}
public void onRowCancel(RowEditEvent event) {
System.out.println("Chamou onRowCancel!" + event.toString());
FacesMessage msg = new FacesMessage("Edit Cancelled", "" + ((Produto) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public ArrayList<Produto> getProdutos() {
return produtos;
}
public void setProdutos(ArrayList<Produto> produtos) {
this.produtos = produtos;
}
public String getMarcaProd() {
return marcaProd;
}
public void setMarcaProd(String marcaProd) {
this.marcaProd = marcaProd;
}
public String getNomeProd() {
return nomeProd;
}
public void setNomeProd(String nomeProd) {
this.nomeProd = nomeProd;
}
public String getTamanhoProd() {
return tamanhoProd;
}
public void setTamanhoProd(String tamanhoProd) {
this.tamanhoProd = tamanhoProd;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getBusca() {
return busca;
}
public void setBusca(String busca) {
this.busca = busca;
}
public String getMostrar2() {
return mostrar2;
}
public void setMostrar2(String mostrar2) {
this.mostrar2 = mostrar2;
}
#Override
public String toString() {
return "BeanProd [produto=" + produto + ", produtos=" + produtos + ", marcaProd=" + marcaProd + ", nomeProd="
+ nomeProd + ", tamanhoProd=" + tamanhoProd + ", ativo=" + ativo + "]";
}
}
sorry for lack of details, it's my first post here, let's go to the details examples
all produtcts in datatable
Here are the products from the database that populate the datatable init () method with #PostConstruct annotation
When I search the form on the left with the word CREME he calls the searchProd method q populates a datatable with products that contain the word CREME
search form populate datatable search string
as you can see the datatable populated only with products containing the word CREAM
before the search I can change the product directly in the datatable normally it changes the product correctly in the database but when I do the search for a product that contains a certain word and I try to change it in the datatable it changes the product with the wrong id see before:
before
after
as you can see he should change the product with id 14 and he changes the product with id 12
wrong product changed
So, what do you think is the problem here?
Is there any way to make the change in the row along with some search filter?
I'm using JSF 2.2 and Primefaces 8.0
Sorry for my bad english.
This may happen if one of your methods updates the products list, but doesn't update the form (the view).
Start your app in the debug mode, and put a breakpoint on the setter of #{beanProd.produtos}, and find when your list is updated.
following is my question:
I have a simple piece of code. The Primeface datatable holds the records and should be filtering. But when i tip some letters into a search field, the datatable is shown the "no records found" message. Why?
Here's my code:
<ui:define name="content">
<h:form>
<h:panelGrid columns="1">
<p:dataTable value="#{mainBean.liste}"
var="daten"
rows="6"
emptyMessage="Keine Daten bisher Erfasst"
widgetVar="erfasstTabelle"
paginator="true" resizableColumns="true" paginatorPosition="bottom"
paginatorTemplate=" {CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown} Springe zu Seite: {JumpToPageDropdown}"
currentPageReportTemplate="{startRecord} - {endRecord} von {totalRecords}, Seite: {currentPage}/{totalPages})"
rowsPerPageTemplate="5,10,15" filteredValue="#{mainBean.gefiltert}">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Alle Felder durchsuchen" />
<p:inputText id="globalFilter" onkeyup="PF('erfasstTabelle').filter()" style="width:150px" placeholder="Suchbegriff"/>
</p:outputPanel>
</f:facet>
<p:column headerText="AVS ID" filterMatchMode="equals" filterBy="#{daten.nummer}">
<h:outputText value="#{daten.nummer}" />
</p:column>
<p:column headerText="Rechtsform">
<h:outputText value="#{daten.rechtsform}" />
</p:column>
<p:column headerText="Erfasser" filterMatchMode="exact" filterBy="#{daten.erfasser}">
<f:facet name="filter">
<p:selectOneMenu onchange="PF('erfasstTabelle').filter()" >
<f:selectItem itemLabel="Erfasser" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{mainBean.erfasser}" />
</p:selectOneMenu>
</f:facet>
<h:outputText value="#{daten.erfasser}" />
</p:column>
<p:column headerText="Datum" >
<h:outputText value="#{daten.datum}" />
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
</ui:define>
And my Bean code:
package de.avs.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import de.avs.entity.Erfasst;
import de.avs.entity.ErfasstDAO;
#ManagedBean
#ViewScoped
public class MainBean implements Serializable{
private static final long serialVersionUID = 1L;
private ErfasstDAO erfasstDAO;
private List<Erfasst> liste;
private List<Erfasst> gefiltert;
private List<String> erfasser;
#PostConstruct
private void init(){
erfasstDAO = new ErfasstDAO();
erfasser = new ArrayList<>();
erfasser.add("Benjamin");
erfasser.add("Uwe");
erfasser.add("Rolf");
liste = erfasstDAO.alleEintraege();
}
public List<Erfasst> getListe() {
return liste;
}
public List<Erfasst> getGefiltert() {
return gefiltert;
}
public void setGefiltert(List<Erfasst> gefiltert) {
this.gefiltert = gefiltert;
}
public List<String> getErfasser() {
return erfasser;
}
public void setErfasser(List<String> erfasser) {
this.erfasser = erfasser;
}
}
I'm using PrimeFaces 4.0 and Netbeans 6.9.1. I followed primefaces demo here:
DataTable Single Selection
Everything working fine expect button view. Here is my code:
Customer_list.xhtml
<p:growl id="msgs" showDetail="true" />
<h:form id="formTable">
<p:dataTable styleClass="table" id="customers" var="customer" value="#{customerBean.customer}">
<p:column>
<f:facet name="header">First Name</f:facet>
#{customer.firstName}
</p:column>
<p:column>
<f:facet name="header">Last Name</f:facet>
#{customer.lastName}
</p:column>
<p:column>
<f:facet name="header">Email</f:facet>
#{customer.email}
</p:column>
<p:column>
<f:facet name="header">DOB</f:facet>
#{customer.dob}
</p:column>
<p:column style="width:4%">
<p:commandButton id="selectButton" update=":formCreate" oncomplete="dialogCustomerCreate.show()" icon="ui-icon-search" title="Update">
<f:setPropertyActionListener value="#{customer}" target="#{customerBean.selectedCustomer}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form id="formCreate">
<p:dialog header="Create New Customer" widgetVar="dialogCustomerCreate" resizable="false" id="dlgCustomerCreate"
showEffect="fade" hideEffect="explode" modal="true">
<h:panelGrid id="display" columns="2" cellpadding="4" style="margin:0 auto;">
<h:outputText value="First Name:" />
<h:outputText value="#{customerBean.selectedCustomer.firstName}" style="font-weight:bold"/>
<h:outputText value="Last Name:" />
<h:outputText value="#{customerBean.selectedCustomer.lastName}" style="font-weight:bold"/>
<h:outputText value="Email:" />
<h:outputText value="#{customerBean.selectedCustomer.email}" style="font-weight:bold"/>
<h:outputText value="DOB:" />
<h:outputText value="#{customerBean.selectedCustomer.dob}" style="font-weight:bold"/>
</h:panelGrid>
</p:dialog>
</h:form>
customerBean.java
public class customerBean {
private List<Customer> customer;
private Customer selectedCustomer;
/** Creates a new instance of customerBean */
public customerBean() {
customer = new ArrayList<Customer>();
}
public List<Customer> getCustomer() {
CustomersDao cust_dao = new CustomersDao();
customer = cust_dao.findAll();
return customer;
}
public Customer getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(Customer selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
}
CustomersDao.java
public class CustomersDao {
public List<Customer> findAll(){
List<Customer> list_cust = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String sql = "FROM Customer";
try{
session.beginTransaction();
list_cust = session.createQuery(sql).list();
session.beginTransaction().commit();
}catch(Exception e){
session.beginTransaction().rollback();
}
return list_cust;
}
}
Hope anyone suggest me what wrong in my code. It takes me 2 days to solve it. Thanks for reading!
You need to have a converter for your Customer class:
#FacesConverter(forClass = Customer.class)
public class CustomerConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value != null && !value.equals("") && !value.equals("0")) {
//find and return object from DAO
} else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
//return object id as string
}
}
1) Try removing your <h:form/>, since you're not submitting any information in that dialog;
2) Try to change your <p:commandButton update=""/> to update=":display";
3) Add process="#form" to your <p:commandButton/>;
4) If that works, i don't think you need that <h:form/>.
you did not mention the correct id for displaying popup dialog at commandButton attribute update.
<p:commandButton id="selectButton" update=":formCreate:display" oncomplete="dialogCustomerCreate.show()" icon="ui-icon-search" title="Update">
<f:setPropertyActionListener value="#{customer}" target="#{customerBean.selectedCustomer}" />
</p:commandButton>
I've tried a few things but I could not do any work on my filter dataTable. Already follow the example of the primefaces showcase and nothing.
I have the following codes:
xhtml:
<p:dataTable id="dataTable" var="valor" value="#{beanMensagemXContato.listaContatoEmail}"
widgetVar="carsTable" emptyMessage="No cars found with given criteria" filteredValue="#{tableBean.filteredCars}">
<f:facet name="header">
</f:facet>
<p:column
style="max-width: 50px; min-width: 50px; overflow: hidden">
<f:facet name="header">
<h:outputText value="Contato" />
</f:facet>
<h:outputText value="#{valor.nomGrupoEmail}" />
</p:column>
<p:column
style="max-width: 50px; min-width: 50px; overflow: hidden">
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{valor.endEmail}" />
</p:column>
<p:column
style="max-width: 50px; min-width: 50px; overflow: hidden">
<f:facet name="header">
<h:outputText value="Telefone" />
</f:facet>
<h:outputText value="#{valor.numTelefone}" />
</p:column>
<p:column
style="max-width: 50px; min-width: 50px; overflow: hidden">
<f:facet name="header">
<h:outputText value="Ações" />
</f:facet>
</p:column>
</p:dataTable>
Bean:
public List<ContatoEmail> getListaContatoEmail() {
listaContatoEmail = new ArrayList<ContatoEmail>();
listaContatoEmail = consultaContatoEmail.listarContatoEmail();
return listaContatoEmail;
}
I want something that when you type a word in dataTable select the row.
Can someone pass me a simple example.
Since I already appreciate.
Debora
Ok, here is an example:
I'll take the popular example of cars.
Use Case: Dynamically update a data-table upon each keystrokes in auto-complete
My Facelet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head />
<h:body>
<h:form>
<p:autoComplete var="carac" converter="carconvertor"
value="#{testBean.selectedCar}" itemLabel="#{carac.carmodel}"
itemValue="#{carac}"
completeMethod="#{testBean.complete}" process="#this"
onSelectUpdate="idGrid">
<p:ajax event="keyup" listener="#{testBean.onValueChange}"
update="idGrid"></p:ajax>
</p:autoComplete>
<p:dataTable value="#{testBean.matchingCarModels}" var="carmatch"
id="idGrid" converter="carconvertor">
<p:column headerText="Car Model">
<h:outputText value="#{carmatch.carmodel}" />
</p:column>
</p:dataTable>
</h:form>
</h:body>
</f:view>
</html>
A Car POJO
public class Car
{
private String carmodel;
public Car(String carmodel) {
super();
this.carmodel = carmodel;
}
// Add setters and getters
}
A Car Faces Convertor
#FacesConverter(forClass=Car.class, value="carconvertor")
public class CarConverter
implements Converter {
#Override
public Object getAsObject(FacesContext arg0, UIComponent component, String stringvalue) {
Car car = new Car(stringvalue);
return car;
}
#Override
public String getAsString(FacesContext arg0, UIComponent component, Object objectvalue) {
Car car = (Car) objectvalue;
if(car == null) {
return StringUtils.EMPTY;
}
return car.getCarmodel();
}
}
And finally the backing bean
#ManagedBean(name="testBean")
#SessionScoped
public class TestBackingBean
{
/**
* The input filter
*/
private String filter = StringUtils.EMPTY;
/**
* Some test data
*/
private final List<Car> carModels = new ArrayList<Car>() {
{
add(new Car("toyota"));
add(new Car("honda"));
add(new Car("suzuki"));
add(new Car("ford"));
add(new Car("renault"));
add(new Car("subaru"));
}
};
/**
* For updating the grid.
*/
public void onValueChange(AjaxBehaviorEvent event)
{
AutoComplete ac = (AutoComplete) event.getSource();
Car input = (Car) ac.getValue();
filter = (input == null) ? StringUtils.EMPTY : input.getCarmodel();
}
/**
* For the auto complete drop down
*/
public List<Car> complete(String input)
{
filter = input;
return getMatchingCarModels();
}
/**
* get the match
*/
public List<Car> getMatchingCarModels()
{
if(StringUtils.isEmpty(filter))
return carModels;
List<Car> matches = new ArrayList<Car>();
for(Car car : carModels)
{
if(car.getCarmodel().startsWith(filter))
{
matches.add(car);
}
}
return matches;
}
/**
* The selected car
*/
private Car selectedCar;
//Add setters and getters for above member
}
HTH
You could see the solution to the same problem in stackoverflow here
As an alternative approach (using auto complete) for the search and capture the keyup event to update the data table. An example tallying to your context:
<p:autoComplete var="address"
value="#{addressBean.address}" itemLabel="#{address.personName}"
itemValue="#{address}" completeMethod="#{addressBean.complete}"
process="#this" converter="personconvertor"
onSelectUpdate="dataTable">
<p:ajax event="keyup" listener="#{addressBean.onValueChange}"
update="dataTable"></p:ajax>
</p:autoComplete>
Problem: searching for some more suitable design .
Goal: I want to have table of some user information and with button "change password" in column for each user, after click : "change password" button disappeared (rendered ="false") and a inputSecreat field appeared - user entering the password and submitting it (by clicking some additional button or by hotkey ). after submit - "change password" button papered as before.
my bean
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
/**
* <p>Type: UserSession
* <p>User: kislo_metal
* <p>Date: Jun 21, 2010
* <p>Time: 4:41:57 PM
*/
#Named
#SessionScoped
public class UserSession implements Serializable {
private String name;
private String role;
#Inject
private org.slf4j.Logger log;
#EJB
private PersistenceService pservice;
#Inject
private RulesBean rules;
private HashMap<Long, Boolean> boolHashmap;
public UserSession() {
}
#PostConstruct
public void postConstruct() {
log.info("session init ");
}
public String getName() {
if (name == null) getUserData();
return name == null ? "" : name;
}
public String getRole() {
return role == null ? "" : role;
}
public void setRole(String newValue) {
role = newValue;
}
public boolean isInRole() {
ExternalContext context
= FacesContext.getCurrentInstance().getExternalContext();
Object requestObject = context.getRequest();
if (!(requestObject instanceof HttpServletRequest)) {
log.info("request object has type " + requestObject.getClass());
return false;
}
HttpServletRequest request = (HttpServletRequest) requestObject;
return request.isUserInRole(role);
}
private void getUserData() {
ExternalContext context
= FacesContext.getCurrentInstance().getExternalContext();
Object requestObject = context.getRequest();
if (!(requestObject instanceof HttpServletRequest)) {
log.info("request object has type " + requestObject.getClass());
return;
}
HttpServletRequest request = (HttpServletRequest) requestObject;
name = request.getRemoteUser();
}
public HashMap getBoolHashmap() {
if (boolHashmap == null)
initBolHashMap();
return boolHashmap;
}
public void setBoolHashmap(HashMap<Long, Boolean> boolHashmap) {
this.boolHashmap = boolHashmap;
}
public void initBolHashMap() {
this.boolHashmap = new HashMap<Long, Boolean>();
System.out.println("");
log.info("init map..");
log.info("loding list");
log.warn("user name = " + rules.getUserPrincipalName());
for (OasysUserEntity user : pservice.getUsersList(pservice.getUserByLogin(rules.getUserPrincipalName()).getPartnerid())) {
boolHashmap.put(user.getId(), false);
log.info("map =" + boolHashmap);
}
log.info("loaded list");
}
public boolean getPWRender(long id) {
if (boolHashmap == null)
initBolHashMap();
//TODO if it null - exception will be thrown
try {
log.info("getting id =" + id);
log.info("map is =" + boolHashmap);
log.info("getting result = =" + boolHashmap.get(id));
log.info("getting result = =" + boolHashmap.get(Long.valueOf(id)));
return boolHashmap.get(Long.valueOf(id));
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
public void setPWrenerTrue(long id) {
if (boolHashmap == null)
initBolHashMap();
log.info("setPWrenerTrue id =" + id);
boolHashmap.put(id, true);
log.info("setPWrenerTrue map is =" + boolHashmap);
}
}
and 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:cc="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<body>
<cc:interface>
</cc:interface>
<cc:implementation>
#{i18n.user_managment_title}
<h:form>
<!--<f:ajax render="#form" execute="#form">-->
<h:dataTable id="userTable" var="puser" value="#{userTable.uList}" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Login"/>
</f:facet>
#{puser.login}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="password"/>
</f:facet>
<h:panelGroup>
<!--#{puser.password} -->
<h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}"
action="#{userSession.setPWrenerTrue(puser.id)}">
<f:ajax render="pswd chps"/>
</h:commandButton>
<h:inputSecret id="pswd" rendered="#{userSession.getPWRender(puser.id)}" value="some"/>
<!--<h:inputSecret id="chpaswd" value="#{managePUser.password}">-->
<!--<f:ajax event="click" render="chpaswd"/>-->
<!--</h:inputSecret>-->
<!--<h:commandButton value="#{i18n.submit_button}">-->
<!--</h:commandButton>-->
</h:panelGroup>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="pId"/>
</f:facet>
#{puser.partnerid}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="groupName"/>
</f:facet>
#{puser.groupName}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="isActive"/>
</f:facet>
#{puser.userStatusid==2}
</h:column>
<h:column>
<h:commandButton value="#{i18n.delete_button}" action="#{managePUser.removeEntity(puser)}"
disabled="#{puser.groupName.equals('admin')}">
<f:ajax render="#form"/>
</h:commandButton>
</h:column>
<!--<h:column>-->
<!---->
<!--<h:commandButton value="#{i18n.edit_button}" action="#{managePUser.removeEntity(puser)}"/>-->
<!--</h:column>-->
<f:facet name="footer">
<!--<f:ajax render="footeradd userTable">-->
<h:panelGroup id="footeradd">
<h:panelGroup layout="block" rendered="#{!managePUser.padd}">
<h:commandButton value="#{i18n.user_manager_add_user}"
action="#{managePUser.setEnablepadd}">
<f:ajax render="footeradd"/>
</h:commandButton>
</h:panelGroup>
<h:panelGroup id="adduser" rendered="#{managePUser.padd}" layout="block">
<h:panelGrid columns="2">
<h:outputText value="#{i18n.username}"/>
<h:inputText id="username" value="#{managePUser.login}"/>
<h:outputText value="#{i18n.password}"/>
<h:inputSecret id="passowrd" value="#{managePUser.password}"/>
<h:commandButton value="#{i18n.cancel_button}"
action="#{managePUser.setDisblepadd}">
<f:ajax render="footeradd"/>
</h:commandButton>
<h:commandButton value="#{i18n.submit_button}" action="#{managePUser.submit}">
<f:ajax render="footeradd userTable" execute="#this username passowrd"/>
</h:commandButton>
</h:panelGrid>
</h:panelGroup>
</h:panelGroup>
<!--</f:ajax>-->
</f:facet>
</h:dataTable>
<!--</f:ajax>-->
</h:form>
</cc:implementation>
</body>
</html>
so I using my bean in column at :
<h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}"
action="#{userSession.setPWrenerTrue(puser.id)}">
<f:ajax render="pswd chps"/>
</h:commandButton>
Question 2: what could be a better design for this situation ?
Question 3: Is it possible to listen to some events (onclick, ondbclick inside component tag ) for some component (inputSecret in my situation) if it steed as disabled=«true» ?
Thank you!
Change your scope to ViewScope, there is no need to keep UserSession class in SessionScope.