是否有可能在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
- 获取键列表,
- generates a
FormInput
from each one
- 生成名字和姓氏的字段
- 将这些字段变成
FormInput
s
- 产生一个
FormInput
它将它们组合成一个Person
- 连接
FormInput
s的结果转化为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(使用前将#替换为@)