IHP框架HSX表单如何实现支持可空枚举的Select选择输入
可空枚举类型selectField修改方案
前置定义
给定PostgreSQL枚举定义如下:
CREATE TYPE CONTENT_TYPE AS ENUM ('video', 'article', 'audio');
目标是让HSX表单中的selectField支持Maybe ContentType可空枚举类型。
现有代码问题
当前表单实现
formFor subscription [hsx| {selectField #contentType allContentTypes} |] where allContentTypes = allEnumValues @ContentType
当前编写的CanSelect实例(存在错误)
instance CanSelect (Maybe ContentType) where type SelectValue (Maybe ContentType) = Maybe ContentType selectValue (Just value) = Just value selectValue Nothing = Nothing selectLabel (Just groupType) = tshow contentType selectLabel Nothing = "none selected"
现有代码存在两个核心问题:
CanSelect实例的selectLabel分支存在变量名笔误:入参定义为groupType,实际调用了不存在的contentType变量- 选项列表仅包含非空枚举值,没有提供对应
Nothing的空选项
修改步骤
- 修正
CanSelect类型类实例,修复变量名错误,简化冗余的分支写法:instance CanSelect (Maybe ContentType) where type SelectValue (Maybe ContentType) = Maybe ContentType selectValue = id selectLabel (Just contentType) = tshow contentType selectLabel Nothing = "none selected" - 修改表单选项列表,在枚举值前添加空选项,同时将所有枚举值包裹为
Just类型,匹配选项的类型要求:formFor subscription [hsx| {selectField #contentType allContentTypes} |] where allContentTypes = Nothing : map Just (allEnumValues @ContentType)
修改完成后下拉框会显示none selected空选项,用户选择该选项即可正确提交空值,也可以正常选择三个枚举值提交。
注意:请确认对应模型中
contentType字段的类型已经定义为Maybe ContentType,否则会出现类型不匹配的编译错误。
内容的提问来源于stack exchange,提问作者Varun Rajput
相关产品推荐
相关产品推荐

