gpt4 book ai didi

grails - 在 Grails/GSP 选择元素中格式化 POJO

转载 作者:行者123 更新时间:2023-12-02 14:23:39 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com