Skip to content
Advertisement

Use value of a local variable as global in thymeleaf

I have a variable that is obtain inside each block in thymeleaf. I want to send that variable to a certain method in my controller. The limitation is that the variable is obtain inside a block which makes it local, not accessible global.Hence I get an error while trying to use it. How can I move inside the scope to get the variable so as I can use it global in thymeleaf.

           <form th:action="@{/masomo/somo(date=${dateMpya.date})}" method="POST">
            <select id="date" name="date" required="true">
                <option value="none" selected disabled hidden > 
                    Select a Date     
               </option>   

            <th:block th:each="somoChagua : ${masomoChagua}">
            <option th:each="dateMpya: ${somoChagua}"  th:value="${dateMpya}" th:text="${dateMpya.date}" ></option>
            
            </th:block>

            </select>
            <button type="submit"><i class="fa fa-search"></i> </button>  
            </form>
             

Advertisement

Answer

There can be many different “dateMpya” objects for each “somoChagua”.

But there is only one submit button.

So which “dateMpya” should be used for the submit button value?

I think what you are actually trying to do here is get the value of the “dateMpya” which the user selected in the drop-down. Is that right?

If that’s the case there is no need to add any attributes to the submit button. You would access that value by using the name of the select element, which is “date”.

EDIT: For the same reason you also need to remove the (date=${dateMpya.date}) part of the form action as well. The value selected in the drop-down will automatically be submitted under the name of the select element “date”, it does not need to be specified.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement