Forms

I’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’d like a solution that addresses the following problems:

  • Ensure data is valid.

  • Marshal string data in the form submission to Haskell datatypes.

  • Generate HTML code for displaying the form.

  • Generate Javascript to do clientside validation and provide more user-friendly widgets, such as date pickers.

  • Build up more complex forms by combining together simpler forms.

  • Automatically assign names to our fields that are guaranteed to be unique.

The yesod-form package provides all these features in a simple, declarative API. It builds on top of Yesod’s widgets to simplify styling of forms and applying Javascript appropriately. And like the rest of Yesod, it uses Haskell’s type system to make sure everything is working correctly.

Synopsis

  1. {-# LANGUAGE MultiParamTypeClasses #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. {-# LANGUAGE QuasiQuotes #-}
  4. {-# LANGUAGE TemplateHaskell #-}
  5. {-# LANGUAGE TypeFamilies #-}
  6. import Control.Applicative ((<$>), (<*>))
  7. import Data.Text (Text)
  8. import Data.Time (Day)
  9. import Yesod
  10. import Yesod.Form.Jquery
  11. data App = App
  12. mkYesod "App" [parseRoutes|
  13. / HomeR GET
  14. /person PersonR POST
  15. |]
  16. instance Yesod App
  17. -- Tells our application to use the standard English messages.
  18. -- If you want i18n, then you can supply a translating function instead.
  19. instance RenderMessage App FormMessage where
  20. renderMessage _ _ = defaultFormMessage
  21. -- And tell us where to find the jQuery libraries. We'll just use the defaults,
  22. -- which point to the Google CDN.
  23. instance YesodJquery App
  24. -- The datatype we wish to receive from the form
  25. data Person = Person
  26. { personName :: Text
  27. , personBirthday :: Day
  28. , personFavoriteColor :: Maybe Text
  29. , personEmail :: Text
  30. , personWebsite :: Maybe Text
  31. }
  32. deriving Show
  33. -- Declare the form. The type signature is a bit intimidating, but here's the
  34. -- overview:
  35. --
  36. -- * The Html parameter is used for encoding some extra information. See the
  37. -- discussion regarding runFormGet and runFormPost below for further
  38. -- explanation.
  39. --
  40. -- * We have our Handler as the inner monad, which indicates which site this is
  41. -- running in.
  42. --
  43. -- * FormResult can be in three states: FormMissing (no data available),
  44. -- FormFailure (invalid data) and FormSuccess
  45. --
  46. -- * The Widget is the viewable form to place into the web page.
  47. --
  48. -- Note that the scaffolded site provides a convenient Form type synonym,
  49. -- so that our signature could be written as:
  50. --
  51. -- > personForm :: Form Person
  52. --
  53. -- For our purposes, it's good to see the long version.
  54. personForm :: Html -> MForm Handler (FormResult Person, Widget)
  55. personForm = renderDivs $ Person
  56. <$> areq textField "Name" Nothing
  57. <*> areq (jqueryDayField def
  58. { jdsChangeYear = True -- give a year dropdown
  59. , jdsYearRange = "1900:-5" -- 1900 till five years ago
  60. }) "Birthday" Nothing
  61. <*> aopt textField "Favorite color" Nothing
  62. <*> areq emailField "Email address" Nothing
  63. <*> aopt urlField "Website" Nothing
  64. -- The GET handler displays the form
  65. getHomeR :: Handler Html
  66. getHomeR = do
  67. -- Generate the form to be displayed
  68. (widget, enctype) <- generateFormPost personForm
  69. defaultLayout
  70. [whamlet|
  71. <p>
  72. The widget generated contains only the contents
  73. of the form, not the form tag itself. So...
  74. <form method=post action=@{PersonR} enctype=#{enctype}>
  75. ^{widget}
  76. <p>It also doesn't include the submit button.
  77. <button>Submit
  78. |]
  79. -- The POST handler processes the form. If it is successful, it displays the
  80. -- parsed person. Otherwise, it displays the form again with error messages.
  81. postPersonR :: Handler Html
  82. postPersonR = do
  83. ((result, widget), enctype) <- runFormPost personForm
  84. case result of
  85. FormSuccess person -> defaultLayout [whamlet|<p>#{show person}|]
  86. _ -> defaultLayout
  87. [whamlet|
  88. <p>Invalid input, let's try again.
  89. <form method=post action=@{PersonR} enctype=#{enctype}>
  90. ^{widget}
  91. <button>Submit
  92. |]
  93. main :: IO ()
  94. main = warp 3000 App

Kinds of Forms

Before jumping into the types themselves, we should begin with an overview of the different kinds of forms. There are three categories:

Applicative

These are the most commonly used (it’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 the Haskell wiki.)

Monadic

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’t fit into the standard two-column look.

Input

Used only for receiving input. Does not generate any HTML for receiving the user input. Useful for interacting with existing forms.

In addition, there are a number of different variables that come into play for each form and field you will want to set up:

  • Is the field required or optional?

  • Should it be submitted with GET or POST?

  • Does it have a default value, or not?

An overriding goal is to minimize the number of field definitions and let them work in as many contexts as possible. One result of this is that we end up with a few extra words for each field. In the synopsis, you may have noticed things like areq and that extra Nothing parameter. We’ll cover why all of those exist in the course of this chapter, but for now realize that by making these parameters explicit, we are able to reuse the individuals fields (like intField) in many different ways.

A quick note on naming conventions. Each form type has a one-letter prefix (A, M and I) which is used in a few places, such as saying MForm. We also use req and opt to mean required and optional. Combining these, we create a required applicative field with areq, or an optional input field with iopt.

Types

The Yesod.Form.Types module declares a few types. We won’t cover all the types available, but will instead focus on the most crucial. Let’s start with some of the simple ones:

Enctype

The encoding type, either UrlEncoded or Multipart. This datatype declares an instance of ToHtml, so you can use the enctype directly in Hamlet.

FormResult

Has one of three possible states: FormMissing if no data was submitted, FormFailure if there was an error parsing the form (e.g., missing a required field, invalid content), or FormSuccess if everything went smoothly.

FormMessage

Represents all of the different messages that can be generated as a data type. For example, MsgInvalidInteger is used by the library to indicate that the textual value provided is not an integer. By keeping this data highly structured, you are able to provide any kind of rendering function you want, which allows for internationalization (i18n) of your application.

Next we have some datatypes used for defining individual fields. We define a field as a single piece of information, such as a number, a string, or an email address. Fields are combined together to build forms.

Field

Defines two pieces of functionality: how to parse the text input from a user into a Haskell value, and how to create the widget to be displayed to the user. yesod-form defines a number of individual Fields in Yesod.Form.Fields.

FieldSettings

Basic information on how a field should be displayed, such as the display name, an optional tooltip, and possibly hardcoded id and name attributes. (If none are provided, they are automatically generated.) Note that FieldSettings provides an IsString instance, so when you need to provide a FieldSettings value, you can actually type in a literal string. That’s how we interacted with it in the synopsis.

And finally, we get to the important stuff: the forms themselves. There are three types for this: MForm is for monadic forms, AForm for applicative and FormInput for input. MForm is actually a type synonym for a monad stack that provides the following features:

  • A Reader monad giving us the parameters submitted by the user, the foundation datatype and the list of languages the user supports. The last two are used for rendering of the FormMessages to support i18n (more on this later).

  • A Writer monad keeping track of the Enctype. A form will always be UrlEncoded, unless there is a file input field, which will force us to use multipart instead.

  • A State monad keeping track of generated names and identifiers for fields.

An AForm is pretty similar. However, there are a few major differences:

  • It produces a list of FieldViews, which are used for tracking what we will display to the user. This allows us to keep an abstract idea of the form display, and then at the end of the day choose an appropriate function for laying it out on the page. In the synopsis, we used renderDivs, which creates a bunch of div tags. Two other options are renderBootstrap and renderTable.

  • It does not provide a Monad instance. The goal of Applicative is to allow the entire form to run, grab as much information on each field as possible, and then create the final result. This cannot work in the context of Monad.

A FormInput is even simpler: it returns either a list of error messages or a result.

Converting

“But wait a minute,” you say. “You said the synopsis uses applicative forms, but I’m sure the type signature said MForm. Shouldn’t it be Monadic?” That’s true, the final form we produced was monadic. But what really happened is that we converted an applicative form to a monadic one.

Again, our goal is to reuse code as much as possible, and minimize the number of functions in the API. And Monadic forms are more powerful than Applicative, if a bit clumsy, so anything that can be expressed in an Applicative form could also be expressed in a Monadic form. There are two core functions that help out with this: aformToForm converts any applicative form to a monadic one, and formToAForm converts certain kinds of monadic forms to applicative forms.

“But wait another minute,” you insist. “I didn’t see any aformToForm!” Also true. The renderDivs function takes care of that for us.

Create AForms

Now that I’ve (hopefully) convinced you that in our synopsis we were really dealing with applicative forms, let’s have a look and try to understand how these things get created. Let’s take a simple example:

  1. data Car = Car
  2. { carModel :: Text
  3. , carYear :: Int
  4. }
  5. deriving Show
  6. carAForm :: AForm Handler Car
  7. carAForm = Car
  8. <$> areq textField "Model" Nothing
  9. <*> areq intField "Year" Nothing
  10. carForm :: Html -> MForm Handler (FormResult Car, Widget)
  11. carForm = renderTable carAForm

Here, we’ve explicitly split up applicative and monadic forms. In carAForm, we use the <$> and <*> operators. This should not be surprising; these are almost always used in applicative-style code. And we have one line for each record in our Car datatype. Perhaps also unsurprisingly, we have a textField for the Text record, and an intField for the Int record.

Let’s look a bit more closely at the areq function. Its (simplified) type signature is Field a → FieldSettings → Maybe a → AForm a. That first argument specifies the datatype of this field, how to parse it, and how to render it. The next argument, FieldSettings, tells us the label, tooltip, name and ID of the field. In this case, we’re using the previously-mentioned IsString instance of FieldSettings.

And what’s up with that Maybe a? It provides the optional default value. For example, if we want our form to fill in “2007” as the default car year, we would use areq intField "Year" (Just 2007). We can even take this to the next level, and have a form that takes an optional parameter giving the default values.

  1. carAForm :: Maybe Car -> AForm Handler Car
  2. carAForm mcar = Car
  3. <$> areq textField "Model" (carModel <$> mcar)
  4. <*> areq intField "Year" (carYear <$> mcar)

Optional fields

Suppose we wanted to have an optional field (like the car color). All we do instead is use the aopt function.

  1. carAForm :: AForm Handler Car
  2. carAForm = Car
  3. <$> areq textField "Model" Nothing
  4. <*> areq intField "Year" Nothing
  5. <*> aopt textField "Color" Nothing

And like required fields, the last argument is the optional default value. However, this has two layers of Maybe wrapping. This is actually a bit redundant, but it makes it much easier to write code that takes an optional default form parameter, such as in the next example.

  1. carAForm :: Maybe Car -> AForm Handler Car
  2. carAForm mcar = Car
  3. <$> areq textField "Model" (carModel <$> mcar)
  4. <*> areq intField "Year" (carYear <$> mcar)
  5. <*> aopt textField "Color" (carColor <$> mcar)
  6. carForm :: Html -> MForm Handler (FormResult Car, Widget)
  7. carForm = renderTable $ carAForm $ Just $ Car "Forte" 2010 $ Just "gray"

Validation

How would we make our form only accept cars created after 1990? If you remember, we said above that the Field itself contained the information on what is a valid entry. So all we need to do is write a new Field, right? Well, that would be a bit tedious. Instead, let’s just modify an existing one:

  1. carAForm :: Maybe Car -> AForm Handler Car
  2. carAForm mcar = Car
  3. <$> areq textField "Model" (carModel <$> mcar)
  4. <*> areq carYearField "Year" (carYear <$> mcar)
  5. <*> aopt textField "Color" (carColor <$> mcar)
  6. where
  7. errorMessage :: Text
  8. errorMessage = "Your car is too old, get a new one!"
  9. carYearField = check validateYear intField
  10. validateYear y
  11. | y < 1990 = Left errorMessage
  12. | otherwise = Right y

The trick here is the check function. It takes a function (validateYear) that returns either an error message or a modified field value. In this example, we haven’t modified the value at all. That is usually going to be the case. This kind of checking is very common, so we have a shortcut:

  1. carYearField = checkBool (>= 1990) errorMessage intField

checkBool takes two parameters: a condition that must be fulfilled, and an error message to be displayed if it was not.

You may have noticed the explicit Text type signature on errorMessage. In the presence of OverloadedStrings, this is necessary. In order to support i18n, messages can have many different datatypes, and GHC has no way of determining which instance of IsString you intended to use.

It’s great to make sure the car isn’t too old. But what if we want to make sure that the year specified is not from the future? In order to look up the current year, we’ll need to run some IO. For such circumstances, we’ll need checkM, which allows our validation code to perform arbitrary actions:

  1. carYearField = checkM inPast $ checkBool (>= 1990) errorMessage intField
  2. inPast y = do
  3. thisYear <- liftIO getCurrentYear
  4. return $ if y <= thisYear
  5. then Right y
  6. else Left ("You have a time machine!" :: Text)
  7. getCurrentYear :: IO Int
  8. getCurrentYear = do
  9. now <- getCurrentTime
  10. let today = utctDay now
  11. let (year, _, _) = toGregorian today
  12. return $ fromInteger year

inPast is a function that will return an Either result in the Handler monad. We use liftIO getCurrentYear to get the current year and then compare it against the user-supplied year. Also, notice how we can chain together multiple validators.

Since the checkM validator runs in the Handler monad, it has access to a lot of the stuff you can normally do in Yesod. This is especially useful for running database actions, which we’ll cover in the Persistent chapter.

More sophisticated fields

Our color entry field is nice, but it’s not exactly user-friendly. What we really want is a drop-down list.

  1. data Car = Car
  2. { carModel :: Text
  3. , carYear :: Int
  4. , carColor :: Maybe Color
  5. }
  6. deriving Show
  7. data Color = Red | Blue | Gray | Black
  8. deriving (Show, Eq, Enum, Bounded)
  9. carAForm :: Maybe Car -> AForm Handler Car
  10. carAForm mcar = Car
  11. <$> areq textField "Model" (carModel <$> mcar)
  12. <*> areq carYearField "Year" (carYear <$> mcar)
  13. <*> aopt (selectFieldList colors) "Color" (carColor <$> mcar)
  14. where
  15. colors :: [(Text, Color)]
  16. colors = [("Red", Red), ("Blue", Blue), ("Gray", Gray), ("Black", Black)]

selectFieldList takes a list of pairs. The first item in the pair is the text displayed to the user in the drop-down list, and the second item is the actual Haskell value. Of course, the code above looks really repetitive; we can get the same result using the Enum and Bounded instance GHC automatically derives for us.

  1. colors = map (pack . show &&& id) [minBound..maxBound]

[minBound..maxBound] gives us a list of all the different Color values. We then apply a map and &&& (a.k.a, the fan-out operator) to turn that into a list of pairs. And even this can be simplified by using the optionsEnum function provided by yesod-form, which would turn out original code into:

  1. carAForm :: Maybe Car -> AForm Handler Car
  2. carAForm mcar = Car
  3. <$> areq textField "Model" (carModel <$> mcar)
  4. <*> areq carYearField "Year" (carYear <$> mcar)
  5. <*> aopt (selectField optionsEnum) "Color" (carColor <$> mcar)

Some people prefer radio buttons to drop-down lists. Fortunately, this is just a one-word change.

  1. carAForm = Car
  2. <$> areq textField "Model" Nothing
  3. <*> areq intField "Year" Nothing
  4. <*> aopt (radioField optionsEnum) "Color" Nothing

Running forms

At some point, we’re going to need to take our beautiful forms and produce some results. There are a number of different functions available for this, each with its own purpose. I’ll go through them, starting with the most common.

runFormPost

This will run your form against any submitted POST parameters. If this is not a POST submission, it will return a FormMissing. This automatically inserts a security token as a hidden form field to avoid cross-site request forgery (CSRF) attacks.

runFormGet

The equivalent of runFormPost for GET parameters. In order to distinguish a normal GET page load from a GET submission, it includes an extra _hasdata hidden field in the form. Unlike runFormPost, it does not include CSRF protection.

runFormPostNoToken

Same as runFormPost, but does not include (or require) the CSRF security token.

generateFormPost

Instead of binding to existing POST parameters, acts as if there are none. This can be useful when you want to generate a new form after a previous form was submitted, such as in a wizard.

generateFormGet

Same as generateFormPost, but for GET.

The return type from the first three is ((FormResult a, Widget), Enctype). The Widget will already have any validation errors and previously submitted values.

Why the nested tuple instead of a specialized datatype? It’s because runFormPostNoToken and runFormGet can both be used with forms that don’t return a FormResult or Widget, which can be useful when dealing with more complicated monadic forms (discussed below).

i18n

There have been a few references to i18n in this chapter. The topic will get more thorough coverage in its own chapter, but since it has such a profound effect on yesod-form, I wanted to give a brief overview. The idea behind i18n in Yesod is to have data types represent messages. Each site can have an instance of RenderMessage for a given datatype which will translate that message based on a list of languages the user accepts. As a result of all this, there are a few things you should be aware of:

  • There is an automatic instance of RenderMessage for Text in every site, so you can just use plain strings if you don’t care about i18n support. However, you may need to use explicit type signatures occasionally.

  • yesod-form expresses all of its messages in terms of the FormMessage datatype. Therefore, to use yesod-form, you’ll need to have an appropriate RenderMessage instance. A simple one that uses the default English translations would be:

  1. instance RenderMessage App FormMessage where
  2. renderMessage _ _ = defaultFormMessage

This is provided automatically by the scaffolded site.

Monadic Forms

Often times, a simple form layout is adequate, and applicative forms excel at this approach. Sometimes, however, you’ll want to have a more customized look to your form.

A non-standard form layout

Forms - 图1

For these use cases, monadic forms fit the bill. They are a bit more verbose than their applicative cousins, but this verbosity allows you to have complete control over what the form will look like. In order to generate the form above, we could code something like this.

  1. {-# LANGUAGE MultiParamTypeClasses #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. {-# LANGUAGE QuasiQuotes #-}
  4. {-# LANGUAGE TemplateHaskell #-}
  5. {-# LANGUAGE TypeFamilies #-}
  6. import Control.Applicative
  7. import Data.Text (Text)
  8. import Yesod
  9. data App = App
  10. mkYesod "App" [parseRoutes|
  11. / HomeR GET
  12. |]
  13. instance Yesod App
  14. instance RenderMessage App FormMessage where
  15. renderMessage _ _ = defaultFormMessage
  16. data Person = Person
  17. { personName :: Text
  18. , personAge :: Int
  19. }
  20. deriving Show
  21. personForm :: Html -> MForm Handler (FormResult Person, Widget)
  22. personForm extra = do
  23. (nameRes, nameView) <- mreq textField "this is not used" Nothing
  24. (ageRes, ageView) <- mreq intField "neither is this" Nothing
  25. let personRes = Person <$> nameRes <*> ageRes
  26. let widget = do
  27. toWidget
  28. [lucius|
  29. ##{fvId ageView} {
  30. width: 3em;
  31. }
  32. |]
  33. [whamlet|
  34. #{extra}
  35. <p>
  36. Hello, my name is #
  37. ^{fvInput nameView}
  38. \ and I am #
  39. ^{fvInput ageView}
  40. \ years old. #
  41. <input type=submit value="Introduce myself">
  42. |]
  43. return (personRes, widget)
  44. getHomeR :: Handler Html
  45. getHomeR = do
  46. ((res, widget), enctype) <- runFormGet personForm
  47. defaultLayout
  48. [whamlet|
  49. <p>Result: #{show res}
  50. <form enctype=#{enctype}>
  51. ^{widget}
  52. |]
  53. main :: IO ()
  54. main = warp 3000 App

Similar to the applicative areq, we use mreq for monadic forms. (And yes, there’s also mopt for optional fields.) But there’s a big difference: mreq gives us back a pair of values. Instead of hiding away the FieldView value and automatically inserting it into a widget, we have the ability to insert it as we see fit.

FieldView has a number of pieces of information. The most important is fvInput, which is the actual form field. In this example, we also use fvId, which gives us back the HTML id attribute of the input tag. In our example, we use that to specify the width of the field.

You might be wondering what the story is with the “this is not used” and “neither is this” values. mreq takes a FieldSettings as its second argument. Since FieldSettings provides an IsString instance, the strings are essentially expanded by the compiler to:

  1. fromString "this is not used" == FieldSettings
  2. { fsLabel = "this is not used"
  3. , fsTooltip = Nothing
  4. , fsId = Nothing
  5. , fsName = Nothing
  6. , fsAttrs = []
  7. }

In the case of applicative forms, the fsLabel and fsTooltip values are used when constructing your HTML. In the case of monadic forms, Yesod does not generate any of the “wrapper” HTML for you, and therefore these values are ignored. However, we still keep the FieldSettings parameter to allow you to override the id and name attributes of your fields if desired.

The other interesting bit is the extra value. GET forms include an extra field to indicate that they have been submitted, and POST forms include a security token to prevent CSRF attacks. If you don’t include this extra hidden field in your form, the form submission will fail.

Other than that, things are pretty straight-forward. We create our personRes value by combining together the nameRes and ageRes values, and then return a tuple of the person and the widget. And in the getHomeR function, everything looks just like an applicative form. In fact, you could swap out our monadic form with an applicative one and the code would still work.

Input forms

Applicative and monadic forms handle both the generation of your HTML code and the parsing of user input. Sometimes, you only want to do the latter, such as when there’s an already-existing form in HTML somewhere, or if you want to generate a form dynamically using Javascript. In such a case, you’ll want input forms.

These work mostly the same as applicative and monadic forms, with some differences:

  • You use runInputPost and runInputGet.

  • You use ireq and iopt. These functions now only take two arguments: the field type and the name (i.e., HTML name attribute) of the field in question.

  • After running a form, it returns the value. It doesn’t return a widget or an encoding type.

  • If there are any validation errors, the page returns an “invalid arguments” error page.

You can use input forms to recreate the previous example. Note, however, that the input version is less user friendly. If you make a mistake in an applicative or monadic form, you will be brought back to the same page, with your previously entered values in the form, and an error message explaining what you need to correct. With input forms, the user simply gets an error message.

  1. {-# LANGUAGE MultiParamTypeClasses #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. {-# LANGUAGE QuasiQuotes #-}
  4. {-# LANGUAGE TemplateHaskell #-}
  5. {-# LANGUAGE TypeFamilies #-}
  6. import Control.Applicative
  7. import Data.Text (Text)
  8. import Yesod
  9. data App = App
  10. mkYesod "App" [parseRoutes|
  11. / HomeR GET
  12. /input InputR GET
  13. |]
  14. instance Yesod App
  15. instance RenderMessage App FormMessage where
  16. renderMessage _ _ = defaultFormMessage
  17. data Person = Person
  18. { personName :: Text
  19. , personAge :: Int
  20. }
  21. deriving Show
  22. getHomeR :: Handler Html
  23. getHomeR = defaultLayout
  24. [whamlet|
  25. <form action=@{InputR}>
  26. <p>
  27. My name is
  28. <input type=text name=name>
  29. and I am
  30. <input type=text name=age>
  31. years old.
  32. <input type=submit value="Introduce myself">
  33. |]
  34. getInputR :: Handler Html
  35. getInputR = do
  36. person <- runInputGet $ Person
  37. <$> ireq textField "name"
  38. <*> ireq intField "age"
  39. defaultLayout [whamlet|<p>#{show person}|]
  40. main :: IO ()
  41. main = warp 3000 App

Custom fields

The fields that come built-in with Yesod will likely cover the vast majority of your form needs. But occasionally, you’ll need something more specialized. Fortunately, you can create new fields in Yesod yourself. The Field constructor has three values: fieldParse takes a list of values submitted by the user and returns one of three results:

  • An error message saying validation failed.

  • The parsed value.

  • Nothing, indicating that no data was supplied.

That last case might sound surprising. It would seem that Yesod can automatically know that no information is supplied when the input list is empty. But in reality, for some field types, the lack of any input is actually valid input. Checkboxes, for instance, indicate an unchecked state by sending in an empty list.

Also, what’s up with the list? Shouldn’t it be a Maybe? That’s also not the case. With grouped checkboxes and multi-select lists, you’ll have multiple widgets with the same name. We also use this trick in our example below.

The second value in the constructor is fieldView, and it renders a widget to display to the user. This function has the following arguments:

  1. The id attribute.

  2. The name attribute.

  3. Any other arbitrary attributes.

  4. The result, given as an Either value. This will provide either the unparsed input (when parsing failed) or the successfully parsed value. intField is a great example of how this works. If you type in 42, the value of result will be Right 42. But if you type in turtle, the result will be Left "turtle". This lets you put in a value attribute on your input tag that will give the user a consistent experience.

  5. A Bool indicating if the field is required.

The final value in the constructor is fieldEnctype. If you’re dealing with file uploads, this should be Multipart; otherwise, it should be UrlEncoded.

As a small example, let’s create a new field type that is a password confirm field. This field has two text inputs- both with the same name attribute- and returns an error message if the values don’t match. Note that, unlike most fields, it does not provide a value attribute on the input tags, as you don’t want to send back a user-entered password in your HTML ever.

  1. passwordConfirmField :: Field Handler Text
  2. passwordConfirmField = Field
  3. { fieldParse = \rawVals _fileVals ->
  4. case rawVals of
  5. [a, b]
  6. | a == b -> return $ Right $ Just a
  7. | otherwise -> return $ Left "Passwords don't match"
  8. [] -> return $ Right Nothing
  9. _ -> return $ Left "You must enter two values"
  10. , fieldView = \idAttr nameAttr otherAttrs eResult isReq ->
  11. [whamlet|
  12. <input id=#{idAttr} name=#{nameAttr} *{otherAttrs} type=password>
  13. <div>Confirm:
  14. <input id=#{idAttr}-confirm name=#{nameAttr} *{otherAttrs} type=password>
  15. |]
  16. , fieldEnctype = UrlEncoded
  17. }
  18. getHomeR :: Handler Html
  19. getHomeR = do
  20. ((res, widget), enctype) <- runFormGet $ renderDivs
  21. $ areq passwordConfirmField "Password" Nothing
  22. defaultLayout
  23. [whamlet|
  24. <p>Result: #{show res}
  25. <form enctype=#{enctype}>
  26. ^{widget}
  27. <input type=submit value="Change password">
  28. |]

Values that don’t come from the user

Imagine you’re writing a blog hosting web app, and you want to have a form for users to enter a blog post. A blog post will consist of four pieces of information:

  • Title

  • HTML contents

  • User ID of the author

  • Publication date

We want the user to enter the first two values, but not the second two. User ID should be determined automatically by authenticating the user (a topic we haven’t covered yet), and the publication date should just be the current time. The question is, how do we keep our simple applicative form syntax, and yet pull in values that don’t come from the user?

The answer is two separate helper functions:

  • pure allows us to wrap up a plain value as an applicative form value.

  • lift allows us to run arbitrary Handler actions inside an applicative form.

Let’s see an example of using these two functions:

  1. {-# LANGUAGE MultiParamTypeClasses #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. {-# LANGUAGE QuasiQuotes #-}
  4. {-# LANGUAGE TemplateHaskell #-}
  5. {-# LANGUAGE TypeFamilies #-}
  6. import Control.Applicative
  7. import Data.Text (Text)
  8. import Data.Time
  9. import Yesod
  10. -- In the authentication chapter, we'll address this properly
  11. newtype UserId = UserId Int
  12. deriving Show
  13. data App = App
  14. mkYesod "App" [parseRoutes|
  15. / HomeR GET POST
  16. |]
  17. instance Yesod App
  18. instance RenderMessage App FormMessage where
  19. renderMessage _ _ = defaultFormMessage
  20. type Form a = Html -> MForm Handler (FormResult a, Widget)
  21. data Blog = Blog
  22. { blogTitle :: Text
  23. , blogContents :: Textarea
  24. , blogUser :: UserId
  25. , blogPosted :: UTCTime
  26. }
  27. deriving Show
  28. form :: UserId -> Form Blog
  29. form userId = renderDivs $ Blog
  30. <$> areq textField "Title" Nothing
  31. <*> areq textareaField "Contents" Nothing
  32. <*> pure userId
  33. <*> lift (liftIO getCurrentTime)
  34. getHomeR :: Handler Html
  35. getHomeR = do
  36. let userId = UserId 5 -- again, see the authentication chapter
  37. ((res, widget), enctype) <- runFormPost $ form userId
  38. defaultLayout
  39. [whamlet|
  40. <p>Previous result: #{show res}
  41. <form method=post action=@{HomeR} enctype=#{enctype}>
  42. ^{widget}
  43. <input type=submit>
  44. |]
  45. postHomeR :: Handler Html
  46. postHomeR = getHomeR
  47. main :: IO ()
  48. main = warp 3000 App

One trick we’ve introduced here is using the same handler code for both the GET and POST request methods. This is enabled by the implementation of runFormPost, which will behave exactly like generateFormPost in the case of a GET request. Using the same handler for both request methods cuts down on some boilerplate.

Summary

Forms in Yesod are broken up into three groups. Applicative is the most common, as it provides a nice user interface with an easy-to-use API. Monadic forms give you more power, but are harder to use. Input forms are intended when you just want to read data from the user, not generate the input widgets.

There are a number of different Fields provided by Yesod out-of-the-box. In order to use these in your forms, you need to indicate the kind of form and whether the field is required or optional. The result is six helper functions: areq, aopt, mreq, mopt, ireq, and iopt.

Forms have significant power available. They can automatically insert Javascript to help you leverage nicer UI controls, such as a jQuery UI date picker. Forms are also fully i18n-ready, so you can support a global community of users. And when you have more specific needs, you can slap on some validation functions to an existing field, or write a new one from scratch.