Skip to content

Instantly share code, notes, and snippets.

@pablohirafuji
Created June 23, 2016 15:23
Show Gist options
  • Save pablohirafuji/46c452341853f8693dee5fa90c877731 to your computer and use it in GitHub Desktop.
Save pablohirafuji/46c452341853f8693dee5fa90c877731 to your computer and use it in GitHub Desktop.
Elm simple form example
module Main exposing (..)
import Http
import Task
import Html.App as Html
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Form exposing (Form)
import Form.Validate as Validate exposing (..)
import Form.Input as Input
-- your expected form output
type alias Foo =
{ bar : String
, baz : Bool
}
-- Add form to your model and msgs
type alias Model =
{ form : Form () Foo }
type Msg
= NoOp
| FormMsg Form.Msg
| Submit Foo
-- Setup form validation
init : ( Model, Cmd Msg )
init =
( { form = Form.initial [] validate }, Cmd.none )
validate : Validation () Foo
validate =
form2 Foo
(get "bar" email)
(get "baz" bool)
-- Forward form msgs to Form.update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg ({ form } as model) =
case msg of
NoOp ->
( model, Cmd.none )
FormMsg formMsg ->
( { model | form = Form.update formMsg form }, Cmd.none )
Submit foo ->
( model, submitFoo foo ) -- Handle foo submit
-- Render form with Input helpers
view : Model -> Html Msg
view { form } =
Html.form
[ Html.Events.onSubmit (onSubmitMsg form) ]
[ Html.map FormMsg (formView form) ]
formView : Form () Foo -> Html Form.Msg
formView form =
let
-- error presenter
errorFor field =
case field.liveError of
Just error ->
-- replace toString with your own translations
div [ class "error" ] [ text (toString error) ]
Nothing ->
text ""
-- fields states
bar =
Form.getFieldAsString "bar" form
baz =
Form.getFieldAsBool "baz" form
in
Html.div []
[ label [] [ text "Bar" ]
, Input.textInput bar []
, errorFor bar
, label []
[ Input.checkboxInput baz []
, text "Baz"
]
, errorFor baz
, button [ type' "submit" ]
[ text "Submit" ]
]
onSubmitMsg form =
case Form.getOutput form of
Nothing ->
FormMsg Form.Submit
Just validForm ->
Submit validForm
submitFoo : Foo -> Cmd Msg
submitFoo foo =
let x = Debug.log "Submited foo" foo
in Cmd.none -- See http://package.elm-lang.org/packages/evancz/elm-http/3.0.1/Http to handle the request
main : Program Never
main =
Html.program
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment