Thursday, February 4, 2010

Grails and Date Inputs

I've been rather frustrated with the datePicker input tag for grails lately. For anyone who writes software for people who do data entry 8 hours a day, 5 days a week, you know that picking a date from pull-down menus, or via a calendar navigation such as the calendar plugin for grails is a huge waste of time and very slow.


To resolve this I've taken the approach of using textInput tags for the dates

<g:textfield name="birthDate" size="12" maxlength="10" value="${personInstance?.birthDate?.format('MM/dd/yyyy')}" class="datePicker" />


And using jQuery UI to add a calendar control to the inputs so that if the user wanted to, they can use a datePicker

// Turn all textFields of class 'datePicker' into jQuery.UI.calendar controls
jQuery(document).ready(function(){
jQuery('.datePicker').datepicker({
showOn: 'button',
buttonImage: '/myapp/images/calendar.gif',
buttonImageOnly: true });
});

Then, because the default date format for text inputs in grails is yyyy-mm-dd hh:mm:ss, which is not the most common format entered for dates in my demographic (US), I added a customPropertyEditorRegistrar in grails-app/conf/spring/resources.groovy

beans = {
customPropertyEditorRegistrar(util.CustomPropertyEditorRegistrar)
}

and then in src/groovy/util/CustomPropertyEditorRegistrar.groovy

package util

import java.util.Date
import java.text.SimpleDateFormat
import org.springframework.beans.propertyeditors.CustomDateEditor
import org.springframework.beans.PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistry

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}
}



And then I'm happier, and the data entry staff that need to use my applications are happy.

No comments: