Here is tricky issue, I have next jspx:

<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>

and my updateForm method:

@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";
}

"department" has two fields: departmentId (int) and divisionName (String).

So, "employee" and "department" are two different objects, I would like to have ability to populate field related to "employee" (departmentId) with string representations from "department". Their departmentId match one another. Once certain department is chosen its id is putting to employee.departmentId.

Thanks in advance!

有帮助吗?

解决方案

I was not quite sure what the updateForm method does in the controller. If that is the one that loads the initial form then the model attribute name should be departments instead of department. These are the changes in the updateForm method. I created an entry set which takes a hash map with the departmentId as value and divisionName as key.

 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);

Now to display this in the 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>

The value and key corresponds to the key value pairs of the departmentsMap which is populated in the controller. The value gets bound to the departmentId, and the divisionName will be shown in the dropdown.

I hope this is what you want.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top