Grails form creation for many-to-one belongsTo

若如初见. 提交于 2020-01-07 06:38:30

问题


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}"
}

}


来源:https://stackoverflow.com/questions/20171921/grails-form-creation-for-many-to-one-belongsto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!