Custom property editor for Grails

Problem:

Create a custom property editor between Model and View to show it as we need. (example: we wanted to change how shows the java Date.class in a view, from default format 'yyyy-MM-dd HH:mm:ss.S' to 'dd-MM-yyyy').

Solution:

There are 2 solutions which I can see now. The first one is, when every time we show a Date object, format it using a java DateFormat implement and show it. But the pretty solution is the second one, create a custom property editor to show it. So you don’t have to modify every date field that views show. To do that you have to create your property editor by implementing PropertyEditor and property editor registrar by implementing PropertyEditorRegistrar to register your property editor.
For example we created our 'CustomPropertyEditorRegistrar' as property editor register and we used spring’s CustomDateEditor as a property editor:

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("dd-MM-yyyy"), true));
}
}

And finally you must add your custom property editor registrar to grails resources ('grails-app/config/spring/resources.groovy'):

beans = {
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
}

That’s all!

Notes

  1. carlin-gardner reblogged this from ishanf
  2. ishanf posted this