Grails:从gsp调用Domain方法

时间:2015-11-04 19:59:09

标签: grails gsp

我有以下域类:

package com.example

class Location {
   String state

    def getStatesList(){

    def states = ['AL','AK','AZ','AR','CA','CO','CT',
         'DC','DE','FL','GA','HI','ID','IL','IN','IA',
         'KS','KY','LA','ME','MD','MA','MI','MN','MS',
         'MO','MT','NE','NV','NH','NJ','NM','NY','NC',
         'ND','OH','OK','OR','PA','RI','SC','SD','TN',
         'TX','UT','VT','VA','WA','WV','WI','WY']
    return states
   }
} 

在我的gsp中,我试图在选择下拉列表中显示状态列表

<g:select name="location.state" class="form-control" from="${com.example.Location?.getStatesList()}" value="${itemInstance?.location?.state}" noSelection="['': '']" />

这样做,我收到“缺少方法异常”

如果我用list更改方法,我不再收到错误,但我不希望这样。

from="${com.example.Location?.list()}"    // works
from="${com.example.Location?.getStatesList()}"     // does not work

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

正如dmahaptro所说,你可以通过getStatesList()静态方法来解决这个问题。

class Location {
   String state

   static List<String> getStatesList() {
         ['AL','AK','AZ','AR','CA','CO','CT',
         'DC','DE','FL','GA','HI','ID','IL','IN','IA',
         'KS','KY','LA','ME','MD','MA','MI','MN','MS',
         'MO','MT','NE','NV','NH','NJ','NM','NY','NC',
         'ND','OH','OK','OR','PA','RI','SC','SD','TN',
         'TX','UT','VT','VA','WA','WV','WI','WY']
   }
} 

然后您就可以执行Location.statesListLocation.getStatesList()

替代

我认为更清洁的选择是使用最终的常量

class Location {
   String state

   static final List<String> STATES =
         ['AL','AK','AZ','AR','CA','CO','CT',
         'DC','DE','FL','GA','HI','ID','IL','IN','IA',
         'KS','KY','LA','ME','MD','MA','MI','MN','MS',
         'MO','MT','NE','NV','NH','NJ','NM','NY','NC',
         'ND','OH','OK','OR','PA','RI','SC','SD','TN',
         'TX','UT','VT','VA','WA','WV','WI','WY']
} 

然后您可以使用相同的方式访问列表:Location.STATES。不同之处在于全大写名称意味着一个不会改变的值(并且不需要访问数据库)。

答案 1 :(得分:0)

list()是域对象的元类的方法。为了做你想做的事情,你必须实例化一个Location实例(或添加到元类)。如果我是你,我会亲自使用Enum

答案 2 :(得分:0)

您必须使getStatesList()静态,因为您没有访问Location类的实例。