Skip to content

Commit

Permalink
Add reference to hx-preserve to the example at "Preserving File Input…
Browse files Browse the repository at this point in the history
…s after Form Errors" (#2474)

* Add reference to hx-preserve to file-upload-input.md

* Address review feedback: add more description behaviour when using .
  • Loading branch information
Matt544 authored Dec 18, 2024
1 parent 7cd5605 commit 1814f99
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion www/content/examples/file-upload-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,19 @@ template = "demo.html"

When using server-side error handling and validation with forms that include both primitive values and file inputs, the file input's value is lost when the form returns with error messages. Consequently, users are required to re-upload the file, resulting in a less user-friendly experience.

To overcome the problem of losing file input value in simple cases, you can adopt the following approach:
To overcome the problem of losing the file input value, you can use the `hx-preserve` attribute on the `input` element:

```html
<form method="POST" id="binaryForm" enctype="multipart/form-data" hx-swap="outerHTML" hx-target="#binaryForm">
<input hx-preserve id="someId" type="file" name="binaryFile">
<!-- Other code here, such as input error handling. -->
<button type="submit">Submit</button>
</form>
```

If the file field is returned with errors on it, they will be displayed provided that `hx-preserve` was placed in the `input` only and not the element that would show the errors (e.g. `ol.errorlist`). If in a given circumstance you want the file upload input to return *without* preserving the user's chosen file (for example, because the file was an invalid type), you can manage that on the server side by omitting the `hx-preserve` attribute when the field has the relevant errors.

Alternatively, you can preserve file inputs after form errors by restructuring the form so that the file input is located outside the area that will be swapped.

Before:

Expand Down

0 comments on commit 1814f99

Please sign in to comment.