Primefaces Dialog and Closable events

UI Components for JSF
User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

24 May 2011, 23:48

Alex, here is my code:

The Layout.xhtml:

Code: Select all

<?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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <link type="text/css" rel="stylesheet" href="#{request.contextPath}/css/sgpc.css"/>
        <script type="text/javascript"  language="JavaScript" src="#{request.contextPath}/js/CloseListener.js"></script>
        <!--ui:insert name="titulo">teste.com</ui:insert-->
    </h:head>
    <h:body>
        <f:view contentType="text/html">
            <p:growl id="growl" showDetail="true" life="2000"/>
            <p:ajaxStatus onstart="wait.show();" oncomplete="wait.hide();"/>
            <p:panel>
                <ui:insert name="topo">
                    <ui:include src="jsfcomponents/globalMenu.xhtml"/>
                </ui:insert>
                <ui:insert name="esquerda"></ui:insert>
                <ui:insert name="conteudo"></ui:insert>
                <ui:insert name="direita"></ui:insert>
            </p:panel>
            <p:panel>
                <ui:insert name="rodape">Copyright ...</ui:insert>
            </p:panel>

            <p:dialog widgetVar="wait" width="180" height="100" header="Processando" resizable="false" draggable="false" closable="false">
                <h:panelGrid columns="1" style="text-align: center" width="100%">
                    <h:outputText value="Por favor aguarde..." style="text-align: center"/>
                    <h:graphicImage value="/images/icons/wait.gif" style="text-align: center"/>
                </h:panelGrid>
            </p:dialog>

            <ui:include src="creditos.xhtml"/>

        </f:view>
    </h:body>
</html>

Instituicoes.xhtml (where the error occurs):

Code: Select all

<?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: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.prime.com.tr/ui">


    <ui:composition template="./layout.xhtml">
        <ui:define name="esquerda">
            <br/>
        </ui:define>
        <ui:define name="conteudo">           
            <h:form id="form1">
                <p:panel header="#{label.general_Find}">
                    <h:panelGrid columns="2">
                        <h:panelGrid columns="2">
                            <h:outputText value="#{label.general_Keyword}" />
                            <p:inputText value="#{instituicaoBancariaMB.pesquisa}">
                                <f:ajax event="keyup" render="tabela" listener="#{instituicaoBancariaMB.pesquisar}" />
                            </p:inputText>
                        </h:panelGrid>
                        <h:panelGrid columns="2">
                            <h:commandLink id="downloadlinkPdf" title="Download PDF">
                                <p:graphicImage value="/images/icons/application_pdf.png" style="border:0"/>
                                <p:fileDownload value="#{instituicaoBancariaMB.downloadReportPdf()}" />
                            </h:commandLink>
                            <h:commandLink id="downloadlinkXls" title="Download XLS">
                                <p:graphicImage value="/images/icons/application_vnd.ms_excel.png" style="border:0"/>
                                <p:fileDownload value="#{instituicaoBancariaMB.downloadReportXls()}" />
                            </h:commandLink>
                        </h:panelGrid>
                    </h:panelGrid>
                </p:panel>
                <p:dataTable id="tabela"
                             value="#{instituicaoBancariaMB.listaInstituicoes}"
                             var="n"
                             rows="10"
                             paginatorPosition="bottom"
                             paginator="true"
                             rendered="true"
                             paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown} Total de #{instituicaoBancariaMB.listaInstituicoes.size()} registros encontrados"
                             rowsPerPageTemplate="5,10,15">
                    <f:facet name="header">
                        <h:outputText value="#{label.ib_Header}" />
                    </f:facet>

                    <p:column sortBy="#{n.nome}">
                        <f:facet name="header">
                            <h:outputText value="#{label.general_Name}" />
                        </f:facet>
                        <h:outputText value="#{n.nome}" id="nome" />
                    </p:column>

                    <p:column>
                        <f:facet name="header">
                            <h:outputText value="#{label.ib_Website}" />
                        </f:facet>
                        <h:outputText value="#{n.website}" id="website" />
                    </p:column>

                    <p:column sortBy="#{n.codigo}">
                        <f:facet name="header">
                            <h:outputText value="#{label.ib_Code}" />
                        </f:facet>
                        <h:outputText value="#{n.codigo}" id="codigo" />
                    </p:column>

                    <p:column>
                        <f:facet name="header">
                            <h:outputText value="#{label.ib_Other_Name}" />
                        </f:facet>
                        <h:outputText value="#{n.nomeFantasia}" id="nomeFantasia" />
                    </p:column>

                    <p:column>
                        <f:facet name="header">
                            <h:outputText value="#{label.general_Action}" />
                        </f:facet>
                        <p:commandLink id="editlink" oncomplete="addEditPopup.show();" update="addEditPanel" action="#{instituicaoBancariaMB.prepareEditar}" immediate="true" disabled="#{!instituicaoBancariaMB.podeEditarInstituicaoBancaria}">
                            <h:graphicImage value="#{instituicaoBancariaMB.imagemEditarRegistro}" style="border:0" />
                            <f:setPropertyActionListener value="#{n}" target="#{instituicaoBancariaMB.instituicaoBancaria}" />                           
                        </p:commandLink>
                        <p:tooltip for="editlink" value="#{label.general_Edit_Tip}" />

                        <p:commandLink id="deletelink" oncomplete="deletePopup.show()" disabled="true">
                            <h:graphicImage value="#{instituicaoBancariaMB.imagemExcluirRegistro}" style="border:0" />
                            <f:setPropertyActionListener value="#{n}" target="#{instituicaoBancariaMB.instituicaoBancaria}" />                            
                        </p:commandLink>
                        <p:tooltip for="deletelink" value="#{label.general_Delete_Tip}" />
                    </p:column>

                    <f:facet name="footer">
                        <p:columnGroup>
                            <p:column colspan="4"/>
                            <p:column>
                                <p:commandLink id="addlink" oncomplete="addEditPopup.show()" update="addEditPanel" action="#{instituicaoBancariaMB.prepareAdicionar}" immediate="true" disabled="#{!instituicaoBancariaMB.podeCriarInstituicaoBancaria}">
                                    <h:graphicImage value="#{instituicaoBancariaMB.imagemCriarRegistro}" style="border:0"/>
                                </p:commandLink>
                                <p:tooltip for="addlink" value="#{label.general_Add_Tip}" />
                            </p:column>
                        </p:columnGroup>
                    </f:facet>
                </p:dataTable>

            </h:form>

            <!-- ################################### -->
            <!-- bloco de edição -->
            <p:dialog widgetVar="addEditPopup"                      
                      width="400"
                      header="#{label.general_Edit}"
                      modal="true"
                      resizable="false"                                            
                      draggable="false"
                      closable="false"
                      closeOnEscape="false">
                <h:panelGrid columns="1" id="addEditPanel">
                    <h:form>
                        <h:panelGrid columns="3">
                            <h:outputText value="#{label.general_Name}:" />
                            <p:inputText value="#{instituicaoBancariaMB.instituicaoBancaria.nome}" id="nome" required="true" requiredMessage="#{label.general_Name_Required}."/>
                            <p:message for="nome" display="icon"/>

                            <h:outputText value="#{label.ib_Website}:" />
                            <p:inputText value="#{instituicaoBancariaMB.instituicaoBancaria.website}" id="website"/>
                            <h:outputText value="" />

                            <h:outputText value="#{label.ib_Code}:" />
                            <p:inputText value="#{instituicaoBancariaMB.instituicaoBancaria.codigo}" id="codigo" required="true" requiredMessage="#{label.general_Code_Required}"/>
                            <p:message for="codigo" display="icon"/>

                            <h:outputText value="#{label.ib_Other_Name}:" />
                            <p:inputText value="#{instituicaoBancariaMB.instituicaoBancaria.nomeFantasia}" id="nomeFantasia"/>
                            <h:outputText value="" />
                        </h:panelGrid>

                        <p:commandButton value="#{label.general_Save}"
                                         actionListener="#{instituicaoBancariaMB.gravar}"
                                         update="form1:tabela, addEditPanel"
                                         oncomplete="handleLocalesDialogComplete(xhr, status, args, addEditPopup)"/>
                        <p:commandButton value="#{label.general_Cancel}"
                                         actionListener="#{instituicaoBancariaMB.prepareAdicionar}"
                                         oncomplete="addEditPopup.hide();" />
                    </h:form>
                </h:panelGrid>
            </p:dialog>
            <!-- ################################### -->
            <!-- bloco de exclusão -->
            <p:dialog widgetVar="deletePopup" width="250" modal="true" header="#{label.general_Confirm}" resizable="false">
                <h:form>
                    <h:outputText value="#{label.general_Delete}"/>
                    <h:panelGrid columns="2">
                        <p:commandButton value="#{label.general_Yes}"
                                         action="#{instituicaoBancariaMB.excluir}"
                                         oncomplete="deletePopup.hide();"
                                         update="form1:tabela"/>

                        <p:commandButton value="#{label.general_Cancel}"
                                         onclick="deletePopup.hide();return false;" />
                    </h:panelGrid>
                </h:form>
            </p:dialog>

        </ui:define>        
    </ui:composition>
</html>
Managed Bean:

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.usp.icmc.sgpc.jsf;

import br.beans.InstituicaoBancariaBean;
import br.beans.PessoaBean;
import br.security.RbacConstantes;
import br.security.service.SecurityService;
import br.service.ReportService;
import br.service.Service;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Herick
 */
// @KeepAlive
@ManagedBean(name = "instituicaoBancariaMB")
@ViewScoped
public class InstituicaoBancariaManagedBean implements Serializable {

    private static final Logger logger = Logger.getLogger(InstituicaoBancariaManagedBean.class);
    public static final String PESQUISAR_STATE = "pesquisar";
    public static final String ADICIONAR_STATE = "adicionar";
    public static final String EDITAR_STATE = "editar";
    private String currentState = PESQUISAR_STATE;
    private InstituicaoBancariaBean instituicaoBancaria;
    private List<InstituicaoBancariaBean> listaInstituicoes = new ArrayList<InstituicaoBancariaBean>();
    private UIPanel panelForm;
    private Integer currentRow;
    private String pesquisa;
    private boolean podeCriarInstituicaoBancaria;
    private boolean podeEditarInstituicaoBancaria;
    private String imagemEditarRegistro = "/images/icons/editar.png";
    private String imagemExcluirRegistro = "/images/icons/delbw.png";
    private String imagemCriarRegistro = "/images/icons/add1.png";

    public String getImagemCriarRegistro() {
        if (podeCriarInstituicaoBancaria) {
            imagemCriarRegistro = "/images/icons/add1.png";
        } else {
            imagemCriarRegistro = "/images/icons/add1bw.png";
        }
        return imagemCriarRegistro;
    }

    public void setImagemCriarRegistro(String imagemCriarRegistro) {
        this.imagemCriarRegistro = imagemCriarRegistro;
    }

    public String getImagemEditarRegistro() {
        if (podeEditarInstituicaoBancaria) {
            imagemEditarRegistro = "/images/icons/editar.png";
        } else {
            imagemEditarRegistro = "/images/icons/editarbw.png";
        }
        return imagemEditarRegistro;
    }

    public void setImagemEditarRegistro(String imagemEditarRegistro) {
        this.imagemEditarRegistro = imagemEditarRegistro;
    }

    public String getImagemExcluirRegistro() {
        return imagemExcluirRegistro;
    }

    public void setImagemExcluirRegistro(String imagemExcluirRegistro) {
        this.imagemExcluirRegistro = imagemExcluirRegistro;
    }

    public boolean isPodeCriarInstituicaoBancaria() {
        return podeCriarInstituicaoBancaria;
    }

    public void setPodeCriarInstituicaoBancaria(boolean podeCriarInstituicaoBancaria) {
        this.podeCriarInstituicaoBancaria = podeCriarInstituicaoBancaria;
    }

    public boolean isPodeEditarInstituicaoBancaria() {
        return podeEditarInstituicaoBancaria;
    }

    public void setPodeEditarInstituicaoBancaria(boolean podeEditarInstituicaoBancaria) {
        this.podeEditarInstituicaoBancaria = podeEditarInstituicaoBancaria;
    }

    public InstituicaoBancariaManagedBean() {
        logger.debug("Instanciando classe");

        UserSessionManagedBean userSessionMB = (UserSessionManagedBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userSessionMB");
        PessoaBean usuarioLogado = userSessionMB.getLoggedUser();

        podeCriarInstituicaoBancaria = SecurityService.getInstance().verificarPermissao(usuarioLogado, RbacConstantes.INSTITUICAO_BANCARIA_CRIAR);
        podeEditarInstituicaoBancaria = SecurityService.getInstance().verificarPermissao(usuarioLogado, RbacConstantes.INSTITUICAO_BANCARIA_EDITAR);

        this.listaInstituicoes = Service.getInstance().listarInstituicoesBancarias();
    }
    /*
     * Pesquisa instituicoes bancarias
     */

    public void pesquisar() {
        logger.debug("PESQUISAR");
        this.setCurrentState(PESQUISAR_STATE);
        this.instituicaoBancaria = new InstituicaoBancariaBean();
        if ("".equals(this.pesquisa) || this.pesquisa == null) {
            logger.debug("PESQUISAR TODOS");
            this.listaInstituicoes = Service.getInstance().listarInstituicoesBancarias();
        } else {
            logger.debug("PESQUISAR COM TERMO");
            this.listaInstituicoes = Service.getInstance().pesquisarInstituicoesBancarias(this.pesquisa);
        }
    }
    /*
     * Prepara view adiciona
     */

    public void prepareAdicionar() {
        this.clear();
        this.setCurrentState(ADICIONAR_STATE);
    }

    /*
     * Prepara view edita
     */
    public void prepareEditar() {
        this.setCurrentState(EDITAR_STATE);
    }

    /*
     * Exclui registro
     */
    public void excluir() {
        logger.debug("EXCLUIR REGISTRO");
        Service.getInstance().excluirInstituicaoBancaria(instituicaoBancaria);
        this.pesquisar();
    }
    /*
     * Limpa atributo
     */

    public void clear() {
        this.instituicaoBancaria = new InstituicaoBancariaBean();
        //this.cleanSubmittedValues(this.panelForm);
    }

    public boolean isPesquisarState() {
        String state = this.getCurrentState();
        return (state == null || PESQUISAR_STATE.equals(state));
    }

    public boolean isAdicionarState() {
        return ADICIONAR_STATE.equals(this.getCurrentState());
    }

    public boolean isEditarState() {
        return EDITAR_STATE.equals(this.getCurrentState());
    }

    /*
     * Limpa os componentes filhos para que depois eles possam ser recriado
     * @param componen
     */
    protected void cleanSubmittedValues(UIComponent component) {
        component.getChildren().clear();
    }

    public String getCurrentState() {
        return currentState;
    }

    public void setCurrentState(String currentState) {
        this.currentState = currentState;
    }

    public InstituicaoBancariaBean getInstituicaoBancaria() {
        return instituicaoBancaria;
    }

    public void setInstituicaoBancaria(InstituicaoBancariaBean instituicaoBancaria) {
        this.instituicaoBancaria = instituicaoBancaria;
    }

    public List<InstituicaoBancariaBean> getListaInstituicoes() {
        return listaInstituicoes;
    }

    public void setListaInstituicoes(List<InstituicaoBancariaBean> listaInstituicoes) {
        this.listaInstituicoes = listaInstituicoes;
    }

    public UIPanel getPanelForm() {
        return panelForm;
    }

    public void setPanelForm(UIPanel panelForm) {
        this.panelForm = panelForm;
    }

    public Integer getCurrentRow() {
        return currentRow;
    }

    public void setCurrentRow(Integer currentRow) {
        this.currentRow = currentRow;
    }

    public String getPesquisa() {
        return pesquisa;
    }

    public void setPesquisa(String pesquisa) {
        this.pesquisa = pesquisa;
    }

    public void gravar() {
        if (ADICIONAR_STATE.equals(this.currentState)) {
            logger.debug("ADICIONAR REGISTRO");
            Service.getInstance().cadastraInstituicaoBancaria(instituicaoBancaria);
        } else if (EDITAR_STATE.equals(this.currentState)) {
            logger.debug("EDITAR REGISTRO");
            Service.getInstance().atualizarInstituicaoBancaria(instituicaoBancaria);
        }
        this.pesquisar();
    }

    public StreamedContent downloadReportPdf() {
        logger.debug("GERAR RELATORIO PDF");
        InputStream stream = ReportService.getInstance().emiteRelatorioInstituicoesBancarias(listaInstituicoes, ReportService.FORMATO_PDF);
        StreamedContent file = new DefaultStreamedContent(stream, "application/pdf", "report.pdf");
        return file;
    }

    public StreamedContent downloadReportXls() {
        logger.debug("GERAR RELATORIO XLS");
        InputStream stream = ReportService.getInstance().emiteRelatorioInstituicoesBancarias(listaInstituicoes, ReportService.FORMATO_XLS);
        StreamedContent file = new DefaultStreamedContent(stream, "application/vnd.ms-excel", "report.xls");
        return file;
    }
}
JS:

Code: Select all

function handleLocalesDialogComplete(xhr, status, args, dialog)
{
    if (args) {
        var isValid = args.isValid;
        if(!isValid) {
            dialog.hide();
        }
    }
}
PhaseListener:

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.usp.icmc.sgpc.fmw;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Herick
 */
public class CloseDialogPhaseListener implements PhaseListener {

    private static final Logger logger = Logger.getLogger(CloseDialogPhaseListener.class);

    public void afterPhase(PhaseEvent phaseEvent) { }

    public void beforePhase(PhaseEvent event) {
        logger.debug("Setando atributos para funcionamento de componentes dialog...");
        RequestContext requestContext = RequestContext.getCurrentInstance();
        if (requestContext != null) {
            boolean messageOccured = FacesMessage.SEVERITY_ERROR.equals(event.getFacesContext().getMaximumSeverity());
            requestContext.addCallbackParam("isValid", messageOccured);
        }
    }

    public PhaseId getPhaseId() {        
        return PhaseId.RENDER_RESPONSE;
    }
}

I found a similar question here:
http://www.coderanch.com/t/491486/JSF/j ... nException

My problem is exactly the same. Attention to the solution proposed on the last post (Yaroslav), I already try but without success.
If you need any more code, just ask!

Thanks in advance for your help.
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

Alex
Posts: 256
Joined: 16 Dec 2010, 14:24
Location: Germany

25 May 2011, 00:52

ah.. as i suggested this might be an update problem.
p:dialog is a namingcontainer, so the childelements are getting the namingcontainers id prepended.
you have to define a id for your dialog and then prepend it to your upload

just have a look at my code again.. my dialog has id="myDialog" and the update of the openerbutton is update="myDialog:contentWrapper"
PrimeFaces 3.2
Mojarra 2.0.2
Glassfish 3.0.1

User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

25 May 2011, 14:47

I tried your solution but without success.

Did you see the link that I posted?
If I open the dialog, insert some data and click on cancel, the dialog will be closed.
When I open it again, the inputs will be empty, that means that my update is ok.

Now, If I open the dialog, insert some wrong data and click on save, my listener will show the error on dialog. If I click on the cancel button, it means that I don't want to save the data anymore, the dialog will be closed.

If I click to open the dialog again, the error occurs. The data that was typed still on the dialog. The update on dialog doesn't work. I did a debug in this moment, and my bean is empty. There's nothing on the backing bean, but the data is on the dialog.

It seems that when I try to save, my listener gets the error and the binding between the GUI and the backing bean is aborted (And it is the correct), but I don't understand how the data still on the dialog, and why my update doesn't work in this specific way (When the dialog returns the error message and I cancel).

I'm stuck on this problem has three days. But if in your application everything is ok, so I must to find where is the problem on my app.
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

Alex
Posts: 256
Joined: 16 Dec 2010, 14:24
Location: Germany

25 May 2011, 16:26

hmmm just a gues,, but try process="@this" and immediate="true" on your cancel button
PrimeFaces 3.2
Mojarra 2.0.2
Glassfish 3.0.1

User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

25 May 2011, 16:58

Nothing happens...the problem persists.

May you try to test my code on your environment or post an entire xhtml with a dialog?
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

Alex
Posts: 256
Joined: 16 Dec 2010, 14:24
Location: Germany

25 May 2011, 17:29

oh.. i just recognized, that dialogs are no namingcontainers...
we use them in composite components in our application which basically are namingcontainers, so its my fault..

ive rebuild a simple example and it works fine, if the updated id is correct :)
HTML:

Code: Select all

<?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://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>

        <script type="text/javascript">
            function hideDialog(xhr, status, args, dialog)
{
    if (args) {
        var isValid = args.isValid;
        if(!isValid) {
            dialog.hide();
        }
    }
}
        </script>

        <p:messages autoUpdate="true" />

        <h:form>
            <p:commandButton value="openDialog"
                             actionListener="#{myBean.actionInitDialog}"
                             update="contentWrapper"
                             oncomplete="myDialogWV.show();" />
        </h:form>


        <p:dialog id="myDialog"
                  widgetVar="myDialogWV"
                  modal="true"
                  closable="false"
                  closeOnEscape="false"
                  header="my Dialog">
            <p:outputPanel id="contentWrapper">
                <p:messages id="msg_dialog" />
                <h:form>
                    <p:inputText required="true"
                                 value="#{myBean.str}" />
                    <p:commandButton value="cancel"
                                     immediate="true"
                                     process="@this"
                                     onclick="myDialogWV.hide()" />
                    <p:commandButton value="save"
                                     action="#{myBean.save}"
                                     update="msg_dialog"
                                     oncomplete="hideDialog(xhr, status, args, myDialogWV);" />
                </h:form>
            </p:outputPanel>                
        </p:dialog>

    </h:body>
</html>
Bean:

Code: Select all

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class MyBean {
    
    private String str;

    public void actionInitDialog() {
        str = "";        
    }
    
    public void save() {
        FacesContext.getCurrentInstance().addMessage(null, 
                new FacesMessage(FacesMessage.SEVERITY_INFO, "saved", null));
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
    
    
}
i additionally used your phaselistener
working fine for me now.. sorry if i costed you some time with my false information..

first i had the same like you explained, then identied the wrappers id with firebug and everything was clear... sorry again
PrimeFaces 3.2
Mojarra 2.0.2
Glassfish 3.0.1

User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

25 May 2011, 18:58

Hey again Alex,

I got your code here, and I just put another input on dialog to see the error happen.
I'm gonna pass a walkthrough so you can see the error.

HTML

Code: Select all

<?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://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>

        <script type="text/javascript">
            function hideDialog(xhr, status, args, dialog)
{
    if (args) {
        var isValid = args.isValid;
        if(!isValid) {
            dialog.hide();
        }
    }
}
        </script>

        <p:messages autoUpdate="true" />

        <h:form>
            <p:commandButton value="openDialog"
                             actionListener="#{myBean.actionInitDialog}"
                             update="contentWrapper"
                             oncomplete="myDialogWV.show();" />
        </h:form>


        <p:dialog id="myDialog"
                  widgetVar="myDialogWV"
                  modal="true"
                  closable="false"
                  closeOnEscape="false"
                  header="my Dialog">
            <p:outputPanel id="contentWrapper">
                <p:messages id="msg_dialog" />
                <h:form>
                    <p:inputText required="true"
                                 value="#{myBean.str}" />
                    <p:inputText required="true"
                                 value="#{myBean.str2}" />
                    <p:commandButton value="cancel"
                                     immediate="true"
                                     process="@this"
                                     onclick="myDialogWV.hide()" />
                    <p:commandButton value="save"
                                     action="#{myBean.save}"
                                     update="msg_dialog"
                                     oncomplete="hideDialog(xhr, status, args, myDialogWV);" />
                </h:form>
            </p:outputPanel>
        </p:dialog>

    </h:body>
</html>
Bean:

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package teste;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class MyBean {

    private String str;
    private String str2;

    public void actionInitDialog() {
        str = "";
        str2 = "";
    }

    public void save() {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "saved", null));

    }

    public String getStr2() {
        return str2;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}
The two inputs are required. So, you need to insert data on one and let the other empty, try to save and the dialog will show the error. So, cancel to close the dialog.
When you open the dialog again, the input where you typed data will not be empty.

If you want, I can send you a project of netbeans with the sample.
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

Alex
Posts: 256
Joined: 16 Dec 2010, 14:24
Location: Germany

25 May 2011, 23:24

wow your right... this is really strange.. have to check if this can happen in our application too..
for my luck we dont have many required fields, but maybe other validations show the same effect..

i will investigate more tomorrow.
PrimeFaces 3.2
Mojarra 2.0.2
Glassfish 3.0.1

User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

26 May 2011, 14:26

Hey Alex,

Now you saw the problem.
Well, I'm facing with this has some days, so I have some ideas about the problem.

First: If you remove the phase listener and insert that verification code on the backing bean, the problem will not happen. But this is not a good solution because you will need to replicate in all backing beans from your application.

Second: Looking about this problem, I found a lot of foruns where the people are using a method to clear the GUI on the backing bean side. This code will need to be replicated too, and in one of my tries, I see that this solution only works on the first time. When you repeat the proccess to see the error, it will happen again and the GUI will not be cleared.

The Cause: It seems that when the phase listener is called, He only does the verifications of validators and required fields. That verification for errors happens before of the binding process, it means that your bean on the Server side, dont has the data typed on your Field yet.

"The Problem at this point is, that the UIComponents doens't know anything about the instance of the data-holding Object, for the View the UIComponent have an error-state and JSF displays the old-values. "

How I Said, I saw this problem on my application and in another forum (without a solution). So now, both of us are trying to find a solution for this.
The first solution is to put this code on the save method of your backing bean:

Code: Select all

 RequestContext requestContext = RequestContext.getCurrentInstance();
        if (requestContext != null) {
            boolean messageOccured = FacesMessage.SEVERITY_ERROR.equals(event.getFacesContext().getMaximumSeverity());
            requestContext.addCallbackParam("isValid", messageOccured);
        }
The second is to make a bind of your dialog to a object on the bean side, and call this method on cancel button:

Code: Select all

private UIPanel panelForm;
public void clear() {        
        this.cleanSubmittedValues(this.panelForm);
    }
Or this code:

Code: Select all

 public static void resetForm(UIComponent form) {  
    for (UIComponent uic : form.getChildren()) {  
      if (uic instanceof EditableValueHolder) {  
        EditableValueHolder evh=(EditableValueHolder)uic;  
        evh.resetValue();  
      }  
      resetForm(uic);  
    }  
  }  
Debugging the second solution, the first time when the method is called, the component will have the childrens cleared. On the second time, when you repeat the proccess of error, the childrens will not exists (size 0).

Any ideas?
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

User avatar
Hericksnake
Posts: 47
Joined: 21 Jan 2011, 22:45
Location: Brasil

27 May 2011, 14:24

Hi Alex,

The problem happened in your app too?
Did you have any idea to solve it?

Just to know, because I'm stuck with this yet.
Thank's for all help.
;)
Primefaces 3.2
JSF 2.0
Glassfish Server 3.1.2
Netbeans7.1.1

Post Reply

Return to “PrimeFaces”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 33 guests