下面是我的表单提交页面。我想从登录用户那里获取author
变量,因为它是数据的一部分,我需要将其与其余这些输入一起放入数据库。我想知道如何在该登录用户的实例中获取用户名并将其传递到作者字段,而无需用户自己输入。
@(itemForm: Form[models.SubmittedWork],user: models.users.User)
@import helper._
@main("Add submission",user){
<p class="lead">Add a new submission</p>
@form(action=routes.HomeController.addSubmissionSubmit(), 'class -> "form-horizontal", 'role -> "form") {
@* CSRF attack prevention *@
@* This token, sent by the controller, will be used to authenticate the form submission *@
@CSRF.formField
@inputText(itemForm("name"), '_label -> "Name", 'class -> "form-control")
@select(
itemForm("Genre.id"),
options(Genre.options),
'_label -> "Genre", '_default -> "-- Choose a Genre --",
'_showConstraints -> false, 'class -> "form-control"
)
@inputText(itemForm("text"), '_label -> "Text", 'class -> "form-control")
@inputText(itemForm("id"), '_label -> "", 'hidden -> "hidden")
@inputText(itemForm("author"),'_label -> "", 'hidden -> "hidden")
<div class="actions">
<input type="submit" value="Add/Update item" class="btn btn-primary">
<a href="@routes.HomeController.works(0)">
<button type="button" class="btn btn-warning">Cancel</button>
</a>
</div>
} @* end of form *@
} @* end of main *@
答案 0 :(得分:1)
您只需通过控制器将其连接。
def myView(): Action[AnyContent] = Action { implicit req =>
val userId = req.session("user_id")
val user = findUser(userId)
Results.Ok(views.yourForm(itemForm, user))
}
然后在您看来:
<p class="username">${user.name}</p>
findUser
方法或任何允许您基于请求内某种数据搜索user
的方法。如果用户未登录,req.session(key)
将返回null
,因此您可能希望使用Option[User]
。
重点是您可以将任何变量传递到表单,并使用@{variable.field}
语法显示所需的任何内容。 Twirl语法允许您执行此操作,也可以让集合上的循环为每个元素等创建div。
快速阅读Twirl Syntax,它应该可以帮助您了解其功能的所有示例。为了“获取数据”,通常最好将逻辑放在控制器中,然后将其传递给视图。