Search code examples
ihp

IHP - How to use Select Inputs with Nullable Enums in HSX Forms?


Given an enum:

CREATE TYPE CONTENT_TYPE AS ENUM ('video', 'article', 'audio');

How should I update the my HSX Form selectField to support Maybe ContentType?

  formFor subscription [hsx|
    {selectField #contentType allContentTypes}
|]
    where
      allContentTypes = allEnumValues @ContentType

The CanSelect instance is defined as follows:

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"


Solution

  • Your CanSelect instance looks correct. The list of allContentTypes should have a type of [Maybe ContentType]. You can wrap the content types with a Just constructor by mapping it over the list: e.g. fmap Just allContentTypes and passing the wrapped list to selectField.