【问题标题】:th:attr is showing value attribute as empty stringth:attr 将值属性显示为空字符串
【发布时间】:2019-08-22 09:41:09
【问题描述】:

我有一个表单,其中输入的数据通过使用th:field 映射到正确的变量。但是当页面加载时,我希望输入字段显示默认值。这样当用户不输入任何数据时,默认值就会映射到变量。

th:field 覆盖th:value,因此我添加了: th:attr="value=${field.placeholder}",我在另一个线程中发现了这一点(评论中的链接),但这似乎不起作用。当我检查元素时,它显示的值为:value=""

我知道 field.placeholder 不为空,因为 th:placeholder="${field.placeholder}" 确实显示了值。

<form th:action="@{/generateData}" th:object="${stepObject}" method="post" class="form-group">
  <div th:each="field, iterStat : ${stepEntry.value}">
     <label th:text="${field.name}"></label><input type="hidden" th:field="*{name}" th:attr="value=${field.name}"/>

     <input th:type="${field.type}" class="form-control" th:maxLength="${field.length}"
            th:field="*{value}" th:attr="value=${field.placeholder}" th:placeholder="${field.placeholder}"/>

  </div>
     <button type="submit" class="btn btn-primary" id="generateButton">Generate away!</button>
</form>

所以在隐藏输入中它应该有值 ${field.name},但值是“”。 在另一个输入中,它的值应该是 ${field.placeholder},但这个值也是“”。

关于为什么会这样以及如何让它发挥作用的任何建议?

当我在输入字段中输入数据时,它们被映射到 stepObject 的值变量。但重要的是,用户也可以直接按下按钮而不输入任何内容。

提前致谢!

【问题讨论】:

  • This question got me to the th:attr solution. 显然对他有用,但对我来说却不行。
  • 为什么不在进入表单之前设置支持对象的值?
  • 因为我不知道用户会选择哪一步。在应用程序中,您可以上传一个文件,该文件包含多个步骤。每个步骤基本上是一个单独的形式。用户一次只能选择一个步骤来生成数据。我认为如果我在进入表单之前设置值,那将导致大量数据未被使用。 -- 谢谢你的评论,无论如何我都会玩它! :-)

标签: java html spring spring-boot thymeleaf


【解决方案1】:

我放弃了使用th:field 并最终在我的控制器方法中使用@RequestParam("form-name-attribute") 来获取(默认)值并手动将其设置为正确的对象。

不过,我本来希望用百里香叶功能来做这件事。 因此,如果有人仍然找到解决方案,请告诉我,以便我学习! :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多