2011-10-10 190 views
0

我有一個應用程序,用戶可以填寫一張表格,並保存一些預設置爲快速重新人口Grails的選擇不設置默認值

class Person { 
    String name 
    TeenageMutantNinjaTurtle favorite 
    static constraints = { 
     name blank:false, unique:true 
     favorite nullable:true 
    } 

    @Override 
    public String toString() { name } 
} 

    package tmnt 

class TeenageMutantNinjaTurtle { 
    String name 
    String colorHeadband 
    static constraints = { 
     name inList:["Leonardo", "Donatello", "Raphael", "Michelangelo"] 
     colorHeadband inList:["blue", "purple", "red", "orange" ] 
    } 

    @Override 
    public String toString() { "${name}" } 
} 

控制器

class PersonController { 


def choose = { 
    if(session.user) { 
     def person = Person.findByName(session.user.username) 
     [ 
     teenageMutantNinjaTurtleInstanceList: TeenageMutantNinjaTurtle.list(), 
     person : person, 
     favorite : person.favorite 
     ] 
    } 
} 

def pickFavoriteTurtle = { TurtleCommandObject tut -> 
    def turtle = tut.turtleName 
    def choice = TeenageMutantNinjaTurtle.findByName(turtle) 
    String message = "Turtle not chosen " 
    if(choice){ 
     def person = Person.findByName(tut.personName) 
     person.favorite = choice 
     person.save() 
     message = "Made ${person}'s favorite turtle ${choice}" 
    } 
    else { 
     message += "could not find ${choice}" 
    } 
    render message 
} 

查看

 <div> 
      <h1>Hello ${person} </h1> 
      <g:form action="pickFavoriteTurtle"> 
       <g:hiddenField name="personName" value="${person}" /> 
       <g:select name="turtleName" from="${teenageMutantNinjaTurtleInstanceList}" value="${favorite}" /> 
       <g:submitToRemote name="pickFavoriteTurtle" 
            url="[action:'pickFavoriteTurtle']" 
            value="Save your favorite turtle" /> 
      </g:form> 
     </div> 

最喜歡的是從來沒有最初選擇的價值,即使我可以證明,它的計算結果等於TRUE作爲User guide描述。是什麼賦予了?

+0

爲什麼是「PERSONNAME」字段設置爲$ {}人的價值?此字段是否正確填充?該視圖可能正在吐出錯誤並忽略填充選擇字段。用於數據綁定的 – therin

+0

。該字段確實填寫正確,並不是問題。 –

回答

1

由Tomas林Grails的郵件列表上回答:

你的生活會更容易些,如果你只是用IDS堅持。

設置的option鍵等於你的對象的ID在標籤。

值= '$ {} favorite.id' 現在應該工作。

0

幾件事情。

  1. 如果喜歡的是一個id一個對象,你需要 值= 「$ {} favorite.id」
  2. 你可以只使用值= 「$ {} person.favorite.id」
+0

我增加了值=「$ {favorite?.id}」,但即使如此,當我回到頁面(在導航到另一個控制器之後)時,它沒有預先選擇的最喜歡的值,儘管我可以驗證它已成功存儲在數據庫中,並傳遞給視圖。 –

+0

愚蠢的問題,但少女MutantNinjaTurtleInstanceList包含用於person.favorite相同的對象?另外,你有沒有重寫你的域中的equals()方法以獲得最喜歡的? – Gregg

+0

您也可以嘗試使用option鍵和optionValue屬性,看看是否有差別。 – Gregg