Working with form
in Elm without storing raw form state in Elm, aka "Use the Platform".
Before
- Use
value someValue
to set form field value when we render a form (e.g. edit form)- we are now obliged to keep
someValue
in sync with user's input
- we are now obliged to keep
- Use
onInput
msg to updatesomeValue
- store this value in model
- this value may not be the desired type, e.g. storing raw
String
on behalf of aTime.Posix
model state
After
- Use
defaultValue someValue
to set form field value when we render a form (e.g. edit form)- no longer obliged to keep
someValue
in sync with user's input
- no longer obliged to keep
- Use
NativeForm.decoder
anytime to retrieve the form values from browserdocument.forms
- No need for
onInput
nor amsg
for every form field; only do so for fields that really need handling - But forms must be given the
id
attribute and form fields must be given aname
attribute
- No need for
Checkout the demo at https://nativeform.netlify.app and its source code at example subdirectory.
-
Pass the browser
document.forms
into 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.Value
from yourFlags
in 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.documentForms
to 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
id
value -
Always give your form fields a
name
value -
Does not handle
input[type=file]
in a useful manner; manage file uploads by other means. -
All user input values are either
OneValue String
orManyValues (List String)
, includinginput[type=number]
; do your own conversion toInt
orTime.Posix
etc. -
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