Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display FacesMessage for specific commandLink/commandButton/form?

Tags:

validation

jsf

On clicking the Submit button I have to do application/business level validations and associate the error message to a link. As I cannot do that is there any way that I can place the error message on top of the link.

My validation for business logic is in the 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 is greatly appreciated

like image 957
Greeshma Avatar asked Jan 26 '12 21:01

Greeshma


1 Answers

The first argument of FacesContext#addMessage() must be the client ID, not the component ID. The client ID is whatever you see as ID of the HTML element in the generated HTML output (as you can see by rightclick page and View Source in browser). For JSF input and command components in a form this is usually prefixed with the ID of the form.

So, for the following link,

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

you should be adding the message as follows:

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

However, the more canonical approach for displaying global messages as you would do from within an action method is just using <h:messages globalOnly="true" /> which you can fill with messages with a null client ID.

So,

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

with

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

See also:

  • How to use JSF h:messages better?
  • Creating FacesMessage in action method outside JSF conversion/validation mechanism?
like image 60
BalusC Avatar answered Sep 26 '22 18:09

BalusC