Add reference to hx-preserve to the example at "Preserving File Inputs after Form Errors" (#2474)

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

* Address review feedback: add more description behaviour when using .
This commit is contained in:
Matt544 2024-12-18 13:09:45 -07:00 committed by GitHub
parent 7cd560571d
commit 1814f99023
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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: