[英]How to customise select tag in Grails
I have this hasMany
relation, between a client and a product. 我在客户和产品之间有hasMany
关系。 When I generate the views and controllers, in the create view of the product I can chose a client. 在生成视图和控制器时,可以在产品的创建视图中选择一个客户端。 By default Grails displays a select containing only the id of the clients. 默认情况下,Grails显示仅包含客户端ID的选择。 How can I change that? 我该如何改变? For example I want to show only the name of the client instead of the id. 例如,我只想显示客户端名称而不是ID。
I'm using Grails 3.3, Here is the domain code: 我正在使用Grails 3.3,这是域代码:
client.groovy : client.groovy :
class client {
String FirstName
String LastName
static hasMany = [products: Product]
}
product.groovy : product.groovy :
class product {
String Name
int Price
Client c
static belongsTo = Client
}
I believe that the default generated select list will use the toString()
method of the object as the display value for each <option>
and the id for the key value. 我相信默认生成的选择列表将使用对象的toString()
方法作为每个<option>
的显示值和键值的id。 The easiest way to change the default display would be to override toString()
in your product class: 更改默认显示的最简单方法是覆盖产品类中的toString()
:
@Override
String toString() {
name
}
You can customize how the select
looks like by specifying optionKey
and optionValue
attributes: 您可以通过指定optionKey
和optionValue
属性来自定义select
外观:
<g:select from="${Client.list()}" name="client" optionKey="FirstName" optionValue="id" />
See the ref doc for details. 有关详细信息,请参见参考文档 。
If you need to do something fancier, like show first AND last name, then you could pre-process the list a bit: 如果您需要做一些更奇特的事情,例如显示名字和姓氏,那么可以对列表进行一些预处理:
<g:select from="${Client.list().collect{ [ id:it.id, name:it.firstName + ' ' + it.lastName ] }}" name="client" optionKey="name" optionValue="id" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.