Yesod Applicative Forms Help
Posted
Friday, April 25th 2014 in
Programming -
Permalink
It took me a little while to start understanding how Applicative forms work in Yesod. I still don’t really understand Applicative, but I can at least write something that will give me what I want. Here are some examples.
To have a form with a single field, simply omit Applicative operators:
someForm = renderDivs $ areq textareaField "Comment" Nothing
To create a form for a data type, the fields must be in the correct order and of the correct type for each data field in the data type. You can combine the fields using Applicative operators:
data MyData = MyData {
myDataText :: Text,
myDataDate :: UTCTime,
myDataInt :: Maybe Int,
myDataDouble :: Double
}
someForm myData = renderDivs $ MyData
<$> areq textField "Enter text:" (myDataText <$> myData)
<*> areq utcTimeField "Enter a date:" (myDataDate <$> myData)
<*> aopt intField "Optional integer:" (myDataInt <$> myData)
<*> areq doubleField "Enter a double:" (myDataDouble <$> myData)
Finally, you can combine multiple data types into a single form. The data types are separated themselves by Applicative operators:
data MyData = MyData {
myDataText :: Text,
myDataDate :: UTCTime,
myDataInt :: Maybe Int,
myDataDouble :: Double
}
someForm myData = renderDivs $ pure (,)
<*> (MyData
<$> areq textField "Enter text:" (myDataText <$> myData)
<*> areq utcTimeField "Enter a date:" (myDataDate <$> myData)
<*> aopt intField "Optional integer:" (myDataInt <$> myData)
<*> areq doubleField "Enter a double:" (myDataDouble <$> myData))
<*> (fileAFormOpt "Upload Image")
|