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

标签 grails model-view-controller groovy grails-controller

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

相关文章:

groovy - 以编程方式验证对 Google Cloud Functions 的调用

grails - 使用Cloud Foundry在云上部署时出错

grails - 找出哪个Quartz触发器触发了作业

grails - 从Grails 1.3.7迁移到2.0.0时出现编码问题

twitter-bootstrap - Bootstrap 中的Grails全局函数

Java MVC - 如何更改 View - JPanel

c# - 从流中更改图像大小

Javascript - Spine MVC - 类

csv - 带有 CSV 的 Grails(无数据库)

grails - 如何重新启动Grails Web应用程序