如何在第一个组合框(g:select)的基础上填充第二个组合框(g:select)值?

时间:2011-01-14 12:44:05

标签: grails grails-domain-class grails-controller

我正在尝试在GSP中选择第一个组合框(g:select)值时加载第二个组合框(g:select)。

域类:

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>

我该如何正确地做到这一点?

4 个答案:

答案 0 :(得分:3)

在渲染页面时不要填充第二个组合框中的项目,在第一个组合框中有值更改时填充它。

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

在第一个组合框上添加onchange事件(您可以使用jquery或普通Javascript),这将根据所选人填充电话数据。在这里,您可以使用对服务器的ajax调用来执行操作,例如:

def getTelephones = {
    def telephoneInstanceList = Telephone.findAllByPerson(Person.get(params.personId))
    def telephones = telephoneInstanceList.collect {[id: it.id, phone: it.tNumber]}
    render telephones as JSON
}

答案 1 :(得分:2)

首先不要使用表格来使用div。 在第一个g中使用remoteFunction:选择将当前选择作为params传递,调用看起来像

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

现在,在控制器上的方法中,您将渲染渲染到包含第二个g:select的模板。这个g:select可以使用来自控制器的字段值或来自参数的信息。希望这有帮助

答案 2 :(得分:0)

此问题与您的问题类似:Grails: Load data on one ComboBox depending on another。基本上,它与yogiebiz的答案相同,但推荐一些不同的选择。

答案 3 :(得分:0)

更新:Grails此后发布了一个维基页面: https://grails.org/AJAX-Driven+SELECTs+in+GSP

相关问题