我认为这将是一个相当快且可能令人尴尬的简单答案。我绞尽脑汁,在互联网上搜索了无数遍,似乎都没有找到可能的解决方案。我使用的是 Play 框架 2.2。为了提出这个问题,我构建了一个简单的“在线大学注册表”示例,供学生填写。
在我们的模型中,我们使用 Ebean。下面的类显示了关系,即一所学院有许多学生。
@Entity
public class College extends Model {
@Id
public Long id;
public String name;
@OneTOMany(cascade=CascadeType.ALL)
public List<Student> Student;
public College(String name) {
this.name = name;
}
// all other variables and methods for College class
}
@Entity
public class Student extends Model {
@Id
public Long id = id;
public String name;
@ManyToOne
public College college;
public Student(College college) {
this.college = college
}
// all other variables and methods for Student class
}
在 Controller 索引方法中,我们实例化我们的表单。我们假设我们知道学生将就读哪所大学,并希望将其设置为表单中的默认隐藏值。目的是呈现学生表单并将其在响应中传回。
Form<Student> form = Form.form(Student.class);
College college = new College("My College");
form.fill(new Student(college));
return ok(student.render(form));
最后一个问题,考虑到所涉及的类,在渲染 View 时如何使用这些默认值设置隐藏字段?我想知道为什么没有隐藏字段助手......
@(studentForm: play.data.Form[Student])
...
@form(routes.Students.create()) {
...
<input type="hidden" name="college.id" value="???">
...
}
更新:
好吧,在掉了很多头发之后,我终于弄清楚问题出在哪里了。最初,正如 biesior 正确建议的那样,我使用了 @(studentForm("college.id").value)
,但是由于这不起作用,我想我一定做错了......是的,有,但是它不在 View 中,而是在 Controller 中。如果我们添加: form = form.fill(new Student(college))
那么它就像梦想一样。愚蠢的错误。由于 biesior 100%正确,我会接受这个答案。
最佳答案
用途:
@(studentForm: play.data.Form[Student])
<input type="hidden" name="college.id" value='@(studentForm("college.id").value)'>
顺便说一句,尽量避免使用 form
单词作为参数的名称,这很容易产生名称冲突,即。 with @helper
import... 而是考虑使用像 studentForm
这样的名称作为经验法则 - 它将始终是干净的,您正在引用哪个参数。
关于java - 播放框架2 : How to access default values for hidden form fields in view templates?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517518/