2013-03-05 33 views
5
「選擇」與實體標籤

我創造與選擇標記,看起來像這樣的形式:使用在Thymeleaf

<form th:object="${version}" method="post" class="form-horizontal"> 
    ... 
    <div class="control-group" th:classappend="${#fields.hasErrors('product')} ? 'error'"> 
     <label class="control-label" for="product" th:text="#{version.product}">Product</label> 
     <div class="controls"> 
      <select id="product" th:field="*{product}"> 
       <option value="" th:text="#{common.select.prompt}"></option> 
       <option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}"></option> 
      </select> 
      <span class="help-inline" th:errors="*{product}"></span> 
     </div> 
    </div> 
    ... 
</form> 

DomainClassConverterSpring Data JPA有助於選擇id到實體Product自動轉換,當我提交表格。該product也應該是不爲空(我在Version類的product場使用@NotNull

,我有這個問題 - 當我回來的數據進行編輯,該Product沒有選擇

。如果我修改select像這樣(th:fieldth:errors):<-- p.s. is not a sad smile

  <select id="product" th:field="*{product.id}"> 
       <option value="" th:text="#{common.select.prompt}"></option> 
       <option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}"></option> 
      </select> 
      <span class="help-inline" th:errors="*{product.id}"></span> 

然後當我回過頭來編輯它成爲選擇,但驗證不工作(product始終實例化,即使選定的ID是null)。

它看起來像一個非常常見的情況(從列表中選擇一個實體),但我找不到任何好看的例子。請分享祕密知識。

+0

你是什麼意思回來編輯它? – 2013-03-05 15:37:05

+0

我使用相同的頁面來創建和編輯Version實體 – 2013-03-05 23:11:58

回答

2

已解決。問題的存在是因爲我沒有重寫equals()hashCode()方法。