Search code examples
htmlspringthymeleafhandsontable

How to insert data into a handsontable script in Spring


I use Handsontable in my project. I needed to insert data in a table from my database in Spring. I know how to do it with Thymeleaf :

 <tr th:each="row : ${tariffs}">
        <td th:text="${row.warehouse}"></td>
 </tr>

But how I can insert or get data from the js script?

It's my code with the table, I think we can add data in const data with cycle help


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.css" rel="stylesheet">
</head>
<body>

<div id="tariffTable" th:each="row : ${tariffs}"></div>

    <script>
        const data = [
          ['1234', Als, Town1],
          ['1235', Bas,Town2],
          ['1236', Oxa, Town3]
        ];

        const container = document.getElementById('tariffTable');
        const hot = new Handsontable(container, {
          data: data,
          rowHeaders: true,
          colHeaders: true,
            colHeaders: [
             'Tariff',
             'Warehouse',
             'Town'
            ],
          manualRowMove: true,
          manualColumnMove: true,
          contextMenu: true,
          filters: true,
          dropdownMenu: true,
        });
    </script>
</body>
</html>

And how we can get data if I insert rows on the web-interface?


Solution

  • I used this logic and its work. Here we get data from spring and parse this data in js, after that we can insert this data in the table

    let dataFromSpring = [[${tariffs}]];
        let dataObj = [];
        for(let obj of dataFromSpring){
            let object = {
                            warehouse: obj["tariff"],
                            fmWarehouse: obj["warehouse"],
                            town: obj["town"],
                        };
        dataObj.push(object);
        }