Spring Thymeleaf send object from select option

南楼画角 提交于 2021-02-08 08:12:11

问题


I have a problem with sending an object with values from inputs fields to controller in add user method. It generates an error ("Bad request") caused by a select box. Tables connection works well, I can print a list of users and add user window, but adding a user is not working.

Code:

Entity class fragment (further are getters and setters with hibernate annotations)

@Entity
@Table(name = "user_emes")
public class UserEmes implements java.io.Serializable {

private long idUser;
private String code;
private String name;
private String surname;
private Permission permission; -> object from another Table called "permissions"
private String login;
private String password;
private boolean isActive;
...
@ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_permissions")
    public Permission getPermission() {
        return permission;
    }

Controller

@RequestMapping(value = "/addUser", method = RequestMethod.GET)
    public String userForm(Model model)  {
        model.addAttribute("user", new UserEmes());
        return "index";
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ModelAndView addUser(@ModelAttribute("user") UserEmes userEmes)  {
        emesUserService.addUser(userEmes);
        return new ModelAndView("redirect:/all-users");
    }

Html (select box):

<div class="form-group input-group has-feedback">
<span class="input-group-addon"> <label>UPRAWNIENIA</label>
</span> 
<div
th:if="${permissionsList != null and not #lists.isEmpty(permissionsList)}">
<select class="form-control" name="permission">
<option th:each="dropDownItem : ${permissionsList}"
    th:value="${dropDownItem.getIdPermission()}"
    th:text="${dropDownItem.toString()}" />
    </select>
</div>

Some screenshots: List of users Add user

This is how it looks. As you can see a list of Permissions is correctly loaded to select box, and when u fill rest of the fields it shows "Bad request" error on blank screen.

Is in the thymeleaf possibility to do such things? I am waiting for your answers.


回答1:


You should use tymeleaf backbean binding for that not raw ids

<select th:object="${user}"  th:field="*{permission} class="form-control" name="permission">
<option th:each="dropDownItem : ${permissionsList}"

    th:value="${dropDownItem.getIdPermission()}"
    th:text="${dropDownItem.toString()}" />
    </select>

This way you will isntruct thymeleaf to bind permission property to given select field (and options). Notice th:object, th:field and * operator, this is not a typo, star should be used here insteed of $.

Check documentation for Spring-Thymeleaf integration, it is described there http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html and check how to create select inputs.

PS: Here is a sample of select field from one of projects of mine

<div class="form-group" th:classappend="${#fields.hasErrors('city') ? 'has-error' : _}">
            <label class="control-label" for="place-city">City</label>
            <select class="form-control" id="place-city" th:field="*{city}">
                <option value="" selected>----SELECT CITY----</option>
                <option th:each="city : ${allCities}" th:value="${city.id}" th:text="${city.name}"></option>
            </select>
            <span class="help-block" th:each="msg : ${#fields.errors('addressLine')}" th:text="${msg}">Some error message for this field</span>
        </div>

Controller side:

@PostMapping(value = "/add")
@Transactional
public String addPlacePost(@Valid final Place place, BindingResult placeValidation, Model model) {

Where root entity is Place that have property of private City city.




回答2:


I just do this.. I set the default value of the object to a new instance, then set the value of the option as the id of the object. but of course depending on your usage you may have to use that id to find the object.

Controller:

@Entity
@Table(name = "user_emes")
public class UserEmes implements java.io.Serializable {

private long idUser;
private String code;
private String name;
private String surname;
private Permission permission = new Permission();
private String login;
private String password;
private boolean isActive;
 ...

Thymeleaf:

 <select th:field="${userEmes.permission.id}" >
     <option th:each="perm : ${perms}" th:value="${perm .id}" th:text="${perm.name}"></option>
 </select>



回答3:


I did everything including registering an object formatter. But only the above solution(@Troll173) worked for me. I modified the th:field to * version to maintain consistency inside form tag.

<select th:field="*{permission.id}" >
     <option th:each="perm : ${perms}" th:value="${perm .id}" th:text="${perm.name}"></option>
 </select>


来源:https://stackoverflow.com/questions/47014727/spring-thymeleaf-send-object-from-select-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!