duminică, 15 martie 2015

[OmniFaces utilities (2.0)] Get the application message bundle


[OmniFaces utilities] The getMessageBundle() method returns the application message bundle as identified by <message-bundle> in faces-config.xml. The instance is already localized via Faces#getLocale(). If there is no <message-bundle>, then this method just returns null.

Method:
See also: Faces#getContext()

Note Do not confuse the <resource-bundle> tag with <message-bundle>. The former is used for registering custom localized static text, while the latter is used for registering custom error/info/warn messages, which are displayed by <h:message> and <h:messages>.It can be used to override the JSF default warning/error messages.

Usage:

This method is a shortcut for Application#getMessageBundle(). For example, you can use it as quick solution for programmatically choose the proper custom warning/error message depending on current locale. Suppose that you have the following message bundle configuration in faces-config.xml (override JSF default warning/error messages which is been used by the JSF validation/conversion and provide three supported locales):

<application>            
 <locale-config>
  <default-locale>fr</default-locale>
  <supported-locale>fr</supported-locale>
  <supported-locale>en</supported-locale>          
  <supported-locale>de</supported-locale>     
 </locale-config>                           
 <message-bundle>com.example.i18n.Messages</message-bundle>    
</application>

Write the Messages_xx.properties (or, you can use Messages_xx_XX.properties) in com.example.i18n package with the following entry which overrides the default required="true" message:

PlayerMessages_en.properties
javax.faces.component.UIInput.REQUIRED = {0}: Please enter value

PlayerMessages_fr.properties
javax.faces.component.UIInput.REQUIRED = {0}: Se il vous plaît entrer une valeur

PlayerMessages_de.properties
javax.faces.component.UIInput.REQUIRED = {0}: Bitte geben Sie einen Wert

Further, we set the locale as fr via <f:view>, or programmatically, via Faces#setLocale().

<f:view locale="fr">...<f:view/>     

or,

import org.omnifaces.util.Faces;
...
Locale frlocale = new Locale("fr");
Faces.setLocale(frlocale);

Now, when a input is required, but no value was provided, JSF will render the below message:

xxx: Se il vous plaît entrer une valeur

Whenever you need to programmatically access this message bundle, you can simply do this:

import org.omnifaces.util.Faces;
...
ResourceBundle rb = Faces.getMessageBundle();
// do something with rb.getString("javax.faces.component.UIInput.REQUIRED"); which returns {0}: Se il vous plaît entrer une valeur

Niciun comentariu:

Trimiteți un comentariu