Thursday, May 24, 2012

Grails data binding does not work on injected methods

Problem:

For Grails projects, you can use inject whole method definitions in the BootStrap.groovy file.

However, there is a drawback to method injection:

Grails will not be able to perform data binding on an injected method

 For example if we define the following method in BootStrap.groovy:

Bootstrap.groovy
domainClass.metaClass.getAttributeMap = {
   return new Map()
}

And then we our GSP file:

GSP file
<g:textField name="attributeMap[123].value" />

Grails will not be able to bind the value of the input element in the GSP defined by "attributeMap[123].value", to the domain object through the injected method getAttributeMap() .

Workaround:

Method injection has a lot of advantages and it would be a shame if you had to give it up simply because data binding could not work. Oneway around this problem, is to define a concrete method that will internally invoke the injected method.

For example,


     public Map<String, Attribute> getAttributeMapForDataBinding() { // <--- Define concrete method
         return this.getAttributeMap() // <--- Invoke the injected method
     }

Then in your GSP you can have:
<g:textField name="attributeMapForDataBinding[123].value" />

No comments:

Post a Comment