我正在尝试使用Play框架2.2.2而且我很困惑。 我有一个对象(Card.java):
@Entity
public class Card extends Model {
private static final long serialVersionUID = 1L;
@Id
public final int id;
@ManyToOne
public Person person; // Card owner
@ManyToOne
public Speciality speciality; // Card Speciality
public Date beginDate; // Begin education date
public Date endDate; // end education date
@ManyToOne
public School school;
. . .
}
另外,我有一个这样的表格(edit.scala.html):
@(itemForm: Form[models.entities.Card], person: models.entities.Person, id: Int)
@import helper._
@main("Personal card") {
@helper.form(action = routes.Cards.save(person.id, id)) {
@helper.select(itemForm("school"), options(models.entities.Person.schools()),'_label -> "School name",'_showConstraints -> false)
@helper.select(itemForm("speciality"), options(models.entities.Person.specialities()),'_label -> "Speciality name",'_showConstraints -> false)
. . . }
}
提交表单并提交后,我会收到school
和speciality
字段的验证错误。我认为这是因为类型不匹配(例如integer
和School
)。
有人有这种形式的例子吗?如何通过验证并设置仅具有整数键值的对象字段?
致以最诚挚的问候和感谢,浪费你的时间。
答案 0 :(得分:0)
作为临时解决方案,我使用form.data()
map来获取所选id的int值,而不是通过此值从数据库中获取对象。但我认为,这不是最好的解决方案。
. . .
Map<String, String> formData = form.data();
String schoolId = formData.get("school.id");
Integer id = Integer.parseInt(schoolId);
if (id == null) {
return badRequest("Incorrect school identifier: " + schoolId);
}
School scl = School.find.byId(id);
if (scl == null) {
return notFound("Can't found school with id " + schoolId);
}
String specialityId = formData.get("speciality.id");
id = Integer.parseInt(specialityId);
if (id == null) {
return badRequest("Incorrect speciality identifier: " + specialityId);
}
Speciality spc = Speciality.find.byId(id);
if (spc == null) {
return notFound("Can't found speciality with id " + specialityId);
}
Card card = form.get();
card.person = p;
card.school = scl;
card.speciality = spc;
. . .
另外,我用过
. . .
@helper.form(...) {
@helper.select(itemForm("school.id"), options(...), ...)
@helper.select(itemForm("speciality.id"), options(...), ...)
. . . }
而不是
. . .
@helper.form(...) {
@helper.select(itemForm("school"), options(...), ...)
@helper.select(itemForm("speciality"), options(...), ...)
. . . }
在edit.scala.html文件中解决验证错误。
P.S。更改模型对象中id
字段的声明让我感觉更好。现在我需要更少的代码来保存Card
实例。仅
. . .
Card card = form.get();
card.person = p;
. . .
而不是之前的例子。