combobox should remember the last selection - javascript

Below is my code to display three comboboxes, which will be Filter by severity, start release and end release. When I refresh the page I want comboboxes to remember what was selected earlier. Now it shows the current release in both the comboboxes.
Any help on this
launch: function() {
var that = this;
this.down('#SevFilter').add({
xtype: 'rallyattributecombobox',
cls: 'filter',
itemId: 'severity',
model: 'Defect',
labelWidth: 117,
fieldLabel : 'Filter By Severity:',
field: 'Severity',
allEntryText: '-- ALL --',
allowNoEntry: true,
_insertNoEntry: function(){
var record;
var doesNotHaveAllEntry = this.store.count() < 1 || this.store.getAt(0).get(this.displayField) !== this.allEntrylText;
if (doesNotHaveAllEntry) {
record = Ext.create(this.store.model);
console.log("record value", record);
record.set(this.displayField, this.allEntryText);
record.set(this.valueField, "-1");
this.store.insert(0, record);
}
/*var doesNotHaveNoEntry = this.store.count() < 2 || this.store.getAt(1).get(this.displayField) !== this.noEntryText;
if (doesNotHaveNoEntry) {
record = Ext.create(this.store.model);
record.set(this.displayField, this.noEntryText);
record.set(this.valueField, null);
this.store.insert(1, record);
}*/
},
listeners: {
//ready: this._onSevComboBoxLoad,
select: this._onSevComboBoxSelect,
scope: this
}
});
var button = this.down('#goButton');
button.on('click', this.goClicked, this);
this.down('#SevFilter').add({
xtype: 'rallyreleasecombobox',
//multiSelect: true,
itemId: 'priorityComboBox',
fieldLabel: 'Release Start:',
model: 'release',
width: 400,
valueField: 'ReleaseStartDate',
displayField: 'Name',
// multiSelect: true,
//field: 'Name',
_removeFunction: function(){
console.log("this.store");
},
listeners: {
//select: this._onSelect,
select: this._onFirstReleaseSelect,
scope: this
}
});
this.down('#SevFilter').add({
xtype: 'rallyreleasecombobox',
itemId: 'priorityComboBox2',
fieldLabel: 'Release End:',
model: 'release',
//multiSelect: true,
stateId: 'rally.technicalservices.trend.defect.release',
stateful: true,
stateEvents: ['change'],
width: 400,
valueField: 'ReleaseDate',
displayField: 'Name',
listeners: {
change: function(box) {
var start_date = this.down('#priorityComboBox2').getDisplayField();
this.logger.log(start_date);
},
ready: this._removeFutureReleases,
select: this._onSecondReleaseSelect,
// ready: this._onLoad,
scope: this
},
});
},

In javascript you may use localstorage.
Here is an app example that retains State and Release selections in respective compboboxes when page is refreshed:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
items: [
{html:'Select a Filter checkbox to filter the grid'},
{
xtype: 'container',
itemId: 'StateFilter'
},
{
xtype: 'container',
itemId: 'ReleaseFilter'
}
],
launch: function() {
document.body.style.cursor='default';
this._createFilterBox('State');
this._createFilterBox('Release');
},
_createFilterBox: function(property){
this.down('#'+property+'Filter').add({
xtype: 'checkbox',
cls: 'filter',
boxLabel: 'Filter table by '+property,
id: property+'Checkbox',
scope: this,
handler: this._setStorage
});
this.down('#'+property+'Filter').add({
xtype: 'rallyattributecombobox',
cls: 'filter',
id: property+'Combobox',
model: 'Defect',
field: property,
value: localStorage.getItem(property+'Filtervalue'), //setting default value
listeners: {
select: this._setStorage,
ready: this._setStorage,
scope: this
}
});
},
_setStorage: function() {
localStorage.setItem('StateFiltervalue',Ext.getCmp('StateCombobox').getValue());
localStorage.setItem('ReleaseFiltervalue',Ext.getCmp('ReleaseCombobox').getValue());
console.log('localStorage State: ', localStorage.StateFiltervalue,', localStorage Release:', localStorage.ReleaseFiltervalue);
this._getFilter();
},
_getFilter: function() {
var filter = Ext.create('Rally.data.wsapi.Filter',{property: 'Requirement', operator: '=', value: 'null'});
filter=this._checkFilterStatus('State',filter);
filter=this._checkFilterStatus('Release',filter);
if (this._myGrid === undefined) {
this._makeGrid(filter);
}
else{
this._myGrid.store.clearFilter(true);
this._myGrid.store.filter(filter);
}
},
_checkFilterStatus: function(property,filter){
if (Ext.getCmp(property+'Checkbox').getValue()) {
var filterString=Ext.getCmp(property+'Combobox').getValue()+'';
var filterArr=filterString.split(',');
var propertyFilter=Ext.create('Rally.data.wsapi.Filter',{property: property, operator: '=', value: filterArr[0]});
var i=1;
while (i < filterArr.length){
propertyFilter=propertyFilter.or({
property: property,
operator: '=',
value: filterArr[i]
});
i++;
}
filter=filter.and(propertyFilter);
}
return filter;
},
_makeGrid:function(filter){
this._myGrid = Ext.create('Rally.ui.grid.Grid', {
itemId:'defects-grid',
columnCfgs: [
'FormattedID',
'Name',
'State',
'Release'
],
context: this.getContext(),
storeConfig: {
model: 'defect',
context: this.context.getDataContext(),
filters: filter
}
});
this.add(this._myGrid);
}
});
The source is available here.

You could use Sencha localstorage proxy. This way you can keep consistency in your project and use a localstorage based store across all your code.

You can use stateful and stateId configurations to enable last selection. Here is an example of my code. Here what I am doing is to create a custom combobox that will show two options: Platform and program. Then for stateId, you can use any string that you want:
_createCategoryFilter: function()
{
// The data store containing the list of states
var platformTypeList = Ext.create('Ext.data.Store',
{
fields: ['abbr', 'name'],
data : [
{"abbr":"PLAN", "name":"Platform"},
{"abbr":"CURR", "name":"Program"},
//...
]
});
// Create the combo box, attached to the states data store
var platformTypeFilter = Ext.create('Ext.form.ComboBox',
{
fieldLabel: 'Select category',
store: platformTypeList,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr',
stateful: true,
stateId: 'categoryFilter',
listeners:
{
afterrender: function(param)
{
console.log('afterrender - category param is', param.rawValue);
CategoryFilterValue = param.rawValue;
LoadInformation();
},
select: function(param)
{
console.log('select - category param is', param.rawValue);
CategoryFilterValue = param.rawValue;
},
scope: this,
}
});
this.add(platformTypeFilter);
},

Related

extjs combo box getCount() on store returns 0

I am trying to get the number of items in the combo box so that I can make the first value by default visible in the combo box using the getCount() method but I see it always return 0 so cannot get the first item to be displayed in the combo box.
Code for my combo box is as shown below:
Ext.define('something....', {
controller: 'some Controller',
initComponent: function() {
var me,
me = this;
me.items = [{
xtype: 'form',
items: [{
xtype: 'combo',
itemId: 'nameId',
name:'nameId',
labelAlign: 'top',
fieldLabel: 'Name',
store: me._getNames(),
//disabled:some condition?true:false,//doesn't gray out combo
valueField:'dataId',
displayField: 'firstName',
editable: false,
listeners:{
afterrender: function(combo,component) {
var combo = me.down('#nameId');
var nameStore = combo.getStore();
var setFirstRecord = function(combo){
var nameStore = combo.getStore();
if(nameStore.getCount() === 1){
combo.setValue(nameStore.getAt(0));
}
}
if(nameStore.isLoaded() === false){
nameStore.on('load', function(nameStore){
setFirstRecord(combo);
},this,{
single:true
});
}else{
setFirstRecord(nameStore);
}
},
}
}]
}];
}
Code for the store is as below:
_getNames: function (){
var nameStore = Ext.create('Ext.data.Store', {
autoLoad: true,
proxy: {
type: 'ajax',
url: 'name.json',
reader: {
type: 'json',
rootProperty:'items',
transform: function (data) {
var data = {
items: [{
dataId: data[0].dataId,
firstName: data[0].name.firstName,
nameDetails: data[0].nameDetails
}]
}
return data;
}
},
},
fields: ['dataId', 'firstName','nameDetails']
});
return namesStore;
}
})
The result returned from the api to populate the store is as follows:
[
{
"dataId":1,
"name":{
"dataId":1,
"firstName":"Julie",
"code":"10",
"connectionList":[
"EMAIL"
]
},
"nameDetails":{
"EMAIL":{
"dataId":1,
"detail":"EMAIL"
}
}
}
]
Any suggestions on what's missing would be great!
I am written that example for you in Sencha Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/3cdl
That solve your problem:
combo.getStore().on("load",
function (store, records, successful, operation, eOpts) {
if (store.getData().length > 0)
combo.setValue(store.getData().get(0).getData().id)
},
this
)
You must check if store is loaded or not and write appropriate code:
...
...
xtype: 'combo',
itemId: 'nameId',
name: 'nameId',
labelAlign: 'top',
fieldLabel: 'Name',
store: this._getNames(),
valueField: 'dataId',
displayField: 'firstName',
editable: false,
listeners: {
afterrender: function (combo) {
var store = combo.getStore();
var setFirstRecord = function (combo) {
var store = combo.getStore();
if (store.getCount() === 1) {
combo.setValue(store.getAt(0));
}
}
if (store.isLoaded() === false) {
store.on('load', function (store) {
setFirstRecord(combo);
}, this, {
single: true
});
} else {
setFirstRecord(combo);
}
}
}
...
...

How to read values from multiselector component

I am trying to use multiselector from EXTJS 6.5.2
This is the code that I am using to create multiselector with the values that I need
{
xtype: 'multiselector',
title: 'I caktohet:',
name: 'Caktohen[]',
bind: '{userfullname.value}',
fieldName: 'userfullname',
viewConfig: {
deferEmptyText: false,
emptyText: 'Askush i zgjedhur'
},
search: {
field: 'userfullname',
model: 'InTenders.model.UserModel',
store: {
type: 'users',
sorters: 'userfullname',
// proxy: {
// type: 'rest',
// limitParam: null,
// url: 'api/User'
// }
}
}
}
When I call form = win.down('form') records I can get all values except the multiselector values, they show like this on console.
Anyone can help me or guide me how to get the values?
Thank you.
//Code that I'm trying to get multiselector items and save them
saveTenderForm: function (button, e, eOpts) {
var userMultiSelector = Ext.getCmp('AssignedUsers'); //save assigned users
var selectedUsers = userMultiSelector.getStore().getData(); //get store and put them in array
var me = this,
win = button.up('window'),
form = win.down('form'),
// formApplyUpload = this.getFormApplyUpload(),
// var ko = win.items.items[0].items.items[0].value;
recordtenderUsers = Ext.create('InTenders.model.TenderSaveModel');
// recordtenderUsers = form.getRecord();
// record = form.getRecord(),
values = form.getValues();
// appFile = this.getApplicationFile(),
// callbacks;
recordtenderUsers.set(values);
recordtenderUsers.set('tenderUsers',selectedUsers.items);
// // me.showMask();
// if (form.isValid()) {
recordtenderUsers.save({
success: function (recordtenderUsers, operation) {
win.close();
me.hideMask();
},
failure: function (recordtenderUsers, operation) {
me.hideMask();
}
});
You can get value using multiselector.down('grid') this will return you the grid. And grid have method getSelection().
In this FIDDLE, I have created a demo. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.create({
xtype: 'form',
renderTo: Ext.getBody(),
items: [{
xtype: 'multiselector',
title: 'Multi selector example',
fieldName: 'text',
viewConfig: {
deferEmptyText: false,
emptyText: 'No value selected'
},
search: {
field: 'text',
store: {
fields: [{
name: 'text',
type: 'string'
}],
data: [{
text: 'ABC'
}, {
text: 'ABC 1'
}, {
text: 'ABC 2 '
}, {
text: 'ABC 3'
}, {
text: 'ABC 4'
}]
}
}
}, {
xtype: 'button',
text: 'Get Value',
margin:15,
handler: function (btn) {
var multiselector = btn.up('form').down('multiselector');
if (multiselector.down('grid')) {
multiselector.down('grid').getSelection().forEach(rec => {
console.log(rec.get('text'));
});
}
}
}]
});
}
});

XTemplate definition on items property of a ListItem

I'm using Sencha 2.3.0 and I want to have a XTemplate side-to-side to a component (textfield) on a ListItem. The code above works fine for DataView/DataItem, but I want to use the grouped property that is only available on List/ListItem.
The nested Xtemplate gets rendered fine as DataItem. How can I make it work for ListItem? I'm also receptive for solutions that drop this nested structure and use the xtemplate as tpl property directly on the ListItem (of course the textfield with listeners must be implemented as well).
list
Ext.define( 'app.view.myList', {
//extend: 'Ext.dataview.DataView',
extend: 'Ext.dataview.List',
xtype: 'mylist',
requires: [
'app.view.MyItem'
],
config: {
title: "myTitle",
cls: 'mylist',
defaultType: 'myitem',
grouped: true,
store: 'myStore',
useComponents: true,
itemCls: 'myitem',
items: [
{
// some components
}
]
}
});
listitem
Ext.define( 'app.view.myItem', {
//extend: 'Ext.dataview.component.DataItem',
extend: 'Ext.dataview.component.ListItem',
xtype: 'myitem',
config: {
cls: 'myitem',
items: [
{
xtype: 'component',
tpl: new Ext.XTemplate([
'<table cellpadding="0" cellspacing="0" class="myitemXTemplate">',
//some xtemplate content
'</table>'
].join( "" ),
{
compiled: true
})
},
{
label: 'some label',
cls : 'myitemtextfield',
xtype: 'textfield',
name: 'myitemtextfield'
}
]
}
});
Thanks in advance!
Modifed /touch-2.4.2/examples/list/index.html
The model:
Ext.define('model1', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'firstName', type: 'string'},
{name: 'lastName', type: 'string'}
]
}
});
The CustomListItem
Ext.define('DataItem', {
extend: 'Ext.dataview.component.ListItem',
xtype: 'basic-dataitem',
requires: [
'Ext.Button',
'Ext.Component',
'Ext.layout.HBox',
'Ext.field.Checkbox'
],
config: {
dataMap : {
/* getFirstname : {
setData : 'firstName'
},*/
getLastname : {
setValue : 'lastName'
}
},
layout: {
type: 'hbox',
height:'200px',
},
firstname: {
cls: 'firstname',
xtype:'component',
data:{data:'hej'},
tpl: new Ext.XTemplate([
'<H1>',
'{data}',
'</H1>'
].join(""),
{
compiled: true
})
},
lastname: {
xtype:'textfield',
css:'lastname'
}
},
applyFirstname : function (config) {
return Ext.factory(config, Ext.Component, this.getFirstname());
},
updateFirstname : function (newName) {
if (newName) {
this.add(newName);
}
},
applyLastname : function (config) {
return Ext.factory(config, Ext.Component, this.getLastname());
},
updateLastname : function (newAge) {
if (newAge) {
this.add(newAge);
}
},
applyFirstName: function (config) {
return Ext.factory(config, 'Ext.Component', this.getLastname());
},
updateRecord: function(record) {
if (!record) {
return;
}
this.getFirstname().setData({data:record.get("firstName")});
this.callParent(arguments);
}
});
The store
var store = Ext.create('Ext.data.Store', {
//give the store some fields
model: 'model1',
//filter the data using the firstName field
sorters: 'firstName',
//autoload the data from the server
autoLoad: true,
//setup the grouping functionality to group by the first letter of the firstName field
grouper: {
groupFn: function (record) {
return record.get('firstName')[0];
}
},
//setup the proxy for the store to use an ajax proxy and give it a url to load
//the local contacts.json file
proxy: {
type: 'ajax',
url: 'contacts.json'
}
});
The list
xtype: 'list',
useSimpleItems: false,
defaultType: 'basic-dataitem',
id: 'list',
ui: 'round',
//bind the store to this list
store: store

ExtJS 5.1.1 Immediately fire binding in ViewModel

Seems like i have some misunderstanding with binding timings. I have a simple combobox with value binded to some object in viewmodel. Selecting new value, firing change event, which fired after setValue method, so my new value is already set, but my viewmodel is not updated yet. When my viewmodel will be updated? I found some information about scheduler, which says i need to run notify() method to immediately apply changes to viewmodel, but it doesn't help me at all.
Ext.define('MyModel', {
extend: 'Ext.data.Model',
idProperty: 'foo',
fields: [{
name: 'bar',
type: 'string'
}]
});
Ext.define('MyViewModel',{
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.my',
data: {
testObj: {
foo: null,
bar: null
}
},
stores:{
combostore: {
model: 'MyModel',
data: [{
foo: '1',
bar: 'qwerty'
},{
foo: '2',
bar: 'ytrewq'
}]
}
}
});
Ext.define('MyViewController', {
extend: 'Ext.app.ViewController',
alias: 'controller.my',
onChange: function() {
var vm = this.getViewModel();
vm.notify();
console.log(vm.get('testObj.foo'));//supposed to be current value
}
});
Ext.application({
name : 'Fiddle',
launch : function() {
Ext.create('Ext.container.Viewport', {
controller: 'my',
viewModel: {
type: 'my'
},
layout : 'vbox',
items : [
{
xtype : 'combo',
valueField: 'foo',
displayField: 'bar',
queryMode: 'local',
bind: {
store: '{combostore}',
value: '{testObj.foo}'
},
listeners:{
change: 'onChange'
}
}
]
});
}
});
Here's fiddle aswell: https://fiddle.sencha.com/#fiddle/r88
I know it is a late response, however I think this problem is still relevant. See this fiddle: https://fiddle.sencha.com/#fiddle/2l6m&view/editor.
Essentially the idea is that you listen to the bound variables changes instead of listening to the combobox selection change (which triggers the re-evaluation of the bound variables).
The key code is in the constructor I added for the view model:
Ext.define('MyViewModel',{
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.my',
// added this to enable the binding
constructor: function () {
var me = this;
me.callParent(arguments);
me.bind('{selectedItem}', function (value) {
console.log('combobox selected item changed (bar value): ' + (value === null ? "null": value.get('bar')));
console.log(me.getView().getController());
});
me.bind('{testObj.foo}', function (value) {
console.log('combobox value (foo value): ' + value);
// you can access the controller
console.log(me.getView().getController());
});
},
data: {
testObj: {
foo: null,
bar: null
},
selectedItem: null,
},
stores:{
combostore: {
model: 'MyModel',
data: [{
foo: '1',
bar: 'qwerty'
},{
foo: '2',
bar: 'ytrewq'
}]
}
}
});
and here is the view (note the binding to the selection):
Ext.application({
name : 'Fiddle',
launch : function() {
Ext.create('Ext.container.Viewport', {
controller: 'my',
viewModel: {
type: 'my'
},
layout : 'vbox',
items : [
{
xtype : 'combo',
valueField: 'foo',
displayField: 'bar',
queryMode: 'local',
bind: {
store: '{combostore}',
value: '{testObj.foo}',
selection: '{selectedItem}'
},
listeners:{
change: 'onChange'
}
}
]
});
}
});
Binding the selection was not necessary but I included it anyway as another option because sometimes you may want to store additional data in the store that is bound to the list.
I hope this helps others.
You should not call notify directly on the viewmodel. It's private:
http://docs.sencha.com/extjs/5.0/5.0.1-apidocs/#!/api/Ext.app.ViewModel-method-notify
Just set the data by calling vm.setData({}).
onChange: function(cb, newValue, oldValue) {
var vm = this.getViewModel();
console.log('newValue', newValue);
console.log('oldValue', oldValue);
this.getViewModel().setData({'testObj': {'foo': newValue}});
console.log(vm.get('testObj.foo'));//supposed to be current value
}
Never the less you could consider the following example, where I use a formula to get the selected model of the combobox. See that I removed the listener, added a reference to the combobox and created a formula to bind deep onto the selected record.
Ext.define('MyModel', {
extend: 'Ext.data.Model',
idProperty: 'foo',
fields: [{
name: 'bar',
type: 'string'
}]
});
Ext.define('MyViewModel',{
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.my',
data: {
testObj: {
foo: null,
bar: null
}
},
stores:{
combostore: {
model: 'MyModel',
data: [{
foo: '1',
bar: 'qwerty'
},{
foo: '2',
bar: 'ytrewq'
}]
}
},
formulas: {
currentRecord: {
bind: {
bindTo: '{myCombo.selection}',
deep: true
},
get: function(record) {
return record;
},
set: function(record) {
this.set('currentRecord', record);
}
}
}
});
Ext.define('MyViewController', {
extend: 'Ext.app.ViewController',
alias: 'controller.my',
onChange: function(cb, newValue, oldValue) {
var vm = this.getViewModel();
console.log('newValue', newValue);
console.log('oldValue', oldValue);
this.getViewModel().setData({'testObj': {'foo': newValue}});
console.log(vm.get('testObj.foo'));//supposed to be current value
}
});
Ext.application({
name : 'Fiddle',
launch : function() {
var vp = Ext.create('Ext.container.Viewport', {
controller: 'my',
viewModel: {
type: 'my'
},
layout : 'vbox',
items : [
{
xtype : 'combo',
reference: 'myCombo',
valueField: 'foo',
displayField: 'bar',
queryMode: 'local',
bind: {
store: '{combostore}',
value: '{testObj.foo}'
}/*,
listeners:{
change: 'onChange'
}*/
},
{
xtype: 'label',
bind: {
text: '{currentRecord.foo}'
}
}
]
});
/* Just an example. You could also select records on the combo itself */
vp.getViewModel().setData({'testObj': {'foo': '2'}});
}
});
Defer would be your savior:
onChange: function() {
var vm = this.getViewModel();
Ext.defer(function(){
console.log(vm.get('testObj.foo'));//supposed to be current value
},10,this);
}
Please use select event instead of change.
I think change event fires even before value is set.

exjts hide column if all cells of the column are empty

I am trying to hide the column if all the cells in the column are empty. I am trying to do this in the column listener by iterating through the store but I guess the store isnt populated at that time. any suggestions to achieve this functionality?
Ext.define('com.abc.MyGrid' , {
extend: 'Ext.grid.Panel',
store : 'MyStore',
columns : [{
text : 'col1',
sortable : true,
dataIndex : 'col1'
}, {
text : 'col2 ',
sortable : true,
dataIndex : 'col2',
listeners:{
"beforerender": function(){
console.log(this.up('grid').store);
this.up('grid').store.each(function(record,idx){
// if all are null for record.get('col1')
// hide the column
console.log(record.get('col1'));
});
}
}
}
})
But this is isnt working. Basically the store loop in the column listener "before render" is not executing where as the above console(this.up('grid').store) prints the store with values.
Here you go, it doesn't handle everything but should be sufficient.
Ext.define('HideColumnIfEmpty', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.hideColumnIfEmpty',
mixins: {
bindable: 'Ext.util.Bindable'
},
init: function(grid) {
this.grid = grid;
this._initStates();
this.grid.on('reconfigure', this._initStates, this);
},
_initStates: function(store, columns) {
var store = this.grid.getStore(),
columns = this.grid.columns;
this.bindStore(store);
this.columns = columns;
if(store.getCount() > 0) {
this._maybeHideColumns();
}
},
/**
*#implement
*/
getStoreListeners: function() {
return {
load: this._maybeHideColumns
};
},
_maybeHideColumns: function() {
var columns = this.columns,
store = this.store,
columnKeysMc = new Ext.util.MixedCollection();
Ext.Array.forEach(columns, function(column) {
columnKeysMc.add(column.dataIndex, column);
});
Ext.Array.some(store.getRange(),function(record){
//don't saw off the branch you are sitting on
//eachKey does not clone
var keysToRemove = [];
columnKeysMc.eachKey(function(key) {
if(!Ext.isEmpty(record.get(key))) {
keysToRemove.push(key);
}
});
Ext.Array.forEach(keysToRemove, function(k) {
columnKeysMc.removeAtKey(k);
});
return columnKeysMc.getCount() === 0;
});
columnKeysMc.each(function(column) {
column.hide();
});
}
});
Here is an example:
Ext.create('Ext.data.Store', {
storeId:'simpsonsStore',
fields:['name', 'email', 'phone'],
data:{'items':[
{ 'name': 'Lisa', "email":"lisa#simpsons.com", "phone":"555-111-1224" },
{ 'name': 'Bart', "email":"bart#simpsons.com", "phone":"555-222-1234" },
{ 'name': 'Homer', "email":"home#simpsons.com", "phone":"555-222-1244" },
{ 'name': 'Marge', "email":"marge#simpsons.com", "phone":"555-222-1254" }
]},
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
}
});
Ext.create('Ext.grid.Panel', {
title: 'Simpsons',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
columns: [
{ text: 'Name', dataIndex: 'name' },
{ text: 'Email', dataIndex: 'email', flex: 1 },
{ text: 'Phone', dataIndex: 'phone' },
{ text: 'Says Doh', dataIndex: 'saysDoh'}
],
plugins: {ptype: 'hideColumnIfEmpty'},
height: 200,
width: 400,
renderTo: Ext.getBody()
});
You can see in the example that saysDoh column is hidden.
If you want to iterate over the store, you need to put a listener on the load event of your store. The beforerender doesn't mean that your store is already loaded.
I would put the creation of you store in the initComponent. Something like this:
Ext.define('com.abc.MyGrid', {
extend: 'Ext.grid.Panel',
columns: [{
text: 'col1',
sortable: true,
dataIndex: 'col1'
}, {
text: 'col2 ',
sortable: true,
dataIndex: 'col2'
},
initComponent: function () {
var me = this;
//Create store
var myStore = Ext.create('MyStore');
myStore.load(); // You can remove this if autoLoad: true on your store.
//Listen to load event (fires when loading has completed)
myStore.on({
load: function (store, records, success) {
store.each(function (record, idx) {
console.log(record.get('col1'));
});
}
});
//Apply the store to your grid
Ext.apply(me, {
store: myStore
});
me.callParent();
}
});

Categories