Steff
Steff

Reputation: 58

Play framework Scala - get session value in a form

I am using the Play 2.0.4 framework with Scala.

I have to models which are User and Team.

case class User {
    var email: String,
    var username: String
}

case class Team {
    var sport: String,
    var captain: String //is the username of a User
}

In my controllers for Users and Teams the objects are created via forms. For a User this works perfect. And with a successfull request a put the username in the session using .withSession(). Also works fine.

But now I am struggeling with creating a team and retrieving the username from the session.

It looks like

val teamForm = Form[Team](
    mapping(
        sport -> nonEmptyText,
        //I actually don't have an input for captain as it should be retrieved from the session
    )
) (
    ((sport, _) => User(sport, request.session.get("username"))
    ((team: Team) => Some(team.sport, team.captain))
)

And the problem is that request is unknown in the "context" of a form.

Does anyone have an idea how to solve that?

Upvotes: 3

Views: 1904

Answers (1)

Kim Stebel
Kim Stebel

Reputation: 42047

Unless I am missing something fundamental, you can just change your val teamForm to a def.

def teamForm(request:Request[_]) = Form[Team](
    mapping(
        sport -> nonEmptyText,
        //I actually don't have an input for captain as it should be retrieved from the session
    )
) (
    ((sport, _) => User(sport, request.session.get("username"))
    ((team: Team) => Some(team.sport, team.captain))
)

Upvotes: 4

Related Questions