jeudi 2 août 2018

Why "checked" attribute doesn't apply to my Thymeleaf's checkboxes?

I was working with Spring and Thymeleaf when I've encountered the following problem: I need a Form object, which has a list of items (Item) as attribute; I'm using an html form to print the Name of the Item, and to generate a checkbox for each Item (any checkbox's value is the corresponding item's id).

The form works correctly, sending to the Controller a list of item's ids corresponding to the checked checkboxes.

However, now, I'm trying to check some checkbox upon the occurrence of a condition (if itemIds, which is a list, contains the current item's id). For that I'm using:

th:checked="${#lists.contains(itemIds, item.id)}"/>

But it doesn't work (checkbox are all unchecked). I tried also with a "dummy test":

th:checked="${1 == 1 ? 'checked' : ''}"/>

But, again, all the checkbox remain unchecked; the "checked" attribute is ignored as you can see in this example of the rendered HTML:

<input type="checkbox" value="12" class="chkCheckBox" id="ids1" name="ids">

What am I doing wrong? What am I missing here?

form.html

<form th:action="@{${uriBase}+'/new/' + ${date}}"
        method="POST" th:object="${form}">
    <div class="table-responsive">
        <table class="table">
            <thead class=" text-primary">
            <tr>
                <th>Name</th>
                <th><input type="checkbox" th:id="checkAll"/>Check</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${items}">
                <td th:text="${item.name}"></td>
                <td>
                    <input type="checkbox" th:field="*{ids}"
                           th:value="${item.id}" th:class="chkCheckBox"
                           th:checked="${#lists.contains(itemIds, item.id)}"/>
                </td>

            </tr>
            </tbody>
        </table>
        <button type="submit" class="btn btn-primary pull-right">Submit</button>
        <div class="clearfix"></div>
    </div>
</form>

Form class

public class Form implements Serializable {

    private List<Long> ids;
    //getter and setter
}

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire