foldLeftReduce foldLeftReduce - 5 months ago 26
Scala Question

How to access request/session data when in form parse error block?

I'm in onError block which returns view, this view has implicit Flash and ApplicationContext passed into. ApplicationContext keeps user data from session, and I don't know how to access it from onError:

def userFormSubmitted() = Action(parse.form(dataForm, onErrors = (formWithErrors: Form[UserForm]) => {
// to get rid of error I provide these 2 implicits
// implicit val applicationContext: ApplicationContext = ApplicationContext(None)
// implicit val flash: Flash = Flash()
})) { implicit request =>
val data = request.body
// rest of code

ApplicationContext is created by a trait:

case class ApplicationContext(user: Option[User])

trait ApplicationController extends Controller {

implicit def context[A](implicit request: Request[A]): ApplicationContext = {


Template has it injected as:

@(dataForm: Form[UserForm])(implicit messages: Messages, context: ApplicationContext, flash: Flash)
@main("User Edit Form") { ... }

If there is bad data onError is entered, but without commented implicits code doesn't even compile with the error:
could not find implicit value for parameter context: traits.ApplicationContext

Answer Source

I think you've reached the upper limit of what you can do in the parse.form body parser.

If you switch to using the bindFromRequest approach to handling form submission you can get those implicits into scope and everything will work:

def userFormSubmittedNew() = Action { implicit request =>

    formWithErrors => {
    goodForm => {