0

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>&nbsp;&nbsp;&nbsp;</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>&nbsp;&nbsp;&nbsp;</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.

Frateschi
  • 1
  • 1

1 Answers1

0

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.

stefan-dan
  • 586
  • 5
  • 19