Resize Ext.form.ComboBox to fit its content - combobox

There are quite few solutions on Ext forums, but I wasn’t able to get any of them work. It seems I am missing something minor.
I need to resize combobox to fit its content when it’s first created. I do not need to worry about resizing it when content is changing.
Is there any working examples using Extjs 3.2?
Current Code:
var store = new Ext.data.ArrayStore({
fields: ['view', 'value', 'defaultselect'],
data: Ext.configdata.dataCP
});
comboCPU = new Ext.form.ComboBox({
tpl: '<tpl for="."><div class="x-combo-list-item"><b>{view}</b><br /></div></tpl>',
store: store,
displayField: 'view',
width: 600,
typeAhead: true,
forceSelection: true,
mode: 'local',
triggerAction: 'all',
editable: false,
emptyText: 'empty text',
selectOnFocus: true,
listeners: { select: AdjustPrice, change: AdjustPrice, beforeselect: function (combo, record, index) { return ('false' == record.data.disabled); } },
applyTo: 'confelement'
});
I've also tried removing width: 600 and replacing it with minListWidth: 600 but that result following and didnt fix the issue.
alt text http://img28.imageshack.us/img28/7665/4272010105134am.png

Try the following:
Determine the list-box option with the most chars
Create a div and set the option with the most chars
Append this div to the body
Get the div's clientWidth
Below codes works in ExtJs 3.2!
myStore = new Ext.data.Store({
...
listeners : {
load: function() {
var maxValue = "";
var charLen = 0, maxCharLen = 0;
var maxListWidth = 300;
/**
* This is a work-around since the 'listWidth' property
* does not accept any values that would simulate auto-resize
* in reference to the category with the most characters.
*/
this.data.each(function(item, index, totalItems ) {
var nameValue = item.data['name']; // 'name' is the field name
if(nameValue == null || nameValue == ''){
// do nothing
}else {
charLen = nameValue.length;
if(charLen > maxCharLen){
maxCharLen = charLen;
maxValue = nameValue;
}
}
});
if(maxValue != ""){
var divEl = document.createElement('div');
divEl.id = 'tempEl';
divEl.style.display = "inline";
divEl.className = "x-combo-list";
divEl.innerHTML = maxValue;
document.body.appendChild(divEl);
// check if appended
divEl = document.getElementById('tempEl');
if(divEl) {
var divWidth = divEl.clientWidth;
if(divWidth == 0 ) {
divEl.style.display = "inline-block";
divWidth = divEl.clientWidth;
}
// the allocated width for the scrollbar at side of the list box
var scrollbarWidth = 30;
// make sure that column width is not greater than
if((divWidth + scrollbarWidth) > maxListWidth) {
maxListWidth = divWidth + scrollbarWidth;
myCombo.listWidth = maxListWidth;
}
document.body.removeChild(divEl);
}
}
}
});
var myCombo = new fm.ComboBox({
...
});

try
autoWidth: true
and remove the width parameter

width: 600 is correct, so you must have some other issue going on that's not obvious from what you posted. You might try removing the applyTo config and instead put renderTo: Ext.getBody() just to see if it has something to do with how it's applied to your element. Are you sure there is not some other code that could be affecting the width?

Found here:
// throw this stuff in a closure to prevent
// polluting the global namespace
(function(){
var originalOnLoad = Ext.form.ComboBox.prototype.onLoad;
Ext.form.ComboBox.prototype.onLoad = function(){
var padding = 8;
var ret = originalOnLoad.apply(this,arguments);
var max = Math.max(this.minListWidth || 0, this.el.getWidth());
var fw = false;
Ext.each(this.view.getNodes(), function(node){
if(!fw){ fw = Ext.fly(node).getFrameWidth('lr'); }
if(node.scrollWidth){ max = Math.max(max,node.scrollWidth+padding); }
});
if( max > 0 && max-fw != this.list.getWidth(true) ){
this.list.setWidth(max);
this.innerList.setWidth(max - this.list.getFrameWidth('lr'));
}
return ret;
};
})();

Related

How can I retrieve the cursor position in an ExtJS text area field?

I defined a text area field in an extJS window as follows:
me.myTextArea = Ext.create({
xtype: 'textareafield',
width: 500,
height: 500,
editable: true,
selectOnFocus: false,
listeners: {
afterrender: function() {
this.focus(true);
let cursorPos = this.getValue().length;
this.selectText(cursorPos, cursorPos);
}
}
});
I added the text area field to a panel contained within a window, and I set the text area field as focus element. I prevented the text there to be selected after the textarea field's being rendered. I would like to add the following feature. On closing the window, I will be able to get the position the cursor has within the text area field. So far, my attemps at resolving the problem were withou success. I set up an alert as follows:
listeners: {
'close': function(me) {
alert(me.getCaretPos(cmp.myTextArea.getEl().getId()));
}
},
Now the function named "getCaretPos" is designed to get the cursor position. I did not invent the function, but I found in on the net. Haplessly, the function does not work, it always returns -1:
getCaretPos: function(id){
var el = document.getElementById(id);
var rng, ii=-1;
if(typeof el.selectionStart=="number") {
ii=el.selectionStart;
} else if (document.selection && el.createTextRange){
rng=document.selection.createRange();
rng.collapse(true);
rng.moveStart("character", -el.value.length);
ii=rng.text.length;
}
return ii;
}
Especially, I do not undertsand, why "el.selectionStart" is always undefined in the function. I would be very glad if somebody could help me in resolving this mystery.
In this FIDDLE, I have created a custometextarea using extend:Ext.form.field.TextArea and putted some custom method. I hope this will help/guide you to achieve your requirements.
I have checked this code is working in ExtJS 4.x and later.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('CustomeTextArea', {
extend: 'Ext.form.field.TextArea',
xtype: 'customtextarea',
inputTypeSelectionSupported: /text|password|search|tel|url/i,
selectDir: {
b: 'backward',
back: 'backward',
f: 'forward'
},
/*
* this event will call get the cursoe postion inside of field
* #return {NUMBER}
*/
getCaretPos: function () {
var dom = this.inputEl.dom,
pos, selection;
if (this.inputTypeSelectionSupported.test(dom.type)) {
pos = dom.selectionStart;
selection = (typeof pos !== 'number') && this.getTextSelection();
if (selection) {
pos = selection[0];
}
} else {
Ext.raise('Input type of "' + dom.type + '" does not support selectionStart');
}
return pos;
},
/*
* this event will call selectText event
* #params {NUMBER} pos
*/
setCaretPos: function (pos) {
this.selectText(pos, pos);
},
/*
* #params {NUMBER} start
* #params {NUMBER} end
* #params {STRING} direction to select it is optional
*/
selectText: function (start, end, direction) {
var me = this,
range,
dom = me.inputEl.dom,
len;
if (dom && me.inputTypeSelectionSupported.test(dom.type)) {
start = start || 0;
len = dom.value.length;
if (end === undefined) {
end = len;
}
direction = me.selectDir[direction] || direction || 'forward';
if (dom.setSelectionRange) {
dom.setSelectionRange(start, end, direction);
} else if (dom.createTextRange) {
range = dom.createTextRange();
range.moveStart('character', start);
range.moveEnd('character', -(len - end));
range.select();
}
} else if (!me.inputTypeSelectionSupported.test(dom.type)) {
Ext.raise('Input type of "' + dom.type + '" does not support setSelectionRange');
}
return me;
},
//This event will select the text inside of textfield/textarea
getTextSelection: function () {
var dom = this.inputEl.dom;
if (this.inputTypeSelectionSupported.test(dom.type)) {
return [
dom.selectionStart,
dom.selectionEnd,
dom.selectionDirection
];
} else {
Ext.raise('Input type of "' + this.dom.type + '" does not support selectionStart, selectionEnd and selectionDirection');
return [];
}
}
});
Ext.create('Ext.window.Window', {
title: 'cursor position',
height: 200,
width: 400,
layout: 'fit',
items: [{
xtype: 'customtextarea',
margin: 5,
grow: true,
name: 'message',
fieldLabel: 'Message',
labelAlign: 'top',
value: 'How can I retrieve the cursor position in an ExtJS text area field?',
anchor: '100%',
listeners: {
afterrender: function (cmp) {
Ext.defer(function () {
cmp.focus(false); //if you pass true then it will automatically select text inside of field
let cursorPos = cmp.getValue().length;
cmp.selectText(0, cursorPos - 5, 'b');
}, 50)
}
}
}],
listeners: {
beforeclose: function (win) {
var textArea = win.down('customtextarea'),
pos = textArea.getCaretPos();
Ext.Msg.alert('Success', `This is your cursor postion <b>${pos}</b>`)
}
}
}).show();
}
});

ExtJS - 'combocolumn' based renderer - rowediting does not register event or do what it is supposed to

http://2gears.com/2011/05/combobox-editor-remote-and-renderer-for-extjs-editorgridpanel/comment-page-2/#comment-11050?
Please see the function.
I am not using the 'combocolumn' completely. However i have used the major components. Please advise if there is a possibility it should work. As of now the grid refuses to render the column itself and I am unable to pinpoint what the bug is as the code is simply the same?
I did this not to act smart :) - but to simplify and run it on 1 column before standardizing the component common to the project.
The COMBO RENDERING fn()
<code>
function ComboBoxRenderer(combo, gridId) {
var getValue = function (value) {
var idx = combo.store.find(combo.valueField, value);
var rec = combo.store.getAt(idx);
if (rec) {
return rec.get(combo.displayField);
}
return value;
};
return function (value) {
if (combo.store.getCount() === 0 && gridId) {
console.log(combo.store.getCount()+gridId);
combo.store.on(
'load',
function () {
var grid = Ext.getCmp(gridId);
if (grid) {
grid.getView().refresh();
}
},
{
single: true
}
);
return value;
}
return getValue(value);
};
// Ext.getCmp(gridId).getView().refresh();
}
</code>
Editor - in Grid Column Model
{
header: 'Plan Type',
dataIndex: 'plan_id',
editor: {
// allowBlank: 'false',
xtype: 'combobox',
queryMode: 'local',
store: planTypeStore,
displayField: 'plan_name',
valueField: 'plan_id'
}
,renderer: ComboBoxRenderer(this.editor, 'gridPanelId')
/*this is the docs based renderrer - which wont work */
//, renderer: function (val) {
// var rec = planTypeStore.findRecord('plan_id', val);
// return (rec !== null ? rec.get("plan_name") : '');
// }

Filter store on combobox selection

I have tried this different ways, but still can't get the filter to work. My ext app lets user to choose a single state from a combobox, and the grid below displays more data on that selected "value"=state.. On select, the combobox fires a function that filters the store of the grid and updates the store...
this is my store for the grid...
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
id: 'OurData',
pageSize: 20,
pageNumber: 1,
remoteSort: true,
fields: [
{ name: 'States' },
{ name: 'FullName' },
{ name: 'Capital' },
{ name: 'Population' }
],
proxy: {
type: 'ajax',
url: 'GetState/getS',
reader: {
type: 'json',
root: 'myTable',
idProperty: 'States',
totalProperty: '#count'
}
}
});
store.loadPage(1);
this is my combobox
xtype: 'combo',
id: 'iccombo',
scope: this,
store: this.Combostore,
fieldLabel: 'Short State',
displayField: 'States',
valueField: 'States',
typeAhead: true,
triggerAction: 'all',
queryMode: 'remote',
name: 'State',
labelWidth: 125,
anchor: '95%',
listeners: {
scope: this,
select: this.fireFilter
}
and this is where the filter should take place...
fireFilter: function (value) {
// Get passed value
this.selectedC = value.getValue();
console.log('selectedValue: ' + this.selectedC);
// Clear existing filters
this.store.clearFilter(false);
// Build filter
var myfilter = Ext.create('Ext.util.Filter', {
scope: this,
filterFn: function (item) {
var fieldNames = item.fields.keys;
for (var j = 0; j < fieldNames.length; j++) {
var fieldName = fieldNames[j];
if (item.data[fieldName] != null) {
var stringVal = item.data[fieldName].toString();
if (stringVal != null && stringVal.toLowerCase().indexOf(value.toLowerCase()) != -1) {
return true;
}
}
}
return false;
}
});
// Apply filter to store
this.store.filter(myfilter);
}
when I run the code, it display all data in the grid, and on selection of combobox, it still shows the same data..
For some reason, the code never runs through the filterFn... because my console.log doesn't show up
this is what I got in firebug's response
_dc 1352902173425
filter [{"property":null,"value":null}]
limit 20
page 1
start 0
as you can clearly see, the selected 'value' is null, but my 'console.log' prints the value selected... I think the way I am getting the passed value and applying the filter is incorrect... can someone please take a look... thanks
UPDATE... I am able to get inside the function and my console.log shows all the fields... but once I get to the last if statement... I get this error
TypeError: value.toLowerCase is not a function
What am I doing wrong here? Thanks
In addition to dbrin's anwser I also can't understand why you are using remoteSort but not remoteFilter? You may also have a scope issue by using this.
Anyway I would recommend you to extend a new combo type so that you are also be able to clear your filter if you have the need to. Here is an extension I have written for my own use. Note that the filtering itself needs to be implemented in the onSearch method, which can be either a remote or a local sort.
Ext.define('Ext.ux.form.field.FilterCombo', {
extend: 'Ext.form.field.ComboBox',
alias: 'widget.filtercombo',
/**
* #cfg {string} recordField
* #required
* The fieldname of the record that contains the filtervalue
*/
/**
* #cfg {string} searchField
* #required
* The fieldname on which the filter should be applied
*/
/**
* #cfg {boolean} clearable
* Indicates if the clear trigger should be hidden. Defaults to <tt>true</tt>.
*/
clearable: true,
initComponent: function () {
var me = this;
if (me.clearable)
me.trigger2Cls = 'x-form-clear-trigger';
else
delete me.onTrigger2Click;
me.addEvents(
/**
* #event clear
*
* #param {Ext.ux.form.field.FilterCombo} FilterCombo The filtercombo that triggered the event
*/
'clear',
/**
* #event beforefilter
*
* #param {Ext.ux.form.field.FilterCombo} FilterCombo The filtercombo that triggered the event
* #param {String/Number/Boolean/Float/Date} value The value to filter by
* #param {string} field The field to filter on
*/
'beforefilter'
);
me.callParent(arguments);
// fetch the id the save way
var ident = me.getId();
me.on('select', function (me, rec) {
var value = rec[0].data[me.recordField],
field = me.searchField;
me.fireEvent('beforefilter', me, value, field)
me.onShowClearTrigger(true);
me.onSearch(value, field);
}, me);
me.on('afterrender', function () { me.onShowClearTrigger(); }, me);
},
/**
* #abstract onSearch
* running a search on the store that may be removed separately
* #param {String/Number/Boolean/Float/Date} val The value to search for
* #param {String} field The name of the Field to search on
*/
onSearch: Ext.emptyFn,
/**
* #abstract onFilterRemove
* removing filters from the the
* #param {Boolean} silent Identifies if the filter should be removed without reloading the store
*/
onClear: Ext.emptyFn,
onShowClearTrigger: function (show) {
var me = this;
if (!me.clearable)
return;
show = (Ext.isBoolean(show)) ? show : false;
if (show) {
me.triggerEl.each(function (el, c, i) {
if (i === 1) {
el.setWidth(el.originWidth, false);
el.setVisible(true);
me.active = true;
}
});
} else {
me.triggerEl.each(function (el, c, i) {
if (i === 1) {
el.originWidth = el.getWidth();
el.setWidth(0, false);
el.setVisible(false);
me.active = false;
}
});
}
// Version specific methods
if (Ext.lastRegisteredVersion.shortVersion > 407) {
me.updateLayout();
} else {
me.updateEditState();
}
},
/**
* #override onTrigger2Click
* eventhandler
*/
onTrigger2Click: function (args) {
this.clear();
},
/**
* #private clear
* clears the current search
*/
clear: function () {
var me = this;
if (!me.clearable)
return;
me.onClear(false);
me.clearValue();
me.onShowClearTrigger(false);
me.fireEvent('clear', me);
}
});
Here is an untested implementation of your combo. Please note that I cleaned up your filterFn but I didn't make any further check.
{
xtype: 'filtercombo',
id: 'iccombo',
scope: this,
store: this.Combostore,
fieldLabel: 'Short State',
displayField: 'States',
valueField: 'States',
typeAhead: true,
triggerAction: 'all',
queryMode: 'remote',
name: 'State',
labelWidth: 125,
anchor: '95%',
// begin new parts
recordField: 'States',
searchField: '',
clearable: false,
onSearch: function (me, value, field) {
// New part!
var store = Ext.StoreMgr.lookup('YourStoreIdName');
// Clear existing filters
store.clearFilter(false);
// Build filter
var myfilter = Ext.create('Ext.util.Filter', {
scope: this,
filterFn: function (item) {
var fieldNames = item.fields.keys,
fieldName, stringVal,
len = fieldNames.length,
j = 0;
for (; j < len; j++) {
fieldName = fieldNames[j];
if (item.data[fieldName] != null) {
stringVal = item.data[fieldName].toString();
if (stringVal != null && stringVal.toLowerCase().indexOf(value.toLowerCase()) != -1) {
return true;
}
}
}
return false;
}
});
// Apply filter to store
store.filter(myfilter);
}
}
I guess this should work too
var myfilter = Ext.create('Ext.util.Filter', {
scope: this,
filterFn: function (rec) {
var fieldValue = rec[this.fieldName];
if (fieldValue && fieldValue === this.value)
return true;
return false;
}
});
I set this before two vars to mark them as from a external scope.
i see 2 issues
store should have remoteFilter: true set
in JavaScript all variables declarations are picked out and hoisted to the beginning of the function. so any variables declared inside a loop should be taken out and declared at the top of the function. JS has no block scope (like Java).

Go back to the selection in Data Grid after reloading the page ExtJS 4.1 [duplicate]

I have a problem. I use extjs grid. This grid will be refreshed every seconds.
I refresh with this function:
ND.refresh = function() {
ND.commList.load();
}
var refreshSeconds = refreshRate * 1000;
var t = setInterval('ND.refresh()', refreshSeconds);
But when someone selected a row to highlight it it reset this selection.
How can I remember the selected row and highlight it again after refresh?
This is my grid:
var grid = Ext.create('Ext.grid.Panel', {
autoscroll: true,
region: 'center',
store: ND.dashBoardDataStore,
stateful: true,
forceFit: true,
loadMask: false,
stateId: 'stateGrid',
viewConfig: {
stripeRows: true
},
columns: [{
text: 'Vehicle',
sortable: true,
flexible: 1,
width: 60,
dataIndex: 'vehicle'
}, {
text: 'CCU',
sortable: true,
flexible: 0,
width: 50,
renderer: status,
dataIndex: 'ccuStatus'
}]
});
Thanks guys
I wrote simple Ext.grid.Panel extension that automatically selects back rows that were selected before store reload. You can try it in this jsFiddle
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}
});
The straightforward solution is just save somewhere in js index of selected row. Then after reload you could easily select this row by index using grid's selection model.
Get selection model: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.grid.Panel-method-getSelectionModel
var selectionModel = grid.getSelectionModel()
Get selected rows: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
var selection = selectionModel.getSelection()
Set selected row back: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-select
selectionModel.select(selection)
Here is another way to select the previously selected record:
var selectionModel = grid.getSelectionModel()
// get the selected record
var selectedRecord = selectionModel.getSelection()[0]
// get the index of the selected record
var selectedIdx = grid.store.indexOfId(selectedRecord.data.id);
// select by index
grid.getSelectionModel().select(selectedIdx);
For some reason the grid.getSelectionModel().select(record) method wasn't working for me, but selecting by index seems to work.
Edit: found out why grid.getSelectionModel().select(record) method wasn't working. Apparently the store is reloaded, the record instances aren't the same (they have different automatically generated Ext IDs). You have to use selectAt() in this case.
for extjs 4.1.7 users
need a workarround about the statement in
refreshSelection() {
...
Ext.defer(this.setScrollTop, 30, this,
[this.getView().scrollState.top])
}
thus setScrollTop no longer exists
so a working soluction is add
me.getView().preserveScrollOnRefresh = true;
in initComponent
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
//-------------------------------------------
me.getView().preserveScrollOnRefresh = true;
//-------------------------------------------
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
}
});
i have make modification on this code.
If you make selection, and aplys a filter on the store and reload it, the selection model have a first empty array in this selected collection ( at index 0 ).
This modification is in the last line of the "refreshSelection" function.
if (newRecordsToSelect.length >= 1){
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}

remember after refresh selected row in extjs grid

I have a problem. I use extjs grid. This grid will be refreshed every seconds.
I refresh with this function:
ND.refresh = function() {
ND.commList.load();
}
var refreshSeconds = refreshRate * 1000;
var t = setInterval('ND.refresh()', refreshSeconds);
But when someone selected a row to highlight it it reset this selection.
How can I remember the selected row and highlight it again after refresh?
This is my grid:
var grid = Ext.create('Ext.grid.Panel', {
autoscroll: true,
region: 'center',
store: ND.dashBoardDataStore,
stateful: true,
forceFit: true,
loadMask: false,
stateId: 'stateGrid',
viewConfig: {
stripeRows: true
},
columns: [{
text: 'Vehicle',
sortable: true,
flexible: 1,
width: 60,
dataIndex: 'vehicle'
}, {
text: 'CCU',
sortable: true,
flexible: 0,
width: 50,
renderer: status,
dataIndex: 'ccuStatus'
}]
});
Thanks guys
I wrote simple Ext.grid.Panel extension that automatically selects back rows that were selected before store reload. You can try it in this jsFiddle
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}
});
The straightforward solution is just save somewhere in js index of selected row. Then after reload you could easily select this row by index using grid's selection model.
Get selection model: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.grid.Panel-method-getSelectionModel
var selectionModel = grid.getSelectionModel()
Get selected rows: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
var selection = selectionModel.getSelection()
Set selected row back: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-select
selectionModel.select(selection)
Here is another way to select the previously selected record:
var selectionModel = grid.getSelectionModel()
// get the selected record
var selectedRecord = selectionModel.getSelection()[0]
// get the index of the selected record
var selectedIdx = grid.store.indexOfId(selectedRecord.data.id);
// select by index
grid.getSelectionModel().select(selectedIdx);
For some reason the grid.getSelectionModel().select(record) method wasn't working for me, but selecting by index seems to work.
Edit: found out why grid.getSelectionModel().select(record) method wasn't working. Apparently the store is reloaded, the record instances aren't the same (they have different automatically generated Ext IDs). You have to use selectAt() in this case.
for extjs 4.1.7 users
need a workarround about the statement in
refreshSelection() {
...
Ext.defer(this.setScrollTop, 30, this,
[this.getView().scrollState.top])
}
thus setScrollTop no longer exists
so a working soluction is add
me.getView().preserveScrollOnRefresh = true;
in initComponent
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
//-------------------------------------------
me.getView().preserveScrollOnRefresh = true;
//-------------------------------------------
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
}
});
i have make modification on this code.
If you make selection, and aplys a filter on the store and reload it, the selection model have a first empty array in this selected collection ( at index 0 ).
This modification is in the last line of the "refreshSelection" function.
if (newRecordsToSelect.length >= 1){
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}

Resources