Programmatically change grid column order - extjs

I want to sort the columns in my grid, just like the rows. I have made a simple sort function that is called from an actioncolumn handler:
sortColumns:function(record) { // The record after which's values the columns are ordered
var columns = this.columns;
Ext.Array.sort(columns,function(col1,col2) {
if(record.get(col1.dataIndex) > record.get(col2.dataIndex)) return 1;
if(record.get(col1.dataIndex) < record.get(col2.dataIndex)) return -1;
if(col1.dataIndex > col2.dataIndex) return 1;
if(col1.dataIndex < col2.dataIndex) return 1;
throw new Error("Comparing column with itself shouldn't happen.");
});
this.setColumns(columns);
});
The setColumns line now throws the error
Cannot add destroyed item 'gridcolumn-1595' to Container 'headercontainer-1598'
which is because the "old" columns are destroyed first, and then the "new" columns, which are the same and thus destroyed, are applied.
I only want to change the order, but I didn't find any function to do it. Do you know how to do it?
Drag-drop ordering of the columns works, so it is doable; but I don't find the source code where sencha did implement that drag-drop thingy. Do you know where to look for that code?

Reconfigure method needs two arguments
grid.reconfigure(store, columns)
Here is the fiddle that changes the columns programatically https://fiddle.sencha.com/#fiddle/17bk

I have found that columns are items of the grid's headerCt, so the following works well, and unlike the other answers, it does not create new column components, keeping the column state and everything:
var headerCt = normalGrid.headerCt,
columns = headerCt.items.getRange();
Ext.Array.sort(columns,function(col1,col2) {
if(record.get(col1.dataIndex) < record.get(col2.dataIndex)) return -1;
if(record.get(col1.dataIndex) > record.get(col2.dataIndex)) return 1;
if(col1.dataIndex < col2.dataIndex) return -1;
if(col1.dataIndex > col2.dataIndex) return 1;
return 0;
});
headerCt.suspendLayouts();
for(var i=0;i<columns.length;i++)
{
headerCt.moveAfter(columns[i],(columns[i-1] || null));
}
headerCt.resumeLayouts(true);

There is a reconfigure method which can be used to achieve reordering, e.g:
grid.reconfigure(columns);
Check the this.

I couldn't manage to do it without storing columns in a custom field and using reconfigure, maybe someone can suggest something better (reconfigure doesn't work well with just regular columns field it seems):
Ext.define('MyGrid', {
extend: 'Ext.grid.Panel',
//just renamed "columns"
myColumnConfigs: [
//all your column configs
]
});
//to rearrange inside controller, also need to call it on grid render
var grid = this.getView();
var columns = grid.myColumnConfigs;
//...do your sorting on columns array
grid.reconfigure(columns);

Related

Adding a custom "ALL" (Total) row to the top of an ag-grid that is selectable like any other row

I have an ag-grid table with 2 columns - one text and one number.
I need to add a custom row to the top of my ag-grid table with the total value of the number column and the word "ALL" in the text column.
This needs to be on the top. And should not change its position even if the table is sorted.
Also, the row should be selectable.
Any help in this regard will be highly appreciated!
Sounds like you are describing Row Pinning which is already a feature in AG Grid. However, since you've also stated that row selection is a requirement, this will not be possible with Row Pinning as it's not supported.
Instead what I'd recommend is adding an extra row object inside the rowData for the custom row, and handling the update of the number column and the custom row position yourself when necessary:
If you want to handle the total value of the number column then you can use the following logic:
function updateTotalRowNode() {
let totalRowNode;
let sum = 0;
gridOptions.api.forEachNode((node) => {
if (node.data.totalRow) {
totalRowNode = node;
} else {
sum += node.data.gold;
}
});
totalRowNode.setDataValue('gold', sum);
}
If you want to keep the custom row always on the top row then you can implement the postSort callback:
postSort: (rowNodes) => {
// here we put All row on top while preserving the sort order
let nextInsertPos = 0;
for (let i = 0; i < rowNodes.length; i++) {
const athlete = rowNodes[i].data.athlete;
if (athlete === 'All') {
rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
nextInsertPos++;
}
}
},
See the following plunker for the implementation.

ag-Grid: use floatingBottomRowData when Pivoting

I'm trying to recreate the following pivot table with ag-Grid:
Using floatingBottomRowData I can't find a way to pass the values for all generated columns. so one pair of values is getting duplicated:
My goal is to access the column group value for each cell of the floating row.
Right now I can't tell the difference between column groups (resulting in duplicated values).
Is there any way to differentiate the different (col1, col2) pairs?
The answer that was given in the ag-grid forum is:
to get the pivot key, do this:
floatingCellRenderer: function(params) {
if (gridOptions.columnApi.isPivotMode()) {
console.log(params.column.getId());
var parent = params.column.getParent();
if (parent) {
var pivotKey = console.log(parent.getOriginalColumnGroup().getColGroupDef().pivotKeys[0]);
}
}
}
to get the columns in the active pivot, use the column API, eg columnApi.getPivotColumns(), which will return a list of the pivot columns. this will be in order, so if you have many columns, there will be one for each parent you traverse.
What I did for the pivot_ type of pinned row: I added a custom pinned row renderer to my column, where I expect the aggregated function to show (for me it was for sum and avg). If I change the pivot function I called a refresh on the pinned row to set the new values.
pinnedRowCellRenderer: function (render)
{
for (var obj_id in render.data)
{
if (obj_id == render.column.colId)
{
return '<div>' + render.data[obj_id] + '</div>';
}
}
return '<div></div>';
}
And the result looks like this:
Result image
Hope it helps!

Preserve selection in angular ui-grid while updating data

http://plnkr.co/edit/r9hMZk?p=preview
I have a ui-grid where I have enabled multi selection. I want to be able to update the data whilst preserving the selection. If I just update the data then the selection is not preserved.
$scope.gridOpts.data = data2;
However I have defined a rowIdentity function, so that the id column uniquely identifies a row.
"rowIdentity" : function(row) {
return row.id;
}
Now if I select rows with id=Bob and id=Lorraine, then update the data, the rows are still selected. However the other fields in those rows are not updated.
How can I both preserve the selection and update all the data?
I think you need to keep track of you IDs yourself. So, you should remove the rowIdentifier, and instead add this piece at the beginning of your swapData function.
$scope.selIds = [];
for (var selRow of $scope.gridApi.selection.getSelectedRows()) {
$scope.selIds.push(selRow.id);
}
In addition to that, add an event handler on rowsRendered to re-select the previously selected rows
gridApi.core.on.rowsRendered($scope,function() {
for (var selId of $scope.selIds) {
for (var row of $scope.gridOpts.data) {
if (selId == row.id) {
$scope.gridApi.selection.selectRow(row);
}
}
}
});
You can put this in your registerApi callback.

ui-grid infinite scroll with row processor filtering

I have an angularjs app using ui.grid with the infinite scrolling module. I am using whole row filtering as described in the documentation like so:
function MyController($scope){
var that = this;
var getData = function(){
//logic left out for brevity
};
var onRegisterApi = function(gridApi){
gridApi.grid.registerRowsProcessor(function (rows) {
return that.filterRowProcessor.apply(that, [rows]);
}, 200);
gridApi.infiniteScroll.on.needLoadMoreData($scope, getData);
};
this.options["onRegisterApi"] = onRegisterApi;
}
//...code excluded for brevity...
MyController.prototype.filterRowProcessor = function(renderableRows){
renderableRows.forEach(function(row) {
if (this.selectedMap[row.entity["Id"]]) {
row.visible = false;
}
});
return renderableRows;
}
The idea is to filter out rows which have an Id belonging to a specific collection; which works as designed. My problem is that when I get my first page of data the filter row processor removes enough rows from visibility that my scroll bar disappears. This in turn causes the infinite scroll api to never raise the "needLoadMoreData" event.
Is this uncharted territory, or is there a way around this? I am also open to not filtering by that mechanism if its easier to do another way.
UPDATE (01/08/2016)
I have found a work around that I don't like very much. Essentially I have a known page size and if the data coming in to the grid is less than that page size and my callback returns false for "end of query", I automatically issue a next page query. I would rather find a solution via the grid api, but for now this will work.
if(this.itemsSource.data.length < constants.PAGE_SIZE && !continuation.endOfQuery){
//call get data again
}
After thinking about it for a while I decided on the below method as my solution. I am still open to suggestions if it makes more sense to do it a different way. Rather than relying on a length of data (which only loosely translates to having a scroll bar) I decided to calculate the height of the total rows visible, compared to the viewport of the grid.
//this method get called from the callback from needsMoreData
//hasMoreData is the same boolean flag sent in to dataLoaded
var shouldRetrieveMore = function (gridApi, hasMoreData){
if (!hasMoreData) {
return false;
}
var totalCountOfRows = gridApi.grid.getVisibleRowCount();
if (totalCountOfRows === 0) {
return true;
}
var height = gridApi.grid.getViewportHeight();
var heightOfRow = gridApi.grid.getVisibleRows()[0].$$height;
return ((heightOfRow * totalCountOfRows) <= height);
}
One additional addendum to the solution could be to sum the $$heights of all the rows, but I decided against it since in my uses they are always the same height.

How to count number of rows in sencha gridview?

I have a Gridview on my page and I'm using buffered store. Is there a way to get the visible number of row count. Thank you
Here is a sample code that you can try: (I hope you'll get some idea from this)
// The below condition has to be checked for each record
// record: record instance
var me = this; // grid scope
Ext.Array.each(me.columns, function (item) { // iterate through each column in the grid
if (item.hidden || !item.dataIndex) { // you can avoid hidden columns and one's that re not bound to the store
return;
}
var cellVal;
try {
cellVal = Ext.fly( me.view.getCell(record, item)).select('cell selector class').elements[0].innerHTML;
} catch (e) {
// handle if you want
}
if (!Ext.isEmpty(cellVal)) {
// this record has been rendered
}
}, this);
This will get you all the records that are rendered. Since you are using a bufferedRenderer, this will also return the records that are rendered but not in the view, you can check and put an offset for the buffer.
Note: I've a similar logic in working in ExtJs 5 but haven't tested in touch.

Resources