简体   繁体   中英

primefaces p:messages are not displayed

I have a button in a form and I want an error message to be displayed when I click on this button. It is a step I want to complete before coding something similar. My code does not work because the error message is not displayed when I click on the button.

My form is:

<h:form id="myForm">
    <p:messages id="errorMessage" for="myForm" autoUpdate="true" />
    <p:fieldset id="myFieldSet"
                style="margin-left:auto ; margin-right:auto ; width:98% ; height:90px;">
        <p:outputLabel for="numSi"
                       value="Value :"
                       style="margin-left:31px;margin-top:25px;" />
        <p:inputText id="numSi"
                     value="#{suppSiBean.researchValue}"
                     maxlength="9" required="true">
        </p:inputText>
        <p:commandButton id="suppSignaButton" type="submit" ajax="true"
                         value="Launch"
                         style="text-align: center ; height:45px; width:150px ; margin-top:20px;"
                        action="#{suppSiBean.lancerRequete()}" />
    </p:fieldset>
</h:form>

Excerpt of my bean :

public void lancerRequete() {}
    FacesContext context = FacesContext.getCurrentInstance();
    //I'm intentionally hide the values of the three following variables because it's confidential
    ResourceBundle bundle = ...
    String message = ...
    String messageFormat = ...
    FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageFormat.toString(), "");
    FacesContext.getCurrentInstance().addMessage(getClientId("myForm"), facesMessage);
}

public String getClientId(String id) {
    FacesContext context = FacesContext.getCurrentInstance();
    UIViewRoot root = context.getViewRoot();
    UIComponent c = findComponent(root, id);
    LOGGER.info("c.getClientId(context) vaut :" + c.getClientId(context));
    return c.getClientId(context);
}

private UIComponent findComponent(UIComponent c, String id) {
    if (id.equals(c.getId())) {
        return c;
    }
    Iterator<UIComponent> kids = c.getFacetsAndChildren();
    while (kids.hasNext()) {
        UIComponent found = findComponent(kids.next(), id);
        if (found != null) {
            return found;
        }
    }
    return null;
}

Why not targeting the ID of the component directly in the addMessage method ?

public void lancerRequete() {}
     ...
     FacesContext.getCurrentInstance().addMessage("errorMessage", facesMessage);
}

Finally, you should tell when to update this component by adding update attribute :

<p:commandButton ... update="errorMessage" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM