Howes
Howes

Reputation: 819

Grails find Domain and then Save it

What I want to do is find a domain and then either create a new one or save the pre-existing one. Here is the code that I am currently working with (in this project, skeleton is the package name):

    def save() {
        Class lob = grailsApplication.getDomainClass('skeleton.'+params.lob.name)
        def instance = lob.get(params.lob.id)
        if (instance){
            params.data.each { name, value ->
                if (instance.metaClass.hasProperty(name)){
                    instance[name] = value
                }
            }
        }else{
            instance = new lob()
            params.data.each { name, value ->
                if (instance.metaClass.hasProperty(name)){
                    instance[name] = value
                }
            }
        }
    }

This doesn't seem to be working. Can anyone help me with the solution?

Upvotes: 1

Views: 419

Answers (1)

ataylor
ataylor

Reputation: 66109

The object returned by getDomainClass is an instance of GrailsDomainClass. To get the actual domain class on which you can call get, first call getClazz on it. For example:

Class lob = grailsApplication.getDomainClass('skeleton.'+params.lob.name).clazz

In addition, you'll have to call newInstance on the class object rather than using the new keyword to create a new instance.

Upvotes: 5

Related Questions