我有一个模特。它包含另一个模型的列表:
case class Account(
_id: ObjectId = new ObjectId,
name: String,
campaigns: List[Campaign]
)
case class Campaign(
_id: ObjectId = new ObjectId,
name: String
)
我有一个用于显示和创建新帐户的表单和操作:
val accountForm = Form(
mapping(
"id" -> ignored(new ObjectId),
"name" -> nonEmptyText,
"campaigns" -> list(
mapping(
"id" -> ignored(new ObjectId),
"name" -> nonEmptyText
)(Campaign.apply)(Campaign.unapply)
)
)(Account.apply)(Account.unapply)
)
def accounts = Action {
Ok(views.html.accounts(AccountObject.all(), accountForm, CampaignObject.all()))
}
def newAccount = Action {
implicit request =>
accountForm.bindFromRequest.fold(
formWithErrors => BadRequest(views.html.accounts(AccountObject.all(), formWithErrors, CampaignObject.all())),
account => {
AccountObject.create(account)
Redirect(routes.AccountController.accounts)
}
)
}
最后,这是我对账户的看法:
@(accounts: List[models.mongodb.Account], account_form: Form[models.mongodb.Account], campaign_list: List[models.mongodb.Campaign])
@import helper._
@args(args: (Symbol, Any)*) = @{
args
}
@main("Account List") {
<h1>@accounts.size Account(s)</h1>
<ul>
@accounts.map { account =>
<li>
@account.name
</li>
}
</ul>
<h2>Add a New Account</h2>
@form(routes.AccountController.newAccount()) {
<fieldset>
@inputText(account_form("name"), '_label -> "Account Name")
@select(
account_form("campaigns"),
options(campaign_list.map(x => x.name):List[String]),
args(
'class -> "chosen-select",
'multiple -> "multiple",
Symbol("data-placeholder") -> "Add campaigns",
'style -> "width:350px;"
): _*
)
<input type="submit" value="Create">
</fieldset>
}
}
问题是,当我提交此表单时,它会提交campaigns
字段的字符串列表。当我发布表单提交时,这给了我400错误。
我想提交提交表单,其中包含广告系列列表而不是字符串,或者使用字符串列表提交表单,然后将字符串处理为控制器中的广告系列列表。哪种方式会更好,我该怎么做?谢谢!
答案 0 :(得分:0)
我最终制作了一个临时表单来保存嵌套模型的字符串。然后我将这些字符串转换为控制器中的模型对象:
val accountTempForm = Form(
tuple(
"id" -> ignored(new ObjectId),
"name" -> nonEmptyText,
"campaigns" -> list(text)
)
)
def newAccount = Action {
implicit request =>
accountTempForm.bindFromRequest.fold(
formWithErrors => {
println("error")
Redirect(routes.AccountController.accounts)
//BadRequest(views.html.account.accounts(AccountObject.all(), formWithErrors, CampaignObject.all()))
},
account => {
val campaign_string_list = account._3
val campaign_list = campaign_string_list.map(x => CampaignObject.getOrCreateByName(x))
val new_account = Account.apply(account._1, account._2, campaign_list)
AccountObject.create(new_account)
Redirect(routes.AccountController.accounts)
}
)
}