Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Reduce verbosity using Monadic Forms #1432
Building forms where some fields validations depend on other fields is simple using Monadic Forms, but as the own Yesod website mentioned:
Some of this verbosity is caused by the need of grouping the
formToAForm $ do (field1F, field1V) <- mreq textField MsgField1 Nothing (field2F, field2V) <- mreq (checkWith field1F textField) MsgField2 Nothing (field3F, field3V) <- mreq (checkWith field1F textField) MsgField3 Nothing return ( MyForm <$> field1F <*> field2F <*> field3F , [field1V, field2V, field3V] )
While the previous example could be refactored to use Applicative Form style, it requires combining the fields in order to be able to run a custom check. Doing that for more than one field that depends on one value is a little bit tricky using Applicative style.
I'll like to propose adding the following variant of a Monadic Form:
type WForm m a = MForm (WriterT [FieldView (HandlerSite m)] m) a
And the correspondent
wreq :: (...) => Field m a -> FieldSettings site -> Maybe a -> WForm m (FormResult a) wopt :: (...) => Field m a -> FieldSettings site -> Maybe (Maybe a) -> WForm m (FormResult (Maybe a)) wFormToAForm :: WForm m (FormResult a) -> AForm m a
The example above then could be rewritten as follows:
wFormToAForm $ do field1F <- wreq textField MsgField1 Nothing field2F <- wreq (checkWith field1F textField) MsgField2 Nothing field3F <- wreq (checkWith field1F textField) MsgField3 Nothing return $ MyForm <$> field1F <*> field2F <*> field3F
I'll be more than happy to submit a PR if this proposal makes sense to the maintainers.
This looks great, just one minor request for changing regarding
Since comment format. Thank you!