How do I process a checkbox input in Play! Framework? Should I catch the value as a String at the controller? How to get what values
are checked by a user?
This is the html code of my checkbox
#{list items:categories, as:'category'}
<tr>
<td><input type="checkbox" name="category" id="category-${category.name}" value="${category.id}" /><label for="category-${category.name}"> ${category.name}</label></td>
</tr>
#{/list}
I think if you have a List<String> category
in your form action, you will get a list of value of checked items.
To show the state of a specific term (actually there are more terms,
think about a Project having multiple terms, that’s why you see the
name being selectedTerms) in a view I did:
#{form @ProjectController.update(project.alias), enctype:'multipart/form-data', class:'well form-horizontal'}
#{list terms, as:'term'}
<input type="checkbox" name="selectedTerms" value="${term.name}"/>
<span>${term.name}<span>
#{/list}
#{/form}
Now the main question is: how do I know which of these terms were
selected by the user?
Well, Play let me to define these terms as a List, check below:
public static void update(String alias, List<String> selectedTerms) {
//play with selected terms
}
Please note: selectedTerms list will contain ONLY the terms which are
selected (TRUE) by the user. Because I have their names (or ids or
what you want) all the problems are solved:)
Ps: You will probably ask: how do you show these in the view after you
saved them in db?
#{list terms, as:'term'}
<input type="checkbox" name="selectedTerms" value="${term.name}" ${term.selected ? 'checked':''}/>
<span>${term.name}</span>
#{/list}
Thanks to Cristian Boariu, here is the link for your inspiration:
http://crisdev.wordpress.com/2012/05/19/play-framework-get-checkbox-value-from-view-in-controller/