1

I have following problem: I have two buttons accept and decline. In my Controller-Class i want to know, which button were clicked. i solved this in a way, which is bad i think. Each button got his own form, so that i can see which button was triggered.

<form method="post" action="save">
    <input type="hidden" name="accept" th:value="true" />
    <button type="submit" name="accepted" id="modalAcceptTrigger"
        class="btn btn-lg myBtn_accept" title="Auftrag annehmen">
        Annehmen
    </button>
</form>
<form method="post" action="save">
    <input type="hidden" name="decline" th:value="false" />
    <button type="submit" name="declined" id="modalDeclineTrigger"
        class="btn btn-lg myBtn_decline" title="Auftrag abgelehnt">
        Ablehnen
    </button>
</form>

In my class i get the hidden input field and know which button was pressed.

@PostMapping("/save")
public String saveJob(@RequestParam(value = "accept") Boolean accept) {

    if (accept) {
        ...
    } else {
        ...
    }
}

My question is now: How can i make only one form and get the triggered button in my java class? Does anybody know and can help me?

Anton Styopin
  • 753
  • 4
  • 17
  • 35

2 Answers2

2

I would have just have one form with 2 buttons as you say. Before submitting the form I would have a js function executed that changes the input hidden value decline/accept. So I would

<form method="post" id="save-form" action="save">
    <input type="hidden" id="action" name="action" />
    <button type="button" name="declined" id="modalDeclineTrigger"
        class="btn btn-lg myBtn_decline" title="Auftrag abgelehnt">
        Ablehnen
    </button>
    <button type="button" name="accepted" id="modalAcceptTrigger"
        class="btn btn-lg myBtn_accept" title="Auftrag annehmen">
        Annehmen
    </button>
</form>

And the js: (That should be place within an on document ready)

<script>
$('#modalAcceptTrigger').on('click', function(){$('#action').val('decline'); $('#save-form').submit();});
$('#modalDeclineTrigger').on('click', function(){$('#action').val('accept'); $('#save-form').submit();});
</script>

And the controller should expect an ENUM {decline, accept} rather than a boolean

kimy82
  • 4,069
  • 1
  • 22
  • 25
1

Leave just one form with hidden input

<input type="hidden" name="userAction" th:value="true" />

add a script to set the userAction to true or false depending on clicked option before submitting form (see e.g. here).

and in the controller

@PostMapping("/save")
public String saveJob(@RequestParam(value = "userAction") Boolean accept) 
Community
  • 1
  • 1
StanislavL
  • 56,971
  • 9
  • 68
  • 98