【问题标题】:Can we have more than one field in g:select optionValue?g:select optionValue 中可以有多个字段吗?
【发布时间】:2010-11-19 05:59:45
【问题描述】:

有没有办法在 optionValue 中显示多个字段名称?

<g:select name="id" from="${Books.list()}" optionKey="id"
          value="" optionValue="name"
          noSelection="${['null':'Select Publisher...']}"/>

经验:

<g:select name="id" from="${Books.list()}" optionKey="id"
          value="" optionValue="name and author"
          noSelection="${['null':'Select Publisher...']}"/>

【问题讨论】:

    标签: grails


    【解决方案1】:

    如果你不想修改你的域类,你可以为你的选项值传递一个闭包:

    <g:select name="id" from="${Books.list()}" optionKey="id"
              value="" optionValue="${{it.name +' '+it.author}}"
              noSelection="${['null':'Select Publisher...']}"/>
    

    【讨论】:

    • 这很好用,但我的 IDE (IntelliJ) 将此标记为不明确的代码块错误。有没有人解决这个问题?
    • 我总是忘记我该怎么做!谢谢! =D
    【解决方案2】:

    您可以在域类中引入一个瞬态属性,您可以在 g:select 的 optionValue 中使用它:

    class Book {
        String name
        String author
    
        static transients = [ 'nameAndAuthor' ]
    
        public String getNameAndAuthor() {
            return "$name, $author"
        }
    }
    

    你的 g:select 看起来像:

    <g:select name="id" from="${Books.list()}" optionKey="id" value="" 
        optionValue="nameAndAuthor" 
        noSelection="${['null':'Select Publisher...']}" />
    

    【讨论】:

      【解决方案3】:

      或者在你的 Book 类中添加一个 toString 方法

      public String toString() {
      "${name} ${author}"
      }
      

      然后省略 optionValue

      <g:select name="id" from="${Books.list()}" optionKey="id"
                value="" noSelection="${['null':'Select Publisher...']}"/>
      

      至少当您在调试器中查看域时,它具有人类可识别的价值。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 2014-08-18
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        相关资源
        最近更新 更多