Cakephp博客添加类别和文章在同一时间


Cakephp Blog add Category and article at same time

我想扩展cakephp 3。X博客教程。

我想有添加文章表单(文章/添加)让您选择一个类别或创建一个新的类别,并将其链接到新的文章。

如果在articles/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();
?>

在articlescontroller。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'));
    }

但我得到一个"未知的方法"错误上类别->添加

如何同时添加类别?

这意味着在表Categories中没有方法。你必须像这样在src/Model/Table/categoriable .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;
}
}
相关文章: