CakePHP1.3.6:更新・削除処理を実装する(CRUD)。

それでは、顧客テーブル(customers)に更新、削除機能を実装して、とりあえずCRUDを完成してしまおう。

更新は、前回の詳細画面に更新のためのリンクを張って実装する。

更新のリンクをクリックすると、以下のように更新画面に遷移し、更新ボタンで更新する。更新後、一覧画面(index)に遷移する。

削除機能は、更新画面に削除リンクを張り、クリックすると以下のように確認ボックスを出して確認をする。ここでOKをするとデータを削除して、一覧画面に遷移する。

コントローラーの作成

customer_controller.phpは以下となる。edit()、deelete()がそれぞれ更新と削除のアクションとなる。

<?php
require_once '../vendors/MyConverter.class.php';

class CustomersController extends AppController{
	public $name = 'Customers';
	public $layout = 'myznala';

	/**
	 * 
	 * 初期画面(一覧表示)
	 */
	function index(){
		$this->set('title_for_layout', "顧客の一覧");
		$req=null;
		if(!empty($this->data)){
			//サニタイズ
			$req = MyConverter::getRequestParams($this->data["Customer"]);
			$result = $this->Customer->find('all',	
							array('conditions' => 
										array('Customer.name like ?' => array("%{$req["name"]}%")),
									'order' => array('Customer.timestamp DESC')
								)
						);
			}else{
			$result = $this->Customer->find('all',
							array(
									'order' => array('Customer.timestamp DESC')
							)
			);
		}
		
		$this->set('result',$result);
	}
	
	/**
	 * 
	 * データの追加
	 * 
	 */
	function add(){
		$this->set('title_for_layout', "顧客の登録");
		if(!empty($this->data)){
			// サニタイズ
			$this->data["Customer"] = MyConverter::getRequestParams($this->data["Customer"]);
			// 登録
			$this->Customer->save($this->data);
			if($this->Customer->validates()){
				// 登録できたらリダイレクト
				$this->redirect('.');
			}
		}
	}
	
	/**
	 * 
	 * データの照会
	 * $paramsにIdが入ってくる。
	 * 
	 */
	function show($param){
		$this->set('title_for_layout', "顧客の詳細");
		$result=null;
		if(!empty($param)){
			// Idフィールドによる検索
			$this->data=$this->Customer->findById($param);
			if(!$this->data){
				// 存在しないIDを参照された場合。
				$this->Session->setFlash('存在しません');
				$this->redirect('.');
			}
		}
		$this->set('data',$this->data);
	}

	/**
	 * 
	 * データの更新
	 * 
	 */
	function edit($param){
		$this->set('title_for_layout', "顧客情報の更新");
		// データの更新
		if(!empty($this->data)){
			// サニタイズ
			$this->data["Customer"] = MyConverter::getRequestParams($this->data["Customer"]);
			// Idフィールドによる検索
			$check=$this->Customer->findById($param);
			if(!$check){
				// 存在しないIDを更新しようとした場合。
				$this->Session->setFlash('存在しません');
				$this->redirect('.');
			}else{
				// 更新
				$this->Customer->save($this->data);
				if($this->Customer->validates()){
					// 更新できたらリダイレクト
					$this->redirect('.');
				}
			}
		// 更新データのセット(初期値)
		}else{
			if(!empty($param)){
				// Idフィールドによる検索
				$check=$this->Customer->findById($param);
				if(!$check){
					// 存在しないIDを更新しようとした場合。
					$this->Session->setFlash('存在しません');
					$this->redirect('.');
				}else{
					// Idフィールドによる検索
					$this->data=$this->Customer->findById($param);
				}
			}
		}
		// エラーの場合も通るようにする
		$this->set('data',$this->data);
	}

	/**
	 * 
	 * データの削除
	 * 
	 */
	function delete($param){
		if(!empty($param)){
			$check=$this->Customer->findById($param);
			if(!$check){
				// 存在しないIDを削除しようとした場合。
				$this->Session->setFlash('存在しません');
			}else{
				// Idフィールドによる削除
				$this->data=$this->Customer->delete($param);
			}
			$this->redirect('.');
		}
	}
	
}
?>

show(), edit(), delete()は、IDを指定して実行される。存在しないIDに対して、これらのアクションが呼ばれる(URLを叩かれる)ことを想定しなくてはならないので、そのためのコードを入れた。存在しないIDでアクションがリクエストされた場合、「存在しません」というメッセージをFlashにセットし、indexで表示している。

ビューの作成

CRUD完成ということで、全てのビューを記載しておく。

index.ctp
<h2>顧客の一覧</h2>
<br>
名前で絞り込みをします。
<?php 
echo $form->create('Customer',array('type'=>'post','action'=>'.'));
echo $form->text('Customer.name', array('size' => 10));
echo $form->end('送信');
?>

<table>
<tr>
	<th>ID</th>
	<th>名前</th>
	<th>郵便番号</th>
	<th>住所</th>
	<th>電話</th>
	<th>携帯</th>
	<th>メール</th>
	<th>更新日</th>
</tr>
<?php 
	foreach ($result as $arr){
		echo '<tr>';
		echo "<td><a href='./show/{$arr['Customer']['id']}'>{$arr['Customer']['id']}</a></td>";
		echo "<td>{$arr['Customer']['name']}</td>";
		echo "<td>{$arr['Customer']['zip']}</td>";
		echo "<td>{$arr['Customer']['address']}</td>";
		echo "<td>{$arr['Customer']['tel']}</td>";
		echo "<td>{$arr['Customer']['mobile']}</td>";
		echo "<td>{$arr['Customer']['mail']}</td>";
		echo "<td>{$arr['Customer']['timestamp']}</td>";
		echo '</tr>';
	}
?>
</table>

<a href="./add">登録</a>
add.ctp
<h2>顧客の登録</h2>
<?php 
echo $form->create(null,array('type'=>'post','action'=>'add'));
?>

<table>

<?php 
echo "<tr><th>名前</th>";
echo "<td>{$form->text('Customer.name',array('size'=>'20'))}{$form->error('Customer.name')} </td>";
echo "</tr>";
echo "<tr><th>郵便番号</th>";
echo "<td>{$form->text('Customer.zip',array('size'=>'10'))}{$form->error('Customer.zip')}</td>";
echo "</tr>";
echo "<tr><th>住所</th>";
echo "<td>{$form->text('Customer.address',array('size'=>'20'))}{$form->error('Customer.address')}</td>";
echo "</tr>";
echo "<tr><th>電話</th>";
echo "<td>{$form->text('Customer.tel',array('size'=>'15'))}{$form->error('Customer.tel')}</td>";
echo "</tr>";
echo "<tr><th>携帯</th>";
echo "<td>{$form->text('Customer.mobile',array('size'=>'15'))}</td>";
echo "</tr>";
echo "<tr><th>メール</th>";
echo "<td>{$form->text('Customer.mail',array('size'=>'40'))}{$form->error('Customer.mail')}</td>";
echo "</tr>";
echo "<tr><th>メモ</th>";
echo "<td>{$form->textarea('Customer.memo')}</td>";
echo "</tr>";
echo $form->end('登録');
?>
</table>
<a href=".">リストに戻る</a>
edit.ctp

この画面には削除のためのリンクがある。ここでは、そのためにHTMLヘルパーを利用した。確認ボックスまで出すことができるので便利。

<h2>顧客情報の更新</h2>
<?php 
echo $form->create('Customer',array('id'=>'Form1','type'=>'post','action'=>'edit'));
echo $form->hidden('Customer.id');
?>

<table>

<?php 
echo "<tr><th>名前</th>";
echo "<td>{$form->text('Customer.name',array('size'=>'20'))}{$form->error('Customer.name')} </td>";
echo "</tr>";
echo "<tr><th>郵便番号</th>";
echo "<td>{$form->text('Customer.zip',array('size'=>'10'))}{$form->error('Customer.zip')}</td>";
echo "</tr>";
echo "<tr><th>住所</th>";
echo "<td>{$form->text('Customer.address',array('size'=>'20'))}{$form->error('Customer.address')}</td>";
echo "</tr>";
echo "<tr><th>電話</th>";
echo "<td>{$form->text('Customer.tel',array('size'=>'15'))}{$form->error('Customer.tel')}</td>";
echo "</tr>";
echo "<tr><th>携帯</th>";
echo "<td>{$form->text('Customer.mobile',array('size'=>'15'))}</td>";
echo "</tr>";
echo "<tr><th>メール</th>";
echo "<td>{$form->text('Customer.mail',array('size'=>'40'))}{$form->error('Customer.mail')}</td>";
echo "</tr>";
echo "<tr><th>メモ</th>";
echo "<td>{$form->textarea('Customer.memo')}</td>";
echo "</tr>";
echo $form->end('更新');
?>
</table>
<a href="../">リストに戻る</a>
&nbsp; &nbsp;
<?php
echo $html->link('削除',
  array('controller'=>'customers', 'action'=>'delete', $data["Customer"]["id"]),
  array(),
 "削除してもいいですか?");
?>
show.ctp
<h2>顧客の詳細</h2>
<br>
<table>

<?php 
echo "<tr><th>名前</th>";
echo "<td>{$data['Customer']['name']}</td>";
echo "</tr>";
echo "<tr><th>郵便番号</th>";
echo "<td>{$data['Customer']['zip']}</td>";
echo "</tr>";
echo "<tr><th>住所</th>";
echo "<td>{$data['Customer']['address']}</td>";
echo "</tr>";
echo "<tr><th>電話</th>";
echo "<td>{$data['Customer']['tel']}</td>";
echo "</tr>";
echo "<tr><th>携帯</th>";
echo "<td>{$data['Customer']['mobile']}</td>";
echo "</tr>";
echo "<tr><th>メール</th>";
echo "<td>{$data['Customer']['mail']}</td>";
echo "</tr>";
echo "<tr><th>メモ</th>";
echo "<td>{$data['Customer']['memo']}</td>";
echo "</tr>";
?>
</table>
<a href="../">リストに戻る</a>
&nbsp; &nbsp;
<?php
echo $html->link('更新',
  array('controller'=>'customers', 'action'=>'edit', $data["Customer"]["id"]));
?>

モデル

customer.php
<?php 
require_once '../vendors/MyValidator.class.php';

class Customer extends AppModel {
	public $name = 'Customer';	
	
	public $validate = array(
				'name'=>array(
							'rule' => 'notEmpty',
							'message' =>'入力してください'
						),
				'zip'=>array(
							array(
								'rule' => array('checkZip','zip'),
								'message' =>'形式がただしくありません'),
							array(
								'rule' => 'notEmpty',
								'message' =>'入力してください'
							)
						),
				'address'=>array(
					'rule' => 'notEmpty',
					'message' =>'入力してください'),
				'tel'=>array(
					'rule' => 'notEmpty',
					'message' =>'入力してください'),
				'mail'=>array(
					'rule' => 'notEmpty',
					'message' =>'入力してください')
	);
	
	public function checkZip($data,$name){
		$ret = MyValidator::validate('ja', 'isZip', $data[$name]);
		return $ret;
	}
	
}