java - 如何在百里香中将形式拆分成碎片?
问题描述
在我的 spring-mvc 项目中,两个 JPA 实体具有不同名称的 Organization 属性:
@Entity
public class Video extends AbstractIdentifiable implements Serializable {
@ManyToOne
@JsonIgnore
@JoinColumn(nullable = false)
private Organization customerOrganization;
public Organization getCustomerOrganization() {
return customerOrganization;
}
public void setCustomerOrganization(Organization customerOrganization) {
this.customerOrganization = customerOrganization;
}
}
@Entity
public class Location extends AbstractIdentifiable implements Serializable {
@ManyToOne
@JoinColumn(nullable = false)
@JsonIgnore
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
不必要的被删除。我在 thymeleaf 模板中有一个 Location 的表格,给负责编辑组织的部分:
<div class="col-md-4 mb-3">
<label for="organization" th:text="#{organization}"/>
<select class="form-control" id="organization" name="organization" th:attrappend="class=${#fields.hasErrors('organization') ? ' is-invalid' : ''}" th:field="*{organization}">
<option th:each="organization: ${organizations}" th:value="${organization.id}" th:text="${organization.title}"/>
</select>
<div class="invalid-feedback" th:if="${#fields.hasErrors('organization')}">
<p th:each="error: ${#fields.errors('organization')}" th:text="${error}"/>
</div>
</div>
考虑到实体可以具有不同的属性名称,我想将它取出来用于所有具有此属性的实体,以免复制和粘贴代码。上面给出的块被替换为:
<div th:replace="~{forms :: organization('organization', *{organization})}"/>
分段:
<div th:fragment="organization(fieldName, organization)" class="col-md-4 mb-3">
<label th:for="${fieldName}" th:text="#{organization}"/>
<select th:id="${fieldName}" th:name="${fieldName}"
th:attrappend="class=${#fields.hasErrors(fieldName) ? ' is-invalid' : ''}"
th:field="${organization}" class="form-control">
<option th:each="organization: ${organizations}" th:object="${organization}"
th:value="*{id}"
th:text="*{title}"/>
</select>
<div class="invalid-feedback" th:if="${#fields.hasErrors(${fieldName})}">
<p th:each="error: ${#fields.errors(${fieldName})}" th:text="${error}"/>
</div>
</div>
结果我收到错误:
<raw>java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'organization' available as request attribute
th:field 有问题,因为它在一个片段中他没有看到我所理解的表单。如何解决这个问题?也许对于在表单中重复使用themeleaf模板,除了片段之外还有其他方法吗?
解决方案
推荐阅读
- php - php 文件不回显来自远程服务器上的 mysql 表的查询但适用于本地 XAMMP mariaDB
- python - Python:在 csv 文件中附加一行会导致它被随机拆分
- r - 从 R 中的弹性网络中提取变量
- c# - 在 SQL Server 中存储程序状态变量的最佳方式
- python - 如何发送具有不同有效负载的多个请求?
- android - Zip 动态数量的 observables
- ios - 从 Cloud Firestore 获取四个随机但唯一的文档 - Swift
- sorting - 在 Spring Data Elastic Search 中使用路径和过滤器进行嵌套排序
- c++ - 如何在 Windows 上的 Sublime Text 3 中修复“Permission denied collect2.exe: error: ld returned 1 exit status”
- java - Android Studio - 无法使用 OpenCV 从我的图库中的图片中检测人脸