Skip to content

Commit

Permalink
new methods: setPreResultCallback, setColumnSearchType, getColumnSear…
Browse files Browse the repository at this point in the history
…chType

updated readme with details on new methods
  • Loading branch information
unknown committed May 28, 2015
1 parent 5deb55c commit 6bfa376
Show file tree
Hide file tree
Showing 2 changed files with 130 additions and 8 deletions.
46 changes: 45 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ This library requires **DataTables 1.10 >**

* Drastically Reduces PHP Code Necessary To Generate a Server Side Table

Chnage Log
-----
* **v1.1**
* New Method `setPreResultCallback(function())`
* New Method `setColumnSearchType(colName, type)` / `getColumnSearchType(colName)`

Install
-----

Expand Down Expand Up @@ -54,9 +60,47 @@ Name | Description | Return
`joinArray` | Join additional tables for DataTable columns to reference. *Tip: Join Types CAN be specifed by using a pipe in the key value `'table_to_join b|left outer'`*| **Assoc. Array** *Key*=Table To Join *Value*=SQL Join Expression.
`whereClauseArray`| Append Static SQL to the generated Where Clause| **Assoc. Array** *Key*= Column Name *Value*=Value To Filter **OR** *NULL*

Methods
----
`setPreResultCallback(function)`
This will get called after the library constructs the associative array that will get converted into JSON. This allows for the manipulation of the data
in the JSON or to add custom properties to the JSON before it is pushed to the browser. Make sure that you use the & when getting the data rows, otherwise,
you will end up with a copy of the array and it will not affect the json. Below is an example of how it is used.
```php
$this -> datatable -> setPreResultCallback(
function(&$json) {
$rows =& $json['data'];
foreach($rows as &$r) {
// example of nested object in row when the
// data propterty in the javascript looks like "$.url"
if(empty($r['$']['url']) === FALSE) {
$newUrl = 'http://www.changeurl.com';
$r['$']['url'] = $newUrl;
}

// change the value of the gender in the Json. data property in the javascript looks like "gender"
$r['gender'] = $r['gender'] == 'M' ? 'Male' : 'Female';


}


$json['a_custom_property'] = 'Check me out with firebug!';
}
);
```

`setColumnSearchType(columnName, type)`
Set the matching type to be done for a given column. This will default to "after" if not specified
*columnName*(string) - Name of the column matching what was passed in from the JavaScript in the data property
*type*(string) - Type of search to perform. This will control the % wildcard on the like. valid values are: before, after, both, none
```php
$this -> datatable -> setColumnSearchType('$.url', 'both');
```


`getColumnSearchType(columnName)`
Returns the current matching for a given column
*columnName*(string) - Name of the column matching what was passed in from the JavaScript in the data property

Basic DatatableModel Implementation
--------
Expand Down
92 changes: 85 additions & 7 deletions libraries/Datatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,19 @@
*/
class Datatable{

private static $VALID_MATCH_TYPES = array('before', 'after', 'both', 'none');

var $model;
private $model;

var $CI;
private $CI;

private $rowIdCol;

private $preResultFunc = FALSE;

// assoc. array. key is column name being passed from the DataTables data property and value is before, after, both, none
private $matchType = array();

var $rowIdCol;

/**
* @params
Expand Down Expand Up @@ -67,13 +74,72 @@ public function __construct($params) {

}

/**
* Register a function that will fire after the JSON object is put together
* in the library, but before sending it to the browser. The function should accept 1 parameter
* for the JSON object which is stored as associated array.
*
* IMPORTANT: Make sure to add a & in front of the parameter to get a reference of the Array,otherwise
* your changes will not be picked up by the library
*
* function(&$json) {
* //do some work and add to the json if you wish.
* }
*/
public function setPreResultCallback($func) {
if(is_object($func) === FALSE || ($func instanceof Closure) === FALSE) {
throw new Exception('Expected Anonymous Function Parameter Not Received');
}

$this -> preResultFunc = $func;

return $this;
}


/**
* Sets the wildcard matching to be a done on a specific column in the search
*
* @param col
* column sepcified in the DataTables "data" property
* @param type
* Type of wildcard search before, after, both, none. Default is after if not specified for a column.
* @return Datatable
*/
public function setColumnSearchType($col, $type) {
$type = trim(strtolower($type));
//make sure we have a valid type
if(in_array($type, self :: $VALID_MATCH_TYPES) === FALSE) {
throw new Exception('[' . $type . '] is not a valid type. Must Use: ' . implode(', ', self :: $VALID_MATCH_TYPES));
}

$this -> matchType[$col] = $type;

// log_message('info', 'setColumnSearchType() ' . var_export($this -> matchType, TRUE));

return $this;
}

/**
* Get the current search type for a column
*
* @param col
* column sepcified in the DataTables "data" property
*
* @return search type string
*/
public function getColumnSearchType($col) {
// log_message('info', 'getColumnSearchType() ' . var_export($this -> matchType, TRUE));
return isset($this -> matchType[$col]) ? $this -> matchType[$col] : 'after';
}

/**
* @param formats
* Associative array.
* Key is column name
* Value format: percent, currency, date, boolean
*/
public function datatableJson($formats = array()) {
public function datatableJson($formats = array(), $debug = FALSE) {

$f = $this -> CI -> input;
$start = (int)$f -> post('start');
Expand Down Expand Up @@ -150,6 +216,9 @@ public function datatableJson($formats = array()) {
return $jsonArry;
}

if($debug === TRUE) {
$jsonArry['debug_sql'] = $this -> CI -> db -> last_query();
}

//process the results and create the JSON objects
$dataArray = array();
Expand Down Expand Up @@ -207,14 +276,19 @@ public function datatableJson($formats = array()) {
$jsonArry['recordsTotal'] = $totalRecords;
$jsonArry['recordsFiltered'] = $totalRecords;
$jsonArry['data'] = $dataArray;
$jsonArry['debug'] = $whereDebug;
//$jsonArry['debug'] = $whereDebug;

if($this -> preResultFunc !== FALSE) {
$func = $this -> preResultFunc;
$func($jsonArry);
}

return $jsonArry;

}

private function formatValue($formats, $column, $value) {
if (isset($formats[$column]) === FALSE) {
if (isset($formats[$column]) === FALSE || trim($value) == '') {
return $value;
}

Expand Down Expand Up @@ -254,6 +328,7 @@ private function formatValue($formats, $column, $value) {
//fetch the data and get a total record count
private function sqlJoinsAndWhere() {
$debug = '';
$this -> CI -> db-> _protect_identifiers = FALSE;
$this -> CI -> db -> from($this -> model -> fromTableStr());

$joins = $this -> model -> joinArray() === NULL ? array() : $this -> model -> joinArray();
Expand All @@ -275,6 +350,8 @@ private function sqlJoinsAndWhere() {
foreach($f -> post('columns') as $c) {
if($c['search']['value'] !== '') {
$colName = $c['data'];
$searchType = $this -> getColumnSearchType($colName);
//log_message('info', 'colname[' . $colName . '] searchtype[' . $searchType . ']');
//handle custom sql expressions/subselects
if(substr($colName, 0, 2) === '$.') {
$aliasKey = substr($colName, 2);
Expand All @@ -285,7 +362,8 @@ private function sqlJoinsAndWhere() {
$colName = $customExpArray[$aliasKey];
}
$debug .= 'col[' . $c['data'] .'] value[' . $c['search']['value'] . '] ' . PHP_EOL;
$this -> CI -> db -> like($colName, $c['search']['value'], 'after');
// log_message('info', 'colname[' . $colName . '] searchtype[' . $searchType . ']');
$this -> CI -> db -> like($colName, $c['search']['value'], $searchType);
}
}

Expand Down

0 comments on commit 6bfa376

Please sign in to comment.