Search code examples
haskellyesodhamlet

Yesod accessing a persistent entity id from hamlet


I currently have persistent pulling a list of products from a database and displaying them on the screen. I would like to use the Id from the database to store some information about these products in a cookie and to link to more detailed information pages. From what I understand the ID is only present in the persistent entity and not in the actual Product type? Does this mean that I should store an additional field with a random string that I can use in the cookie or is there a way to access the id used in the database? I will be adding the cookies using JavaScript.

Up until now I have just used PHP and for that I would use the ID. I'm not sure if this is the same in Yesod because of type safety or if there is a best practice way to do this.


Solution

  • If you want to get the id of a record entity inside a handler do something like:

    (Entity key _) <- runDB $ getBy ...
    

    a query that does not use the id to get the values(eg: get) will return an entity that contains both the id and the values.

    See: http://www.yesodweb.com/book/persistent#persistent_fetching_by_unique_constraint

    you can see getBy returns a (Entity personId person) wrapped in a maybe this also works with selectList