前回、Articles関連のadd関連のファイルを編集して、新規記事投稿ができるようになったので、今回は、投稿した記事を編集できるようにして行きます。
Controller ArticlesController.php を編集。
前回、同様先ず初めにsrc/Controller/ArticlesController.phpを編集していきます。
編集箇所はEdit methodです。bakeで作成したのでarticlesのidを渡す形になっているのをslugを渡すように変更します。
変更後のEdit methodは下記の通りです。
public function edit($slug = null) { $article = $this->Articles->findBySlug($slug)->firstOrFail(); if ($this->request->is(['patch', 'post', 'put'])) { $query = $this->request->getData(); $sluggedTitle = Text::slug($this->request->getData('title')); $query['slug'] = substr($sluggedTitle, 0, 191); $article = $this->Articles->patchEntity($article, $query); if ($this->Articles->save($article)) { $this->Flash->success(__('The article has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The article could not be saved. Please, try again.')); } $tags = $this->Articles->Tags->find('list'); $this->set(compact('article', 'tags')); }
Template Articles index.ctp を編集。
現在edit actionなどがidを使用する形になっているのでslugを使用する方法に編集していきます。
table内のtdタグ、クラスにactionが付与されている箇所を下記のように編集します。
<!-- 省略 --> <td class="actions"> <?= $this->Html->link(__('View'), ['action' => 'view', $article->slug]) ?> <?= $this->Html->link(__('Edit'), ['action' => 'edit', $article->slug]) ?> <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $article->slug], ['confirm' => __('Are you sure you want to delete # {0}?', $article->id)]) ?> </td> <!-- 省略 -->
これでedit画面にアクセスができるようになります。
edit画面を編集。
add.ctpと同じようにフォーム部分の「user_id」を変更「slug」を削除して下記のように編集します。
<!-- 省略 --> <?= $this->Form->create($article) ?> <fieldset> <legend><?= __('Edit Article') ?></legend> <?php echo $this->Form->control('user_id', ['type' => 'hidden']); echo $this->Form->control('title'); echo $this->Form->control('body'); echo $this->Form->control('published'); echo $this->Form->control('tags._ids', ['options' => $tags]); ?> </fieldset> <?= $this->Form->button(__('Submit')) ?> <?= $this->Form->end() ?> <!-- 省略 -->
動作が無事確認できたらここまでの作業は完了です。