首页 > 解决方案 > 如何在百里香中将形式拆分成碎片?

问题描述

在我的 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模板,除了片段之外还有其他方法吗?

标签: javaspringspring-mvcthymeleaf

解决方案


推荐阅读