ページネーションを利用した中での複数のフォームを使った編集機能の実装
2ページ目
input 「タイトル」 input「コメント」(更新ボタン)(削除ボタン)
input 「タイトル」 input「コメント」(更新ボタン)(削除ボタン)
input 「タイトル」 input「コメント」(更新ボタン)(削除ボタン)
input 「タイトル」 input「コメント」(更新ボタン)(削除ボタン)
input 「タイトル」 input「コメント」(更新ボタン)(削除ボタン)
というような感じの複数フォームがあったとします。
削除ボタンに関してはpostlinkで実装済なのですが、更新の機能がうまく実装できません。
postされた場合には、is('post')が使われることは確認できるのですが(echo "hoge"は確認済)、その中身の内容の書き方についてよくわかっていません。
おそらく、同一ページ内のidの引き渡し方と受け取り方がよくわかっていないと思っています。
エラーメッセージは
Record not found in table "articles" with primary key [NULL]
や
Method Not Allowed
が出てきます。
主にやりたいことは次の通りです。
・編集画面(別ページ)に飛ばさずに、すぐ編集できるようにしたい。
・バリテーションもかかるようにしたい。(たぶんこれはやってくれるから大丈夫?)
・リダイレクト先はページネーションのページ番号のページに飛ばしたい。
どのように実装したらいいのでしょうか。
現在のコード
controller
PHP
1editメソッド 2 3public function edit($id = null) 4 { 5 $this->ViewBuilder()->layout('auth'); 6 7 if($this->request->is(['post','patch','put'])){ 8 //ポストされた場合 9 //echo "hoge"; 10 $article = $this->Articles->get($id); 11 $this->request->allowMethod(['post','edit']); 12 $article = $this->Articles->patchEntity($article ,$this->request->data); 13 14 if($this->Articles->save($article)){ 15 $this->Flash->success('更新成功'); 16 $this->redirect(['action' => 'edit']);//ここにページネーションのページ番号をリダイレクト先にしたい。 17 18 }else{ 19 $this->Flash->error('更新エラー'); 20 return $this->redirect(['action' => 'edit']);//ここにページネーションのページ番号をリダイレクト先にしたい。もしくはバリテーションエラーを出すならこの一行は書かない方がよい? 21 } 22 } 23 24 25 $paginate = [ 26 'limit' => 10, 27 'order' => [ 28 'Articles.id' => 'desc' 29 ] 30 ]; 31 $user_id = $this->request->session()->read('Auth.User.id'); 32 $articles = $this->Articles->find('all')->where(['user_id' => $user_id])->order(['id' => 'desc']); 33 34 $this->set('articles', $this->paginate($articles)); 35 } 36 37
view
PHP
1edit.ctp 2 foreach($articles as $article){ 3 echo $this->Form->create($article); 4 echo $this->Form->hidden('id',['value' => h($article->id)]); 5 echo $this->Form->input('title',['label' => 'タイトル'],['value' => h($article->title)]); 6 echo $this->Form->input('comment',['label' => 'コメント'],['value' => h($article->comment)]); 7 echo $this->Form->button('更新'); 8 echo $this->Form->end(); 9 10 echo $this->Form->postlink( 11 '[削除]', 12 ['action' => 'delete' ,$article->id ], 13 ['confirm' => 'この記事を削除しますか?', 'class' => ''] 14 ); 15 16 } 17