Options
-
ajax
-
url
string
""
The search url/JSON data source.
-
type
string
GET
The ajax method in which to execute the search url/JSON data source.
-
templateUrl
string
options.templateDir + options.theme + "/row.html"
The url to the row template.
-
optionsUrl
string
""
The url to the JSON source for sorting/heading names
-
key
string
dataTemplates
The ajaxExtend key.
-
text
string
Retrieving Search Results
The processing text for ajaxExtend to display.
-
abort
Boolean
false
To decide whether to cancel searching.
-
url
string
""
-
Classes
-
empty
string
dataTemplatesEmptyContent
The empty row class.
-
empty
string
dataTemplatesEmptyContent
-
Language
-
searchText
string
Search
The placeholder for the search input.
-
showingText
string
Showing {0} to {1} of {2}
The template text for showing information.
-
empty
string
No Results
The text for when there are no results.
-
title
string
""
The text used to set the text in the header bar.
-
relevance
string
Relevance
The text used to to order by relevance.
-
searchText
string
Search
-
scroll
Boolean
false
Whether to enable scrolling.
-
scrollMin
int
14
Minimum number of items to start scrolling.
-
scrollY
string
400px
Scroll viewport height.
-
scrollX
string
auto
Scroll viewport width.
-
sorting
Boolean
true
Whether to enable sorting if data source method is POST
-
relevance
Boolean
true
Whether to enable relevance sorting if data source method is POST
This is for use with server full text searches that return a relevance.
-
searching
Boolean
true
Whether to enable searching if data source method is POST
-
header
Boolean
true
Whether to enable the auto header.
-
headerId
string
""
Selector for header.
-
beforeSend
Function
function( dataTemplatesObject self ){}
Function to run before searching.
-
afterSend
Function
function( PlainObject data, dataTemplatesObject self, Function callback ){ if($.isFunction(callback)){ callback(data); } }
Function to run after retrieving results.
-
completeCallback
Function
function( dataTemplatesObject self ){}
Function to run after searching.
-
rowClickCallback
Function
function( int id ){}
Function to run on row click.
-
createdRow
Function
function( JQueryHTMLObject row, PlainObject data, dataTemplatesObject self ){}
Function to run when a row is created, to be run as well as the below.
-
rowCreatedRow
Function
function( JQueryHTMLObject row, PlainObject data, dataTemplatesObject self ){ var id = row.attr('id'); var options = self.options; if(options.multiSelect){ row.on('click', {'self': self, 'id': id}, function (e) { var self = e.data['self']; var id = e.data['id']; self.check(id); }); /// stop the row click happening when the checkbox is clicked row.find('input[type="checkbox"]').on('click', {'self': self, 'id': id}, function (e) { var self = e.data['self']; var id = e.data['id']; if ($(this).prop('checked') == true) { $(this).prop('checked', false); } else { $(this).prop('checked', true); } self.check(id); e.stopPropagation(); }); row.find('label[for="' + options.element.attr('id') + '-' + id + 'Input"]').on('click', {'self': self, 'id': id}, function (e) { var self = e.data['self']; var id = e.data['id']; var input = $('#' + $(this).attr('for')); if (input.prop('checked') == true) { input.prop('checked', false); } else { input.prop('checked', true); } self.check(id); e.stopPropagation(); }); }else { /// Add rowClick event to row row.on('click', {'self': self, 'id': id}, function (e) { var self = e.data['self']; var id = e.data['id']; self.rowClick(id); }); } }
Standard function to run when a row is created, so that it can be overridden.
-
multiSelect
Boolean
false
Whether to enable multi-select mode.
-
paging
Boolean
true
Whether to enable paging.
-
pageNumbers
Boolean
true
Whether to show page number list.
-
pageLength
int
10
Default number of items to show on a page.
-
pageList
Array
[10,25,50,100]
List of different page length options.
-
sort
Array
[[0],['asc']]
Default sort options.
-
autoShow
Boolean
true
Whether to show dataTemplates on load.
-
theme
String
materialize
The theme to use
-
templateDir
String
/templates/dataTemplates/
Theme location.
Attributes
Some of dataTemplates options can be set with attributes.
-
title
Used to set the text in the header bar.
-
multiselect
Used to enable multiselect mode.
-
data-title
This can be used instead of the title attribute to set the text in the header bar.
-
data-ajax-url
Used to set the search url.
-
data-ajax-templateurl
Used to set the template url.
-
data-ajax-optionsurl
Used to set the options url.
-
data-type
Used to set the ajax method.
Methods
-
destroy
$('#id').dataTemplates('destroy');
Destroy dataTemplates.
-
search
$('#id').dataTemplates('search');
Get the data again, with any page, search or sort option current set.
-
check
$('#id').dataTemplates( 'check', id );
Activate checkbox on row, where id is the DT_RowId.
-
deselectAll
$('#id').dataTemplates('deselectAll');
Deselect all rows.
-
selectAll
$('#id').dataTemplates('selectAll');
Select all rows.
-
addRow
var data = {"DT_RowId": 5, "Key":"value", "Key1":"value1" }; $("#id").dataTemplates("addRow", data);
Adds a new row to the dataTemplates.
-
removeRow
$('#id').dataTemplates('removeRow', id);
Remove a row from the dataTemplates. Where id is the DT_RowId of the record to remove.
-
clear
$('#id').dataTemplates('clear');
Clears all rows from the dataTemplates.
-
sort
$('#id').dataTemplates('sort', [[0],['asc']]);
Sort the dataTemplates. Where 0 is the column id in the optionsUrl and 'asc' is ascending. For descending use 'desc'.
-
setOptions
var options = { "ajax": { "key": "dataTemplates", "text": "Get me some records." } }; $('#id').dataTemplates('setOptions', options);
Set options for the dataTemplate.
-
changePage
$('#id').dataTemplates('changePage', pageNumber);
Change to page number.
-
execute
$('#id').dataTemplates({"autoShow": false}); var data = { 'username': $('#username-input'), 'extraInfo': { 'name': 'Badger' } }; $('#id').dataTemplates('execute', data);
Start a search with extra post data variables. These could then be used to customise your search results.
-
getSelected
var checkedRowsArray = $('#id').dataTemplates('getSelected');
Get an array of selected ids.
-
getTotalRecords
var numRecords = $('#id').dataTemplates('getTotalRecords');
Get an number records.
Events
-
_create
$("#id").on("_create", {}, function(e){});
When dataTemplates is finished being created.
-
buildInterface
$("#id").on("buildInterface", {}, function(e, self){});
When dataTemplates is finished being built.
-
selectAll
$("#id").on("selectAll", {}, function(e){});
When dataTemplates selectAll is finished being called.
-
deselectAll
$("#id").on("deselectAll", {}, function(e){});
When dataTemplates deselectAll is finished being called.
-
updatePageLength
$("#id").on("updatePageLength", {}, function(e){});
When dataTemplates updatePageLength is finished being called.
-
sort
$("#id").on("sort", {}, function(e){});
When dataTemplates sort is finished being called.
-
changePage
$("#id").on("changePage", {}, function(e){});
When dataTemplates changePage is finished being called.
-
execute
$("#id").on("execute", {}, function(e){});
When dataTemplates execute is finished being called.
-
setOptions
$("#id").on("setOptions", {}, function(e){});
When dataTemplates setOptions is finished being called.
-
rowClick
$("#id").on("rowClick", {}, function(e){});
When dataTemplates rowClick is finished being called.
-
check
$("#id").on("check", {}, function(e, dataTemplatesObject self){});
When dataTemplates check is finished being called.
-
search
$("#id").on("search", {}, function(e){});
When dataTemplates search is finished being called.
-
searchResults
$("#id").on("searchResults", {}, function(e){});
When dataTemplates searchResults is finished being called.
-
clear
$("#id").on("clear", {}, function(e){});
When dataTemplates clear is finished being called.
-
addRow
$("#id").on("addRow", {}, function(e){});
When dataTemplates addRow is finished being called.
-
removeRow
$("#id").on("removeRow", {}, function(e){});
When dataTemplates removeRow is finished being called.
Examples
Default
The HTML for an inline dataTemplates
<div class="dataTemplates" title="Module Information"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/templates/json/dataTemplates.json" } });
The JSON for optionsURL would be:
{ "results": [ {"html": "Name", "colId": 0, "sort": true}, {"html": "Parent ", "colId": 1, "sort": true}, {"html": "Code", "colId": 2, "sort": true}, {"html": "Online", "colId": 3, "sort": true} ] }
The JSON for URL would be:
{ "iTotalDisplayRecords": 11, "iTotalRecords": 11, "aaData": [ { "0": "Home", "1": "", "2": "HOME", "3": "Yes", "DT_RowId": "1", "DT_RowClass": "" }, { "0": "About", "1": "", "2": "AB", "3": "No", "DT_RowId": "2", "DT_RowClass": "" }, { "0": "Portfolio", "1": "", "2": "PO", "3": "Yes", "DT_RowId": "3", "DT_RowClass": "" }, { "0": "JQuery", "1": "Portfolio", "2": "JQuery", "3": "Yes", "DT_RowId": "4", "DT_RowClass": "" }, { "0": "JQuery Widgets", "1": "Portfolio", "2": "Widgets", "3": "Yes", "DT_RowId": "5", "DT_RowClass": "" }, { "0": "dataTemplates", "1": "JQuery Widgets", "2": "AS", "3": "Yes", "DT_RowId": "6", "DT_RowClass": "" }, { "0": "searchSelect", "1": "JQuery Widgets", "2": "SS", "3": "Yes", "DT_RowId": "7", "DT_RowClass": "" }, { "0": "dataTemplates", "1": "JQuery Widgets", "2": "DT", "3": "Yes", "DT_RowId": "8", "DT_RowClass": "" }, { "0": "templateEngine", "1": "JQuery", "2": "TE", "3": "Yes", "DT_RowId": "9", "DT_RowClass": "" }, { "0": "ajaxExtend", "1": "JQuery", "2": "AA", "3": "Yes", "DT_RowId": "10", "DT_RowClass": "" }, { "0": "Designs", "1": "Portfolio", "2": "DES", "3": "Yes", "DT_RowId": "11", "DT_RowClass": "" } ] }
Multi-Select
The HTML for an inline dataTemplates
<div class="dataTemplates"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/templates/json/dataTemplates.json", "templateUrl": "/templates/dataTemplates/materialize/multiRow.html" }, "multiSelect": true });
The JSON for optionsURL would be:
{ "results": [ {"html": "Name", "colId": 0, "sort": true}, {"html": "Parent ", "colId": 1, "sort": true}, {"html": "Code", "colId": 2, "sort": true}, {"html": "Online", "colId": 3, "sort": true} ] }
The JSON for URL would be:
{ "iTotalDisplayRecords": 11, "iTotalRecords": 11, "allIds": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], "aaData": [ { "0": "Home", "1": "", "2": "HOME", "3": "Yes", "DT_RowId": "1", "DT_RowClass": "" }, { "0": "About", "1": "", "2": "AB", "3": "No", "DT_RowId": "2", "DT_RowClass": "" }, { "0": "Portfolio", "1": "", "2": "PO", "3": "Yes", "DT_RowId": "3", "DT_RowClass": "" }, { "0": "JQuery", "1": "Portfolio", "2": "JQuery", "3": "Yes", "DT_RowId": "4", "DT_RowClass": "" }, { "0": "JQuery Widgets", "1": "Portfolio", "2": "Widgets", "3": "Yes", "DT_RowId": "5", "DT_RowClass": "" }, { "0": "dataTemplates", "1": "JQuery Widgets", "2": "AS", "3": "Yes", "DT_RowId": "6", "DT_RowClass": "" }, { "0": "searchSelect", "1": "JQuery Widgets", "2": "SS", "3": "Yes", "DT_RowId": "7", "DT_RowClass": "" }, { "0": "dataTemplates", "1": "JQuery Widgets", "2": "DT", "3": "Yes", "DT_RowId": "8", "DT_RowClass": "" }, { "0": "templateEngine", "1": "JQuery", "2": "TE", "3": "Yes", "DT_RowId": "9", "DT_RowClass": "" }, { "0": "ajaxExtend", "1": "JQuery", "2": "AA", "3": "Yes", "DT_RowId": "10", "DT_RowClass": "" }, { "0": "Designs", "1": "Portfolio", "2": "DES", "3": "Yes", "DT_RowId": "11", "DT_RowClass": "" } ] }
Paging
Default
The HTML for an inline dataTemplates
<div class="dataTemplates"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/templates/json/dataTemplates.json", "templateUrl": "/templates/dataTemplates/materialize/multiRow.html" }, "paging": true });
Multi-Select
The HTML for an inline dataTemplates
<div class="dataTemplates"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/templates/json/dataTemplates.json", "templateUrl": "/templates/dataTemplates/materialize/multiRow.html" }, "multiSelect": true, "paging": true });
Server Interaction
Default
The HTML for an inline dataTemplates
<div class="dataTemplates"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/controller/dataTemplates.php?func=search", "type": "POST" }, "paging": true, "searching": true, "sorting": true });
The PHP, using MySQL, for ajax.url is:
$requests = json_decode(file_get_contents("php://input"), true); $request = $requests['requestObject']; $limitArray = array(); $columnFilter = array(); $whereArray = array(); $orderArray = array(); $indexColumn = 'id'; $columns = array('name', 'parent','code', 'online'); $iColumnCount = count($columns); /// Paging if (isset($request['iDisplayLength'])){ if($request['iDisplayLength'] != '-1') { $limitArray = array($request['iDisplayStart'], $request['iDisplayLength']); } } /// Get Number of sorted columns $iSortingCols = intval( $request['iSortingCols'] ); /// Global Filtering if ( isset($request['sSearch']) && $request['sSearch'] != "" ) { for ( $i=0 ; $i<$iColumnCount ; $i++ ) { $colData = $columns[$i]; $whereArray[] = array( "key"=>$colData, "operator"=>"LIKE", "term"=>'%'.$request['sSearch'].'%', "type"=>"OR" ); } $columnFilter = $request['sSearch']; } /// Ordering /// Loop through column variables for ( $i=0 ; $i<$iSortingCols ; $i++ ) { /// If sorting on column is true if ( $request[ 'bSortable_'.intval($request['iSortCol_'.$i]) ] == 'true' ) { $key = $columns[intval( $request['iSortCol_'.$i] )]; if( is_array( $key ) ){ $newKey = $key['data']; $key = $newKey; } $orderArray[] = array( "key"=>$key, "direction"=>( $request['sSortDir_'.$i] === 'asc' ? 'ASC' : 'DESC' ) ); } } /// Build SELECT $sql = "SELECT " . $indexColumn . ", " . implode( ', ', $columns ) . " FROM test"; /// Build WHERE $sql_clause = ""; if( count( $whereArray ) > 0 ) { $sql_clause .= " WHERE"; for($i = 0; $i < count( $whereArray ); $i++ ) { $whereClause = $whereArray[$i]; $sql_clause .= " " . $whereClause['key'] . " " . $whereClause['operator'] . " '" . $whereClause['term'] . "' " . $whereClause['type']; $lastType = $whereClause['type']; } /// Remove last type $sql_clause = substr( $sql_clause, 0, -(strlen( $lastType) ) ); } /// Build ORDER BY $sql_order = ""; if( count( $orderArray ) > 0 ) { $sql_order .= " ORDER BY "; for($i = 0; $i < count( $orderArray ); $i++ ) { $orderClause = $orderArray[$i]; $sql_order .= $orderClause['key'] . " " . $orderClause['direction']; } } /// Build LIMIT $sql_limit = ""; if( count( $limitArray ) > 0 ) { $sql_limit .= " LIMIT " . $limitArray[0] . ", " . $limitArray[1]; } $mysql_host = "localhost"; $mysql_user = "user"; $mysql_password = "password"; $database = "test"; $link = mysql_connect( $mysql_host, $mysql_user, $mysql_password ) or die( 'Could not connect: ' . mysql_error() ); mysql_select_db( $database ) or die( 'Could not select database' ); $input = array(); /// Performing SQL query $sql = $sql . $sql_clause . $sql_order; $result_all = mysql_query( $sql ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); $result = mysql_query( $sql . $sql_limit ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); if( mysql_num_rows( $result ) > 0 ) { $input['count'] = mysql_num_rows( $result ); $input['totalCount'] = mysql_num_rows( $result_all ); $input['data'] = array(); while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) { $input['data'][] = $row; } } /// array format $output = array( "sEcho" => intval($request['sEcho']), "iTotalRecords" => $input['count'], "iTotalDisplayRecords" => $input['totalCount'], "sql" => $sql . $sql_limit, "aaData" => array() ); /// Put data into DataTables format. if ( count( $input['data'] ) > 0 ){ foreach ( $input['data'] as $row ) { $row["DT_RowId"] = $row[$indexColumn]; if ( isset($row['class'] ) ) { $row["DT_RowClass"] = $row['class']; } $i = 0; foreach( $columns as $column ) { if( $column != $indexColumn ){ if( !is_null( $row[$column] ) ) { $row[$i] = $row[$column]; }else{ $row[$i] = ''; } unset($row[$column]); $i++; } } unset($row[$indexColumn]); unset($row['class']); $output['aaData'][] = $row; } }else{ $output['aaData'] = array(); } echo json_encode( $output ); exit;
Multi-Select
The HTML for an inline dataTemplates
<div class="dataTemplates"> </div>
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ "templateDir": "/templates/dataTemplates/", "ajax": { "optionsUrl": "/templates/json/dataTemplatesOptions.json", "url": "/controller/dataTemplates.php?func=search", "templateUrl": "/templates/dataTemplates/materialize/multiRow.html", "type": "POST" }, "multiSelect": true, "paging": true, "searching": true, "sorting": true });
The PHP, using MySQL, for ajax.url is:
$requests = json_decode(file_get_contents("php://input"), true); $request = $requests['requestObject']; $limitArray = array(); $columnFilter = array(); $whereArray = array(); $orderArray = array(); $indexColumn = 'id'; $columns = array('name', 'parent','code', 'online'); $iColumnCount = count($columns); /// Paging if (isset($request['iDisplayLength'])){ if($request['iDisplayLength'] != '-1') { $limitArray = array($request['iDisplayStart'], $request['iDisplayLength']); } } /// Get Number of sorted columns $iSortingCols = intval( $request['iSortingCols'] ); /// Global Filtering if ( isset($request['sSearch']) && $request['sSearch'] != "" ) { for ( $i=0 ; $i<$iColumnCount ; $i++ ) { $colData = $columns[$i]; $whereArray[] = array( "key"=>$colData, "operator"=>"LIKE", "term"=>'%'.$request['sSearch'].'%', "type"=>"OR" ); } $columnFilter = $request['sSearch']; } /// Ordering /// Loop through column variables for ( $i=0 ; $i<$iSortingCols ; $i++ ) { /// If sorting on column is true if ( $request[ 'bSortable_'.intval($request['iSortCol_'.$i]) ] == 'true' ) { $key = $columns[intval( $request['iSortCol_'.$i] )]; if( is_array( $key ) ){ $newKey = $key['data']; $key = $newKey; } $orderArray[] = array( "key"=>$key, "direction"=>( $request['sSortDir_'.$i] === 'asc' ? 'ASC' : 'DESC' ) ); } } /// Build SELECT $sql = "SELECT " . $indexColumn . ", " . implode( ', ', $columns ) . " FROM test"; /// Build WHERE $sql_clause = ""; if( count( $whereArray ) > 0 ) { $sql_clause .= " WHERE"; for($i = 0; $i < count( $whereArray ); $i++ ) { $whereClause = $whereArray[$i]; $sql_clause .= " " . $whereClause['key'] . " " . $whereClause['operator'] . " '" . $whereClause['term'] . "' " . $whereClause['type']; $lastType = $whereClause['type']; } /// Remove last type $sql_clause = substr( $sql_clause, 0, -(strlen( $lastType) ) ); } /// Build ORDER BY $sql_order = ""; if( count( $orderArray ) > 0 ) { $sql_order .= " ORDER BY "; for($i = 0; $i < count( $orderArray ); $i++ ) { $orderClause = $orderArray[$i]; $sql_order .= $orderClause['key'] . " " . $orderClause['direction']; } } /// Build LIMIT $sql_limit = ""; if( count( $limitArray ) > 0 ) { $sql_limit .= " LIMIT " . $limitArray[0] . ", " . $limitArray[1]; } $mysql_host = "localhost"; $mysql_user = "user"; $mysql_password = "password"; $database = "test"; $link = mysql_connect( $mysql_host, $mysql_user, $mysql_password ) or die( 'Could not connect: ' . mysql_error() ); mysql_select_db( $database ) or die( 'Could not select database' ); $input = array(); /// Performing SQL query $sql = $sql . $sql_clause . $sql_order; $result_all = mysql_query( $sql ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); $result = mysql_query( $sql . $sql_limit ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); if( mysql_num_rows( $result ) > 0 ) { $input['count'] = mysql_num_rows( $result ); $input['totalCount'] = mysql_num_rows( $result_all ); $input['data'] = array(); while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) { $input['data'][] = $row; } } /// array format $output = array( "sEcho" => intval($request['sEcho']), "iTotalRecords" => $input['count'], "iTotalDisplayRecords" => $input['totalCount'], "sql" => $sql . $sql_limit, "aaData" => array(), "allIds" => array() ); /// Put data into DataTables format. if ( count( $input['data'] ) > 0 ){ foreach ( $input['data'] as $row ) { $row["DT_RowId"] = $row[$indexColumn]; $output['allIds'][] = $row[$indexColumn]; if ( isset($row['class'] ) ) { $row["DT_RowClass"] = $row['class']; } $i = 0; foreach( $columns as $column ) { if( $column != $indexColumn ){ if( !is_null( $row[$column] ) ) { $row[$i] = $row[$column]; }else{ $row[$i] = ''; } unset($row[$column]); $i++; } } unset($row[$indexColumn]); unset($row['class']); $output['aaData'][] = $row; } }else{ $output['aaData'] = array(); } echo json_encode( $output ); exit;
Dealing with Dates
This version of the PHP script also includes types, the date type is to be used with a MySQL DateTime column:
$requests = json_decode(file_get_contents("php://input"), true); $request = $requests['requestObject']; $limitArray = array(); $columnFilter = array(); $whereArray = array(); $orderArray = array(); $indexColumn = 'id'; $columns = array('name', 'parent','code', array('data'=>'date', 'type'=>'date')); $iColumnCount = count($columns); /// Paging if (isset($request['iDisplayLength'])){ if($request['iDisplayLength'] != '-1') { $limitArray = array($request['iDisplayStart'], $request['iDisplayLength']); } } /// Get Number of sorted columns $iSortingCols = intval( $request['iSortingCols'] ); /// Global Filtering if ( isset($request['sSearch']) && $request['sSearch'] != "" ) { for ( $i=0 ; $i<$iColumnCount ; $i++ ) { $colData = $columns[$i]; $type = 'string'; if( is_array( $colData )) { $type = $colData['type']; $colData = $colData['data']; } if( $type == 'string' ) { $whereArray[] = array( "key"=>$colData, "operator"=>"LIKE", "term"=>'%'.$request['sSearch'].'%', "type"=>"OR" ); }else if( $type == 'date' ) { $term = $request['sSearch']; if( DateTime::createFromFormat('d/m/Y', $request['sSearch']) !== false ){ $term = DateTime::createFromFormat('d/m/Y H:i:s', $request['sSearch'] . ' 00:00:00')->format('Y-m-d H:i:s'); }else if( DateTime::createFromFormat('Y-m-d', $request['sSearch']) !== false ){ $term = $request['sSearch'] . ' 00:00:00'; } if( $term != '' ) { $termB = str_replace('00:00:00', '23:59:59', $term); $whereArray[] = array( "key" => '(', "operator" => "", "term" => "", "type" => "" ); $whereArray[] = array( "key" => $colData, "operator" => ">=", "term" => $term, "type" => "AND" ); $whereArray[] = array( "key" => $colData, "operator" => "<=", "term" => $termB, "type" => "OR" ); $whereArray[] = array( "key" => ')', "operator" => "", "term" => "", "type" => "OR" ); } } } $columnFilter = $request['sSearch']; } /// Ordering /// Loop through column variables for ( $i=0 ; $i<$iSortingCols ; $i++ ) { /// If sorting on column is true if ( $request[ 'bSortable_'.intval($request['iSortCol_'.$i]) ] == 'true' ) { $key = $columns[intval( $request['iSortCol_'.$i] ) ]; if( is_array( $key ) ){ $newKey = $key['data']; $key = $newKey; } $orderArray[] = array( "key"=>$key, "direction"=>( $request['sSortDir_'.$i] === 'asc' ? 'ASC' : 'DESC' ) ); } } /// Build SELECT $sql = "SELECT " . $indexColumn . ", "; foreach( $columns as $columnD){ $column = $columnD; if( is_array( $columnD )) { $column = $columnD['data']; } $sql .= $column . ', '; } $sql = substr( $sql, 0, -2 ); $sql .= "FROM test"; /// Build WHERE $sql_clause = ""; if( count( $whereArray ) > 0 ) { $sql_clause .= " WHERE"; for($i = 0; $i < count( $whereArray ); $i++ ) { $whereClause = $whereArray[$i]; if( $whereClause['key'] == '(' ) { $sql_clause .= " ("; }else if( $whereClause['key'] == ')' ) { $sql_clause = substr( $sql_clause, 0, -(strlen( $lastType) ) ); $sql_clause .= ") " . $whereClause['type']; }else { $sql_clause .= " " . $whereClause['key'] . " " . $whereClause['operator'] . " '" . $whereClause['term'] . "' " . $whereClause['type']; } $lastType = $whereClause['type']; } /// Remove last type $sql_clause = substr( $sql_clause, 0, -(strlen( $lastType) ) ); } /// Build ORDER BY $sql_order = ""; if( count( $orderArray ) > 0 ) { $sql_order .= " ORDER BY "; for($i = 0; $i < count( $orderArray ); $i++ ) { $orderClause = $orderArray[$i]; $sql_order .= $orderClause['key'] . " " . $orderClause['direction']; } } /// Build LIMIT $sql_limit = ""; if( count( $limitArray ) > 0 ) { $sql_limit .= " LIMIT " . $limitArray[0] . ", " . $limitArray[1]; } $mysql_host = "localhost"; $mysql_user = "user"; $mysql_password = "password"; $database = "test"; $link = mysql_connect( $mysql_host, $mysql_user, $mysql_password ) or die( 'Could not connect: ' . mysql_error() ); mysql_select_db( $database ) or die( 'Could not select database' ); $input = array(); /// Performing SQL query $sql = $sql . $sql_clause . $sql_order; $result_all = mysql_query( $sql ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); $result = mysql_query( $sql . $sql_limit ) or die( 'Query failed: ' . mysql_error() . 'SQL: ' . $sql ); if( mysql_num_rows( $result ) > 0 ) { $input['count'] = mysql_num_rows( $result ); $input['totalCount'] = mysql_num_rows( $result_all ); $input['data'] = array(); while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) { $input['data'][] = $row; } } /// array format $output = array( "sEcho" => intval($request['sEcho']), "iTotalRecords" => $input['count'], "iTotalDisplayRecords" => $input['totalCount'], "sql" => $sql . $sql_limit, "aaData" => array(), "allIds" => array() ); /// Put data into DataTables format. if ( count( $input['data'] ) > 0 ){ foreach ( $input['data'] as $row ) { $row["DT_RowId"] = $row[$indexColumn]; $output['allIds'][] = $row[$indexColumn]; if ( isset($row['class'] ) ) { $row["DT_RowClass"] = $row['class']; } $i = 0; foreach( $columns as $columnD ) { $column = $columnD; $type = "string"; if( is_array( $columnD )) { $column = $columnD['data']; $type = $columnD['type']; } if( $column != $indexColumn ){ if( !is_null( $row[$column] ) ) { if ($type == 'date') { $row[$i] = $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $row[$column])->format('d/m/Y'); }else { $row[$i] = $row[$column]; } }else{ $row[$i] = ''; } unset($row[$column]); $i++; } } unset($row[$indexColumn]); unset($row['class']); $output['aaData'][] = $row; } }else{ $output['aaData'] = array(); } echo json_encode( $output ); exit;
For all you americans out there, change the occurrences of d/m/Y to m/d/Y.
Themes
Materialize (default)
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ theme: "materialize", templateDir: "/templates/dataTemplates/" });
Bootstrap
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ theme: "bootstrap", templateDir: "/templates/dataTemplates/" });
Custom
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ theme: "themeFolderName", templateDir: "/templates/dataTemplates/" });
You would then need to add a folder to the themes directory with the following files:
themeFolderName inline.html itemsItem.html multiRow.html row.html sortItem.html
Please see the supplied theme files for template variable locations
In the above example, the inline template has been altered to have the class row on the dataTemplatesContent div.
The JavaScript initialisation would be:
$('.dataTemplates').dataTemplates({ ajax: { "optionsUrl": "/templates/json/dataTemplatesCustomOptions.json", "url": "/templates/json/dataTemplatesCard.json", "templateUrl": "/templates/dataTemplates/custom/row.html" }, theme: "custom", header: false });
The JSON for the optionsUrl would be:
{ "results": [ {"html": "Image", "colId": 0, "sort": false}, {"html": "Title ", "colId": 1, "sort": true} ] }
The JSON for the url would be:
{ "iTotalDisplayRecords": 5, "iTotalRecords": 5, "aaData": [ { "0": "http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg", "1": "Oooh Blue", "DT_RowId": "1" }, { "0": "http://suamimarlik.com/wp-content/uploads/2013/10/Background-pretty-little-liars-tv-show-33571722-1920-1440.jpg", "1": "Pretty Bubbles", "DT_RowId": "2" }, { "0": "http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg", "1": "More Triangles", "DT_RowId": "3" }, { "0": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTugsDXau02kn6coUN5nRYUGgXHxR0pCGQvKKZzCCLs1ba9pzhF", "1": "Flowers", "DT_RowId": "4" }, { "0": "http://www.planwallpaper.com/static/images/Christmas-Background-Picture-1920-1080-493006.jpeg", "1": "Stars", "DT_RowId": "5" } ] }
The HTMl for the templateUrl would be:
<div class="col s4"> <div class="card hoverable" id="{DT_RowId}"> <div class="card-image"> <img src="{0}" class="responsive-img" /> </div> <div class="card-content"> <span class="card-title">{1}</span> </div> </div> </div>