我是 Play Framework 的新手,所以我希望这是可以理解的。
我如何告诉 play 将表单元素映射到表单类中的对象字段?
我有一个表单,其中包含来 self 的 ORM 的对象名称的选择下拉列表。下拉项的值是 ORM 对象的 ID 字段。
Java 端的表单对象有一个带有 ORM 对象类型的字段,以及一个获取字符串并将其转换为对象的 setter ,但是在提交表单时我只收到一个表单错误“无效值”,表明翻译根本没有发生。
我的模板有一个表单组件:
@helper.select(
createAccountForm("industry"),
helper.options(industries)
)
其中 industries
在模板构造函数中定义为:industries: Map[String, String]
由用户可读名称的 ID 字符串组成。
我的 Controller 定义类:
public static class CreateAccountForm {
public String name;
public Industry industry;
public void setIndustry(String industryId) {
this.industry = Industry.getIndustry(Integer.parseInt(industryId));
}
}
编辑:我在类里面做二传手因为this answer指示这样做,但这没有用。
编辑2: 事实证明,setter 方法完全不是解决这个问题的方法。在试图让注释工作时我的头有点撞,我注意到了 Formatters.SimpleFormatter 并尝试了它。它起作用了,尽管我不明白为什么需要在它周围添加额外的 block 。
全局.java:
public class Global extends GlobalSettings {
// Yes, this block is necessary; no, I don't know why.
{
Formatters.register(Industry.class, new Formatters.SimpleFormatter<Industry>() {
@Override
public Industry parse(String industryId, Locale locale) throws ParseException {
return Industry.getIndustry(Integer.parseInt(industryId));
}
@Override
public String print(Industry industry, Locale locale) {
return industry.name;
}
});
}
最佳答案
当您按照文档中的描述使用它时,Play 会为您将表单绑定(bind)到一个对象:https://github.com/playframework/Play20/wiki/JavaForms
所以你的 Controller 应该是这样的:
Form<models.Task> taskForm = form(models.Task.class).bindFromRequest();
if (taskForm.hasErrors()) {
return badRequest(views.html.tasks.create.render(taskForm));
}
Task task = taskForm.get();
任务对象可以有一个Priority
选项列表。并且您以如下形式( View )使用它:
@select(editForm("priority.id"), options(Task.priorities), 'class -> "input-xlarge", '_label -> Messages("priority"), '_default -> Messages("make.choice"), 'showConstraints -> false, '_help -> "")
请注意,我正在使用 priorities.id
来告诉游戏选择的值应该由优先级 ID 绑定(bind)。当然还有获得任务的优先级:
public static Map<String, String> priorities() {
LinkedHashMap<String, String> prioritiesList = new LinkedHashMap<String, String>();
List<Priority> priorities = Priority.getPrioritiesForTask("task");
for (Priority orderPrio : priorities) {
prioritiesList.put(orderPrio.getId().toString(), orderPrio.getDescription());
}
return prioritiesList;
}
关于java - 提交时将表单字段转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528234/