Primefaces datatable filter - java

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>

Related

Primefaces datatable change item with wrong id (onrowedit) when I have a separate method for searching the datatable [duplicate]

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.

Datatable Primefaces editor does not send updated value for editing

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

JSF doesn't update values in the view when f:validateRegex fails

I'm using JSF 2.2 in a web application and I'm having problems in the view when I use f:validateRegex and fails (because when I use immediate="true" and try to navigate to the same page again, the view isn't updated when I have a new Instance of the object in my backing bean). I was thinking richfaces has a bug (because I'm using jsf and richfaces in my main application) so I made a test code with richfaces and without richfaces (only jsf) to identify where is the error, but in both cases the view fails.
Here is my test code without richfaces (Only jsf):
View:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title>Mis pruebas con JSF</title>
</h:head>
<h:body>
<h:form id="lista">
<h:panelGrid id="principal">
<h:dataTable value="#{indexBB.personas}" var="persona">
<h:column>
<f:facet name="header">Activo</f:facet>
<h:selectBooleanCheckbox value="#{persona.activo}"></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
<h:outputText value="#{persona.nombre}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Correo</f:facet>
<h:outputText value="#{persona.correo}"></h:outputText>
</h:column>
</h:dataTable>
<h:commandButton action="#{indexBB.crearPersona}" value="Crear Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.activarBoton}" value="Activar Boton">
</h:commandButton>
</h:panelGrid>
</h:form>
<h:form id="crear">
<h:panelGrid id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.cancelar}" value="Cancelar" immediate="true">
</h:commandButton>
</h:panelGrid>
</h:form>
</h:body>
</html>
Bean:
package com.kanayet.martin.view.bb;
import com.kanayet.martin.model.entity.Persona;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named(value = "indexBB")
#ViewScoped
public class indexBB implements Serializable {
private Persona persona;
private List<Persona> personas;
private boolean crear;
/**
* Creates a new instance of indexBB
*/
public indexBB() {
}
#PostConstruct
public void onInit(){
personas = new ArrayList<>();
personas.add(new Persona("Martin", "martin#gmail.com", true));
personas.add(new Persona("Andrea", "andrea#gmail.com", true));
personas.add(new Persona("Camilo", "camilo#gmail.com", true));
personas.add(new Persona("Felipe", "felipe#gmail.com", true));
personas.add(new Persona("David", "david#gmail.com", true));
}
public void activarBoton() {
persona = personas.get(0);
}
public void crearPersona(){
crear = true;
persona = new Persona();
}
public void guardarPersona(){
personas.set(0, persona);
}
public void cancelar(){
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public List<Persona> getPersonas() {
return personas;
}
public void setPersonas(List<Persona> personas) {
this.personas = personas;
}
public boolean isCrear() {
return crear;
}
public void setCrear(boolean crear) {
this.crear = crear;
}
}
Model: (Object)
package com.kanayet.martin.model.entity;
public class Persona {
private String nombre;
private String correo;
private Boolean activo;
public Persona() {
}
public Persona(String nombre, String correo, Boolean activo) {
this.nombre = nombre;
this.correo = correo;
this.activo = activo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public Boolean getActivo() {
return activo;
}
public void setActivo(Boolean activo) {
this.activo = activo;
}
}
Here is my test code with richfaces: (Bean and Model are the same)
View:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Mis pruebas con RichFaces</title>
</h:head>
<h:body>
<h:form id="lista">
<a4j:outputPanel id="principal">
<rich:dataTable id="personas" value="#{indexBB.personas}"
var="persona" rows="50">
<rich:column>
<h:selectBooleanCheckbox label="Activo" value="#{persona.activo}">
</h:selectBooleanCheckbox>
</rich:column>
<rich:column>
<h:outputText value="#{persona.nombre}"></h:outputText>
</rich:column>
<rich:column>
<h:outputText value="#{persona.correo}"></h:outputText>
</rich:column>
</rich:dataTable>
<h:commandButton action="#{indexBB.crearPersona}" value="Crear Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.activarBoton}" value="Activar Boton">
</h:commandButton>
</a4j:outputPanel>
</h:form>
<br></br>
<h:form id="crear">
<a4j:outputPanel id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.cancelar}" value="Cancelar" immediate="true">
</h:commandButton>
</a4j:outputPanel>
</h:form>
</h:body>
</html>
The problem is when I click "Crear Persona" button, I write for example "Nombre": Felix and "Correo": Felix and click "Guardar Persona" button so f:validateRegex fails because isn't a valid email, then click "Cancelar" because my final user doesn't know email required value (immediate="true"). Again, click "Crear Persona" button, (new object in my bean) and jsf page isn't updated, the form should be empty but it isn't, in field "Nombre" stills "Felix" value, but in my bean I have a new and empty object without values in its attributes, do you know why?
The problem is with and without richfaces (because I thought the problem could be richfaces, but it isn't), so I don't know why jsf page isn't updated if I have a new object in my bean, I used netbeans debug tool to verify but I'm right, the object that I see in my bean is different (server side new and empty object) but in my JSF page "Nombre" has "Felix" value and I want to know why it happens, and how I can resolve this problem.
Thank you so much.
The problem is that JSF maintains two representations of your model. There is the Java object, IndexBB, but there is also the component tree, the thing that keeps track of UI state.
When you fail validation, the component tree still contains the values entered. (This is a useful feature so that the user can correct the values.) You've used immediate=true to skip validation, but that doesn't reset the component tree values.
In JSF 2.2, you can use resetValues to reset component tree values:
<h:form id="crear">
<h:panelGrid id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText id="nombreId" label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText id="correoId" label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton
action="#{indexBB.cancelar}" value="Cancelar">
<f:ajax resetValues="true" render="crear:nombreId crear:correoId"/>
</h:commandButton>
</h:panelGrid>
</h:form>
Changes:
Remove immediate=true.
Add ids to inputs you want to reset.
Add f:ajax to Cancelar button.
Add resetValues property to f:ajax and list your IDs (separate IDs with spaces, not comma).
Make sure your cancelar method actually resets persona -- the code you posted doesn't do this.
If you also want to reset the error messages, add an h:messages to the form, give it an ID, and reset it too.
See also
JSF 2.2: Reset input fields
How to skip validation when a specific button is clicked?

Primefaces 4.0 dataTable dialog details doesn't working

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>

How to add multiple rows in rich:datatable when by manually clicking add new Button?

I am designing a web page in which there is a rich:DataTable which I am using to add new customer information in the Database .
So each time a click the "Add New" button, a new row should appear in the rich datatable with Blank Input Text Fields .
Problem : Even how many times I am clicking the "Add New" Button, there remains only one row in table .
Following is the code of my web page :
<a4j:outputPanel id="rep" rendered="#{adminBean.currentItem == 'Participant' || adminBean.currentItem == 'Administrator'}">
<rich:panel rendered="#{not empty adminBean.currentItem}" header="Add Customer" id="out">
<h:panelGrid columns="2">
<h:commandButton value="Add New" type="button" style="width: 70px" actionListener="#{adminBean.addCustAction}">
<a4j:ajax render="out"/>
</h:commandButton>
<a4j:commandButton value="Delete" style="margin-left: 10px; width: 70px"></a4j:commandButton>
</h:panelGrid>
<rich:dataScroller for="setcust" style="margin-top: 17px"></rich:dataScroller>
<rich:dataTable id="setcust" value="#{adminBean.customerList}" var="custl" rows="10" style="width: 900px;margin-top: 5px">
<rich:column id="col1">
<f:facet name="header">
<h:outputText value="Customer ID" style="font-size: smaller; font-weight: bolder; "/>
</f:facet>
<h:inputText value="#{custl.Id}"></h:inputText>
</rich:column>
<rich:column id="col2">
<f:facet name="header">
<h:outputText value="First Name" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.FirstName}"></h:inputText>
</rich:column>
<rich:column id="col3">
<f:facet name="header">
<h:outputText value="Last Name" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.lastName}"></h:inputText>
</rich:column>
<rich:column id="col4">
<f:facet name="header">
<h:outputText value="Phone" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.phoneNo}"></h:inputText>
</rich:column>
<rich:column id="col5">
<f:facet name="header">
<h:outputText value="Address" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.address}"></h:inputText>
</rich:column>
<rich:column id="col6">
<f:facet name="header">
<h:outputText value="City" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.city}"></h:inputText>
</rich:column>
<rich:column id="col7">
<f:facet name="header">
<h:outputText value="Email" style="font-size: smaller; font-weight: bolder;"/>
</f:facet>
<h:inputText value="#{custl.email}"></h:inputText>
</rich:column>
</rich:dataTable>
</rich:panel>
</a4j:outputPanel>
Following is the code of the AdminBean:
#ManagedBean
#ViewScoped
public class AdminBean {
private String currentType;
private String currentItem;
private List<Customer> customerList = new ArrayList<Customer>();
private List<Account> accountList;
private List optionList;
public List getOptionList() {
optionList = new ArrayList<String>();
if (currentType.equals("Add New User")) {
optionList.add("Participant");
optionList.add("Administrator");
} else if (currentType.equalsIgnoreCase("Manage Balance")) {
optionList.add("Withdrawl");
optionList.add("Deposit");
}
return optionList;
}
public void setOptionList(List optionList) {
this.optionList = optionList;
}
public List<Account> getAccountList() {
return accountList;
}
public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
}
public List<Customer> getCustomerList() {
System.out.println("got list..................");
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}
public String getCurrentItem() {
return currentItem;
}
public void setCurrentItem(String currentItem) {
this.currentItem = currentItem;
}
public String getCurrentType() {
return currentType;
}
public void setCurrentType(String currentType) {
this.currentType = currentType;
}
public void addCustAction(){
System.out.println("kshitij jain.......actionListener"+customerList.size());
Customer cust = new Customer();
customerList.add(cust);
}
}
You have some problems in your code:
Every UICommand should be wrapped inside a <h:form> in order to work. Please refer to commandButton/commandLink/ajax action/listener method not invoked or input value not updated, section 1.
You're not declaring the actionListener method in the right way, the method needs an ActionEvent event parameter. It looks like you wanted to use action instead. Refer to Differences between action and actionListener for more info.
In RichFaces 4, there's no need to use <h:commandButon> together with <a4j:ajax>, this is the purpose of <a4j:commandButton>. From the documentation:
The component is similar to the JavaServer Faces (JSF) component, but additionally includes Ajax support.
Tying all these advices together, your JSF code should be (I've omitted not necessary code to test the results like styles and rendered conditions)
<a4j:outputPanel id="rep" >
<rich:panel id="out">
<h:form id="frmCustomerData">
<h:panelGrid columns="2">
<a4j:commandButton value="Add New"
action="#{adminBean.addCustAction}"
render="setcust" />
<a4j:commandButton value="Delete" />
</h:panelGrid>
<rich:dataScroller for="setcust" style="margin-top: 17px"></rich:dataScroller>
<rich:dataTable id="setcust" value="adminBean.customerList" var="custl" rows="10" style="width: 900px;margin-top: 5px">
<!-- datatable content... -->
</rich:dataTable>
</h:form>
</rich:panel>
</a4j:outputPanel>
There's no need to make any change on the managed bean.

Categories