在Lift框架中有一个简单的表单,一个带有render方法的Class处理表单:
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)
这看起来即使没有点击提交,只是访问网址,就会运行注册方法。为什么呢?
编辑:这是我原来的实体
@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 = _
}
答案 0 :(得分: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
...
答案 1 :(得分:1)
由于pr1001写的是person.human很可能是布尔值。
寄存器未被调用,但是person.human已经被评估,因为人类字符串是通过寄存器方法设置的。您只需更改作业:
person.human = if (human == "yes") true else false