From Mike Kienenberger, posted on MyFaces mailing list:

<h:messages globalOnly="true" showDetail="true"/>
<h:message for="<optionalRelatedComponentId>" showDetail="true"/>

FacesContext facesContext = FacesContext.getCurrentInstance();

facesContext.addMessage(<optionalRelatedComponentReference>.getClientId(facesContext),
                   new FacesMessage(FacesMessage.SEVERITY_<WHATEVER>,
                       "<messageSummary>", "<messageDetail>"));

optionalRelatedComponentReference.getClientId(facesContext) can be replaced with null if you want a global message.

Mike's example of the above in use:

This is an example of how I've used it. Note that I can change to any kind of UIInput to represent an externalCustomerLastName, and my code remains unchanged. Probably not as useful for a last name field, but for input components that might change between inputCalendars or pulldowns or inputText fields, it's very helpful.

   // myBackingBean
   private transient UIInput externalCustomerLastNameInput;

   public UIInput getExternalCustomerLastNameInput()
   {
       return this.externalCustomerLastNameInput;
   }
   public void setExternalCustomerLastNameInput(UIInput externalCustomerLastNameInput)
   {
       this.externalCustomerLastNameInput = externalCustomerLastNameInput;
   }

   facesContext.addMessage(externalCustomerLastNameInput.getClientId(facesContext),
     new FacesMessage(FacesMessage.SEVERITY_ERROR,
         "Last name mismatch", "The last name doesn't match the record found."));

<h:outputLabel for="ExternalCustomerLastNameInput">
   <h:outputText value="Customer Last Name:"/>
</h:outputLabel>
<h:inputText id="ExternalCustomerLastNameInput"
   binding="#{myBackingBean.externalCustomerLastNameInput}"
   value="#{myDataModel.externalCustomerLastName}"/>
<h:message for="ExternalCustomerLastNameInput" styleClass="errors" showDetail="true"/>

Multilanguage Support

There is a helper class MessageUtil which allows to set language dependent messages:

FacesMessage message = org.apache.myfaces.util.MessageUtils.getMessage(FacesMessage.Severity severity, String bundleBaseName, String messageId, Object params[]);

The language is taken from the FacesContext.

Create_and_Display_Messages (last edited 2009-09-20 23:01:03 by localhost)