Search code examples
springthymeleaf

Load a selectbox from a persisted list of objects and use that selectbox value to load the full object from the selectbox


I have a Hibernate table with my business object : campaign (Id, name, description, ...). Using Thymeleaf, I am preloading a select box with the campaign names. Once the user selects a name and I am trying to submit the campaign Id to the controller or since I have an arrays with all campaigns object, I would only pass the selected object from the selectbox.

What do you think would be the best way to do this ?

<div class="form-group blu-margin">
<form th:object="${campaign}" th:action="@{/campaign}" method="post">
    Select the campaign you would like to execute : 
    <select
        class="form-control" id="dropCampaign" name="dropCampaign">
        <option value="0">select campaign</option>
        <option th:each="INcampaign : ${campaigns}"
                th:value="${INcampaign.id}" 
                th:text="${INcampaign.name}">
        </option>
    </select>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>


Solution

  • Reading various articles and trying different things, I think I got it. Sharing my solution in case it can help someone. The trick is to add id and name in the select tag. Then of course, in your controller you need to add @RequestParam Long id in your method signature.

    But note this is not the usual way to do this. The more standard way is to call a URL such as /campaign/{id}/edit. But I wasn't sure about the security because not all users have access to all the campaigns so I didn't want to expose the URL to this edit possibility (even if I am sure you can secure this somehow). For me, that way seems easier.

    <form name="f" th:action="@{/campaign}" th:object="${campaign}" method="post">
    <select id="id" name="id">
        <option value="0">select campaign</option>
        <option th:each="campaign : ${campaigns}"
                th:value="${campaign.id}" 
                th:text="${campaign.name}"
                >
        </option>
    </select>
    <button type="submit" class="btn btn-primary">Submit</button>