Chapter 8. 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 in forms. Coding forms is complex; in an ideal world, we’d like a solution that can do all of the following:

  • Ensure data is valid.

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

  • Generate HTML code for displaying the form.

  • Generate JavaScript to do client-side 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

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
import           Control.Applicative ((<$>), (<*>))
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 ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.