Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play 2: How to parse a dynamic list of form inputs in Scala controller?

I have a form where the number of input fields is dynamic.

How can these input fields be mapped with a play form? Let's say, the name of each input tag is 'foo_x' where x is an integer that is incremented each time a new input field is dynamically created on the client side. Is there any automatic mapping in Play available or do I have to do this 'by hand' and if so, how can this be done?

like image 216
schub Avatar asked Aug 08 '12 15:08

schub


2 Answers

As Brian mentioned, the Play documentation has an example of repeated values that should suit your needs.

Also, bear in mind that you can nest mapping definitions. As an example, I have something like the following:

val editUserForm: Form[User] = Form(
    mapping(
        "username" -> text(minLength = 4, maxLength = 50),
        "emails" -> list(optional(email)).verifying(Messages("error.mandatoryEmail"), e => e.size > 0),
        "urls" -> list(text(maxLength = 255)),
        {
            // Binding: Create a User from the mapping result
            (username, emails, urls) => {
              // Here, emails is a List[Option[String]] 
              // and urls is a List[String]
            }
        } {
            // Unbinding: Create the mapping values from an existing User value
            user => Some(user.username, 
                        user.emails.map(e => Some(e.email)), 
                        user.urls.map(_.url))
        }
    )

There's quite a bit happening there, but the important bit that I wanted to show is that I'm nesting list with optional with email, and verifying that the list has at least one non-empty element - effectively forcing the user to enter at least one element in the list.

Hope this helps.

like image 132
Alejandro Lujan Avatar answered Nov 15 '22 09:11

Alejandro Lujan


See "Repeated values" in the Play2 Documentation.

You can have these mapped into a List automatically provided you follow the naming convention.

like image 38
Brian Smith Avatar answered Nov 15 '22 08:11

Brian Smith