Search code examples
grailsgrails-ormgrails-2.0grails-domain-classgrails-controller

How to show parent domain field in select box in grails


I am using grails 2.1.0. I need to show a parent domain's field value through parent chain in select box in a gsp page. But I am getting error. So far I have tried as follows ::

my first domain which contains parents as named adtAuditPack >>>

    class AdtAuditorSchdlPack {
    ......
    static belongsTo = [adtAuditPack: AdtAuditPack,fiscalYear:FiscalYear]
    ......
}

my first parent of above domain named AdtAuditPack >>>

class AdtAuditPack {
    ......
    static belongsTo = [auditFirm:AuditFirm]
    ......
}

my second parent of adtAuditorSchdlPack named AuditFirm >>>

    class AuditFirm {
    ......
    String auditFirmName
    ......
}

Now I want to show auditFirm name as optionValue and AdtAuditorSchdlPack.id as optionKey. For that I have the following select as follows >>>

<g:select id="auditPack0" name="auditPack0" from="${AdtAuditorSchdlPack?.adtAuditPack?.auditFirm}" style="width: 200px;"
                          optionKey="id" optionValue="auditFirmName" noSelection="['': 'Select One']"
                          required="" class="form-control"/>

It's showing the following tool-tip >>

Cannot reference non-static symbol 'adtAuditPack' from static context

Can anyone please help me on this please ?!!! Isn't there any way to do this ???


Solution

  • You can construct the drop down list on Service/Controller and pass via modal to gsp page and use.

    The controller/service method will look like:

    def c = AdtAuditorSchdlPack .createCriteria()
        def results = c.list() {
            and{ 
               // your criteria logic
            }
            order('id', 'asc')
        }
    

    Construct the list based on your logic:

    List auditFirmList= new ArrayList()
            results.each { AdtAuditorSchdlPack adtAuditPack->
                dataReturns.add([id: adtAuditPack?.auditFirm?.id, name: "${adtAuditPack?.auditFirm?.auditFirmName}"])
            }
    

    Now you can pass this list via model and use on dropdown as follows.

    <g:select class=" form-control" id="auditPack0" name='auditPack0'
    noSelection="${['': 'Select one...']}" from="${auditFirmList}" optionKey="id" optionValue="name"></g:select>
    

    The optionKey and optionValue may red mark in gsp view page, but will work on run.