|
3 | 3 | external myForm: DOMAPI.htmlFormElement = "myForm" |
4 | 4 |
|
5 | 5 | let formData = FormData.make(~form=myForm) |
6 | | -let phone: null<string> = formData->FormData.get("phone") |
7 | | -let image: null<FileAPI.file> = formData->FormData.getFile("image") |
| 6 | + |
| 7 | +// Get a form field - returns formDataEntryValue which could be string or File |
| 8 | +let phoneEntry: null<FetchAPI.formDataEntryValue> = formData->FormData.get("phone") |
| 9 | + |
| 10 | +// Decode the entry to handle both string and File cases |
| 11 | +let _ = switch phoneEntry->Null.toOption { |
| 12 | +| None => Console.log("No phone field") |
| 13 | +| Some(entry) => |
| 14 | + switch entry->FormDataEntryValue.decode { |
| 15 | + | FormDataEntryValue.String(value) => Console.log(`Phone: ${value}`) |
| 16 | + | FormDataEntryValue.File(file) => Console.log(`Unexpected file: ${file.name}`) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// Get all values for a field (useful for multi-select or multiple file inputs) |
| 21 | +let allImages: array<FetchAPI.formDataEntryValue> = formData->FormData.getAll("images") |
| 22 | + |
| 23 | +// Process all entries |
| 24 | +let _ = allImages->Array.forEach(entry => { |
| 25 | + switch entry->FormDataEntryValue.decode { |
| 26 | + | FormDataEntryValue.String(value) => Console.log(`String value: ${value}`) |
| 27 | + | FormDataEntryValue.File(file) => Console.log(`File: ${file.name}`) |
| 28 | + } |
| 29 | +}) |
| 30 | + |
| 31 | +// Create formDataEntryValue from string or file |
| 32 | +let stringEntry = FormDataEntryValue.fromString("test value") |
| 33 | +let fileEntry = FormDataEntryValue.fromFile(File.make(~fileBits=[], ~fileName="test.txt")) |
| 34 | + |
| 35 | +// Iterate over all entries in the FormData |
| 36 | +let entries: Iterator.t<(string, FetchAPI.formDataEntryValue)> = formData->FormData.entries |
| 37 | +let _ = entries->Iterator.forEach(((key, value)) => { |
| 38 | + switch value->FormDataEntryValue.decode { |
| 39 | + | FormDataEntryValue.String(s) => Console.log(`${key}: ${s}`) |
| 40 | + | FormDataEntryValue.File(f) => Console.log(`${key}: [File] ${f.name}`) |
| 41 | + } |
| 42 | +}) |
0 commit comments