Play2.1中inputRadioGroup的Scala示例

时间:2013-03-01 15:38:22

标签: forms scala radio-group playframework-2.1

我正在浏览文档但我找不到如何在我的Controller中使用inputRadioGroup的示例。

我想我应该使用this帮助器。但是如何将它绑定到我的控制器中的表单? 我想展示一个代表1 - 5年级的广播组

控制器:

object Sms extends Controller {  

val testForm: Form[Test] = Form (
    mapping(
      "firstname" -> nonEmptyText,
      "lastname" -> nonEmptyText,
      "password" -> tuple(
        "main" -> text(minLength = 6),
        "confirm" -> text
      ).verifying(
        "Passwords don't match", passwords => passwords._1 == passwords._2
      ),
      "email" -> tuple(
        "main" -> (text verifying pattern("^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$".r, error="A valid email is req")),
        "confirm" -> text
        ).verifying(
        "Emails don't match", emails => emails._1 == emails._2
      ),
      "grade" -> Do the magic happen here?
    )(Test.apply)(Test.unapply)
  )



case class Test(
                    firstname: String,
                    lastname: String,
                    password: String,
                    email: String,
                    grade: Int
                    )

}

查看:

@inputRadioGroup(
testForm("grade"),
options = Seq("1"->1,"2"->2....and so on)
'_label -> "Grade",
'_error -> testForm("grade").error.map(_.withMessage("some error")))

我无法弄清楚如何做到这一点。

1 个答案:

答案 0 :(得分:3)

在您的控制器中,您可以创建可能等级的Seq并将Seq传递给您的视图。我更喜欢使用案例类Grade然后将Tuple2 [String,String]传递给视图。但我想这是一个意见问题。

case class Grade(value: Int, name: String)
private val grades = Seq(Grade(1, "Brilliant"), Grade(2, "Good"), Grade(3, "Ok")) 

val testForm: Form[Test] = Form (...
"grade"-> number
)(Test.apply)(Test.unapply)

def edit(id: Long) = Action {
  val model = ...obtain model
  Ok(views.html.edit(testForm.fill(model), grades))
}

def submit() = Action { 
  testForm.bindFromRequest.fold(
   formWithErrors => Ok(views.html.edit(formWithErrors, grades))
  }, test => {
    Logger.info("grade: " +  grades.find(_.value == test.grade).map(_.name))
    //save model...
    Redirect(...
  })
}

在您的视图中,您将等级Seq映射到Tuple2 [String,String]以馈送inputRadioGroup

@(testForm: Form[Test], grades: Seq[Grade])

@inputRadioGroup(contactForm("grade"), 
options = grades.map(g => g.value.toString -> g.name), 
'_label -> "Grade")