gooamoko
gooamoko

Reputation: 658

How can I set selected option in Play2 scala template?

I have file form.scala.html that looks like

@(ac: models.entities.Account)
. . .
<form id="accountForm" action="@routes.Accounts.save(ac.getId())" method="POST">
<table>
    <tbody>
    . . .
    <tr>
    <td>Role</td>
    <td>
    <select name="role" id="role">
        @for((value, text) <- models.entities.Account.getRoles()) {
        <option @if(value == ac.role){"selected"} value="@value"> @text </option>
        }
    </select>
    </td>
    </tr>
    . . .
    </tbody>
</table>
<p align="center">
    <input type="submit" value="Save">
    <a class="button" href="@routes.Accounts.index()">Cancel</a>
</p>
</form>

I want output HTML like

. . .
<td>Role</td>
<td>
    <select name="role" id="role">
        <option  value="1"> Admin </option>
        <option selected value="2"> User </option>
    </select>
</td>
. . .

But selected isn't appears. What's wrong in the layout? Maybe I'm tired, but I just can't understand. Thanks for wasting your time.

Upvotes: 1

Views: 1789

Answers (2)

gooamoko
gooamoko

Reputation: 658

Oh! I found mistake! It's because of two reasons, I think:

  1. Different datatypes (String and integer)
  2. Using == instead of string.contentEquals(otherString)

Working code is

<select name="role" id="role">
@for((value, text) <- ac.getRoles()) {
  <option @if(value.contentEquals(ac.role + "")){selected} value="@value"> @text </option>
}  
</select>

Upvotes: 0

acjay
acjay

Reputation: 36551

There can sometimes be weirdness with the template engine trying to escape string data, and I've run into this when trying to write entire attributes with template variables, rather than templating their values. You should be able to get around this by wrapping "selected" in an Html constructor to make Twirl treat it literally. So:

<option @if(value == ac.role){Html("selected")} value="@value"> @text </option>

You should also open an issue in the Twirl project, because I personally would think the way you had it should work as-is.

Upvotes: 1

Related Questions