Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails binddata in service

Tags:

grails

Is there a way to utilize bindData in a service other than using the deprecated BindDynamicMethod? I can't just use

TestObject testObject = new TestObject()
TestObject testObject.properties = params

or

TestObject testObject = new TestObject(params)

because I have a custom bind method utilizing the @BindUsing annotation within my TestObject class.

like image 819
dvisco Avatar asked Aug 31 '15 18:08

dvisco


2 Answers

If you are using Grails 3.* then the service class can implement DataBinder trait and implement bindData() as shown below example:

import grails.web.databinding.DataBinder

class SampleService implements DataBinder {

    def serviceMethod(params) {
        Test test = new Test()
        bindData(test, params)

        test
    }

    class Test {
        String name
        Integer age
    }
}

This is how I quickly tried that in grails console:

grailsApplication.mainContext.getBean('sampleService').serviceMethod(name: 'abc', age: 10)
like image 167
dmahapatro Avatar answered Sep 27 '22 23:09

dmahapatro


In Grails 2.4.4 you can do something like this:

// grails-app/services/demo/HelperService.groovy
package demo

import org.grails.databinding.SimpleMapDataBindingSource

class HelperService {

    def grailsWebDataBinder

    TestObject getNewTestObject(Map args) {
        def obj = new TestObject()
        grailsWebDataBinder.bind obj, args as SimpleMapDataBindingSource
        obj
    }
}
like image 29
Jeff Scott Brown Avatar answered Sep 27 '22 22:09

Jeff Scott Brown