Tuesday, February 2, 2010

Custom Grails Property Editor

Grails uses Spring's mechanism for binding the html (String) representation of an object with the object representation on the server side. I wanted all my currency fields (which are BigDecimal) to be formatted with dollar signs so I declared a CustomPropertyEditorRegistrar to modify how the BigDecimal conversion.

1. Added this to my resources.groovy
configurer(org.springframework.beans.factory.config.CustomEditorConfigurer) {
propertyEditorRegistrars = [ref("registrar")]
}

registrar(com.sungard.stallion.format.CustomPropertyEditorRegistrar)
2. Create a class that implements PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(java.math.BigDecimal.class, new CurrencyPropertyEditor());
}
}


3. It seems like this could have been done in a single step... but also define the class that the Registrar adds which implements PropertyEditor. Spring provides a helper class, PropertyEditorSupport, that the custom editor can extend:

import java.math.BigDecimal;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;

public class CurrencyPropertyEditor extends PropertyEditorSupport implements PropertyEditor {

public void setAsText(String text) {
setValue(... parsing goes here...);
}

public String getAsText() {
Object value = getValue();
if (value instanceof BigDecimal) {
return ... formatting goes here...;
}
return ("" + value);
}

}

- Ben Hidalgo

No comments:

Post a Comment

Post a Comment