0
votes

I am still fairly new to CakePHP, though I like to think I have some basic understanding.

I have made a basic blog, based on an 'articles' table and bake all, piece of cake so far ;D. Now I've added a 'comments' table. 'articles' hasMany 'comments' and 'comments' belongsTo 'articles'. I again baked all for both tables and edited the 'view' action in ArticlesController.php and Articles/view.ctp to display all the comments of an article. No issues yet.

Now I'd like to be able to add a comment on the 'view' page of an article, much like you can comment on this forum. So I've added an Html->Form to view.ctp and copied some parts from the comment's add() to the article's view(). Article's view action:

public function view($id = null) {

$article = $this->Articles->get($id, [
    'contain' => ['Comments']
]);

// Part from the add-action from Comments
$comment = $this->Comments->newEntity();
if ($this->request->is('post')) {
    $comment = $this->Comments->patchEntity($comment, $this->request->data);
    if ($this->Comments->save($comment)) {
        $this->Flash->success(__('The comment has been saved.'));
        return $this->redirect(['action' => 'index']);
    } else {


      $this->Flash->error(__('The comment could not be saved. Please, try again.'));
        }
    }

    // Set the selected article
    $this->set('article', $article);
    $this->set('_serialize', ['article']);
}

A part from Articles/view.ctp :

<?php foreach ($article->comments as $comment) : ?>

    <h5><?= $comment->author ?></h5>

    <p><?= $comment->body ?></p>

<?php endforeach; ?>


<b>Add comment</b>

<?= $this->Form->create($comment) ?>
<?php
echo $this->Form->input('comment.author');
echo $this->Form->input('comment.body');
?>
<?= $this->Form->button(__('Submit Comment')) ?>
<?= $this->Form->end() ?>

But this gives me a fatal error, :

Error: Call to a member function newEntity() on boolean File C:\xampp\htdocs\blog_simple\src\Controller\ArticlesController.php Line: 45

Any suggestions on how to accomplish what I'm looking for?

1

1 Answers

1
votes

Error: Call to a member function newEntity() on boolean File C:\xampp\htdocs\blog_simple\src\Controller\ArticlesController.php Line: 45

Because you are in Articles Controller and you are trying Comments related functions (without Loading Model).

You have two option.

  1. If you have correct relationship set up, then append Articles to calls like,

    $comment = $this->Comments->newEntity();
    

    to

    $comment = $this->Articles->Comments->newEntity();
    

Similarly do for all the comments PatchEntity and Save function.

  1. Add

    $this->loadModel('Comments');

    before calling Comments related functions. No need to append Articles like mentioned in previous point. Because, we are loading model.

Try which one you prefer. Good luck!