开发者

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

开发者 https://www.devze.com 2023-02-04 21:55 出处:网络
I\'m t开发者_Python百科rying to load 2nd combobox (g:select) values on the selection of 1st combobox (g:select) value in GSP.

I'm t开发者_Python百科rying 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?


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
}


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消