1
votes

I'm using Spring boot + thymeleaf and I'm trying to set the default value of a select element in order to show the selected object that is stored in database (edit form).

To do that, from the controller, I insert into the model the entity with its values, but, when I try to set the default value of the select, it always gets the first option.

This is the code:

    <select class="selectpicker"
        id="alarmPeriod" name="alarmPeriod"                                                     
        th:selected="${alarm.alarmPeriod}" 
        th:value="${alarm.alarmPeriod}"> 

        <option th:each="period:${periods}" 
            th:value="${period}" th:text="${period}">
        </option></select>

I have tried with th:field="*{alarm.alarmPeriod}" but the thymeleaf processor crash.

How could I set the default value of the select with my stored entity value?

PD: alarm is my entity and alarmPeriod is an attribute of alarm.

2
You have to add th:selected on the option, not on the select - Ayrton
@ayrton that only shows the last option of the select, but it is not the stored value that I want to show. - tovarichML
You want to mark the right option as selected, right? Then you should add th:selected to the option with an expression that evaluates to true or false depending on your alarmPeriod - Ayrton
@ayrton, that works! thanks a lot. - tovarichML

2 Answers

1
votes

selected is an attribute for the option tag. Since you're trying to mark one of the options as selected, you must add the th:selected attribute to your options, with an expression that will evaluate to true or false depending on your alarmPeriod.

0
votes

The selected option should be put as an option like you would do with with an htnl select tag, the following piece of code should work

    <select class="selectpicker"
    id="alarmPeriod" name="alarmPeriod"> 
    <option value="${alarm.alarmPeriod}" selected="selected">
         ${alarm.alarmPeriod} 
    </option>

    <option th:each="period:${periods}" 
        th:value="${period}" th:text="${period}">
    </option></select>