java spring thymeleaf:将带有enum-list-attribute属性的对象绑定到html表单

时间:2015-02-02 13:07:01

标签: spring enums thymeleaf

我有一个包含可能的送货方式列表的实体:

//ShippingType.java
public enum ShippingType {
    DOWNLOAD,
    SHIPPING
}


//SoftwareType.java
@Entity
public class SoftwareType {

    //...
    @Column(unique = true)
    private String name;

    @ElementCollection(targetClass=ShippingType.class)
    @CollectionTable(name = "softwaretype_shippingtype", joinColumns = @JoinColumn(name = "softwaretype_id"))
    @Column(name = "shippingtype", nullable = false)
    @Enumerated(EnumType.STRING)
    private List<ShippingType> supportedShippingTypes;

    //...

    public List<ShippingType> getSupportedShippingTypes() {
        return supportedShippingTypes;
    }

    public void setSupportedShippingTypes(List<ShippingType> supportedShippingTypes) {
        this.supportedShippingTypes = supportedShippingTypes;
    }
}

现在我想将对象与thymeleaf绑定到一个html格式,以便轻松创建/编辑这样的实体。

<div class="panel-body" th:fragment="createUpdateForm(action, SoftwareType)">
    <form role="form" action="#" th:action="@{${action}}" th:object="${SoftwareType}" method="post">

        <label for="softwareTypeName">Name</label>
        <input type="text" th:field="*{name}" id="softwareTypeName"/>

        <!-- how to insert checkboxes of shippingTypes ?? -->
        <button type="submit" value="submit"/>
    </form>
</div>

但是如何插入包含所有ShippingTypes的复选框列表并将其绑定到对象?

1 个答案:

答案 0 :(得分:5)

您可以迭代枚举ShippingType,例如:

<div th:each="shippingType : ${T(com.example.ShippingType).values()}">
    <input type="checkbox" th:id="${{shippingType}}" th:value="${{shippingType}}" th:field="*{supportedShippingTypes}" />
    <label th:for="${{shippingType}}">Shipping Types</label>
</div>