1

I'm trying to go through the ihp blog tutorial, but I'm not sure how to resolve this error. I'm new to haskell. I've tried asking chat gpt, but no luck so far.

Do I need to initialize an empty comment when I create a post? I assume so because NewView is defined with that field.

error

Web/Controller/Posts.hs:47:37
    * Fields of `NewView' not initialised:
        comment :: Comment
    * In the first argument of `render', namely `NewView {..}'
      In the expression: render NewView {..}
      In a case alternative: Left post -> render NewView {..}
   |
47 |                 Left post -> render NewView { .. }
   |                                     ^^^^^^^^^^^^^^

source code

-- Web/Controller/Posts.hs
action CreatePostAction = do
    let post = newRecord @Post
    post
        |> buildPost
        |> ifValid \case
            Left post -> render NewView { .. }
            Right post -> do
                post <- post |> createRecord
                setSuccessMessage "Post created"
                redirectTo PostsAction
-- ./Web/View/Comments/New.hs
data NewView = NewView
    { comment :: Comment
    , post :: Post
    }
Geoff Langenderfer
  • 746
  • 1
  • 9
  • 21

2 Answers2

2

The error happens as the view requires the comment variable to be passed from the controller action.

You've likely already set the comment variable inside your NewPostAction, something like this:

action NewPostAction = do
    let post = newRecord @Post
    let comment = newRecord @Comment
    render NewView { .. }

The CreatePostAction is also rendering the NewView when the validation of the newly submitted post has failed, to display the validation error messages. So you also need to set the let comment = newRecord @Comment inside the Left branch of the CreatePostAction:

-- Web/Controller/Posts.hs
action CreatePostAction = do
    let post = newRecord @Post
    post
        |> buildPost
        |> ifValid \case
            Left post -> do
                let comment = newRecord @Comment -- <--- THIS IS NEW
                render NewView { .. }
            Right post -> do
                post <- post |> createRecord
                setSuccessMessage "Post created"
                redirectTo PostsAction
Marc Scholten
  • 1,351
  • 3
  • 5
0

I added a comment field to a post's NewView. That was a mistake. Removing that field fixed things:

diff --git a/Web/View/Posts/New.hs b/Web/View/Posts/New.hs
index 79b073f..9cd06d0 100644
--- a/Web/View/Posts/New.hs
+++ b/Web/View/Posts/New.hs
@@ -3,8 +3,7 @@ import Web.View.Prelude
 import qualified Text.MMark as MMark
 
 data NewView = NewView
-    { comment :: Comment
-    , post :: Post
+    { post :: Post
     }
 
 instance View NewView where
Geoff Langenderfer
  • 746
  • 1
  • 9
  • 21