初心者です。
初歩的な質問をしてしまい、申し訳ございませんがよろしくお願い致します。
下記に載っているサンプルプログラムの作成を行っていますが、
更新処理(URLでの表題は【投稿記事の編集】になります)の方が正常に実施できません。
サンプルプログラム:リンク内容
動作確認をおこなったところ、saveメソッドでidが設定されず更新ではなく、新規追加と判断されているようです。
そこで疑問なのですが、editメソッド内のsave処理直前で
php
1$this->Post->id = $id;
という処理がされているの、こちらで更新用のidを追加していると勝手に思っていたのですが、それは間違いでしょうか?
<実行環境>
CakePHP2.7.6
また、どのようにすればsaveメソッドを使用して更新処理が行えますでしょうか?
こちら上記2点お答えいただければ幸いでございます。
下記にソースを添付致します。
コントローラー
php
1public function edit($id = null) { 2 if (!$id) { 3 throw new NotFoundException(__('Invalid post')); 4 } 5 6 $post = $this->Post->findById($id); 7 if (!$post) { 8 throw new NotFoundException(__('Invalid post')); 9 } 10 11 if ($this->request->is(array('post', 'put'))) { 12 $this->Post->id = $id; 13 if ($this->Post->save($this->request->data)) { 14 $this->Flash->success(__('Your post has been updated.')); 15 return $this->redirect(array('action' => 'index')); 16 } 17 $this->Flash->error(__('Unable to update your post.')); 18 } 19 20 if (!$this->request->data) { 21 $this->request->data = $post; 22 } 23} 24
View(更新用)
php
1<h1>Edit Post</h1> 2<?php 3echo $this->Form->create('Post'); 4echo $this->Form->input('title'); 5echo $this->Form->input('body', array('rows' => '3')); 6echo $this->Form->input('id', array('type' => 'hidden')); 7echo $this->Form->end('Save Post'); 8?> 9
view(一覧表示用)
php
1<h1>Blog posts</h1> 2<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p> 3<table> 4 <tr> 5 <th>Id</th> 6 <th>Title</th> 7 <th>Action</th> 8 <th>Created</th> 9 </tr> 10 11<!-- $posts 配列をループして、投稿記事の情報を表示 --> 12 13<?php foreach ($posts as $post): ?> 14 <tr> 15 <td><?php echo $post['Post']['id']; ?></td> 16 <td> 17 <?php 18 echo $this->Html->link( 19 $post['Post']['title'], 20 array('action' => 'view', $post['Post']['id']) 21 ); 22 ?> 23 </td> 24 <td> 25 <?php 26 echo $this->Html->link( 27 'Edit', 28 array('action' => 'edit', $post['Post']['id']) 29 ); 30 ?> 31 </td> 32 <td> 33 <?php echo $post['Post']['created']; ?> 34 </td> 35 </tr> 36<?php endforeach; ?> 37 38</table>
お手数おかけいたしますが、よろしくお願い致します。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。