问题
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