Now I'm using play2.2.1, and I know Java, but I don't know Scala. And if you learn PlayFramework even just a little bit, you will know Scala is used in some extent in the framework. This is just a background about me. The question is why is Tuple2 used in below code although the number of passing values is one not plural.
This is the controller's code:
//Action for making a message
public static Result add() {
Form<Message> f = new Form(Message.class);
List<Member> mems = Member.find.select("name").findList();
List<Tuple2<String, String>> opts =
new ArrayList<Tuple2<String, String>>();
for(Member mem: mems) {
opts.add(new Tuple2(mem.name, mem.name));
}
return ok(add.render("fill-in form", f, opts));
}
This is the Model's code:
@Entity
public class Member extends Model {
@OneToMany(cascade = CascadeType.ALL)
public List<Message> messages = new ArrayList<Message>();
@Id
public Long id;
@Required(message = "This item is Required")
public String name;
@Email(message = "Please Fill in a message")
public String mail;
public String tel;
public static Finder<Long, Member> find = new Finder<Long, Member>(Long.class, Member.class);
@Override
public String toString() {
String ids = "{id:";
for (Message m: messages) {
ids += " " + m.id;
}
ids += "}";
return ("[id:" + id + ", message:" + ids + ", name:" + name + ", mail:" + mail + ", tel:" + tel + "]");
}
public static Member findByName(String input) {
return Member.find.where().eq("name", input).findList().get(0);
}
}
This is the View's code:
@(msg:String, form1: Form[models.Message], opts: List[Tuple2[String, String]])
@main("Sample page") {
<h1>ADD MESSAGE</h1>
<p>@msg</p>
@helper.form(action = routes.Application.create) {
@(helper.select (
field = form1("name"),
options = opts
))
@(helper.textarea (
field = form1("message")
))
<input type="submit">
}
}
Again, why is Tuple2, which contains two String values, used despite one value passed from the controller to the view? If the information I showed here is not enough, please give me a comment.
The role of a tuple is to provide multiple values in a single instance. Perhaps it's a bit like an unnamed class? To summarise the comments and give a clear example, the structure of the
<option>
tag in a<select>
structure isWe use it often for foreign key situations - the foreign key value is in "internal-value" and the name or other attribute from the linked table is in the shown-value.
If you use the play helper @select to generate it, you should provide a
Seq
of tuple2s - i.e. two strings for each option. The first for the internal value, and the second for the displayed value. I use adefining
but that is just one way to do it. For example:You can generate it yourself manually if you have some special needs or reason not to use the helper (or you can write your own helper :) ). For example: