我使用 Play 2.6.3
这里是index.scala.html:
@import models.MyForm.FormData
@(theForm:Form[FormData])(implicit messages: Messages, request:RequestHeader)
@main("Welcome to Play") {
<h1>Welcome to Play!</h1>
@if(theForm.hasGlobalErrors) {
<ul>
@for(error <- theForm.globalErrors) {
<li>@error.format</li>
}
</ul>
}
@helper.form(action = helper.CSRF(routes.HomeController.processForm())){
@helper.inputRadioGroup(theForm("field1"), Seq("Yes" -> "Yes", "No" -> "No"))
@helper.inputRadioGroup(theForm("field2"), Seq("Yes" -> "Yes", "No" -> "No"))
<button type="submit">Send</button>
}
}
这里是MyForm 定义在models 包中的对象:
package models
import play.api.data.Form
import play.api.data.Forms._
/**
* Created by alex on 8/17/17.
*/
object MyForm {
case class FormData(firstYesNo:Option[String], secondYesNo:Option[String])
val theForm = Form(
mapping(
"field1" -> optional(text),
"field2" -> optional(text)
)(FormData.apply)(FormData.unapply) verifying(
"Form failed the validation",
fields => fields match{
case formData => formData.firstYesNo match{
case None => false
case Some("No") => if(!formData.secondYesNo.isDefined) true else false
case Some("Yes") => if(formData.secondYesNo.isDefined) true else false
}
}
)
)
}
这是我唯一的控制器的代码:
import javax.inject._
import models.MyForm.theForm
import play.api.mvc._
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with play.api.i18n.I18nSupport{
/**
* Create an Action to render an HTML page.
*
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
*/
def index() = Action { implicit request: Request[AnyContent] =>
Ok(views.html.index(theForm))
}
def processForm() = Action{implicit request:Request[AnyContent] =>
theForm.bindFromRequest().fold(
formWithErrors => BadRequest(views.html.index(formWithErrors)),
data => Ok("Form successfully submitted")
)
}
}
我的routes 文件的内容:
GET / controllers.HomeController.index
POST /processForm controllers.HomeController.processForm
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
最后,我们需要将其添加到application.conf:
play.filters.enabled += play.filters.csrf.CSRFFilter
希望对你有所帮助。