Search code examples
hibernatevalidationgrailsgroovygrails-orm

Binding only some properties onto a grails domain object?


I have a map like this:

['var1':'property1', 'var2':'3']

and a class like this:

class MyClass{
   MyEnum var1
   int var2
   String var3
}
enum MyEnum{
   PROP1( "property1" )
   PROP2( "property2" );

   private final String variable;

   public MyEnum( String variable ){ this.variable = variable }
   public String getVariable(){ return variable }
}

I'd like to just try to bind var1 and var2 onto some existing object to get the validations, but how do I do this?


Solution

  • You can use bindData inside a controller. This method has optional arguments that allow you to explicitly state which properties should be included or excluded by the binding, e.g.

    def map = ['var1':'property1', 'var2':'3']
    def target = new MyClass()
    
    // using inclusive map
    bindData(target, map, [include:['var1', 'var2']])
    
    // using exclusive map
    bindData(target, this.params, [exclude:['var2']])
    

    If you want to do this kind of binding outside a controller use one of the methods of org.codehaus.groovy.grails.web.binding.DataBindingUtils, e.g.

    /**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclud
     * @param filter The prefix to filter by
     *
     * @return A BindingResult or null if it wasn't successful
     */
    public static BindingResult bindObjectToInstance(Object object, Object source, List include, List exclude, String filter) 
    

    Here's an example of using this method to perform the same binding as the "inclusive map" invocation of bindData above

    def map = ['var1':'property1', 'var2':'3']
    def target = new MyClass()
    DataBindingUtils.bindObjectToInstance(target, map, ['var1', 'var2'], [], null)