2013-06-12 22 views
0

這裏下拉列表是棘手的問題,我有未來JSPX:Spring MVC。填充來自不同對象的

<form:form modelAttribute="employee" id="employeeUpdateForm" method="post"> 
    <form:select path="departmentId">   
    <form:options items="${departments}" /> 
</form:select> 

<button type="submit">Save</button> 
    <button type="reset">Reset</button> 
</form:form> 

和我updateForm方法:

@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET) 
public String updateForm(@PathVariable ("id") Long id, Model uiModel) { 
uiModel.addAttribute("employee", employeeService.findById(id)); 

List<Department> departments = employeeService.getAllDepartments(); 
uiModel.addAttribute("department", departments); 

return "staff/update"; 
} 

「部門」 有兩個字段:DepartmentID的(int)和divisionName (串)。因此,「員工」和「部門」是兩個不同的對象,我希望能夠使用來自「部門」的字符串表示填充與「員工」(departmentId)相關的字段。他們的部門是彼此匹配的。一旦某個部門被選中,其ID將被放入employee.departmentId。

在此先感謝!

+0

您是否遇到一些問題?什麼是錯誤或問題? – Usha

+0

問題是我不知道如何去執行它,這就是問題 – orionix

回答

3

我不太確定updateForm方法在控制器中的作用。如果這是加載初始表單的那個,那麼模型屬性名稱應該是departments而不是department。這些是updateForm方法中的更改。 我創建了一個條目集,它以departmentId作爲值並將divisionName作爲關鍵字使用哈希映射。

Set<Map.Entry<String, String>> departments; 
uiModel.addAttribute("employee", employeeService.findById(id)); 
List<Department> departmentsList = employeeService.getAllDepartments(); 
final Map<String, String> departmentsMap = new HashMap<String, String>(); 
if(departmentsList != null && !departmentsList.isEmpty()){ 
    for(Department eachDepartment : departmentsList){ 
     if(eachDepartment != null){ 
      departmentsMap.put(eachDepartment.getDivisionName(), eachDepartment.getDepartmentId()); 
     } 
    } 
    } 
    departments = departmentsMap.entrySet(); 
    uiModel.addAttribute("departments", departments); 

現在在jsp中顯示這個。

<form:form modelAttribute="employee" id="employeeUpdateForm" method="post"> 
    <form:select path="departmentId">   
    <form:options items="${departments}" var="department" itemValue="value" itemLabel="key"/> 
    </form:select> 
<button type="submit">Save</button> 
<button type="reset">Reset</button> 
</form:form> 

valuekey對應於departmentsMap的鍵值對,其在控制器填充。值被綁定到departmentId,並且divisionName將顯示在下拉列表中。

我希望這是你想要的。

+0

是的,你已經幫助了我,你的提議絕對是毫無疑問的合適!這是我一直在尋找的!謝謝你,Usha。 :設置>部門;最終Map departmentsMap = new HashMap () - 因爲departmentId是Long。 – orionix