Custom property editor for Grails

by ishanf March 6, 2010

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!

Ishan Fernando

Groovy tip for a simpler test case

by Mauro Piccini March 4, 2010

When writing a groovy test case you almost want to be concise and expressive… next time you’ll see the test you must undestand it quickly.

Here’s a small tip to enhance test writing.

Having  :

def car = new Car()
def jack = new People()
def tom = new Cat();

Instead of wrinting somethings like :

car.addPeople ( people )
car.addCat ( tom )

it’s really simpler to write:

car += jack
car += tom

To achieve this it’s as easy as writing a plus method in you model object.

public Object plus(Object o) {
   if(o instanceof People) {
      this.addPeople((People)o);
   }
   if(o instanceof Cat) {
      this.addCat((Cat)o);
   }
   return this;
}

Just remember this method must return this.

Bleen site is online

by mauropiccini February 26, 2010

Come and visit www.bleen.it !