Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use embedded GORM classes in Grails?

Following the GORM docs I tried to use the following domain class with Grails 2.2.1:

package grailscompositiontest

class ScafPerson {
    String name
    ScafAddress homeAddress
    ScafAddress workAddress

    static constraints = {
        name(nullable: false, blank: false)
    }

    static embedded = ['homeAddress', 'workAddress']
}

class ScafAddress {
    String number
    String code
}

The controller just uses scaffolding:

package grailscompositiontest

class ScafPersonController {
    static scaffold = true
}

Unfortunately this does not work, it triggers a server error as soon as I browse to the "create" view:

URI:     /GrailsCompositionTest/scafPerson/create
Class:   java.lang.NullPointerException
Message: Cannot get property 'id' on null object

Any idea what I am doing wrong?

like image 503
blerontin Avatar asked Jan 13 '23 17:01

blerontin


1 Answers

I ran into this same problem the other day. I believe there may be a bug in the templates used by the scaffolding functionality. You can either update the template or if you don't want to muck with the templates, run generate-all as Benoit mentioned then fix the generated view.

To update template:

  1. grails> install-templates
  2. open src/templates/scaffolding/renderEditor.template
  3. find the following line:
    sb << ' value="${' << domainInstance << '.' << property.name << '}"'

and change to

    sb << ' value="${' << domainInstance << '?.' << property.name << '}"'

To fix the generated view:

  1. grails> generate-all grailscompositiontest.ScafPerson
  2. open views/scafPerson/_form.gsp
  3. look for
    <g:field name="id" type="number" value="${scafAddressInstance.id}" required=""/>
    <g:field name="version" type="number" value="${scafAddressInstance.id}" required=""/>

and change to

    <g:field name="id" type="number" value="${scafAddressInstance?.id}" required=""/>
    <g:field name="version" type="number" value="${scafAddressInstance?.id}" required=""/>

Note you'll do it twice since you have homeAddress/workAddress

like image 190
user553180 Avatar answered Feb 02 '23 01:02

user553180