(備忘録)cakePHP1.3 & jqGrid(json)で顧客一覧表示 | ゆうの音(ね)

ゆうの音(ね)

ソフトウェア開発会社の社長兼SEの
日々のもろもろを綴ったブログ

コントローラー
custmers_controller.php

/**
* beforeFilter
*
* @param
* @return void
*/
function beforeFilter() {
/* 処理 */
parent::beforeFilter();
// ajax:json の場合
if ($this->RequestHandler->isAjax()) {
// action が jsonの場合
if ($this->action === "json") {
$this->layout = "ajax";
Configure::write("debug" , 0);
$this->RequestHandler->setContent("json");
$this->RequestHandler->respondAs('application/json; charset=UTF-8');
}
}
}

/**
* index
*
* @param
* @return void
*/
function index() {
$this->set('title_for_layout', '顧客一覧');
}

/**
* json
*
* @param
* @return void
*/
function json() {
$page = $this->params['url']['page'];
$limit = $this->params['url']['rows'];
$sidx = $this->params['url']['sidx'];
$sord = $this->params['url']['sord'];

if(!$sidx) $sidx =1;
$row = $this->Customer->find('count');
$count = $row;

if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}

if ($page > $total_pages) $page=$total_pages;

$start = $limit*$page - $limit;

if($start <0) $start = 0;

$limit_range = $start.",".$limit;
$sort_range = $sidx." ".$sord;

$ret = $this ->Customer->find('all',array('fields'=>array('Customer.id','Customer.name','Customer.kana')));
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;

$i=0;
foreach($ret as $row){
$responce->rows[$i]['id'] =$row['Customer']['id'];
$responce->rows[$i]['cell'] = array($row['Customer']['id'],$row['Customer']['name'],$row['Customer']['kana']);
$i++;
}
$this->set('customers', $responce);
}

モデル
customers/index.ctp

<script type="text/javascript">
jQuery(document).ready(function(){
//Grid For Master Table
jQuery("#list").jqGrid({
url:'<?php echo $html->url(array("controller" => "customers", "action" => "json")); ?>',
datatype: 'json',
mtype: 'GET',
colNames:['Id','氏名','フリガナ'],
colModel :[
{name:'id', index:'id', width:100},
{name:'name', index:'name', width:200,editable:true},
{name:'kana', index:'kana', width:200,editable:true}
],
rowNum:5,
rowTotal: 2000,
rowList:[5,10,15],
loadonce:true,
rownumbers: true,
rownumWidth: 40,
gridview: true,
pager: '#pager',
sortname: 'id',
sortorder: 'asc',
multiselect: false,
viewrecords: true,
caption: '顧客一覧',
width:800,
height:500,
loadError : function(xhr,st,err) { jQuery("#rsperror").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText); }
});
jQuery("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false});
});
</script>

customers/json.ctp
<?= $javascript->object($customers); ?>