Yesod:将当前用户传递给表单

时间:2017-06-13 12:45:15

标签: haskell yesod yesod-forms

我已经找到了这个,但找到的答案here最终会出现在包含该值的列表中。我想知道是否还有另一种更直接的方式来做我需要的事情。

我有一张表格:

formReview :: UserId -> Form Review
formReview uid = renderDivs $ Review <$>
              areq textField "Text" Nothing <*>
              areq intField "Rating" Nothing <*>
              areq (selectField films) "Film" Nothing <*>
              pure uid

你可以看到我试图将用户ID传递给表单,因为这些是Review的字段:

Review
    text Text
    rating Int
    film FilmId
    author UserId

它需要作者的ID。 我尝试这样做的方法是在postReviewsR上执行以下操作:

postReviewsR :: Handler Html
postReviewsR = do
                uid <- lookupSession "_ID"
                case uid of
                  Nothing -> do
                     defaultLayout [whamlet| <h1> User isn't logged in.|]
                  Just uid -> 
                     ((result, _), _) <- runFormPost $ formReview uid
                     case result of
                        FormSuccess review -> do
                            runDB $ insert review
                            defaultLayout [whamlet|
                                <h1> Review posted. 
                            |]
                        _ -> redirect ReviewsR

它必须是一个Maybe,因为理论上你可以试着发布一些东西而不登录,所以uid可能是空的。如果我尝试直接转到((result, _), _) <- runFormPost $ formReview uid它会说Maybe Text

现在我的问题与其他帖子类似,这是错误:

• Couldn't match type ‘Text’ with ‘Key User’
  Expected type: UserId
    Actual type: Text
• In the first argument of ‘formReview’, namely ‘uid’
  In the second argument of ‘($)’, namely ‘formReview uid’
  In a stmt of a 'do' block:
    ((result, _), _) <- runFormPost $ formReview uid

并且链接帖子中的建议是使用keyToValues :: Key record -> [PersistValue]将Key(显然只是Text)转换为我需要的UserId。 我似乎太笨重了,我需要做所有这些,然后在该列表上使用head来获取值,所有这些都将ID输入到表单中。必须有另一种更正确的方法,对吗?我在这里错过了什么?如何获取在那里进行审核的用户的ID?

编辑:我应该指出我没有使用Yesod.Auth,所以我无法使用它的功能。

1 个答案:

答案 0 :(得分:3)

假设您正在使用SQL后端,请查看persistent SQL documentation。你会找到toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record功能。基本上,您需要将Text解析为Int64并使用toSqlKey获取密钥。您可能也应检查您获得的密钥是否确实有效。

(您显然误解了错误,您的uid只是Text值,但您需要UserID Key User}。