10.1.12 投稿記事の編集
The original text for this section has changed since it was translated. Please help resolve this difference. You can:
投稿記事の編集:それではさっそく作業です。もうCakePHPプロのあなたは、パターンを見つけ出したでしょうか。アクションをつくり、それからビューを作る、というパターンです。PostsControllerのedit()アクションはこんな形になります。
function edit($id = null) {
$this->Post->id = $id;
if (empty($this->data)) {
$this->data = $this->Post->read();
} else {
if ($this->Post->save($this->data['Post'])) {
$this->flash('Your post has been updated.','/posts');
}
}
}
function edit($id = null) {$this->Post->id = $id;if (empty($this->data)) {$this->data = $this->Post->read();} else {if ($this->Post->save($this->data['Post'])) {$this->flash('Your post has been updated.','/posts');}}}
このアクションはまず、送信されたフォームデータをチェックします。もし何も送信されていないなら、投稿記事を見つけて(find)ビューに渡します。もし、何かデータが送信されているなら、Postモデルを使ってデータを保存しようとし(バリデーションエラーが見つかれば、ユーザに戻し)ます。
editビューはこんな感じです。
/app/views/posts/edit.ctp
<h1>Edit Post</h1>
<?php
echo $form->create('Post', array('action' => 'edit'));
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->input('id', array('type'=>'hidden'));
echo $form->end('Save Post');
?>
/app/views/posts/edit.ctp<h1>Edit Post</h1><?phpecho $form->create('Post', array('action' => 'edit'));echo $form->input('title');echo $form->input('body', array('rows' => '3'));echo $form->input('id', array('type'=>'hidden'));echo $form->end('Save Post');?>
(値が入力されている場合、)このビューは、編集フォームを出力します。必要であれば、バリデーションのエラーメッセージも表示します。
ひとつ注意:
CakePHPは、'id'フィールドがデータ配列の中に存在している場合は、モデルを編集しているのだと判断します。もし、'id'がなければ、(addのビューを復習してください。)save()が呼び出された時、Cakeは新しいモデルの挿入だと判断します。
これで、特定の記事をアップデートするためのリンクをindexビューに付けることができます。
/app/views/posts/index.ctp (編集リンクを追加済み)
<h1>Blog posts</h1>
<p><?php echo $html->link("Add Post", "/posts/add"); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- $post配列をループして、投稿記事の情報を表示 -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $html->link($post['Post']['title'],'/posts/view/'.$post['Post']['id']);?>
<?php echo $html->link(
'Delete',
"/posts/delete/{$post['Post']['id']}",
null,
'Are you sure?'
)?>
<?php echo $html->link('Edit', '/posts/edit/'.$post['Post']['id']);?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
/app/views/posts/index.ctp (編集リンクを追加済み)<h1>Blog posts</h1><p><?php echo $html->link("Add Post", "/posts/add"); ?></p><table><tr><th>Id</th><th>Title</th><th>Created</th></tr><!-- $post配列をループして、投稿記事の情報を表示 --><?php foreach ($posts as $post): ?><tr><td><?php echo $post['Post']['id']; ?></td><td><?php echo $html->link($post['Post']['title'],'/posts/view/'.$post['Post']['id']);?><?php echo $html->link('Delete',"/posts/delete/{$post['Post']['id']}",null,'Are you sure?')?><?php echo $html->link('Edit', '/posts/edit/'.$post['Post']['id']);?></td><td><?php echo $post['Post']['created']; ?></td></tr><?php endforeach; ?></table>

