Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle errors with HTMX

Tags:

htmx

<form  
 class="" id="form" hx-post="/add/" hx-swap="afterbegin" hx-target="#big_list" hx-trigger="submit">
    <input type="text" name="langue1" >
    <input type="text" name="langue2">
    <div id="errors"></div>
    <button type="submit">GO</button>
</form> 
<div id="big_list"> 
.....
</div>

I have a big list in #big_list, and I want my #form appends only one row when submitted.

How with htmx, can I handle errors and show message in #errors ?

like image 676
jgirardet Avatar asked Sep 06 '25 21:09

jgirardet


1 Answers

If your code raises the errors (validation?), you can change target and swap behavior with response headers.

Response.Headers.Add("HX-Retarget", "#errors"); 
Response.Headers.Add("HX-Reswap", "innerHTML");

If you want to return a status other than 200, you have to tell htmx to accept it. 4xx would normally not do a swap in htmx. In case of validation errors you could use 422.

document.body.addEventListener('htmx:beforeOnLoad', function (evt) {
    if (evt.detail.xhr.status === 422) {
        evt.detail.shouldSwap = true;
        evt.detail.isError = false;
    }
});

It works in htmx 1.8.

If you want to remove the error message on then next sucessfull request, you could use hx-swap-oob. Out of band elements must be in the top level of the response. So the response could look like this:

<div>
    your new row data...
</div>
<div id="errors" hx-swap-oob="true"></div>

Update
You can now use the new powerful extension multi-swap to swap multiple elements arbitrarily placed and nested in the DOM tree.
See

Update
Take a look at the new extension The response-targets Extension.
This extension allows you to specify different target elements to be swapped when different HTTP response codes are received.

like image 147
Mueller-Nico Avatar answered Sep 08 '25 11:09

Mueller-Nico