我使用的控制器中有一个更新功能:
public static Result updateCustomer(Long id) {
Form<CustomerData> customerDataForm = form(CustomerData.class)
.bindFromRequest();
if (customerDataForm.hasErrors()) {
return badRequest(views.html.admin.customerFormEdit
.render(customerDataForm));
}
customerDataForm.get().update(id);
flash("success", "Customer " + customerDataForm.get().customerName
+ " has been updated");
return CLIENT_HOME;
}
但它不会保存空的输入文本值,甚至不会保存未选中的复选框。
当我选中一个复选框,或者在任何字段中输入任何值时,它会在更新时保存,但如果我想保存空输入或未选中复选框,则不会删除以前保存的更新值。
我该如何解决这个问题?
答案 0 :(得分:0)
以下示例显示我们可以保存/更新输入的空值或勾选/不勾选复选框:
public static Result editCustomer() {
// find CustomerData, Note: this use hard coded ID
CustomerData customerData = CustomerData.find.byId(1L);
Form<CustomerData> customerDataForm = Form.form(CustomerData.class)
.fill(customerData);
return ok(views.html.editCustomer.render(customerDataForm));
}
public static Result updateCustomer() {
Form<CustomerData> customerDataForm = Form.form(CustomerData.class)
.bindFromRequest();
if (customerDataForm.hasErrors()) {
return badRequest(editCustomer.render(customerDataForm));
}
CustomerData customerData = customerDataForm.get();
// update data, Note: this use hard coded ID
customerData.update(1L);
flash("success", "Customer ID " + customerData.id + " has been updated");
return redirect(routes.Application.editCustomer());
}
@Entity
public class CustomerData extends Model {
@Id
public Long id;
public String name;
public boolean isMember;
public static Finder<Long, CustomerData> find = new Finder<>(
Long.class, CustomerData.class
);
}
@(customerDataForm: Form[models.CustomerData])
@import views.html.helper._
@main(title = "Edit Customer Data") {
@form(routes.Application.updateCustomer()) {
@*** Note: this use hard coded ID ***@
<input type="hidden" name="id" value="1">
@inputText(customerDataForm("name"), 'label -> "Customer Name")
@checkbox(customerDataForm("isMember"))
<input type="submit" value="Submit">
}
}
希望这会有所帮助。 :)