Reputation: 11
Below is my form submission page. The author
variable is what I want to be taken from the logged-in user, as it is a part of the data I need to be put in the database with the rest of these inputs. I want to know how I can get the username in this instance of the logged in user and pass it into the author field without the user needing to type it in himself.
@(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 *@
Upvotes: 1
Views: 278
Reputation: 28511
You can simply wire this in through your controller.
def myView(): Action[AnyContent] = Action { implicit req =>
val userId = req.session("user_id")
val user = findUser(userId)
Results.Ok(views.yourForm(itemForm, user))
}
Then in your view:
<p class="username">${user.name}</p>
The findUser
method or whatever will allow you to search for a user
based on some kind of data within the request. req.session(key)
will return null
if the user is not logged in potentially so you may want an Option[User]
instead.
The point is that you can pass through whatever variables to your form, and use @{variable.field}
syntax to display whatever you like. The Twirl syntax allows you to do this, as well as for loops on collections to create a div for each element etc.
Have a quick read through the Twirl Syntax, it should help you see all the examples of what it can do. To "get the data", it's generally preferable to put your logic in the controller, and pass it to your view.
Upvotes: 1