Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Steff Avatar asked Feb 08 '26 05:02

Steff


1 Answers

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))
)
like image 135
Kim Stebel Avatar answered Feb 12 '26 03:02

Kim Stebel