Working with form in Elm without storing raw form state in Elm, aka "Use the Platform".
Before
- Use
value someValueto set form field value when we render a form (e.g. edit form)- we are now obliged to keep
someValuein sync with user's input
- we are now obliged to keep
- Use
onInputmsg to updatesomeValue- store this value in model
- this value may not be the desired type, e.g. storing raw
Stringon behalf of aTime.Posixmodel state
After
- Use
defaultValue someValueto set form field value when we render a form (e.g. edit form)- no longer obliged to keep
someValuein sync with user's input
- no longer obliged to keep
- Use
NativeForm.decoderanytime to retrieve the form values from browserdocument.forms- No need for
onInputnor amsgfor every form field; only do so for fields that really need handling - But forms must be given the
idattribute and form fields must be given anameattribute
- No need for
Checkout the demo at https://nativeform.netlify.app and its source code at example subdirectory.
-
Pass the browser
document.formsinto your Elm app through Flags<script> var app = Elm.Main.init({ node: document.getElementById('myapp'), flags: { documentForms: document.forms // <-- important! } }) </script> -
Store the
documentForms : Json.Encode.Valuefrom yourFlagsin yourModel -
Wire up any (or many) events, e.g.
form [ on "change" OnFormChange ]orinput [ onInput (always OnFormChange) ] -
And call
Json.Decode.decodeValue (NativeForm.decoder formId) model.documentFormsto get the list of form field name and values.
-
No matter how many fields you have, you only need one
Msg -
Always give your form an
idvalue -
Always give your form fields a
namevalue -
Does not handle
input[type=file]in a useful manner; manage file uploads by other means. -
All user input values are either
OneValue StringorManyValues (List String), includinginput[type=number]; do your own conversion toIntorTime.Posixetc. -
When using this library, your form id and field names are "stringly typed". You should use a custom type to manage a fixed set of form fields, but this library does not require you to do so.
-
Do not deal with the
List (String, Value)returned fromNativeForm.decoder. Instead, you should parse them into a value of your desired type. e.g.parseDontValidate : List ( String, NativeForm.Value ) -> Result String UserInfo