Suraj
Suraj

Reputation: 173

Play framework 2.3.2: How to render List or Map in scala template

I am trying to display a list of strings as a repeatable input text control in my view. Here is my model:

public class User {
    @Required
    public String email;
    public String password;
    public List<String> products;
}

Controller:

    public static Result index() {
    Form<User> userForm = Form.form(User.class);

    Map<String,String> anyData = new HashMap<String,String>();
    List<String> listProduct = new ArrayList<String>();
    listProduct.add("p1");
    listProduct.add("p2");
    userForm = userForm.fill(new User("[email protected]", "secret", listProduct));
    return ok(views.html.index.render(userForm));
}

View:

@(userForm: Form[models.User])
@import helper._
@import models.User
@import scala._

@main("Welcome to Play") {

<form id="formUser" action="/user/apply" method="post">
    @inputText(userForm("email"))
    @inputText(userForm("password"))
    @for(product <- userForm("products")) {
      <input type="text" name="@product" value="@product">
    }

    <input type="submit" value="submit"/>
</form>
}

Error is:

value map is not a member of play.data.Form.Field

I also tried form helper @repeat. But its just not working.

    @repeat(userForm("products"), min = 0) { 
        product => @inputText(product)
    }

Error:

not found: value product

I am using Play 2.3.2 in Java. Any idea whats going wrong?

Suraj

Upvotes: 0

Views: 1801

Answers (1)

Daniel Olszewski
Daniel Olszewski

Reputation: 14401

You just need to remember that view templates are parsed to Scala functions and code is escaped with @ character. Your second solution works fine. In this case you just need to format your code in proper way and it works like a charm.

@repeat(userForm("products"), min = 0) { product => 
  @inputText(product)
}

Upvotes: 1

Related Questions