Last active
August 29, 2015 14:04
-
-
Save deigote/bc7c12d8b8b0d442c400 to your computer and use it in GitHub Desktop.
Grails - Simple domain class property editor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DomainClassLookupPropertyEditor extends PropertyEditorSupport { | |
Class domainClass | |
String property | |
Boolean doAssert = true | |
String getAsText() { | |
value."$property" | |
} | |
void setAsText(String text) { | |
value = searchValueInNewSession(text) | |
assert doAssert && value, "no $domainClass found for $property '$text'" | |
} | |
private searchValueInNewSession(String text) { | |
domainClass.withNewSession { | |
domainClass."findBy${property.capitalize()}"(text) | |
} | |
} | |
static DomainClassLookupPropertyEditor newInstance(Class domainClass, String propToLookup) { | |
new DomainClassLookupPropertyEditor(domainClass: domainClass, property: propToLookup) | |
} | |
} | |
public class MyPropertyEditorRegistrar implements PropertyEditorRegistrar { | |
static Map<Class, String> domainClassByPropertyCustomBinders = [ | |
(User): 'id', (Role): 'authority' | |
] | |
public void registerCustomEditors(PropertyEditorRegistry propertyEditorRegistry) { | |
domainClassByPropertyCustomBinders.each { domainClass, prop -> | |
registerDomainClassLookupPropEditor(propertyEditorRegistry, domainClass, prop) | |
} | |
} | |
private registerDomainClassLookupPropEditor( | |
PropertyEditorRegistry propertyEditorRegistry, Class domainClass, String propToLookup | |
) { | |
propertyEditorRegistry.registerCustomEditor( | |
domainClass, DomainClassLookupPropertyEditor.newInstance(domainClass, propToLookup) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment