Play Framework - Checkbox processing

2019-08-04 05:04发布

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}

2条回答
ら.Afraid
2楼-- · 2019-08-04 05:43

I think if you have a List<String> category in your form action, you will get a list of value of checked items.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-04 06:01

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/

查看更多
登录 后发表回答