简体   繁体   中英

Spring Boot Thymeleaf Dropdown List

I'm trying to persist values in database from a dropdown list in Spring Boot , thymeleaf but the database is populated with empty values.

Apparently the controller doesn't pass the value.

While I can fetch and display the values in GET but I cannot persist them in POST .

I'm not able to get a clear example from anywhere and even the examples on Thymeleaf are not clear.

Please help with some good example or a solution.

The code is as below.

@Controller
public class HomeController {

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signupPost(@ModelAttribute("user") User user,
        Model model, BindingResult result) {

        if (!result.hasErrors()) {
            userService.saveUser(user);
        }
        return "redirect:/";

    }

}

The User class is as below

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id", nullable = false, updatable = false)
    private Long userId;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "award_partner_id")
    private AwardPartner awardPartner;

    getters and setters....
}

The HTML snippet is here:

<!--Award Partner-->
<div class="form-group">
    <label class="col-md-4 control-label">Award Partner</label>
    <div class="col-md-6 selectContainer">
        <div class="input-group">
            <span class="input-group-addon"><i
                class="glyphicon glyphicon-list"></i></span> 
                <select name="awardPartner" roleId="awardPartner" id="awardPartner"
                th:field="*{awardPartner}" class="form-control selectpicker">
                <option value="">Select Award Partner</option>
                <option th:each="awardPartner : ${awardPartners}"
                    th:value="${awardPartner.id}"
                    th:text="${awardPartner.title}"></option>
            </select>
        </div>
    </div>
</div>

<!-- end snippet -->

In your form tag, I think there is th:object="user" .

In your select tag, there is th:field="*{awardPartner}" . It means that you will put the selected value (the value of the selected option tag) in the field awardPartner of the object user. This field awardPartner is of type AwardPartner

In the option values, you have got an id (int or string?) as value but not an object of type AwardPartner

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