简体   繁体   中英

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?

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))
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM