Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active Jul 20, 2020
Embed
What would you like to do?
{-| Maybe like how data from remote server can be modelled with 4 states `krisajenkins/remotedata`
perhaps form input can be modelled similarly too, giving us a convenient way to work with them
`err` stores validation errors for the form values, e.g. Dict String String
`a` stores the raw value from user input, e.g. Dict String String
`b` is the data type that we expect to wield if `a` is valid, e.g. API.CreateUser.Input
-}
type FormData err a b
= NotValid a err
| Valid a b
| Submitted a b
{-| a standard helper function to get that raw values, e.g. for rendering as html
-}
raw : FormData err a b -> a
{-| a standard helper function to get that err values, e.g. for rendering error messages in form html
-}
err : FormData err a b -> Maybe err
{-| a standard helper function to move `Valid` to `Just (Submitted...)`
otherwise, return `Nothing` if it was `NotValid` or `Submitted`
-}
submit : FormData err a b -> Maybe (FormData err a b)
--- Main.elm
{-| A custom function for each form of the app
update raw value `a` to store the values as-is and values are valid to create a `b` then we should return `Valid a b`
-}
updateUserProfileForm : FormData err a b -> String -> String -> FormData err a b
updateUserProfileForm oldForm fieldName inputValue =
{-|
Our app's `view` can
1. enable buttons only for `Valid` variant
1. show `Processing...` when in the `Submitted` variant
1. each field can thus do something like `onInput (OnUpdateUserProfile "name")`
then our `update` can also be ...
-}
update msg model =
case msg of
OnUpdateUserProfile fieldName inputValue ->
let
newForm =
updateUserProfileForm model.form fieldName inputValue
in
({ model | form = newForm }, Cmd.none)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment