Tuesday, June 10, 2014

Grails - dataBind in Service Layer

Here is quick tip how you can use dataBind grails command outside of grails controller.
import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

class DataBinder {

    private static BindDynamicMethod bindDynamicMethod = new BindDynamicMethod()

    /**
     * make the controller bindData method statically available, e.g. for service layer use
     * implemented as closure to allow static import emulating controller layer bindData usage 1:1
     */
    static Closure bindData = { Object[] args ->
        bindDynamicMethod.invoke(args ? args[0] : null, BindDynamicMethod.METHOD_SIGNATURE, args)
    }
}

//usage
class TestBind {
    public void intermediateNotification(Map params) {
        Test test = new Test()
        DataBinder.bindData(test, params)
        test.save()    
    }
}

No comments:

Post a Comment