Cakephp Blog同时添加类别和文章

时间:2016-11-09 22:00:54

标签: php database cakephp

我想扩展cakephp 3.x博客教程。

我想让ADD ARTICLE FORM(文章/添加)让您选择一个类别或创建一个新类别并将其链接到新文章。

如果在文章/ add.ctp中有这个:

<h1>Add Article</h1>
<?php
    echo $this->Form->create($article);
    echo $this->Form->input('title');
    echo $this->Form->input('category_id');
    echo $this->Form->input('name');
    echo $this->Form->input('body', ['rows' => '3']);
    echo $this->Form->button(__('Save Article'));
    echo $this->Form->end();
?>

这在ArticlesContoller.php中添加

    public function add()
    {
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {

        if($this->request->data['category_id']==""){




   $this->Categories->add($category );



        }

        $article = $this->Articles->patchEntity($article, $this->request->data);
        // Added this line
        $article->user_id = $this->Auth->user('id');
        // You could also do the following
        //$newData = ['user_id' => $this->Auth->user('id')];
        //$article = $this->Articles->patchEntity($article, $newData);
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('Your article has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to add your article.'));
    }
    $this->set('article', $article);

        $categories = $this->Articles->Categories->find('treeList');
        $this->set(compact('categories'));

    // Just added the categories list to be able to choose
    // one category for an article
   // $categories = $this->Articles->Categories->find('treeList');
    //$this->set(compact('categories'));
    }

但是我在“类别 - &gt;添加

上遇到”未知方法“错误

如何同时添加类别?

1 个答案:

答案 0 :(得分:0)

这意味着您没有表格类别中的方法。 你可以在src / Model / Table / CategoriesTable.php中创建方法,如下所示:

public function add($data)
{
$category = new Entity();
$category->...
//add columns what you need to save in table
if($this->save($category)){
return true;
}else{
return false;
}
}