Skip to content

Commit 1c6ff2e

Browse files
committed
Improve statefulness in tables
1 parent f60c43e commit 1c6ff2e

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

src/DataTableState.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ private function handleOrderBy(ParameterBag $parameters)
108108
$this->orderBy = [];
109109
foreach ($parameters->get('order', []) as $order) {
110110
$column = $this->getDataTable()->getColumn((int) $order['column']);
111-
$this->addOrderBy($column, $order['dir']);
111+
$this->addOrderBy($column, $order['dir'] ?? DataTable::SORT_ASCENDING);
112112
}
113113
}
114114
}

src/Resources/assets/js/datatables.js

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@
3131
var persistOptions = config.state === 'none' ? {} : {
3232
stateSave: true,
3333
stateLoadCallback: function(settings) {
34-
state.time = Date.now();
35-
return state;
34+
var copy = JSON.parse(JSON.stringify(state));
35+
copy.time = Date.now();
36+
return copy;
3637
}
3738
};
3839

@@ -45,7 +46,7 @@
4546
_init: true
4647
}
4748
}).done(function(data) {
48-
var rebuild = true, cached;
49+
var rebuild = (Object.keys(state).length === 0), cached, baseState;
4950

5051
var dtOpts = $.extend({}, data.options, config.options, options, persistOptions, {
5152
ajax: function (request, drawCallback, settings) {
@@ -66,7 +67,25 @@
6667
});
6768

6869
root.html(data.template);
69-
fulfill(dt = $('table', root).DataTable(dtOpts));
70+
dt = $('table', root).DataTable(dtOpts);
71+
if (config.state !== 'none') {
72+
dt.on('stateSaveParams.dt', (e, settings, data) => {
73+
//$.extend(data, $('form[name={{ filterForm.vars.name }}]').serializeObject());
74+
data = $.param(data).split('&');
75+
baseState = baseState || data;
76+
var diff = data.filter(el => { return baseState.indexOf(el) === -1 && el.indexOf('time=') !== 0; });
77+
switch (config.state) {
78+
case 'fragment':
79+
history.replaceState(null, null, '#' + decodeURIComponent(diff.join('&')));
80+
break;
81+
case 'query':
82+
history.replaceState(null, null, '#' + decodeURIComponent(diff.join('&')));
83+
break;
84+
}
85+
});
86+
}
87+
88+
fulfill(dt);
7089
}).fail(function(xhr, cause, msg) {
7190
console.error('DataTables request failed: ' + msg);
7291
reject(cause);

0 commit comments

Comments
 (0)