Yesod - Form with foreign key

178 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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"
0
On

If you are working with a SQL backend, there is toSqlKey in Database.Persist.Sql module. Since you are given Text, you first need to convert it into Int64 using Data.Text.Read.