【问题标题】:Populate the default values of an input tag from a list of objects in Thymeleaf从 Thymeleaf 中的对象列表填充输入标签的默认值
【发布时间】:2020-11-06 15:15:53
【问题描述】:

我有一个对象列表,我想从中填充表单中的输入标签。

例如,假设我有一个列表x = [{id:1, email:"one@xyz.com"},{id:2,"two@xyz.com"}]

这里 x 是一个列表,{} 代表一个对象(考虑一个通用学生类的实例)。

我想要的是: 在 thymeleaf 中有一个输入字段,预先填充列表 x 中每个对象的电子邮件。

所以输入字段的默认值为one@xyz.com, two@xyz.com

我尝试过的:

<input th:field="${x}"/> 仅使用 id 填充输入字段,但我希望它们填充电子邮件。 截至目前,输入字段的默认值为1,2

实际代码:

<div class="form-group">
                <label for="modulePOCinput">POC </label>
                
                    <input type="text" class="form-control" id="modulePOCinput"
                        th:field="*{notificationList}" />
                
            </div>

通知列表是包含几个 ModuleNotificationDetails 对象的列表,如下所示 注意:通知列表是一个更大的对象的属性,我没有在这里展示。

@Entity
@NoArgsConstructor
@Data
public class ModuleNotificationDetails 
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "modulePoc_id_generator")
    @SequenceGenerator(name="modulePoc_id_generator", sequenceName = "NOTIFICATION_DETAILS_ID_SEQ", allocationSize = 1)
    private int id;
    
    @NonNull
    private String email;
    
    
}


你能帮我解决这个问题吗?谢谢。

【问题讨论】:

    标签: java spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    在 Thymeleaf 中调用方法绝对不是问题 - 所以只要 ${obj} 代表 ModuleNotificationDetails 类的对象,您就可以像 ${obj.getEmail()} 或更短的那样在其上调用方法 getEmail Thymeleaf 识别的版本是 ${obj.email}

    你也可以在 Thymeleaf 中进行迭代,所以因为 x 是列表:

    <ul>
        <li th:each="item: ${x}"> <input th:field="${item.email}"/> </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2014-05-17
      • 2010-11-22
      • 2018-07-26
      • 2017-04-16
      • 2022-10-14
      • 1970-01-01
      • 2015-06-19
      • 2010-12-05
      • 2021-01-06
      相关资源
      最近更新 更多