<commit_before><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<?asciidoc-toc?>
<?asciidoc-numbered?>

<article lang="en">
<section id="forms_forms">
<title>Forms</title>
<simpara>I&#8217;ve mentioned the boundary issue already: whenever data enters or leaves an
application, we need to validate it. Probably the most difficult place this
occurs is forms. Coding forms is complex; in an ideal world, we&#8217;d like a
solution that addresses the following problems:</simpara>
<itemizedlist>
<listitem>
<simpara>
Ensure data is valid.
</simpara>
</listitem>
<listitem>
<simpara>
Marshal string data in the form submission to Haskell datatypes.
</simpara>
</listitem>
<listitem>
<simpara>
Generate HTML code for displaying the form.
</simpara>
</listitem>
<listitem>
<simpara>
Generate Javascript to do clientside validation and provide more
  user-friendly widgets, such as date pickers.
</simpara>
</listitem>
<listitem>
<simpara>
Build up more complex forms by combining together simpler forms.
</simpara>
</listitem>
<listitem>
<simpara>
Automatically assign names to our fields that are guaranteed to be unique.
</simpara>
</listitem>
</itemizedlist>
<simpara>The yesod-form package provides all these features in a simple, declarative
API. It builds on top of Yesod&#8217;s widgets to simplify styling of forms and
applying Javascript appropriately. And like the rest of Yesod, it uses
Haskell&#8217;s type system to make sure everything is working correctly.</simpara>
<section id="forms_synopsis">
<title>Synopsis</title>
<programlisting language="haskell" linenumbering="unnumbered">{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
import           Control.Applicative ((&lt;$&gt;), (&lt;*&gt;))
import           Data.Text           (Text)
import           Data.Time           (Day)
import           Yesod
import           Yesod.Form.Jquery

data App = App

mkYesod "App" [parseRoutes|
/ HomeR GET
/person PersonR POST
|]

instance Yesod App

-- Tells our application to use the standard English messages.
-- If you want i18n, then you can supply a translating function instead.
instance RenderMessage App FormMessage where
    renderMessage _ _ = defaultFormMessage

-- And tell us where to find the jQuery libraries. We'll just use the defaults,
-- which point to the Google CDN.
instance YesodJquery App

-- The datatype we wish to receive from the form
data Person = Person
    { personName          :: Text
    , personBirthday      :: Day
    , personFavoriteColor :: Maybe Text
    , personEmail         :: Text
    , personWebsite       :: Maybe Text
    }
  deriving Show

-- Declare the form. The type signature is a bit intimidating, but here's the
-- overview:
--
-- * The Html parameter is used for encoding some extra information. See the
-- discussion regarding runFormGet and runFormPost below for further
-- explanation.
--
-- * We have our Handler as the inner monad, which indicates which site this is
-- running in.
--
-- * FormResult can be in three states: FormMissing (no data available),
-- FormFailure (invalid data) and FormSuccess
--
-- * The Widget is the viewable form to place into the web page.
--
-- Note that the scaffolded site provides a convenient Form type synonym,
-- so that our signature could be written as:
--
-- &gt; personForm :: Form Person
--
-- For our purposes, it's good to see the long version.
personForm :: Html -&gt; MForm Handler (FormResult Person, Widget)
personForm = renderDivs $ Person
    &lt;$&gt; areq textField "Name" Nothing
    &lt;*&gt; areq (jqueryDayField def
        { jdsChangeYear = True -- give a year dropdown
        , jdsYearRange = "1900:-5" -- 1900 till five years ago
        }) "Birthday" Nothing
    &lt;*&gt; aopt textField "Favorite color" Nothing
    &lt;*&gt; areq emailField "Email address" Nothing
    &lt;*&gt; aopt urlField "Website" Nothing

-- The GET handler displays the form
getHomeR :: Handler Html
getHomeR = do
    -- Generate the form to be displayed
    (widget, enctype) &lt;- generateFormPost personForm
    defaultLayout
        [whamlet|
            &lt;p&gt;
                The widget generated contains only the contents
                of the form, not the form tag itself. So...
            &lt;form method=post action=@{PersonR} enctype=#{enctype}&gt;
                ^{widget}
                &lt;p&gt;It also doesn't include the submit button.
                &lt;button&gt;Submit
        |]

-- The POST handler processes the form. If it is successful, it displays the
-- parsed person. Otherwise, it displays the form again with error messages.
postPersonR :: Handler Html
postPersonR = do
    ((result, widget), enctype) &lt;- runFormPost personForm
    case result of
        FormSuccess person -&gt; defaultLayout [whamlet|&lt;p&gt;#{show person}|]
        _ -&gt; defaultLayout
            [whamlet|
                &lt;p&gt;Invalid input, let's try again.
                &lt;form method=post action=@{PersonR} enctype=#{enctype}&gt;
                    ^{widget}
                    &lt;button&gt;Submit
            |]

main :: IO ()
main = warp 3000 App</programlisting>
</section>
<section id="forms_kinds_of_forms">
<title>Kinds of Forms</title>
<simpara>Before jumping into the types themselves, we should begin with an overview of
the different kinds of forms. There are three categories:</simpara>
<variablelist>
<varlistentry>
<term>
Applicative
</term>
<listitem>
<simpara>
These are the most commonly used (it&#8217;s what appeared in the
synopsis). Applicative gives us some nice properties of letting error messages
coallesce together and keep a very high-level, declarative approach. (For more
information on applicative code, see
<ulink url="http://www.haskell.org/haskellwiki/Applicative_functor">the Haskell
wiki</ulink>.)
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
Monadic
</term>
<listitem>
<simpara>
A more powerful alternative to applicative. While this allows you
more flexibility, it does so at the cost of being more verbose. Useful if you
want to create forms that don&#8217;t fit into the standard two-column look.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
Input
</term>
<listitem>
<simpara>
Used only for receiving input. Does not generate any HTML for receiving
the user input. Useful for interacting with existing forms.
</simpara>
</listitem>
</varlistentry>
</variablelist>
<simpara>In addition, there are a number of different variables that come into play for<commit_msg>Travis auto-generate XML files, 2016-02-20T16:52:30+0000<commit_after><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<?asciidoc-toc?>
<?asciidoc-numbered?>

<article lang="en">
<section id="forms_forms">
<title>Forms</title>
<simpara>I&#8217;ve mentioned the boundary issue already: whenever data enters or leaves an
application, we need to validate it. Probably the most difficult place this
occurs is forms. Coding forms is complex; in an ideal world, we&#8217;d like a
solution that addresses the following problems:</simpara>
<itemizedlist>
<listitem>
<simpara>
Ensure data is valid.
</simpara>
</listitem>
<listitem>
<simpara>
Marshal string data in the form submission to Haskell datatypes.
</simpara>
</listitem>
<listitem>
<simpara>
Generate HTML code for displaying the form.
</simpara>
</listitem>
<listitem>
<simpara>
Generate Javascript to do clientside validation and provide more
  user-friendly widgets, such as date pickers.
</simpara>
</listitem>
<listitem>
<simpara>
Build up more complex forms by combining together simpler forms.
</simpara>
</listitem>
<listitem>
<simpara>
Automatically assign names to our fields that are guaranteed to be unique.
</simpara>
</listitem>
</itemizedlist>
<simpara>The yesod-form package provides all these features in a simple, declarative
API. It builds on top of Yesod&#8217;s widgets to simplify styling of forms and
applying Javascript appropriately. And like the rest of Yesod, it uses
Haskell&#8217;s type system to make sure everything is working correctly.</simpara>
<section id="forms_synopsis">
<title>Synopsis</title>
<programlisting language="haskell" linenumbering="unnumbered">{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
import           Control.Applicative ((&lt;$&gt;), (&lt;*&gt;))
import           Data.Text           (Text)
import           Data.Time           (Day)
import           Yesod
import           Yesod.Form.Jquery

data App = App

mkYesod "App" [parseRoutes|
/ HomeR GET
/person PersonR POST
|]

instance Yesod App

-- Tells our application to use the standard English messages.
-- If you want i18n, then you can supply a translating function instead.
instance RenderMessage App FormMessage where
    renderMessage _ _ = defaultFormMessage

-- And tell us where to find the jQuery libraries. We'll just use the defaults,
-- which point to the Google CDN.
instance YesodJquery App

-- The datatype we wish to receive from the form
data Person = Person
    { personName          :: Text
    , personBirthday      :: Day
    , personFavoriteColor :: Maybe Text
    , personEmail         :: Text
    , personWebsite       :: Maybe Text
    }
  deriving Show

-- Declare the form. The type signature is a bit intimidating, but here's the
-- overview:
--
-- * The Html parameter is used for encoding some extra information. See the
-- discussion regarding runFormGet and runFormPost below for further
-- explanation.
--
-- * We have our Handler as the inner monad, which indicates which site this is
-- running in.
--
-- * FormResult can be in three states: FormMissing (no data available),
-- FormFailure (invalid data) and FormSuccess
--
-- * The Widget is the viewable form to place into the web page.
--
-- Note that the scaffolded site provides a convenient Form type synonym,
-- so that our signature could be written as:
--
-- &gt; personForm :: Form Person
--
-- For our purposes, it's good to see the long version.
personForm :: Html -&gt; MForm Handler (FormResult Person, Widget)
personForm = renderDivs $ Person
    &lt;$&gt; areq textField "Name" Nothing
    &lt;*&gt; areq (jqueryDayField def
        { jdsChangeYear = True -- give a year dropdown
        , jdsYearRange = "1900:-5" -- 1900 till five years ago
        }) "Birthday" Nothing
    &lt;*&gt; aopt textField "Favorite color" Nothing
    &lt;*&gt; areq emailField "Email address" Nothing
    &lt;*&gt; aopt urlField "Website" Nothing

-- The GET handler displays the form
getHomeR :: Handler Html
getHomeR = do
    -- Generate the form to be displayed
    (widget, enctype) &lt;- generateFormPost personForm
    defaultLayout
        [whamlet|
            &lt;p&gt;
                The widget generated contains only the contents
                of the form, not the form tag itself. So...
            &lt;form method=post action=@{PersonR} enctype=#{enctype}&gt;
                ^{widget}
                &lt;p&gt;It also doesn't include the submit button.
                &lt;button&gt;Submit
        |]

-- The POST handler processes the form. If it is successful, it displays the
-- parsed person. Otherwise, it displays the form again with error messages.
postPersonR :: Handler Html
postPersonR = do
    ((result, widget), enctype) &lt;- runFormPost personForm
    case result of
        FormSuccess person -&gt; defaultLayout [whamlet|&lt;p&gt;#{show person}|]
        _ -&gt; defaultLayout
            [whamlet|
                &lt;p&gt;Invalid input, let's try again.
                &lt;form method=post action=@{PersonR} enctype=#{enctype}&gt;
                    ^{widget}
                    &lt;button&gt;Submit
            |]

main :: IO ()
main = warp 3000 App</programlisting>
</section>
<section id="forms_kinds_of_forms">
<title>Kinds of Forms</title>
<simpara>Before jumping into the types themselves, we should begin with an overview of
the different kinds of forms. There are three categories:</simpara>
<variablelist>
<varlistentry>
<term>
Applicative
</term>
<listitem>
<simpara>
These are the most commonly used (it&#8217;s what appeared in the
synopsis). Applicative gives us some nice properties of letting error messages
coalesce together and keep a very high-level, declarative approach. (For more
information on applicative code, see
<ulink url="http://www.haskell.org/haskellwiki/Applicative_functor">the Haskell
wiki</ulink>.)
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
Monadic
</term>
<listitem>
<simpara>
A more powerful alternative to applicative. While this allows you
more flexibility, it does so at the cost of being more verbose. Useful if you
want to create forms that don&#8217;t fit into the standard two-column look.
</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
Input
</term>
<listitem>
<simpara>
Used only for receiving input. Does not generate any HTML for receiving
the user input. Useful for interacting with existing forms.
</simpara>
</listitem>
</varlistentry>
</variablelist>
<simpara>In addition, there are a number of different variables that come into play for
{'fraction_non_alphanumeric': 0.10137941263719964, 'fraction_numerical': 0.008157816671610798, 'mean_word_length': 3.4622766379880874, 'pattern_counts': {'":': 0, '<': 159, '<?xml version=': 2, '>': 159, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2201032', 'n_tokens_mistral': 4104, 'n_tokens_neox': 3916, 'n_words': 1533}