How to store value in array type variable in thymeleaf

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

How to store value in array type variable in thymeleaf

ashwini
This is alias array which one I am processing below but in hidden filed all alias name want to comma separated string.
<th:block th:each="aliasLists : ${aliasArr}">
                               
                                [[${aliasLists.alias}]]
                                <span class="close" onclick="RemoveList(this)" > x

                               
                   </th:block>

Now How i can to convert all value of [[${aliasLists.alias}]]  and convert into string and assign below hidden value?
<input id="alias" name="alias" type="hidden" value=""> 
Reply | Threaded
Open this post in threaded view
|

Re: How to store value in array type variable in thymeleaf

Reiju
1. First of all u need some converter @Components (org.springframework.core.convert.converter.Converter)
- YourEntityToStringConverter
- StringToYourEntityConverter

For example ur entity has ID:
In YourEntityToStringConverter u can return id value.
And in StringToYourEntityConverter u can go to service with this id.

@Component
public class StringToYourEntityConverter implements Converter<String, YourEntity> {
   
    @Autowired
    private YourEntityService yourEntityService;
   
    @Override
    public YourEntity convert(String s) {
        //don't forget about NumberFormatException
        return yourEntityService.findById(Long.valueOf(s));
    }
}

2. HTML (use th:attr)
<div th:each="o : ${someArray}"
         th:text="${o.name}"
         th:attr="data-value=${o.id}"
         onclick="doSomething(this)">
</div>
<input id="array" type="hidden" th:field="*{array}">

3. JS (simple concatenation)
let doSomething = function (elem) {
        let value = elem.getAttribute('data-value');

        let field = document.getElementById('array');
        let currentValue = field.value;
        field.value = currentValue === '' ? value : (currentValue + ',' + value);
}