Lukas Novicky
Lukas Novicky

Reputation: 952

spring boot passing parameter from list to controller

I have a list of objects in my view:

<tbody>
    <tr th:each="object : ${myObjects}">
        <td><span th:text="${object.id}"> </span></td>
        <td><span th:text="${object.name}"> </span></td>
        <td><span th:text="${object.address}"></span></td>
        <td>
            <a href="#" data-toggle="modal" data-target="#ADD_SOME_INFO_MODAL">
                <i class="fas fa-plus"></i>
            </a>
        </td>
    </tr>
</tbody>

button in last column starts a modal. In modal I can add some value for a record:

    <form th:action="@{/add-data}"
          method="post"
          class="form">
        <input name="NEW-DATA">
        <div class="modal-footer">
            <button name="login-submit"
                    type="submit">
                <i class="fas fa-plus"></i>
            </button>
        </div>
    </form>

and this is my controller:

@PostMapping("/add-data")
public String addData(@RequestParam String URL) {
   ... do logic...
    return "index";
}

I get correct input value in my addData() method, but I cannot find a way to pass an id from object that was clicked on a list in a first place. I need this object id to be able to correctly store additional information. I think of maybe doing separate page for adding this information for each record but that seems not right with easy and small eddits/additions. Is there any way to be able to add edits on modals in Spring Boot? I was not able to find proper answer for that anywhere, so here I am.

Upvotes: 0

Views: 283

Answers (1)

KevinB
KevinB

Reputation: 1202

You are passing the URL param to the Controller, simply pass the value to the controller in the same way.

The glue you need is in JavaScript. When the user clicks the button to open the modal, use JS to copy the value to a hidden input field on the modal Form tag. When the form is submitted, then your copied value will also be submitted and available in your controller. You can write the hidden input field with a dummy value and then change the value via JS.

 <input type="hidden" id="myHiddenField" name="myHiddenField" value="CHANGE_ME">

Your button to open the modal can look like this:

<i class="fas fa-plus" onclick="document.getElementById('myHiddenField').value='${object.id}'"></i>

Now hidden field in modal form has the value you want.

Upvotes: 1

Related Questions