Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I am using <strong>Play!Framework 2.1.0</strong>, below is the solution :</p> <p><strong>1. In the scala template, you must give all checkbox name like this:</strong></p> <pre class="lang-scala prettyprint-override"><code>@form(action = routes.Application.newPaper()) { @inputText(paperForm("title")) @******* Indexed chekbox name *********@ @for((t, index) &lt;- topics.zipWithIndex) { &lt;input type="checkbox" name="topics[@index]" value="@t"&gt;@t &lt;br&gt; } &lt;input type="submit" value="Create"&gt; } </code></pre> <p><strong>2. Then in your controller, as an action to handle form submit, you should doing something like this</strong> :</p> <pre class="lang-java prettyprint-override"><code>public static Result newPaper() { // Bind submitted form value to your model, ex. Paper.java Form&lt;Paper&gt; paperForm = Form.form(Paper.class).bindFromRequest(); Paper paper = paperForm.get(); Logger.info("Title entered = " + paper.title); // Because in template we use indexed name, unchecked item are binded with null value paper.topics.removeAll(Collections.singleton(null)); // remove value for unchecked topic for (String t : paper.topics) { Logger.info("The topic is " + t); } Logger.info("Total topic selected = " + paper.topics.size()); return redirect(routes.Application.index()); // redirect page } </code></pre> <hr> <h3>UPDATE</h3> <p>This is <strong>another idea</strong> to the solution. Your checkbox code on scala template is <strong>not modified</strong>. </p> <pre class="lang-scala prettyprint-override"><code>@for(t &lt;- topics) { &lt;input type='checkbox' name='topic' value=@t&gt;@t &lt;br&gt; } </code></pre> <p>So the <strong>controller</strong> should be like this :</p> <pre class="lang-java prettyprint-override"><code>public static Result newPaper() { // Bind submitted form value to your model, ex. Paper.java Form&lt;Paper&gt; paperForm = Form.form(Paper.class).bindFromRequest(); Paper paper = paperForm.get(); // get request value from submitted form Map&lt;String, String[]&gt; map = request().body().asFormUrlEncoded(); String[] checkedVal = map.get("topic"); // get selected topics // assign checked value to model paper.topics = Arrays.asList(checkedVal); // for debugging purpose for (String t : paper.topics) { Logger.info("The topic is " + t); } Logger.info("Total topic selected = " + paper.topics.size()); return redirect(routes.Application.index()); // redirect page } </code></pre> <p>Hope this idea is more elegant.. :)</p> <p>Note: I have tested on Play!Framework 2.1.1 too, and that is work for me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload