今回からは記事投稿「Articles」関連のファイルを変更していきます。先ずは新規記事作成のadd部分から変更します。
今回のページでは、CakePHP3でのユーザー情報の編集関連から下記の3項目をまとめています。
- 「CakePHP3でPOST データを取得する方法」
- 「add.ctpの編集」
- 「新規記事を作成テスト」
Controller ArticlesController.php を編集。
先ず初めにsrc/Controller/ArticlesController.phpを編集していきます。
isAuthorized method を Delete method の下に追加します。追加するコードは下記です。
</** * isAuthorized method */ public function isAuthorized($user) { $action = $this->request->getParam('action'); if (in_array($action, ['add', 'tags'])) { return true; } $slug = $this->request->getParam('pass.0'); if (!$slug) { return false; } $article = $this->Articles->findBySlug($slug)->first(); return $article->user_id === $user['id']; }
isAuthorized methodを追加後、ArticlesController.phpの4行目辺りにある「use App\Controller\AppController;」の下に追加します。追加するコードは下記です。
use Cake\Utility\Text;
続いて、bakeで書き出されたadd method内を編集していきます。
/** * Add method * * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $article = $this->Articles->newEntity(); if ($this->request->is('post')) { // ここから追加・編集 $query = $this->request->getData(); // POSTデータの取得 $query['user_id'] = $this->Auth->user('id'); // ユーザーidの追加 $sluggedTitle = Text::slug($this->request->getData('title')); // タイトルをURLに安全な文字列へ編集 $query['slug'] = substr($sluggedTitle, 0, 191); // slugの追加 $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.')); } $users = $this->Articles->Users->find('list', ['limit' => 200]); $tags = $this->Articles->Tags->find('list', ['limit' => 200]); $this->set(compact('article', 'users', 'tags')); }
CakePHP3でPOSTデータを取得する方法のgetData()で取得して、add内で必要なデータをPOSTデータに足しています。
slugはユニーク(一意)な必要があるので今回はコントローラーでデータを加工して、Tableでバリデーションを行う方法にしました。
ここまででArticlesController.phpの編集は完了です。
Template Articles add.ctp を編集。
続いてsrc/Template/Articles/add.ctpを編集していきます。
フォーム部分の「user_id」を変更「slug」を削除して下記のように編集します。
<!-- 省略 --> <?= $this->Form->create($article) ?> <fieldset> <legend><?= __('Add 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() ?> <!-- 省略 -->
ここまででadd.ctpの編集は完了です。
新規記事作成をテスト
上記の工程が全て完了後、ログインをして新規記事作成をしてみます。
New Articleから新規記事作成画面に遷移をして、適当な記事を投稿します。
同じタイトルの記事は新規作成ができないことも確認してみましょう。
上記動作が無事確認できたらここまでの作業は完了です。