Skip to content

Instantly share code, notes, and snippets.

@etaque
Forked from nmk/Main.elm
Created February 1, 2017 06:17
Show Gist options
  • Save etaque/9f8d50a4a9de0a105adcfaff0426d410 to your computer and use it in GitHub Desktop.
Save etaque/9f8d50a4a9de0a105adcfaff0426d410 to your computer and use it in GitHub Desktop.
module Main exposing (..)
import Form exposing (..)
import Form.Input as Input
import Form.Validate exposing (..)
import Html exposing (..)
type Color
= Red
| Green
| Blue
colors : List Color
colors =
[ Red
, Green
, Blue
]
type alias Output =
List Color
type alias Model =
{ outputForm : OutputForm }
type MyError
= InvalidColor
type alias OutputForm =
Form MyError Output
checkboxList : List ( String, value ) -> Validation e (List value)
checkboxList items =
let
validateItem ( key, value ) =
field key
(bool
|> andThen
(\checked ->
if checked then
succeed (Just value)
else
succeed Nothing
)
)
in
sequence (List.map validateItem items)
|> Form.Validate.map (List.filterMap identity)
validate : Validation e Output
validate =
let
colorsOptions =
List.map (\c -> ( toString c, c )) colors
in
field "colors" (checkboxList colorsOptions)
sequence : List (Validation e a) -> Validation e (List a)
sequence validations =
List.foldr (Form.Validate.map2 (::)) (Form.Validate.succeed []) validations
update : Form.Msg -> Model -> Model
update msg model =
let
_ =
Debug.log "form msg" msg
in
{ model | outputForm = Form.update msg model.outputForm }
initialModel : Model
initialModel =
{ outputForm = Form.initial [] validate }
view : Model -> Html Form.Msg
view { outputForm } =
div
[]
[ Input.dumpErrors outputForm
, pre [] [ text (toString (Form.getOutput outputForm)) ]
, div []
(colors
|> List.map
(\color ->
label
[]
[ Input.checkboxInput (Form.getFieldAsBool ("colors." ++ toString color) outputForm) []
, text (toString color)
]
)
)
]
main : Program Never Model Form.Msg
main =
beginnerProgram
{ model = initialModel
, update = update
, view = view
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment