Grails选择不设置默认值
我有一个应用程序,用户可以在其中填写表单,并保存一些预设值,以便快速重新填充 域Grails选择不设置默认值,grails,gsp,Grails,Gsp,我有一个应用程序,用户可以在其中填写表单,并保存一些预设值,以便快速重新填充 域 class Person { String name TeenageMutantNinjaTurtle favorite static constraints = { name blank:false, unique:true favorite nullable:true } @Override public String toStr
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>
你好${person}
收藏夹永远不会成为最初选择的值,即使我可以显示它的计算结果等于true,如中所述。有什么好处 有几件事
Grails邮件列表上的Tomas Lin回答: 如果你坚持使用ID,你的生活会更轻松 将optionKey设置为与标记中对象的id相等 value='${favorite.id}'现在应该可以工作了
为什么将“personName”字段设置为${person}的值?该字段是否正确填充?视图可能会抛出错误并忽略填充数据绑定的select字段。该字段填充正确,这不是问题。我添加了value=“${favorite?.id}”,但即使如此,当我返回页面时(导航到另一个控制器后),它也没有预先选择favorite值,虽然我可以验证它是否已成功存储在数据库中,并已传递给视图fine。这是一个愚蠢的问题,但TeenageMutantInjectEntertleInstanceList是否包含用于person.favorite的相同对象?另外,您是否已在域中为favorite重写了equals()方法?您还可以尝试使用optionKey和optionValue属性来查看这是否有区别。否。字符串值恢复正常。这完全没有道理。将value属性设置为TeenageMutantInjactletInstanceList[2]有效。将其设置为等于TeenageMutantInjactletInstanceList.each{it==favorite}则不会,不过我可以验证favorite是否正确进入视图。(>\u字符串值是什么意思?它们是您创建的对象还是仅仅是字符串?您可以编辑您的问题并显示您的TeenageMutantInjactle域吗?