2

Lift 框架中有一个简单的表单和一个带有处理表单的渲染方法的类:

 def render(xhtml:NodeSeq) = {
        var name = ""
        var role = ""
        var human = ""
        def register = {
            val person = new Person
            person.name = name
            person.role = role
            person.human = if (human == "yes") "true" else "false"
            model.create(person)
            S.redirectTo("/index")
        }
        bind("user",
        xhtml,
        ("name" -> SHtml.text(name, name = _)),
        ("role" -> SHtml.text(role, role = _)),
        ("human" -> SHtml.text(human,human = _)),
        ("submit" -> SHtml.submit("Register",register)))
    }

当我运行这个例子时,例如。我访问绑定到相应表单的 url,我收到以下错误:

Message: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
...
...
...
    epsilon.sjbs.CrudModel$class.create(Sjbs.scala:14)
    epsilon.sjbs.PersonModel.create(Sjbs.scala:7)
    epsilon.snippet.PersonSnippet.register$1(Snippet.scala:33)
    epsilon.snippet.PersonSnippet.render(Snippet.scala:41)

这看起来即使没有点击提交,也运行了注册方法,只是访问了 url。为什么?
编辑:这是我原来的实体

@NamedQuery(name = "findAll", query = "select x from Person x")
@Entity class Person extends Id with Name{
    @OneToMany(mappedBy="person", cascade=Array(CascadeType.REMOVE))
    var participated:java.util.List[Participant] = new java.util.ArrayListParticipant
    var role:String = Role.User
    var human:String = _
}

4

2 回答 2

3

我认为这Person.human是一个Boolean,而不是一个String...

看起来您正在使用类似于 Mapper 的东西。如果您使用的是 Mapper,我会这样做:

def render(xhtml:NodeSeq) = {
  val person = Person.create
  bind(
    "user",
    xhtml,
    "name" -> SHtml.text(person.name, person.name(_)),
    "role" -> SHtml.text(person.role, person.role(_)),
    "human" -> SHtml.text(
      if (person.human) ? "yes" else "no",
      (human) => person.human(if (human == "yes") true else false)
    ),
    "submit" -> SHtml.submit("Register", () => {
      person.save
      S.redirectTo("/index")
    })
  )
}

当然只是个人喜好,但这样你就不会使用显式vars并且可以轻松地重用它来编辑现有的Person......

于 2010-08-03T13:00:43.880 回答
1

正如 pr1001 所写, person.human 很可能是布尔值。

register 没有被调用,但 person.human 已经被评估,因为人类字符串设置在 register 方法之外。您只需更改分配:

person.human = if (human == "yes") true else false
于 2010-08-03T12:17:36.363 回答