我有一个应用程序,用户可以填写表格,并保存一些预设,以便快速重新填充
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
}
<<p> 视图/strong> <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。到底发生了什么事?
Tomas Lin在Grails邮件列表上的回答:
如果你坚持使用id,你的生活会更容易。
设置optionKey等于标签中对象的id。
value = '${favorite. 'Id}'现在可以工作了。
几件事
- 如果favorite是一个有id的对象,你需要value = " $ {favorite.id} "
- 你可以直接使用value="${person.favorite.id}"