从另一个模型的视图编辑关联的模型(CakePHP 3)

时间:2016-05-21 16:18:13

标签: cakephp view cakephp-3.0 edit

我仍然是CakePHP的新手,不过我想我有一些基本的了解。

我根据一篇'文章制作了一个基本博客。桌子和bake all,到目前为止一块蛋糕; D.现在我已经添加了评论'表。 '文章' hasMany'评论'和评论' belongsTo' articles'。我再次baked all对两个表格进行了编辑,并编辑了'视图'在ArticlesController.php和Articles / view.ctp中执行操作以显示文章的所有注释。还没有问题。

现在,我希望能够在“视图”中添加评论。一篇文章的页面,就像你可以对这个论坛发表评论一样。所以我在view.ctp中添加了Html->Form,并将评论的add()中的一些部分复制到了文章的视图()中。文章的观点行动:

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']);
}

来自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() ?>

但这给了我一个致命的错误,:

  

错误:在布尔文件上调用成员函数newEntity()   C:\ XAMPP \ htdocs中\ blog_simple的\ src \控制器\ ArticlesController.php   行:45

有关如何完成我正在寻找的内容的任何建议?

1 个答案:

答案 0 :(得分:1)

  

错误:在布尔文件上调用成员函数newEntity()   C:\ XAMPP \ htdocs中\ blog_simple的\ src \控制器\ ArticlesController.php   行:45

因为您在Articles控制器中并且您正在尝试Comments相关功能(不加载模型)。

你有两个选择。

  1. 如果您设置了正确的关系,请将Articles附加到<,p>之类的调用上

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

    $comment = $this->Articles->Comments->newEntity();
    
  2. 同样适用于所有评论PatchEntitySave功能。

    1. 添加

      $this->loadModel('Comments');

      在调用Comments相关函数之前。无需像前面提到的那样附加Articles。因为,我们正在加载模型。

    2. 尝试你喜欢哪一个。祝你好运!

相关问题