简体   繁体   中英

In Thymeleaf, how can I choose the th:selected value for an HTML selector based on the current model object?

From the following controller, I pass a list of resource values, ie serviceRequestList into the model, which I then bind an HTML selector (drop-down menu). On this page, however, exists a single object, ServiceRequestDO . I want the selector to default to the value of the present object, so that when changes are saved the user doesn't have to remember what all the values initially were and then reset them. Makes sense, right? Is there some Thymeleaf condition that will match the value of the present model object for some field to the selector that should be selected by default?

ServiceRequestController:

@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    String GetEditDetails(Model model, Principal principal, @PathVariable("id") Long id, @Valid @ModelAttribute(value = "requestModel") RequestModel requestModel, BindingResult bindingResult, RedirectAttributes redirectAttributes)
    {
        UserDO currentUser = userRepository.findOneByInitialName(principal.getName());

        // Redirect to index if user is not a manager
        if (currentUser.getRole() != Role.MANAGER) {
            return "redirect:/index";
        }

        ServiceRequestDO service = serviceRequestRepository.findById(id);
        model.addAttribute("service", service);

        model.addAttribute("currentUser", currentUser);
        model.addAttribute("requestModel", new RequestModel());

        List<ServiceRequestTypeResource> serviceRequestList = serviceRequestTypeRepository.findAll();
        List<SubServiceRequestTypeResource> subServiceRequestTypeList = subServiceRequestTypeRepository.findAll();
        List<ServiceLineTypeResource> serviceLineList = serviceLineRepository.findAll();
        List<ProductTypeResource> productList = productRepository.findAll();
        List<CustomerNameTypeResource> customerNameList = customerNameRepository.findAll();
        List<LocalTeamTypeResource> localTeamList = localTeamRepository.findAll();

        serviceRequestList.sort(null);
        subServiceRequestTypeList.sort(null);
        serviceLineList.sort(null);
        productList.sort(null);
        customerNameList.sort(null);
        localTeamList.sort(null);

        /* Drop-Down List */
        model.addAttribute("serviceRequestList", serviceRequestList);
        model.addAttribute("subServiceRequestList", subServiceRequestTypeList);
        model.addAttribute("serviceLineList", serviceLineList);
        model.addAttribute("productList", productList);
        model.addAttribute("customerNameList", customerNameList);
        model.addAttribute("localTeamList", localTeamList);

        return "edit";
    }

HTML:

<tr>
   <td>
      <label rel="tooltip"
         title="" data-placement="bottom" data-html="true">Service Request Type</label>
   </td>
   <td>
      <select th:name="*{serviceRequestType}">
         <option th:each="serviceRequestItem : ${serviceRequestList}"
            th:value="${serviceRequestItem}"
            th:text="${serviceRequestItem}"
            th:selected="${service.serviceRequestType}">
         </option>
      </select>
   </td>
</tr>

With the template above, the selector just defaults to the bottom value in the list, regardless of the present object model's value for ${service.serviceRequestType} , for example.

If I understand everything correctly, I would go like that (created a simple example):

@GetMapping("/test/{id}")
public String test(Model model, @PathVariable("id") long id) {
    //This part represent your serviceRequestRepository.findById(id);
    User requestedUser = new User(id, "User " + id);
    model.addAttribute("requestedUser", requestedUser);

    //List of users represent your serviceRequestTypeRepository.findAll();
    List<User> users = new ArrayList<>();
    users.add(new User(1, "User 1"));
    users.add(new User(2, "User 2"));
    users.add(new User(3, "User 3"));

    model.addAttribute("users", users);

    return "test";
}

And your select looks like that:

<select th:name="*{requestedUser}">
  <option th:each="user : ${users}"
     th:value="${user.id}"
     th:text="${user.name}"
     th:selected="${requestedUser.id == user.id}">
  </option>
</select>

If you enter now http://localhost:8080/test/2 the second user is selected:

<option value="1">User 1</option>
<option selected="selected" value="2">User 2</option>
<option value="3">User 3</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM