2012-06-26 17 views

risposta

5

Qui hai buon esempio come si fa in Play:

https://github.com/playframework/Play20/blob/master/samples/scala/zentasks/app/controllers/Application.scala

val loginForm = Form(
    tuple(
    "email" -> text, 
    "password" -> text 
) verifying ("Invalid email or password", result => result match { 
    case (email, password) => User.authenticate(email, password).isDefined 
    }) 
) 



/** 
* Handle login form submission. 
*/ 
def authenticate = Action { implicit request => 
    loginForm.bindFromRequest.fold(
    formWithErrors => BadRequest(html.login(formWithErrors)), 
    user => Redirect(routes.Projects.index).withSession("email" -> user._1) 
) 
} 

E 'descritto nella documentazione del forms submission

2

come sottolinea @Marcus, bindFromRequest è la approccio preferito Per semplici casi una tantum, però, un campo

<input name="foo" type="text" value="1"> 

si può accedere tramite modulo post'd in questo modo

val test = Action { implicit request => 
    val maybeFoo = request.body.get("foo") // returns an Option[String] 
    maybeFoo map {_.toInt} getOrElse 0 
} 
+11

'Errore di compilazione [valore get non è un membro di play.api.mvc.AnyContent]'? – Meekohi

+1

Prova 'request.body.asFormUrlEncoded.get (" foo "). Lift (0)' - Sembravo che ricevessi un 'ArrayBuffer' e' lift (0) 'restituisce una' Option' dell'elemento che contiene – Techmag

8

Come of Play 2.1, ci sono due modi per arrivare a parametri POST:

1) dichiarare il corpo come form-urlencoded tramite un parametro Azione parser, nel qual caso il request.body viene automaticamente convertito in una mappa [String, Seq [String]]:

def test = Action(parse.tolerantFormUrlEncoded) { request => 
    val paramVal = request.body.get("param").map(_.head) 
} 

2) Chiamando request.body.asFormUrlEncoded per ottenere la mappa [String, Seq [String]]:

def test = Action { request => 
    val paramVal = request.body.asFormUrlEncoded.get("param").map(_.head) 
} 
0

Qui hai buon esempio come si fa in Play 2:

def test = Action(parse.tolerantFormUrlEncoded) { request => 
 
    val paramVal = request.body.get("param").map(_.head).getorElse(""); 
 
}

Problemi correlati