[play-scala 2.4, Silhouette 3.0] Accessing current user in form mapping

64 views
Skip to first unread message

Edgars Kursitis

unread,
Oct 10, 2015, 8:38:50 AM10/10/15
to play-framework
Hi,

is it possible to access users session in form definition. This is not available in session, maybe by additionally DI Silhouette, something like this?

def docForm(implicit request: UserAwareRequestHandler, silhouette: ...) = Form(
    mapping(
      "id" -> optional(number()),
      "heading" -> nonEmptyText,
      "path" -> nonEmptyText,
      "user_id" -> ignored(request.identity.firstName.getOrElse("NoUser"))
    )(Document.apply)(Document.unapply)
  )

Christian Kaps

unread,
Oct 10, 2015, 4:52:55 PM10/10/15
to play-framework
Hi,

why do you not pass the user directly to your form?

Best regards,
Christian

Edgars Kursitis

unread,
Oct 10, 2015, 11:51:42 PM10/10/15
to play-framework
HI, 

I'm new to play+scala, and can't find any other good examples...

Christian Kaps

unread,
Oct 11, 2015, 2:19:21 AM10/11/15
to play-framework
Hi,

you should do something like this:

def docForm(user: User) = Form(
   mapping(
     "id" -> optional(number()),
     "heading" -> nonEmptyText,
     "path" -> nonEmptyText,
     "user_id" -> ignored(user.firstName.getOrElse("NoUser"))
   )(Document.apply)(Document.unapply)
 )

And your action should look like this:

def action = SecuredAction { implicit request =>
  docForm
(request.identity).bindFromRequest.fold(
    error
=> ...,
    data
=> ...
 
)
}

Best regards,
Christian

Edgars Kursitis

unread,
Oct 11, 2015, 3:53:21 AM10/11/15
to play-framework
Dang, so simple, thank you, got it working


On Saturday, October 10, 2015 at 3:38:50 PM UTC+3, Edgars Kursitis wrote:
Reply all
Reply to author
Forward
0 new messages