CakePHP 編集機能を作成してみた
前回に引き続き、編集機能を作成してみます。
編集機能の作成
- コントローラの編集
users_controller.phpにeditアクションを追加します。
POSTでなければ、DBからユーザのデータを取得し、フォームのvalueに代入します。
POSTの場合は、パラメータを受け取りDBを更新します。
<?php
class UsersController extends AppController
{
var $name = 'Users';
function index() {
$this->set('users', $this->User->find('all'));
}
function view($id) {
$this->User->id = $id;
$this->set('user', $this->User->read());
}
function add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->flash('ユーザの登録が完了しました。','/users/index');
return;
}
}
}
function edit($id = null) {
$this->User->id = $id;
if (empty($this->data)) {
$this->data = $this->User->read();
} else {
if ($this->User->save($this->data['Post'])) {
$this->flash('ユーザの更新が完了しました。','/users/index');
}
}
}
}
- ビューの作成
app/veiws/にedit.ctpというファイルを作成します。
<h1>ユーザ一編集</h1>
<?= $form->create('User', array('action' => 'add', 'type' => 'post')); ?>
<?= $form->label('User.name', '名前');?>
<?= $form->text('User.name', array('size' => '10'));?>
<?= $form->label('User.age', '年齢');?>
<?= $form->text('User.age', array('size' => '10'));?>
<?= $form->end(array('label' => '更新', 'name' => 'submit')); ?>
<p><?= $html->link("戻る", "/users/"); ?></p>
POSTで無い場合は、以下の画面のように表示されます。
完了です。

















