Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To me, this doesn't really look like a binding problem.</p> <p>The issue is around the Model-View-Controller split. Binding is a Controller activity, and it's about binding web data (from your View) to your data model (for use by the Model). Querying the data, on the other hand, would very much be handled by the Model.</p> <p>So, the standard way to do this would be something like the following:</p> <pre><code>// Defined in the model somewhere def lookupBlog(id: Long): Option[Blog] = ??? // Defined in your controllers val boundForm = form.bindFromRequest() val blogOption = boundForm.value.flatMap { case (id, comment) =&gt; lookupBlog(id) } blogOption match { case Some(blog) =&gt; ??? // If the blog is found case None =&gt; ??? // If the blog is not found } </code></pre> <p>However, if you are determined to handle database lookup in your binding (I'd strongly advise against this, as it will lead to spaghetti code in the long run), try something like the following:</p> <pre><code>class BlogMapping(val key: String = "") extends Mapping[Blog] { val constraints = Nil val mappings = Seq(this) def bind(data: Map[String, String]) = { val blogOpt = for {blog &lt;- data.get(key) blog_id = blog.toLong blog &lt;- lookupBlog(blog_id)} yield blog blogOpt match { case Some(blog) =&gt; Right(blog) case None =&gt; Left(Seq(FormError(key, "Blog not found"))) } } def unbind(blog: Blog) = (Map(key -&gt; blog.id.toString), Nil) def withPrefix(prefix: String) = { new BlogMapping(prefix + key) } def verifying(constraints: Constraint[Blog]*) = { WrappedMapping[Blog, Blog](this, x =&gt; x, x =&gt; x, constraints) } } val blogMapping = new BlogMapping() val newform = Form( tuple( "blog_id" -&gt; blogMapping, "comment" -&gt; nonEmptyText ) ) // Example usage val newBoundForm = newform.bindFromRequest() val newBoundBlog = newBoundForm.get </code></pre> <p>The main thing we've done is to create a custom Mapping subclass. This can be a good idea under some circumstances, but I'd still recommend the first approach.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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