columnDefs and savestate (1.10.13)
columnDefs and savestate (1.10.13)
What I want to achieve is a column toggle (have a set of available columns, and allow them to be toggled). The way I was attempting to achieve this was:
a) Build the DOM with all columns
b) Initialize the table with the columns that I want
c) Present the selection of columns to the user, and if they toggle columns repeat steps (a) and (b)
I know this isn't terribly efficient, but my table size is relatively small, and mostly it works well if savestate is not enabled.
If savestate is enabled, then the "visible" property of the column appears to be ignored.
This works, and hides the column(s), but doesn't save state:
$('#' + tableid).DataTable(
{
"columnDefs": [
{
"targets": [0],
"visible": true,
"searchable": false
},
{
"targets": [1, 2],
"visible": true,
"searchable": true
},
{
"targets": [3],
"visible": false,
"searchable": true
}
]
}
);
This saves state properly, but shows all columns:
$('#' + tableid).DataTable(
{
"columnDefs": [
{
"targets": [0],
"visible": true,
"searchable": false
},
{
"targets": [1, 2],
"visible": true,
"searchable": true
},
{
"targets": [3],
"visible": false,
"searchable": true
}
],
stateSave: true
}
);
};
To be honest, I would be OK with any of the following outcomes:
1) A widget that would allow me to toggle columns
2) A way of toggling columns on an initialized table, rather than destroying and re-creating (am I missing something in the docs?)
3) A complete hack that involves messing with the saved state
I really like to have state saved, since re-drawing columns isn't great user experience if they have made search or other selections, but I also need to be able to toggle columns, since I potentially have too many to comfortably fit on a page and some are only needed occasionally.
Thanks,
Dave
This question has accepted answers - jump to:
Answers
OK - so I found the columns API, and something along the lines of this post-initialization works (coldefs is my own data structure):
Not sure why something that isn't available by default to the user would override the init settings, but I guess it isn't that hard to work around.
Dave
Perhaps you want this:
https://datatables.net/extensions/buttons/examples/column_visibility/simple.html
It will be, yes. It is the value that is stored in the state that is used rather than the initialisation option (otherwise the state wouldn't be used!). You may need to clear the state using
state.clear()
.Allan
I ended up rolling my own for greater control of the look and feel. I think my primary mistake was trying to "force" the table to do what I wanted - after running around in circles for a while I just got to:
I was way overthinking step two, trying to clear the state to set what the user already had set while initializing the table, taking into account defaults etc. Works nicely now.
Good to hear - thanks for the update!
Allan