Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do it all in the form definition.</p> <p>I have made some simple scala classes and objects from your example.</p> <p><code>models/Blog.scala</code></p> <pre class="lang-scala prettyprint-override"><code>package models /** * @author maba, 2013-04-10 */ case class User(id:Long) case class Blog(id:Long, author:User) case class Comment(id:Long, blog:Blog, comment:String) object Blog { def findById(id: Long): Option[Blog] = { Some(Blog(id, User(1L))) } } object Comment { def create(comment: Comment) { // Save to DB } } </code></pre> <p><code>controllers/Comments.scala</code></p> <pre class="lang-scala prettyprint-override"><code>package controllers import play.api.mvc.{Action, Controller} import play.api.data.Form import play.api.data.Forms._ import models.{Comment, Blog} /** * @author maba, 2013-04-10 */ object Comments extends Controller { val form = Form( mapping( "comment" -&gt; nonEmptyText, "blog" -&gt; mapping( "id" -&gt; longNumber )( (blogId) =&gt; { Blog.findById(blogId) } )( (blog: Option[Blog]) =&gt; Option(blog.get.id) ).verifying("The blog does not exist.", blog =&gt; blog.isDefined) )( (comment, blog) =&gt; { // blog.get is always possible since it has already been validated Comment(1L, blog.get, comment) } )( (comment: Comment) =&gt; Option(comment.comment, Some(comment.blog)) ) ) def index = Action { implicit request =&gt; form.bindFromRequest.fold( formWithErrors =&gt; BadRequest, comment =&gt; { Comment.create(comment) Ok } ) } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload