如何在百里香叶中分解成碎片?

时间:2018-08-07 17:46:27

标签: java spring spring-mvc thymeleaf

在我的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;
    }
}

不必要的已删除。我在百里香模板中有一个用于位置的表单,请负责编辑组织的部分:

<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的问题,因为它在一个片段中看不到我所理解的形式。如何解决?也许要重复使用形式的模板模板,除了片段以外,还有其他方法吗?

0 个答案:

没有答案