CakePHP3(3.0.0-alpha1)のブログチュートリアルで記事にコメント機能を追加する2
view.ctpにコメント一覧を表示したのでコメント入力欄を足してみる
①ArticlesControllerのview()を編集
public function view($id = null) { if (!$id) { throw new NotFoundException(__('Invalid article')); } //$article = $this->Articles->get($id); $article = $this->Articles->find('all')->contain(['Comments'])->where(['id'=>$id])->first(); $this->set(compact('article')); $this->loadModel('Comments'); $comment_entity = $this->Comments->newEntity($this->request->data); $this->set('comment_entity', $comment_entity); }
$this->loadModel('Comments');
を省いて
$this->Articles->Comments->newEntity($this->request->data)
でも。
2.Xは$usesで使うモデルを指定していたけれど3.Xでは違うっぽい?
http://book.cakephp.org/3.0/en/controllers.html#Controller::loadModel
※2014/07/16追記:pdf版のドキュメントには
Note: CakePHP merges the following variables from the AppController into your application’s controllers:
・$components
・$helpers
・$uses
と書かれていて、$usesだけリンクがない状態。様子見。
②view.ctpに入力欄を追加する
<h1>Comment</h1> <?php echo $this->Form->create($comment_entity,['action'=>'comment']); echo $this->Form->input('title'); echo $this->Form->input('body', ['rows' => '3']); echo $this->Form->button(__('Save Comment')); echo $this->Form->hidden('article_id',array('value'=>$article->id)); echo $this->Form->end(); ?>
add.ctpみたいに入力欄が空だとメッセージが出る。