I am using jqGrid with the option sortable:true
and also using the columnChooser plugin.
I would like to create a reset button which will
However, how do I accomplish the first point reordering the column to original state.
Restore hidden
state of all columns is very simple and you found already the corresponding code examples. Thus I answer how to reset the column order.
The problem is that the method remapColumns
which can be used to reorder the columns use column numbers instead of column names. The same problem exist in many other methods or internal parameters of jqGrid. To use the method remapColumns
you need to use the index of columns based on the current index order. After the user changed the order of columns multiple times it would be difficult to provide the column numbers which you want to have relatively to the current column order. It would be much more easy to hold the names of columns instead of column indexes.
I develop free jqGrid as a fork of jqGrid after Tony had changed the licence agreement of jqGrid and renamed it to Guriddo jqGrid JS. I implemented many changes in jqGrid which disturbs my and have implemented many new features. One from the changes was moving all internal options to holding names instead of indexes as far it was possible without breaking the compatibility to the previous versions. I added the method remapColumnsByName
, which simplifies the usage of column remapping (see the answer with the demo).
The implementation of your requirements in free jqGrid could be very simple. You need just save the original column order in an array and then use it as the parameter of remapColumnsByName
to reset the columns
$("#grid1").jqGrid({
...
onInitGrid: function () {
var p = $(this).jqGrid("getGridParam");
// save names of columns in custom option of jqGrid
p.originalColumnOrder = $.map(p.colModel, function (cm) {
return cm.name;
});
//alert(JSON.stringify(p.originalColumnOrder));
}
}).jqGrid("navGrid", { add: false, edit: false, del: false })
.jqGrid("navButtonAdd", {
buttonicon: "fa-repeat",
caption: "",
title: "Reset original column order",
onClickButton: function () {
var $self = $(this), p = $self.jqGrid("getGridParam");
$self.jqGrid("remapColumnsByName", p.originalColumnOrder, true);
}});
See the demo https://jsfiddle.net/OlegKi/r6b2os5b/2/
If you can't migrate to free jqGrid because of some reasons then you have to simulate the same behavior. You should save original column order as array of column names and then to convert the names to indexes directly before calling of remapColumns
. It should work too.