Search code examples
springspring-bootthymeleafbootstrap-modal

Spring Boot opening a modal if there are errors using Thymeleaf


I'm trying to validate a modal, and right now I can't make it open using Thymeleaf. I have a table, and for each row I have a different modal, the modal ID takes its name myModal + the id of the object from the table

<div class="modal" th:id="*{'myModal'+{object.ID}}" tabindex="-1" role="dialog" aria-labelledby="#myModal" aria-hidden="true">

If there are errors for the object I'm updating in the modal (if I receive the param err) I want to make the modal open. I can validate the object and everything, but I don't know how to use Thymeleaf to take the ID of that object that I validated I can make the modal open when there are errors only if I hard-code the ID - for example the ID 20

<script th:inline="javascript" th:if="${param.err}">$("#myModal20").modal("show");</script>

In the Controller when I verify if it has errors or not, I can send a model attribute "id-modal" and I think I can put it in the place of the hard-coded '20' using Thymeleaf, but I don't know how, can someone help? I keep receiving the error in the browser conole when I'm trying to do it "Uncaught Error: Syntax error, unrecognized expression: 'myModal'+${id-modal}"


Solution

  • You shouldn't use a dash - in your model attributes. The expression ${id-modal} means to subtract the value of modal from id -- literally the math expressions id - modal. Once you've changed that (I will use modalId in this example), your JavaScript could look something like this. (Also, see the documentation on JavaScript inlining.)

    <script th:inline="javascript" th:if="${param.err}">
      let id = /*[[${modalId}]]*/ 0;
      $("#myModal" + id).modal("show");
    </script>
    

    (I'd probably also surround it with the jQuery document ready, but you might not want/need that.)