I'm new to Play Framework 2. I have 2 models: Book and Author, one book can have many authors, so I think its many to many. Here are my models:
@Entity
public class Book extends Model {
@Id
public Long id;
@Constraints.Required
public String title;
@Constraints.Required
@ManyToMany(cascade=CascadeType.ALL,mappedBy="books")
public Set<Author> authors = new HashSet<Author>();
public static Model.Finder<Long,Book> find = new Model.Finder<Long,Book>(Long.class, Book.class);
public static Page<Book> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("title", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.findPagingList(pageSize)
.getPage(page);
}
}
@Entity
public class Author extends Model {
@Id
public Long id;
@Constraints.Required
public String name;
@ManyToMany(cascade=CascadeType.ALL)
public Set<Book> books = new HashSet<Book>();
public static Model.Finder<Long,Author> find = new Model.Finder<Long,Author>(Long.class, Author.class);
public static Page<Author> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.findPagingList(pageSize)
.getPage(page);
}
}
and I'm using this select tag in the entry form, like this:
<select name="authors.id" multiple="multiple">
<option value="1">bejo</option>
<option value="2">joko</option>
</select>
and here is my controller code:
Map<String, String> newData = new HashMap<String, String>();
Map<String, String[]> urlFormEncoded = play.mvc.Controller.request().body().asFormUrlEncoded();
if (urlFormEncoded != null) {
for (String key : urlFormEncoded.keySet()) {
String[] value = urlFormEncoded.get(key);
if (value.length == 1) {
newData.put(key, value[0]);
} else if (value.length > 1) {
for (int i = 0; i < value.length; i++) {
newData.put(key + "[" + i + "].id", value[i]);
}
}
}
}
Form<Book> bookForm = new Form<Book>(Book.class).bind(newData);
if(bookForm.hasErrors()) {
return badRequest(createForm.render(bookForm));
}
bookForm.get().save();
but these codes does not work. can some body help me? Thanks