Skip to content

Play Framework: Get checkbox form value in controller

May 19, 2012

I’ll post a short help for those who are struggling with this.

I have a Model class called Term which has two fields: name and selected

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="${}"/>

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.selected ? 'checked':''}/>

My route entry for this is simple:

POST /projects/{alias}/update ProjectController.update

Good luck!

  1. Jesper Werge permalink

    I like your post, but could you expand it with your html form tags and your routes file for this aswell, please?

    • Post updated;)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: