How to get play-salat and play-cashbah working in the Play 2.0 Scala web framework
Scala?Scala has anonymous functions, type inference, list comprehensions, lazy initialization, excellent pattern matching, case classes, delimited continuations, higher-order types, and complexity that exceeds 10.
What is that stuff after the mapping binder? The apply and unapply functions of the Post model are curried with the form mapping. Check out the views.html.helper package in the Play 2.0 API.
Controller: controllers/Posts.scala
View: views/posts.scala.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val postForm: Form[Post] = Form ( | |
mapping( | |
"name" -> nonEmptyText, | |
"description" -> nonEmptyText, | |
"group" -> ignored(Group.findOneByName("Test group").get.id), | |
"updated" -> optional(date) | |
)((name, description, group, updated) => Post(new ObjectId, name, description, Option(group), new java.util.Date, updated)) | |
((post: Post) => Some((post.name, post.description, post.group.get, post.updated))) | |
) | |
def create = Action { implicit request => | |
postForm.bindFromRequest.fold( | |
errors => BadRequest(views.html.posts.list(Post.findAll().toList, errors)), | |
value => { | |
Post.save(value) | |
Redirect(routes.Posts.list) | |
} | |
) | |
} |
View: views/posts.scala.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@(posts: List[Post], postForm: Form[Post])(implicit flash: Flash) | |
@main(Messages("posts.list")) { | |
<dl class="posts"> | |
@for(post <- posts) { | |
<dt> | |
<a href="@controllers.routes.Posts.view(post.id)">@post.name</a> | |
</dt> | |
<dd>@post.description</dd> | |
} | |
</dl> | |
<p><a href="@controllers.routes.Posts.create()" class="btn"> | |
<span class="icon-plus"></span> @Messages("posts.new.command")</a></p> | |
@helper.form(routes.Posts.create) { | |
@helper.inputText(postForm("name")) | |
@helper.inputText(postForm("description")) | |
@helper.inputText(postForm("group_id")) | |
<input type="submit" value="Create"> | |
} | |
} |