我希望我的网络应用程序中的用户发帖。该帖子将包含他的用户名,以表明他发布了它。我该怎么做?
更新<!/强>
这是我的工作代码
请参阅下面的代码:
def createlisting = isAuthenticated { username => implicit request =>
Ok(html.createlisting(listingsForm))
}
def postlisting = withUser {user => implicit request => {
listingsForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.createlisting(formWithErrors)),
listing => {
val username = val username = User.getUserName(user)
Listings.create(listing.categorytype, listing.title, listing.description, username)
Redirect(routes.Application.active).flashing("success" -> "Listing %s has been posted".format(listing.title))
}
)
}
}
val listingsForm = Form(
mapping(
"_id" -> ignored(new ObjectId()),
"categorytype" -> mapping(
"category" -> nonEmptyText,
"subcategory" -> nonEmptyText)(Type.apply)(Type.unapply),
"title" -> nonEmptyText,
"description" -> nonEmptyText,
"username" -> igrnored(String)
)(Listings.apply)(Listings.unapply)
)
scala.html
@(createForm: Form[Listings])
@import helper._
@implicitFieldConstructor = @{ FieldConstructor(twitterBootstrapInput.f) }
<h1>Add a Listing</h1>
@form(routes.Application.postlisting()) {
<fieldset>
@inputText(createForm("categorytype.category"), '_label -> "Main Category")
@inputText(createForm("categorytype.subcategory"), '_label -> "Sub Category")
@inputText(createForm("title"), '_label -> "Title")
@inputText(createForm("description"), '_label -> "Description")
</fieldset>
<div class="actions">
<input type="submit" value="Post Add" class="btn primary" href="/"> or
<a href="/" class="btn primary">Cancel</a>
</div>
}
如何将用户名自动传递到postlistings函数并保存在我的数据库中?
答案 0 :(得分:1)
如果用户名在会话中(就像在另一个函数中使用withUser
一样),您无需做任何事情,它将随每个请求自动传递。
但您需要做的就是恢复它。您可以将Action
打包到withUser
的另一个电话中,这样就可以了。