处理 Yesod 表单中的数据集合

2024-02-18

是否有可能在Yesod https://en.wikipedia.org/wiki/Yesod_(web_framework)处理包含数据集合的表单?

我有一个用户可以添加多个人的表单,在前端它目前看起来像这样:

{ people.map((person, key) => (
  <td>
    <input type="hidden" name={ `person[${key}][firstName]` } value={person.firstName} />
    <input type="hidden" name={ `person[${key}][lastName]` } value={person.lastName} />
    { person.firstName } { person.lastName }
  </td>
)) }

然后我希望能够将其转换到后端,如下所示:

[Person "Michael" "Snoyman", Person "Ed" "Kmett"]

该列表的长度是可变的,因此它可以包含尽可能多的人people用户喜欢的价值。到目前为止,我一直无法弄清楚如何使用复制这种东西FormInput在耶索德。


您可以创建自己的FormInput通过定义unFormInput功能。该函数可以从表单中提取字段名称,提取键,然后您可以使用ireq推动相关领域的发展。

这可能看起来像

getPeople :: FormInput (your handler type) [People]
getPeople = FormInput $ \m l env fenv ->
    (unFormInput (peopleField peopleKeys)) m l env fenv
        where
            peopleKeys = getPeopleKeys env

获取人员钥匙

此辅助函数将为您表单中的人员生成所有关键值。它们还不需要有效,因为字段解析稍后会处理这个问题。

getPeopleKeys :: Env -> [Text]
getPeopleKeys env = mapMaybe extractKey (keys env)
    where
        extractKey :: Text -> Maybe Text
        extractKey key = ... -- you could use e.g. regex here
                             -- to pull the keys out of the field names
                             -- and return Nothing otherwise

人场

这个助手产生FormInput. It

  1. 获取键列表,
  2. generates a FormInput from each one
    1. 生成名字和姓氏的字段
    2. 将这些字段变成FormInputs
    3. 产生一个FormInput它将它们组合成一个Person
  3. 连接FormInputs的结果转化为FormInput ... [Person]

peopleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => [Text] -> FormInput m [Person]
peopleField = mapM personField
    where
        personField :: Text -> Field ... Person
        personField key = (liftA2 (Person)) (personFNameField) (personLNameField)
            where
                personFNameField = (ireq hiddenField) . fNameField key
                personLNameField = (ireq hiddenField) . lNameField key

fNameField key = ... -- this outputs "person[${key}][firstName]"
lNameField key = ... -- etc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理 Yesod 表单中的数据集合 的相关文章

随机推荐