How to populate 2nd combobox(g:select) values on b

2019-07-20 02:56发布

I'm trying to load 2nd combobox (g:select) values on the selection of 1st combobox (g:select) value in GSP.

Domain classes:

class Person {    
   String name
   static hasMany = [telephones:Telephone]
}

class Telephone {    
   String tNumber
   Person person

   static belongsTo = [person:Person]

}

GSP:

<td>
<g:select id="person" name="selectedPersonId" from="${Person.list(sort:name, order:asc)}" value="name" optionValue="name" optionKey="id" noSelection="['0':'--Select--']" />
</td>
<td>
<g:select id="telephone" name="selectedTelephoneId" from ="${person.telephones}" value="tNumber" optionValue="tNumber" optionKey="id" noSelection="['0','--Select--']"/>
</td>

How can I do this properly?

4条回答
劳资没心,怎么记你
2楼-- · 2019-07-20 03:35

First off dont use tables for fomating use div's. Use a remoteFunction inside the first g:select passing in the current selection as params, the call would look something like

"${remoteFunction(action: 'methodName', update: 'DivToUpdate', params: '\'id=\'+this.value')}"

Now in your method on the controller you call render to a template containing your second g:select. This g:select can use either field values from the controller or info from the params. Hope this helps

查看更多
看我几分像从前
3楼-- · 2019-07-20 03:36

An update: Grails has since posted a wiki page on this: https://grails.org/AJAX-Driven+SELECTs+in+GSP

查看更多
叼着烟拽天下
4楼-- · 2019-07-20 03:37

Don't populate the items in the second combobox when the page is rendered, populate it when there is a value change in the 1st combobox.

<td>
<g:select id="person" name="selectedPersonId" from="${Person.list(sort:name, order:asc)}" value="name" optionValue="name" optionKey="id" noSelection="['0':'--Select--']" />
</td>
<td>
<g:select id="telephone" name="selectedTelephoneId" from ="${[]}" value="tNumber" optionValue="tNumber" optionKey="id" noSelection="['0','--Select--']"/>
</td>

Add onchange event on the first combobox (you can use jquery or plain Javascript) that will fill telephone data population based on chosen person. Here you can use an ajax call to the server to an action, something like:

def getTelephones = {
    def telephoneInstanceList = Telephone.findAllByPerson(Person.get(params.personId))
    def telephones = telephoneInstanceList.collect {[id: it.id, phone: it.tNumber]}
    render telephones as JSON
}
查看更多
forever°为你锁心
5楼-- · 2019-07-20 03:39

This question is similar to yours: Grails: Load data on one ComboBox depending on another . Basically, it's the same to yogiebiz's answer, but recommend some different options.

查看更多
登录 后发表回答