How to display FacesMessage for a specific CommandLink / commandButton / form?

When I click the Submit button, I have to run application / business layer checks and link the error message to the link. Since I cannot do this, I can put an error message on top of the link.

My check for business logic in an action method

FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary("ERROR MESSAGE"); message.setDetail("ERROR MESSAGE"); FacesContext.getCurrentInstance().addMessage("linkId", message); 

Help with thanks

+4
source share
2 answers

The first argument to FacesContext#addMessage() should be the client identifier, not the component identifier. The client identifier is what you see as the identifier of the HTML element in the generated HTML output (as you can see by right-clicking and View Source in the browser). For input components and JSF commands in a form, the form identifier prefix is โ€‹โ€‹usually used.

So for the next link

 <h:form id="formId"> ... <h:commandLink id="linkId" ... /> <h:message for="linkId" /> </h:form> 

You should add a message as follows:

 FacesContext.getCurrentInstance().addMessage("formId:linkId", message); 

However, a more canonical approach for displaying global messages, as you would from an action method, simply uses <h:messages globalOnly="true" /> , which you can fill with messages with a client identifier of null .

So,

 <h:form id="formId"> ... <h:commandLink id="linkId" ... /> <h:messages globalOnly="true" /> </h:form> 

with

 FacesContext.getCurrentInstance().addMessage(null, message); 

See also:

+10
source

You can associate the error message with a link. To do this, write an action method for your button, as shown below:

 <h:commandButton label="Submit" action="#{actionBean.actionMethod}"/> 

And the action method is as follows:

 public String actionMethod(){ if(error){ return "error"; else return "index"; } 

The method returns the result. For example, the page is moved to /error.xhtml if an error occurs.

0
source

Source: https://habr.com/ru/post/1393264/


All Articles