如何使用<select> input element </select>设置对象字段

时间:2014-05-13 01:01:28

标签: java playframework ebean

我正在尝试使用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)
. . . }
}

提交表单并提交后,我会收到schoolspeciality字段的验证错误。我认为这是因为类型不匹配(例如integerSchool)。

有人有这种形式的例子吗?如何通过验证并设置仅具有整数键值的对象字段?

致以最诚挚的问候和感谢,浪费你的时间。

1 个答案:

答案 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;
    . . .

而不是之前的例子。