haskellyesodyesod-forms

Yesod - Form with foreign key


I am developing my first application with Yesod and I am creating some CRUD api to start.

I have a model that looks like

User json
    ...

Activity json
    userId UserId
    ...

where userId is a foreign key.

I need to create an endpoint to be able to create a new Activity and the client needs to be able to specify the userId.

To do this I am using a form like

postCreateActivityR :: Hadler Value
postCreateActivityR = do
    activity <- runInputPost $ Activity
        <$> ...
        <*> ireq textField "userId"
    ...

Doing so I get an error like the following:

Couldn't match type ‘Text’ with ‘Key User’ expected type: FormInput (HandlerT App IO) (Key User)

Is there a standard way to solve this?


Solution

  • For the records, this is how I solved it in the end

    I had to create a new field

    userIdField :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m UserId
    userIdField = Field
        { fieldParse = parseHelper $ \s ->
            case signed decimal s of
                Right (a, "") -> Right $ toSqlKey a
                _ -> Left $ MsgInvalidInteger s
        , fieldView = \_ _ _ _ _ -> ""
        , fieldEnctype = UrlEncoded
        }
    

    and then use it like

    <*> ireq userIdField "userId"