我有以下 POJO/POGO:
class Person {
String firstName
String lastName
int age
// ... lots of other fields
}
还有一个 Grails 2.3.6 Controller :
class PeopleController {
List<Person> people = new ArrayList<Person>()
def populatePeople() {
// Add lots of people to the 'people' list.
}
def doSomething() {
populatePeople()
render(
view: "people",
model:[
people: people,
]
)
}
}
然后在 GSP 中:
<div id="peopleSelector">
<g:select name="people" from="${people}" />
</div>
当我运行我的应用程序时,我得到
<select>
带有 com.me.myapp.domain.Person@398r4d99
的元素- 外观值为 <option>
s。这显然是 Grails 没有反序列化我的 Person
实例成 pretty-print 形式。我希望人们的名字和姓氏显示为选择选项。因此,如果
Person
之一people
中的实例 list 是:Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")
然后我希望“Smeeb McGuillocuty”作为最终 HTML 中的一个选择选项。 我怎样才能做到这一点?
最佳答案
将以下方法添加到您的 Person
类(class):
@Override public String toString() {
"$firstName $lastName"
}
而且,与实际问题有些无关,您可能必须在选项行中添加一个标识符以唯一标识此人。假设
Person
类有 id
属性(property):<g:select name="people" from="${people}" optionKey="id" />
以便您获得以下 HTML:
<select name="people" id="people">
<option value="123">Smeeb McGuillocuty</option>
:
官方文档的有用链接:http://grails.org/doc/latest/ref/Tags/select.html :
"..默认行为是在
toString()
属性中的每个元素上调用 from
.."
关于grails - 在 Grails/GSP 选择元素中格式化 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26533157/