views:

258

answers:

2

I know Grails has a map based constructor for domain objects, to which you can pass the params of a URL to and it will apply the appropriate field settings to the object using introspection, like this...

myDomainInstance = new MyObject(params)

I was wondering whether there was an equivalent method of taking the params and applying them to an existing object and updating values in the same way that the map constructor must work, something like...

myDomainInstance = params

or

myDomainInstance = fromParams(params)

Am I just wishful thinking or does such a thing exist? I can code it up myself but would rather not if it exists already.

Thanks

+3  A: 

Adapted from the grails user guide:

obj = MyObject.get(1)
obj.properties = params

Check out the documentation for 'params' under the controller section for more information.

Gareth Davis
I just came here to post exactly that! Thanks +1. I have a problem with collections that are passed as JSON arrays, however. I think I'll have to parse those separately.
Simon
+1  A: 

It really depends on what you are trying to do but an equivalent approach use databinding.

def sc = new SaveCommand()
bindData(sc, params)

This give you the benefit of using custom binding. If let say your date format is not the default one you can redefine it through a bean like this:

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
  public void registerCustomEditors(PropertyEditorRegistry registry) {
      registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
  }
}
Julien Gagnet
perfectly valid approach, very similar to the approach required for the extended data binding http://www.grails.org/Extended+Data+Binding+Plugin
Gareth Davis