Component lost during rerender, how to reattach? - javascript

I am rendering a component into a grid rowExpander plugin rowBodyTpl:
plugins: [{
ptype: 'rowexpander',
rowBodyTpl : [
'<div id="contact-row-{Id}"> </div>'
]
}],
var row = 'contact-row-' + record.get('Id'),
grid = Ext.getCmp(gridId),
if(!grid) me.createSubGrid(record,gridId).render(row);
This works fine. But when the grid receives an update event for a record with certain modifiedFields, that record's rowExpander is rerendered using the rowTpl only, and the inner grid is dangling somewhere. I can access the grid using Ext.getCmp, and grid.rendered is true, but it is not shown. So I guess I have to reattach the grid after the row has been rerendered.
I think I can attach to the update event, and find out whether the rowTpl has been rerendered without the child grid using
if(!grid.container.contains(grid.el))
But is there a way to put the grid back into the dom?
I have tried
grid.container.insertFirst(grid.el);
but this does not work. The element is inserted but the grid is not displayed.
Any ideas?

The way you are doing leads to memory leaks (because your component is not destroy when the grid is re-render).
I suggest to check at : Component Template (http://skirtlesden.com/ux/ctemplate) or if you try to render a nested grid, there was several attempt to build something correct and I think a working one is the following : http://blogs.walkingtree.in/2015/06/30/nested-grid-in-sencha-ext-js/

With my trials, I already was on the right track, and the error was somewhere else entirely. The problem was that my update event fn which did the reattach was executed before the update event fn that broke everything, because the fn was fired on the same event and had the same priority, but was attached to the store earlier. Changing the priority was one option, but I just put the creation into the boxready event, which is executed after the view has attached its events to the store:
xtype:'grid',
listeners:{
boxready:function(grid) {
var store = grid.getStore();
...
store.on({
update:function(store, record) {
me.restoreSubgridDom(record);
},
beforeload:function(store) {
var records = store.getRange();
Ext.each(records,me.destroySubgrid);
}
});
}
}
with the two functions:
restoreSubgridDom: function(record) {
var row = 'contact-row-' + record.get('Id'),
gridId = 'ContactRow'+record.get('Id')+'Grid',
grid = Ext.getCmp(gridId);
if(grid && !grid.container.contains(grid.el))
{
grid.container.insertFirst(grid.el);
}
},
destroySubgrid: function(record) {
var gridId = 'ContactRow'+record.get('Id')+'Grid',
grid = Ext.getCmp(gridId);
if(grid) grid.destroy();
}

Related

SAPUI5 TreeTable's getRows method returns empty array on the first call

I am trying to build an SAPUI5 application using TreeTable and I'm facing some problems to use its methods.
In my app, I have a button which triggers this method.
onChangeViewContext: function(oEvent) {
.........
.........
var aViewContext = oContext.oModel.getProperty(sPath + "/ViewContext");
var aDataModel = oContext.oModel.getProperty("/ApplicationCollection/" + sAppId + "/DataModel");
var oStructure = this._createParentChildStructure(aDataModel);
var oTreeModel = this.getView().getModel("treeModel");
oTreeModel.setData(oStructure);
this._oViewDetailLine = oSource.getParent().getParent().getParent();
this._oViewDetailLine.setVisible(false);
this.byId("idSelectElementsPanel").setVisible(true);
this._setSelectedItems(aViewContext, oTree);
}
What I'm trying to do here is only bind the rows with my treeModel, get tree table object and send it to my _setSelectedItems method which below.
_setSelectedItems: function(aViewContext, oTree) {
oTree.clearSelection();
var sElementName;
var aSelectedIndices = [];
var aElements = [];
var aRows = oTree.getRows();
aRows.forEach(function(row) {
if (row._oNodeState !== undefined) {
aElements.push(row.getCells()[0].getText());
}
});
I need to get rows array here because I will use it for setting selected items of tree table. The problem is when "onChangeViewContext" triggered, oTable.getRows() returns an empty array. But when I click cancel button (which just hides my tree table, nothing more) and then trigger "onChangeViewContext" function again, I can get the rows array completely.
Even on the first call when I try to get table's model, I can get the treeModel and its data correctly.
I've tried to refresh bindings, aggregations etc. But no luck.
By the way, I'm using row binding in my xml view like this :
<t:TreeTable id="idSelectElementsTree" rows="{path: 'treeModel>/'}" selectionMode="MultiToggle" enableSelectAll="false"
rowSelectionChange="onSelectElement">
I'm really drowning here so any any help would be appreciated.
Edit : rest of the setSelectedIndexes function :
aViewContext.forEach(function(name) {
sElementName = name;
if (aElements.indexOf(sElementName) !== -1) {
aSelectedIndices.push(aElements.indexOf(sElementName));
}
});
aSelectedIndices.forEach(function(idx) {
if (oTree.getRows()[idx]._bHasChildren) {
oTree.expand(idx);
}
oTree.addSelectionInterval(idx, idx);
});
What could help here is to add an event rowsUpdated="onRowsUpdated" to the table in the XML view. This event is triggered after the table has been loaded and will hence provide you with the data via;
this.getView().byId("sTableId").getRows();
The difference to your approach is that the event would not be triggered by the press of a button but automatically, as the table is rendered. You can then also use this function to trigger another one as per your use case.

Kendo Grid Is there an event for when a row changes (not selected)?

I was hoping to detect when a Kendo grid's row changes, by navigation as opposed to selecting.
By this I mean I would have a grid with selectable: false, in batch edit mode, and I would like to update the data source (in code) when the user tabs to a new row (just as Access does).
I have looked at this example and changed the following properties..
selectable: false,
navigatable: true,
editable: true,
Unfortunately the changed event does not when seem to fire for tabs or arrow keys (when in navigation mode).
Would anyone know any other way I can do as described above (ie know when we have changed row via navigation)
Thanks in advance for any help!
You can use the edit event to determine whether you're in a new row.
Here you go:
selectable: false,
navigatable: true,
editable: true,
edit: function(e) {
if (e.sender.cellIndex($(e.container)) === 0 &&
$(e.container).closest("tr").index() !== 0) {
console.log("next row; update DS");
}
},
You could also store the last row you were in and determine the change using that, if switching between rows in other ways than by tabbing (or when tabbing backwards) is relevant.
If you don't want the grid to be editable, it's more difficult. Here's a quick hack:
var grid = $("#grid").data("kendoGrid");
var elem = $(grid.table)[0];
var handlers = $._data(elem, "events")["keydown"][2];
var oldHandler = handlers.handler;
// replace the existing event handler attached by kendo grid
var newHandler = function (e) {
oldHandler(e);
var current = grid.current();
var closestRow = $(current).closest("tr");
var rowIndex = $(closestRow).index();
if (rowIndex !== grid._lastNavRowIndex) {
if (typeof grid._lastNavRowIndex !== "undefined") {
kendoConsole.log("we just changed to row " + rowIndex);
}
grid._lastNavRowIndex = rowIndex;
}
};
handlers.handler = newHandler;
});
Try it here.
This is probably what you are looking for. When you want events related to the data, you have to look for the DataSource events. When you want events related to the UI, than you look at the Grid events.

Ext js grid remove selection model

I have a situation where I need to dynamically add or remove grids selection model.
Searching the documentation I see that the selection model doesn't have a destroy() method or anything similar. How can I remove or destroy a selection model from a grid in ext js 4.x.?
If this is not possible I still have an option to revert some functionallity and dynamically add the selection model to an already created grid. But I'm also not sure if this is possible.
I'd suggest to disable the selection model instead of destroying it.
You can clear the current selection (deselectAll) and lock the selection model to prevent further selection (setLocked):
selModel.deselectAll();
selModel.setLocked(true);
As you're using a checkbox selection model, you'll also need to hide the corresponding column which is added to the grid:
grid.headerCt.child('gridcolumn[isCheckerHd]').hide();
Selection models are not designed to be replaced, so... it's gonna be complicated!
You'd have to reproduce the initialization of the sel model, unwire the previous one, and rewire the new one...
Here's an example that works in substituting a row selection model for a checkbox model. It may still contains memory leaks from listeners registered by the first selection model that I would have forgot. The creation of the new selection model relies on the getSelectionModel method of the grid, which implements the disableSelection, simpleSelect, and multiSelect options of the grid (see the code).
Ext.widget('grid', {
renderTo: Ext.getBody()
,store: ['Foo', 'Bar', 'Baz']
,selType: 'checkboxmodel'
,columns: [{
dataIndex: 'field1'
,text: "Name"
}]
,listeners: {
selectionchange: function(sm, records) {
var grid = sm.view.up(),
item = grid.down('tbtext');
if (records.length) {
item.setText(
'Selection: ' + Ext.pluck(Ext.pluck(records, 'data'), 'field1').join(', ')
);
} else {
item.setText('No selection');
}
}
}
,tbar: [{
text: "Replace selection model"
,handler: function(button) {
var grid = button.up('grid'),
headerCt = grid.headerCt,
checkColumn = headerCt.down('[isCheckerHd]'),
view = grid.view,
previous = grid.selModel,
sm;
// try to clean up
previous.deselectAll();
previous.destroy();
// sel model doesn't clear the listeners it has installed in its
// destroy method... you'll have to chase the listeners that are
// installed by the specific type of sel model you're using
if (previous.onRowMouseDown) {
view.un('itemmousedown', previous.onRowMouseDown, previous);
}
if (previous.onRowClick) {
view.un('itemclick', previous.onRowClick, previous);
}
// clear references
delete grid.selModel;
delete view.selModel;
// create another selModel
grid.selType = 'rowmodel';
//grid.disableSelection = true;
sm = grid.getSelectionModel();
// assign new sel model
view.selModel = sm;
sm.view = view;
// remove checkbox model column
if (checkColumn) {
headerCt.remove(checkColumn);
}
// init sel model is trigerred in view render events, so we must do it
// now if the view is already rendered
if (view.rendered) {
sm.beforeViewRender(view);
sm.bindComponent(view);
}
// finally, refresh the view
view.refresh();
}
}]
// a place to display selection
,bbar: [{
xtype: 'tbtext'
,text: 'No selection'
}]
});

how to revert single edited row in dojo dgrid?

Is there a way to revert/reset the edited row in the dojo-dgrid ?
I can see the grid.revert() which does clear the dirty items and calls the refresh method, which will refresh the whole grid. I don't want this whole grid-refresh.
Is it possible to reset/revert only that single edited row, upon clicking a Revert/Cancel Icon on the Actions-column (which will be the last column in the grid as mentioned here and here)
If you're wrapping your store with Observable, you can use notify() to update a single row.
For example, you can create the following code for onClick event of your Revert/Cancel button:
renderCell: function(object, data, cell){
var btnRevert = new Button({
label: "Revert",
// ...
onClick: function(evt){
var dirty = that.grid.dirty,
id = object.id;
if(dirty.hasOwnProperty(id)){
// remove dirty data
delete dirty[id];
// ..and notify the store to update
myStore.notify(object, object.id);
}
}
}, cell.appendChild(put("div")) );
return btnRevert;
}
Here is a jsfiddle with an example: revert example

ExtJS display RowExpander on condition only

I currently have a rather big Grid and am successfully using the RowExpander plugin to display complementary informations on certain rows. My problem is that it's not all rows that contain the aforementioned complementary informations and I do not wish the RowExpander to be active nor to show it's "+" icon if a particular data store's entry is empty. I tried using the conventional "renderer" property on the RowExpander object, but it did not work.
So basically, how can you have the RowExpander's icon and double click shown and activated only if a certain data store's field != ""?
Thanks in advance! =)
EDIT: I found a solution
As e-zinc stated it, part of the solution (for me at least) was to provide a custom renderer that would check my conditional field. Here is my RowExpander:
this.rowExpander = new Ext.ux.grid.RowExpander({
tpl: ...
renderer: function(v, p, record) {
if (record.get('listeRetourChaqueJour') != "") {
p.cellAttr = 'rowspan="2"';
return '<div class="x-grid3-row-expander"></div>';
} else {
p.id = '';
return ' ';
}
},
expandOnEnter: false,
expandOnDblClick: false
});
Now, the trick here is that for this particular Grid, I chose not to allow the expandOnEnter and expanOnDblClick since the RowExpander will sometimes not be rendered. Also, the CSS class of the grid cell that will hold the "+" icon is 'x-grid3-td-expander'. This is caused by the fact that the CSS class is automatically set to x-grid3-td-[id-of-column]. So, by setting the id to '' only when I'm not rendering the rowExpander, I'm also removing the gray background of the un-rendered cells. So, no double click, no enter, no icon, no gray-background. It really becomes as if there is strictly no RowExpander involved for the columns where my data store field is empty (when I want no RowExpander).
That did the trick for me. For someone that wishes to preserve the ID of the cell, or that wishes to keep the double click and enter events working, there is nothing else to do other than extending the class I guess. Hope this can help other people stuck in the position I was!
As e-zinc stated it, part of the solution (for me at least) was to provide a custom renderer that would check my conditional field. Here is my RowExpander:
this.rowExpander = new Ext.ux.grid.RowExpander({
tpl: ...
renderer: function(v, p, record) {
if (record.get('listeRetourChaqueJour') != "") {
p.cellAttr = 'rowspan="2"';
return '<div class="x-grid3-row-expander"></div>';
} else {
p.id = '';
return ' ';
}
},
expandOnEnter: false,
expandOnDblClick: false
});
Now, the trick here is that for this particular Grid, I chose not to allow the expandOnEnter and expandOnDblClick specifically since the RowExpander will sometimes not be rendered. Also, the CSS class of the grid cell that will hold the "+" icon is 'x-grid3-td-expander'. This is caused by the fact that the CSS class is automatically set to x-grid3-td-[id-of-column]. So, by setting the id to an empty string only when I'm not rendering the rowExpander, I'm also removing the gray background of the cells that won't offer any expanding. So, no double click, no enter, no icon, no gray-background. It really becomes as if there is strictly no RowExpander involved for the columns where my data store field is empty (when I want no RowExpander).
That did the trick for me. For someone that wishes to preserve the ID of the cell, or that wishes to keep the double click and enter events working, there is nothing else to do other than extending the RowExpander class in my opinion. Of course, one could also use Ext.override(), but then all instances of RowExpander would be hit by the override.
I have the same task, there is my solution
var rowExpander = new Ext.ux.grid.RowExpander({
renderer : function(v, p, record){
return record.get('relatedPageCount') > 0 ? '<div class="x-grid3-row-expander"> </div>' : ' ';
}
});
I have overridden render method which test relatedPageCount field in store and render + or white space.
I think I've found a cleaner solution.Give me a feedback pls :)
I extend the toggleRow method of RowExpander and if I match a condition avoid to toggle the row.Otherwise the standard flow continues
Ext.create('customplugins.grid.plugin.ClickRowExpander',{
pluginId : 'rowexpander',
rowBodyTpl : new Ext.XTemplate(
'<p><b>Last Modified By:</b> {usermodify}</p>',
'<p><b>User data:</b> {userdata}</p>',
'<p><b>Correlation ID:</b> {correlationid}</p>',
'<p><b>Description:</b> {descr}</p>'
),
toggleRow : function(rowIdx, record) {
if(record.get('directory')) return false;
customplugins.grid.plugin.ClickRowExpander.prototype.toggleRow.apply(this, arguments);
}
})
This version works in Ext JS 5 and 6 (classic)
One thing is to remove the +/- icon, which can be done via grid viewConfig:
getRowClass: function (record, rowIndex, rowParams, store) {
var yourFieldofChoice = record.get('yourFieldofChoice');
if (yourFieldofChoice == null) {
return 'hide-row-expander';
}
},
Define css for hide-row-expander:
.hide-row-expander .x-grid-row-expander {
visibility: hidden;
}
Now you disable expanding on enter key ('expandOnEnter' config is no longer supported in Ext JS 6) or double click by overriding toggleRow, or if you do not wish the override you create your custom rowexpander built on existing plugin:
Ext.define('RowExpander', {
extend: 'Ext.grid.plugin.RowExpander',
alias: 'plugin.myExpander',
init: function (grid) {
var me = this;
me.grid = grid;
me.callParent(arguments);
},
requiredFields: ['yourFieldofChoice'],
hasRequiredFields: function (rec) {
var valid = false;
Ext.each(this.requiredFields, function (field) {
if (!Ext.isEmpty(rec.get(field))) {
valid = true;
}
});
return valid;
},
toggleRow: function (rowIdx, record) {
var me = this, rec;
rec = Ext.isNumeric(rowIdx)? me.view.getStore().getAt(rowIdx) : me.view.getRecord(rowIdx);
if (me.hasRequiredFields(rec)) {
me.callParent(arguments);
}
}
});
I have handled the beforeexpand event inside the listeners of Ext.ux.grid.RowExpander. beforeexpand method got the whole row data injected. Checking the data conditionally we can return true or false. If we return false it wont expand otherwise it will do.
var expander = new Ext.ux.grid.RowExpander({
tpl: '<div class="ux-row-expander"></div>',
listeners: {
beforeexpand : function(expander, record, body, rowIndex){
var gpdata = record.data.GROUP_VALUES[1].COLUMN_VALUE
if(gpdata == null){
return false;
}
else{
return true;
}
}
}
});

Categories