Split the jqGrid code out a bit further, giving the application controller full responsibility for handling the jqGrid requests. Virtual functions have been added to allow a derived controller to customize this action as needed.

git-svn-id: file:///svn-source/pmgr/branches/ledger_transactions_20090605@111 97e9348a-65ac-dc4b-aefc-98561f571b83
This commit is contained in:
abijah
2009-06-14 00:53:08 +00:00
parent e7b4b21328
commit 90a16c721e
2 changed files with 193 additions and 87 deletions

View File

@@ -63,17 +63,75 @@ class AppController extends Controller {
* - Fetches the actual data requested by jqGrid as XML
*/
function jqGridData($model, $records, $query) {
function jqGridData() {
// Grab a copy of the parameters that control this request
$params = array();
if (isset($this->params['url']) && is_array($this->params['url']))
$params = $this->params['url'];
// Do any preliminary setup necessary
$this->jqGridDataSetup($params);
// Get the top level model for this grid
$model = $this->jqGridDataModel($params);
// Establish the basic query and conditions
$query = array_intersect_key($this->jqGridDataTables($params),
array('link'=>1, 'contain'=>1));
$query['conditions'] = $this->jqGridDataConditions($params);
// Get the number of records prior to pagination
$count = $this->jqGridDataRecordCount($params, $model, $query);
// Verify a few parameters and determine our starting row
$limit = $params['rows'];
$total = ($count < 0) ? 0 : ceil($count/$limit);
$page = ($params['page'] <= 1) ? 1 : (($params['page'] > $total) ? $total : $params['page']);
$start = $limit*$page - $limit;
$sidx = isset($params['sidx']) ? $params['sidx'] : '';
$sord = isset($params['sord']) ? ' ' . $params['sord'] : '';
// Grab the actual records taking pagination into account
$query['group'] = $model->alias . '.id';
$query['order'] = $sidx ? $sidx . $sord : null;
$query['limit'] = $start . ', ' . $limit;
$query['fields'] = $this->jqGridDataFields($params);
$results = $this->jqGridDataRecords($params, $model, $query);
// DEBUG PURPOSES ONLY
$params['query'] = $query;
// Finally, dump out the data
$this->jqGridDataOutputHeader($params);
echo "<?xml version='1.0' encoding='utf-8'?>\n";
echo "<rows>\n";
$this->jqGridDataOutputSummary($params, $page, $total, $count);
$this->jqGridDataOutputRecords($params, $model, $results);
echo "</rows>\n";
// Call out to finalize everything
$this->jqGridDataFinalize($params);
}
/**************************************************************************
**************************************************************************
**************************************************************************
* virtual: jqGridData* functions
* - These set up the context for the jqGrid data, and will
* need to be overridden in the derived class for anything
* other than the most basic of grids.
*/
function jqGridDataSetup(&$params) {
// Assume we're debugging.
// The actual jqGrid request will set this to false
$debug = true;
$model_alias = $model->alias;
$model_id = $model_alias . '.id';
if (isset($this->passedArgs['debug']))
$debug = $this->passedArgs['debug'];
$params['debug'] = $debug;
if (!$debug) {
$this->layout = null;
$this->autoLayout = false;
@@ -81,80 +139,96 @@ class AppController extends Controller {
Configure::write('debug', '0');
}
// Set up some defaults
$page = 1; // page number
$rows = 20; // rows in the grid - rowNum parameter
$sidx = $model_id; // sort column - index from colModel
$sord = 'ASC'; // sort order
// Extract the actual settings from the jqGrid request
if (isset($this->params['url']) && is_array($this->params['url']))
extract($this->params['url']);
// Unserialize our complex structure of fields
// This SHOULD be always set, except when debugging
if (isset($fields))
$fields = unserialize($fields);
if (isset($params['fields']))
$fields = unserialize($params['fields']);
else
$fields = array($model_id);
$fields = array($this->modelClass . '.id');
if (isset($_search) && $_search === 'true') {
$ops = array('eq' => array('op' => null, 'pre' => '', 'post' => ''),
'ne' => array('op' => '<>', 'pre' => '', 'post' => ''),
'lt' => array('op' => '<', 'pre' => '', 'post' => ''),
'le' => array('op' => '<=', 'pre' => '', 'post' => ''),
'gt' => array('op' => '>', 'pre' => '', 'post' => ''),
'ge' => array('op' => '>=', 'pre' => '', 'post' => ''),
'bw' => array('op' => 'LIKE', 'pre' => '', 'post' => '%'),
'ew' => array('op' => 'LIKE', 'pre' => '%', 'post' => ''),
'cn' => array('op' => 'LIKE', 'pre' => '%', 'post' => '%'),
);
$params['fields_str'] = $params['fields'];
$params['fields'] = $fields;
$op = $ops[$searchOper];
$field = $searchField . ($op['op'] ? ' '.$op['op'] : '');
$val = $op['pre'] . $searchString . $op['post'];
$query['conditions'][] = array($field => $val);
}
// Establish some defaults before extracting params
$params = array_merge(array('page' => 1,
'rows' => 20),
$params);
}
// Verify a few parameters and determine our starting row
$total = ($records < 0) ? 0 : ceil($records/$rows);
$page = ($page < 1) ? 1 : (($page > $total) ? $total : $page);
$start = $rows*$page - $rows;
function jqGridDataModel(&$params) {
return $this->{$this->modelClass};
}
// the actual query for the grid data
$query['group'] = $model_id;
$query['order'] = "$sidx $sord";
$query['limit'] = "$start, $rows";
$results = $model->find('all', $query);
function jqGridDataTables(&$params) {
return array('contain' => false);
}
if ($debug) {
function jqGridDataConditions(&$params) {
if (!isset($params['_search']) || $params['_search'] !== 'true')
return array();
$ops = array('eq' => array('op' => null, 'pre' => '', 'post' => ''),
'ne' => array('op' => '<>', 'pre' => '', 'post' => ''),
'lt' => array('op' => '<', 'pre' => '', 'post' => ''),
'le' => array('op' => '<=', 'pre' => '', 'post' => ''),
'gt' => array('op' => '>', 'pre' => '', 'post' => ''),
'ge' => array('op' => '>=', 'pre' => '', 'post' => ''),
'bw' => array('op' => 'LIKE', 'pre' => '', 'post' => '%'),
'ew' => array('op' => 'LIKE', 'pre' => '%', 'post' => ''),
'cn' => array('op' => 'LIKE', 'pre' => '%', 'post' => '%'),
);
$op = $ops[$params['searchOper']];
$field = $params['searchField'] . ($op['op'] ? ' '.$op['op'] : '');
$val = $op['pre'] . $params['searchString'] . $op['post'];
return array($field => $val);
}
function jqGridDataFields(&$params) {
return null;
}
function jqGridDataRecordCount(&$params, $model, $query) {
return $model->find('count', $query);
}
function jqGridDataRecords(&$params, $model, $query) {
return $model->find('all', $query);
}
function jqGridDataOutputHeader(&$params) {
if ($params['debug']) {
ob_start();
print_r(compact('records', 'rows', 'total', 'page', 'start'));
}
else {
header("Content-type: text/xml;charset=utf-8");
}
}
echo "<?xml version='1.0' encoding='utf-8'?>\n";
echo "<rows>\n";
/* echo " <req><![CDATA[\n" . print_r($this->params['url'], true) . "\n]]></req>\n"; */
/* echo " <query><![CDATA[\n" . print_r($query, true) . "\n]]></query>\n"; */
function jqGridDataOutputSummary(&$params, $page, $total, $records) {
echo " <params><![CDATA[\n" . print_r($params, true) . "\n]]></params>\n";
echo " <page>$page</page>\n";
echo " <total>$total</total>\n";
echo " <records>$records</records>\n";
}
foreach ($results AS $result) {
function jqGridDataOutputRecords(&$params, $model, $records) {
$model_alias = $model->alias;
foreach ($records AS $record) {
// Add the calculated fields (if any), to the model fields
if (isset($result[0]))
$result[$model_alias] += $result[0];
if (isset($record[0]))
$record[$model_alias] += $record[0];
echo " <row id='{$result[$model_alias]['id']}'>\n";
foreach ($fields AS $field) {
list($tbl, $col) = explode(".", $field);
if (isset($col))
$data = $result[$tbl][$col];
else
$data = $result[$model_alias][$tbl];
echo " <row id='{$record[$model_alias]['id']}'>\n";
foreach ($params['fields'] AS $field) {
if (preg_match("/\./", $field)) {
list($tbl, $col) = explode(".", $field);
$data = $record[$tbl][$col];
}
else {
$data = $record[$model_alias][$field];
}
// be sure to put text data in CDATA
if (preg_match("/^\d*$/", $data))
@@ -164,9 +238,10 @@ class AppController extends Controller {
}
echo " </row>\n";
}
echo "</rows>\n";
}
if ($debug) {
function jqGridDataFinalize(&$params) {
if ($params['debug']) {
$xml = ob_get_contents();
ob_end_clean();
@@ -177,6 +252,5 @@ class AppController extends Controller {
echo ("\n<PRE>\n$xml\n</PRE>\n");
}
}
}
?>

View File

@@ -46,45 +46,77 @@ class CustomersController extends AppController {
/**************************************************************************
**************************************************************************
**************************************************************************
* action: jqGridData
* - Fetches the actual data requested by jqGrid as XML
* virtuals: jqGridData
* - With the application controller handling the jqGridData action,
* these virutal functions ensure that the correct data is passed
* to jqGrid.
*/
function jqGridData() {
function jqGridDataSetup(&$params) {
parent::jqGridDataSetup($params);
if (!isset($params['action']))
$params['action'] = 'all';
}
$action = 'all';
if (isset($this->params['url']['action']))
$action = $this->params['url']['action'];
// Set up the basic query
$query = array
function jqGridDataTables(&$params) {
return array
('link' =>
array(// Models
'PrimaryContact',
'CurrentLease' => array('fields' => array()),
),
'fields' => 'Customer.*, COUNT(CurrentLease.id) AS lease_count',
);
}
// Calculate the number of rows for the query, and figure out
// any special query conditions that will be necessary
$records = $this->Customer->find('count', array('contain'=>false));
if ($action != 'all') {
$records_past = $this->Customer->find('count',
array('link' => array('CurrentLease' => array('fields' => array())),
'conditions' => 'CurrentLease.id IS NULL'));
function jqGridDataFields(&$params) {
return array('Customer.*',
'COUNT(CurrentLease.id) AS lease_count');
}
if ($action == 'current') {
$records = $records - $records_past;
$query['conditions'][] = 'CurrentLease.id IS NOT NULL';
}
elseif ($action == 'past') {
$records = $records_past;
$query['conditions'][] = 'CurrentLease.id IS NULL';
}
function jqGridDataConditions(&$params) {
$conditions = parent::jqGridDataConditions($params);
if ($params['action'] === 'current') {
$conditions[] = 'CurrentLease.id IS NOT NULL';
}
elseif ($params['action'] === 'past') {
$conditions[] = 'CurrentLease.id IS NULL';
}
parent::jqGridData($this->Customer, $records, $query);
return $conditions;
}
function jqGridDataRecordCount(&$params, $model, $query) {
// We don't have a good way to use the query to obtain
// our count. The problem is that we're relying on the
// group by for the query, which will destroy the count,
// whether we omit the group by or leave it in.
// So, build a fresh query for counting.
$query['conditions'] = parent::jqGridDataConditions($params);
$count = $model->find('count',
array_merge(array('link' => array_diff_key($query['link'],
array('CurrentLease'=>1))),
array_diff_key($query, array('link'=>1))));
if ($params['action'] === 'all')
return $count;
$query['conditions'][] = 'CurrentLease.id IS NULL';
$count_past = $model->find('count', $query);
// Since we can't easily count 'current' directly, we
// can quickly derive it since 'current' customers
// are mutually exclusive to 'past' customers.
if ($params['action'] == 'current')
$count = $count - $count_past;
elseif ($params['action'] == 'past') {
$count = $count_past;
}
return $count;
}