2013-02-28 57 views
0

我是新來玩框架。我有我的用戶模型以及伴隨的對象的靜態方法...從案例分類播放表格

case class User(id: Int, username: String, password: String, fullname: String,/
    lastLogin : Date, updatedOn: Date, updatedBy: Int, createdOn: Date, createdBy: Int) 

我想創建一個表單該類忽略一些細節。目前,我有一個窗體案例類

case class UserForm(fullName:String, username: String, password:String, confirm:String) 

要允許我使用:

val userForm = Form(
    mapping(
     "fullName" -> of[String], 
     "username" -> of[String], 
     "password" -> of[String], 
     "confirm" -> of[String] 
    )(UserForm.apply)(UserForm.unapply) 
) 

這種感覺那種Hacker-ish。有沒有一種慣用的和更有說服力的方式來做到這一點?

+1

給予用戶案例類的一些默認值和/或使用「默認「或」忽略「attribs在窗體映射,這樣你就不需要一個單獨的UserForm案例類 – virtualeyes 2013-02-28 15:15:35

+1

爲什麼這個'黑客ish'?這是表單提交和模型的完全分離。 – 2013-02-28 15:43:59

+0

在我的腦海中,當我在scala中輸入太多的內容(並且重複這個事情)時,情況就是我通常做錯了事情。 @Marius – korefn 2013-02-28 16:12:26

回答

3

如何

val userForm = Form(
    mapping(
     "fullName" -> text, 
     "username" -> text, 
     "password" -> text, 
     "confirm" -> text 
)(UserForm.apply)(UserForm.unapply) 
) 

有很多更有內置的檢查和驗證。基礎知識在這裏列出:http://www.playframework.com/documentation/2.1.0/ScalaForms

如果你不需要他們的對象,你可以使用一個元組

val userForm = Form(
    tuple(
     "fullName" -> text, 
     "username" -> text, 
     "password" -> text, 
     "confirm" -> text 
) 
) 

你的情況的元組,你有以下類型:(String, String, String, String),你可以使用像這個:val (fullName, username, password, confirm) = refToTuple

+0

感謝這個鏈接確實有幫助。 – korefn 2013-03-01 04:43:37

3

遲到了,但我剛剛發佈了一個實用程序來幫助這個!使用你的類,你的代碼應該是這樣的:

case class User(id: Int, username: String, password: String, fullname: String, lastLogin : Date, updatedOn: Date, updatedBy: Int, createdOn: Date, createdBy: Int) 
object User { implicit val mapping = CaseClassMapping.mapping[User] } 

val userForm = Form(implicitly[Mapping[User]]) 

你可以找到源和說明,包括在您的項目在GitHub上:https://github.com/Iterable/iterable-play-utils