3

I need your assistant in updating the <p:message> component in a JSF page once the non-ajax <p:commandButton> is clicked. Currently in the case, I need to validate if the employee number is null, then show the error message in the message component, else, nothing to be shown. But now,the form is not showing anything once the <p:commandButton> is clicked.

Below is the JSF code:

<h:form id="form">
    <p:inputText value="#{pdf.refNo}"/>

    <p:message id="message" for=":form:cmd2" showDetail="true"/>

    <p:commandButton id="cmd2"
                     value="Validate"
                     ajax="false"
                     actionListener="#{pdf.validate}"/>

</h:form>

And the Java bean is:

public void validate() {
    if (refNo.equals("") || refNo == null) {
        FacesContext.getCurrentInstance().addMessage(":form:cmd2", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Please enter the Employee No."));
    }
}

So is the above code is correct and how to show the message once the button is clicked?

Tiny
  • 27,221
  • 105
  • 339
  • 599
99maas
  • 1,239
  • 12
  • 34
  • 59
  • 1
    Is the `validate()` method invoked or not, when the command button is clicked? The order of conditional checks in the `if` statement needs to be interchanged. It is likely to cause a `java.lang.NullPointerException`, otherwise, if `refNo` is `null`. – Tiny Aug 14 '15 at 12:23
  • @Tiny it is invoked. I tried to keep System.out.println("test"); and it was printed in the console. Even though, I tried to remove the validation and to show only the message, it is still not shown. – 99maas Aug 14 '15 at 12:59
  • You will need to change `:form:cmd2` to `form:cmd2` in the backing bean. Thus, this should do, `FacesContext.getCurrentInstance().addMessage("form:cmd2", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Please enter the Employee No."));` – Tiny Aug 14 '15 at 17:21
  • @Tiny Thanks for the help I will try this and come back ... But one stupid question why in the jsf I am using the colon before the form name and in the backing bean I am using also the colon before the form name if I am updating a component from the form, but in this case I need to remove it. I am now a little bit confused. – 99maas Aug 14 '15 at 17:54
  • http://stackoverflow.com/q/12367597/1391249 (In this case, only `` or `` will also work). – Tiny Aug 14 '15 at 18:03

1 Answers1

1

The issue was solved by using the for in order to specify the target component. So in the above case, I referred to the command button, so we it is clicked, a specific message component should be updated. This can be done by:

<p:message id="message" for="cmd2" showDetail="true"/> or

<p:message id="message" for="form:cmd2" showDetail="true"/>
99maas
  • 1,239
  • 12
  • 34
  • 59