How to populate 2nd combobox(g:select) values on basis of 1st combobox(g:select)?

柔情痞子 提交于 2019-12-12 17:30:16

问题


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?


回答1:


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
}



回答2:


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:


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.




回答4:


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



来源:https://stackoverflow.com/questions/4691175/how-to-populate-2nd-comboboxgselect-values-on-basis-of-1st-comboboxgselect

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