【问题标题】:Formatting POJO inside Grails/GSP select element在 Grails/GSP 选择元素中格式化 POJO
【发布时间】:2014-10-23 16:46:16
【问题描述】:

我有以下 POJO/POGO:

class Person {
    String firstName
    String lastName
    int age
    // ... lots of other fields
}

还有一个 Grails 2.3.6 控制器:

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,
            ]
        )
    }
}

然后在普惠制中:

<div id="peopleSelector">
    <g:select name="people" from="${people}" />
</div>

当我运行我的应用程序时,我得到了 &lt;select&gt; 元素,其 com.me.myapp.domain.Person@398r4d99 外观值为 &lt;option&gt;s。这显然是 Grails 没有将我的 Person 实例反序列化为漂亮的打印形式。

我希望人们的名字和姓氏显示为选择选项。因此,如果people 列表中的Person 实例之一是:

Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")

然后我希望“Smeeb McGuillocuty”作为最终 HTML 中的选择选项。 我怎样才能做到这一点?

【问题讨论】:

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


    【解决方案1】:

    将以下方法添加到您的 Person 类中:

    @Override public String toString() {
        "$firstName $lastName"
    }
    

    而且,与实际问题有些无关,您可能必须在您的选项行中添加一个标识符以唯一标识此人。假设Person 类有一个id 属性:

    <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: “..默认行为是在from 属性中的每个元素上调用toString()..”

    【讨论】:

      【解决方案2】:

      如果您不能/不会“牺牲”toString() 以在 HTML 中呈现,您还可以告诉 g:select 如何呈现选项。通过在optionValue 中提供属性的名称(例如optionValue="fullName" 然后提供String getFullName() 方法(注意瞬态,如果您传递了一个GORM 对象))或直接在GSP 中提供它:

      <g:select name="person" optionKey="theId" optionValue='${{"$it.lastName, $it.firstName"}}' from="${people}" />
      

      【讨论】:

      • 这是一种奇怪的态度,但很常见 - 为什么要浪费 toString 格式的 html 下拉菜单,而您可以做更多的工作来配置下拉菜单本身。这不是我很虔诚的事情,但它似乎很倒退。
      • @BurtBeckwith 可能是因为你曾经不得不从一些断言或调试打印中做出正面或反面?或者它可能只是我;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多