skip to Main Content

I have a datatable and add item form which shows as a modal ( bootstrap ) I’m using htmx to add an entry and swap the datatable with latest data.

Now, I want to handle things like validation and errors.

How to approach this problem, I want to close modal and show updated table if request was successful, or I want to keep the modal and show form with error messages on modal.

Can i conditionally swap the target ? if xhr.status == 400, swap id_add_form else if xhr.status == 201 modal.close(); swap id_item_list

here is the outline of my code

<!--begin::Card-->
<div class="card" id="user_list_table">
...
    <button
                type="button"
                class="btn btn-primary"
                data-bs-toggle="modal"
                data-bs-target="#modal_add_item"
                hx-get="/add-item"
                hx-target="#add_user_form"
                hx-swap="innerHTML"
                hx-trigger="click">
    Add Item
    </button>

    <div class="modal">
    <form
        id="add_item_form"
        class="form"
        hx-post="/add-item"
        hx-trigger="submit"
        hx-swap="none"
    >
    ...
    </form>
    </div>
    ...

    <div id="item_list">
    ...
    </div>

...
</div>

and js


    document.addEventListener("htmx:afterRequest", function (event) {
    
                if (event.detail.elt == "add_item_form") {
    
                    var form = document.getElementById('add_item_form');
    
                    // if event is 200 ok
                    if (event.detail.xhr.status == 200) {
                        // close modal
                        form.reset();
                        modal.hide();
            }
        }
    }

2

Answers


  1. Chosen as BEST ANSWER

    There is an extention for htmx https://htmx.org/extensions/response-targets/

    which allows us to target different elements for different responses.

    <button hx-post="/register"
            hx-target="#response-div"
            hx-target-5*="#serious-errors"
            hx-target-404="#not-found">
        Register!
    </button>
    

    when combining this with javascript, I could make it work


  2. You can listen to a beforeSwap event on the form. The event.detail will have the shouldSwap attribute which which can conditionally set.

    document.getElementById("add_item_form").addEventListener("htmx:beforeSwap", (event)=>{
        // After server validation
        if (event.detail.xhr.status !== 200) {
            event.detail.shouldSwap = false
            // No need to set new target since the form is already the target
            return
      }
       // Else reset form and hide modal
    })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search