Localized Date Patterns
We have two property files, namely, application.properties and application_nl.properties to hold the localized messages. Using the two, we added a key to the files holding the localized date pattern:
date.pattern=MM/dd/yyyy
and
date.pattern=dd-MM-yyyy
Configuring a localized CustomDateEditor
To achieve this, first, we need a controller which is aware of localized date patterns defined above; simply, we make the controller an instance of MessageSourceAware so that the applications's localized message source is injected.
public class AbstractController implements MessageSourceAware { protected final Log logger = LogFactory.getLog(getClass()); @Resource @Qualifier("messageSource") protected MessageSource messages; @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, getCustomDateEditor()); } protected CustomDateEditor getCustomDateEditor() { String datePattern = messages.getMessage(Constants.DATE_PATTERN_KEY, new Object[] {}, getLocale()); logger.debug("Customer editor for date pattern: " + datePattern); return new CustomDateEditor(new SimpleDateFormat(datePattern), true); } protected Locale getLocale() { Locale locale = getDefaultLocale(); try { locale = LocaleContextHolder.getLocale(); } catch (Exception e) { } logger.debug("Current Locale: " + locale); return locale; } protected Locale getDefaultLocale() { return Locale.US; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = messageSource; } }
So, when the controller is initializing the MVC, it registers a custom date editor which is based on the current locale. The use of LocaleContextHolder is interesting as it holds (through ThreadLocal) the locale currently set for the FrameworkServlet in the current thread.
Customizing Dojo DateTextBox
Now, we can simply add a localized DateTextBox to a form:
<spring:message code="date.pattern" var="datePattern" /> <script type="text/javascript"> Spring.addDecoration(new Spring.ElementDecoration({ elementId : 'myFormInputId', widgetType : 'dijit.form.DateTextBox', widgetAttrs : { constraints: {min: new Date().setDate(0), max: new Date().setDate(31), datePattern: '${datePattern}'}, promptMessage : 'Prompt Message', invalidMessage : 'Validation Message', required : true, datePattern : '${datePattern}', } })); </script>
Note that, originally, the second datePattern is enough, however, as integration of Spring JS and Dojo is not complete, so you need the additional constraint on the datePattern.
No comments:
Post a Comment