Grails form creation for many-to-one belongsTo

2019-09-05 16:36发布

问题:

I am a beginner in grails and I have a basic question. I want to display a list of instances of a parent class in the child class form creation.

My Domain class are as follows. The Parent class is the Company.

class Company {
    String name
    static constraints = {
        name(blank:false)
    }
    String toString(){name}
}

My Child Class is the Location of the company.

class Location {
    String name
    String address
    static belongsTo= {companyLocation:Company}

    static constraints = {
    name(blank: false)
    address blank:false 
}

    String toString(){"company:"+companyLocation+"Location:"+name}
}

Now in the _form template' of location view I have the code for thecompanyLocation dropdown`

<div class="fieldcontain ${hasErrors(bean: locationInstance, field: 'companyLocation', 'error')} required">
<label for="companyLocation">
<g:message code="location.companyLocation.label" default="companyLocation" />
    <span class="required-indicator">*</span>
    <g:select id="companyLocation" name="companyLocation.id" from="${first_project.Company.list()}" optionKey="id" required="" value="${locationInstance?.companyLocation?.id}" class="many-to-one"/>
</label>
</div>

When I go to the the create page I get the error:

Error 500: Internal Server Error
URI /first_project/location/create
Class  groovy.lang.MissingPropertyException
Message No such property: companyLocation for class: first_project.Location

Why am I getting this error when I have a static variable companyLocation defined in the Location Domain class? Could some please let me know where I have gone wrong?

Thanks in advance.

回答1:

This looks like a syntax issue,

static belongsTo= {companyLocation:Company}

should really be

static belongsTo= [companyLocation:Company]


回答2:

There is one more OO method of doing this, instead of using has many and belongs to...

create another CompanyLocation Domain class.

Class CompanyLocation {
   Company company
   Location location

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

public String toString() {
    return "${company} ${location}"
}

}