dvisco
dvisco

Reputation: 491

Grails binddata in service

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.

Upvotes: 5

Views: 3958

Answers (3)

Jay Edwards
Jay Edwards

Reputation: 1025

In 2.5, I found that emulating the behaviour of the Controller API in a helper service worked:

def bindData(def domainClass, def bindingSource, String filter) {
    return bindData(domainClass, bindingSource, Collections.EMPTY_MAP, filter)
}
def bindData(def domainClass, def bindingSource, Map includeExclude, String filter) {
    DataBindingUtils
        .bindObjectToInstance(
            domainClass, 
            bindingSource,
            convertToListIfString(includeExclude.get('include')),
            convertToListIfString(includeExclude.get('exclude')), 
            filter);
    return domainClass;
}

convertToListIfString is as per the controller method:

@SuppressWarnings("unchecked")
private List convertToListIfString(Object o) {
    if (o instanceof CharSequence) {
        List list = new ArrayList();
        list.add(o instanceof String ? o : o.toString());
        o = list;
    }
    return (List) o;
}

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

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
    }
}

Upvotes: 5

dmahapatro
dmahapatro

Reputation: 50245

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)

Upvotes: 20

Related Questions