korrekorre
korrekorre

Reputation: 1034

Validation of mapping form with tuple of checkboxes in it

I have a form containing several fields and some checkboxes. It looks like this now and that is working excelent

val postForm = Form(
mapping(
  "author" -> text(minLength = 3),
  "title" -> text(minLength = 3),
  "heading" -> text(minLength = 3),
  "content" -> text(minLength = 5),
  "tagNews" -> boolean,
  "tagBlog" -> boolean
  )((author, title, heading, content, tagNews, tagBlog) => domain.Post(author, title, heading, content, tagNews, tagBlog, None))
   ((post: domain.Post) => Some(post.author, post.title, post.heading, post.content, , post.tagNews, post.tagBlog))
)

One thing I want to change from my solution now is that I need at least one of the checkboxes to be checked. As it is now you don't have to check any of them.

I came up with this:

val postForm = Form(
mapping(
  "author" -> text(minLength = 3),
  "title" -> text(minLength = 3),
  "heading" -> text(minLength = 3),
  "content" -> text(minLength = 5),
  //TODO: this is not working!
  "tags" -> tuple(
    "tagNews" -> boolean,
    "tagBlog" -> boolean
  ).verifying("One tag must be used", f => f._1 || f._2)
  )((author, title, heading, content, tags) => domain.Post(author, title, heading, content, tags._1, tags._2, None))
   ((post: domain.Post) => Some(post.author, post.title, post.heading, post.content, (post.tagNews, post.tagBlog)))
)

I dont know if this is the right way to go though. It compiles but I don't know how to use the form with the helpers in the template.

Now, when it works without need of checking, it looks like this in the template:

@form(presentation.controllers.routes.Post.addPost()){

            @inputText(postForm("author"), '_label -> "", 'placeholder -> "Author", '_showConstraints -> false)
            @inputText(postForm("title"), '_label -> "", 'placeholder -> "Title", '_showConstraints -> false)
            @inputText(postForm("heading"), '_label -> "", 'placeholder -> "Heading", '_showConstraints -> false)
            @textarea(postForm("content"), '_label -> "", 'placeholder -> "Content", '_showConstraints -> false)
            <span class="label label-info">News</span>
            @checkbox(postForm("tagNews"), '_label -> "", '_help -> "")
            <span class="label label-info">Blog</span>
            @checkbox(postForm("tagBlog"), '_label -> "", '_help -> "")

            <input type="submit" class="btn btn-primary btn-success" data-loading-text="Loading..." value="Save Post"/>
        }

So. Any ideas?

/Regards

Upvotes: 3

Views: 1052

Answers (1)

maba
maba

Reputation: 48105

You can read about nested values here.

Basically it means that you have to add the outer value as a prefix to the inner value; outer.inner.

In your case you should use the form

@checkbox(postForm("tags.tagNews"), '_label -> "", '_help -> "")

and

@checkbox(postForm("tags.tagBlog"), '_label -> "", '_help -> "")

respectively.

Upvotes: 1

Related Questions