简体   繁体   English

Grails选择不设置默认值

[英]Grails select not setting default value

I've got an app where users can fill out a form, and save some pre-sets for quick re-population 我有一个应用程序,用户可以填写表格,并保存一些预设,以便快速重新填充

Domain

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}" }
}

Controller 调节器

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
 }

View 视图

        <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>

The favorite is never made the initially selected value, even though I can show that it evaluates equals to true as described in the User guide . 最喜欢的东西永远不会成为最初选择的值,即使我可以显示它评估等于true,如用户指南中所述 What gives? 是什么赋予了?

Answered by Tomas Lin on the Grails mailing list: Tomas Lin在Grails邮件列表上的回答:

Your life would be easier if you just stick with ids. 如果你坚持使用id,你的生活会更容易。

Set an optionKey to equal the id of your object in the tag. 将optionKey设置为等于标记中对象的id。

value = '${ favorite.id }' should now work. value ='$ {favorite.id}'现在应该可以使用了。

A couple of things. 有几件事。

  1. If favorite is an object with an id, you'll need value="${favorite.id}" 如果favorite是具有id的对象,则需要value =“$ {favorite.id}”
  2. You could just use value="${person.favorite.id}" 你可以使用value =“$ {person.favorite.id}”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM