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
Related
I have two entities, sent from two different APIs, with a one to one relationship.
I want to load both models in the same grid panel. The problem is that I can only load one store. To load the other store, I attached a callback to the grid reload event which edits the grid DOM manually to insert data form the second store.
My Question is: Can I load both the model and the association without using DOM hacks like I did?
The entities from APIs look like this:
Get /Users/Details:
{
"Id" : "55b795827572761a08d735ac",
"Username" : "djohns",
"Email" : "admin#mail.com",
"FirstName" : "Davey",
"LastName" : "Johns"
}
And:
Get /Users/Rights:
{
"_id" : "55b795827572761a08d735ac",
"Status" : "Activated",
"Roles" : [
"portal",
"dataApp"
]
}
Notice the same id, which is used in the API as the key/foreign key).
Now these are the models:
Ext.define('Portal.model.users.UserRights', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
mapping: 'Id'
},
{
name: 'Status'
},
{
name: 'UserId',
mapping: 'Id',
reference: 'Portal.model.users.UserDetails'
}
],
schema: {
namespace: 'Portal.model.users',
proxy: {
type: 'rest',
url: Portal.util.Util.constants.apiBaseURL + 'Users/Rights',
reader: {
type: 'json',
rootProperty: 'Objects'
}
}
}
});
And:
Ext.define('Portal.model.users.UserDetails', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
mapping: 'Id'
},
'FirstName',
'LastName',
'Username',
'Email'
],
});
And I defined a store for user details (while the store of the user rights is inside its own model):
Ext.define('Portal.store.UsersDetails', {
extend: 'Ext.data.Store',
model: 'Portal.model.users.UserDetails',
proxy: {
type: 'rest',
url: Portal.util.Util.constants.apiBaseURL + 'Users/Details',
reader: {
type: 'json',
rootProperty: 'Objects'
}
}
});
Here is how I configured the Grid:
Ext.define('Portal.view.users.UsersGrid', {
extend: 'Ext.grid.Panel',
store: 'UsersDetails',
columns: [
{
dataIndex: 'id',
text: 'Id'
},
{
dataIndex: 'Username',
text: 'Username'
},
{
dataIndex: 'Email',
text: 'Email'
},
{
dataIndex: 'FirstName',
text: 'First Name'
},
{
dataIndex: 'LastName',
text: 'Last Name'
},
{
text: "Status",
cls: "status-column",
renderer: function (value, meta, record) {
return "loading...";
}
}
],
loadUserRights: function () {
var columns = this.getEl().select('.status-column');
var cells = this.getEl().select(".x-grid-cell-" + columns.elements[0].id + " .x-grid-cell-inner");
data = this.getStore().getData();
Ext.each(data.items, function (record, index) {
var userRights = record.userUserRights();
userRights.load({
callback: function (records, operation, success) {
if (success) {
cells.elements[index].innerText = userRights.data.items[0].data.Status;
}
}
});
});
}
});
And then I load the gird from an external function:
grid.getStore().reload({
callback: function (records, operation, success) {
grid.loadUserRights();
}
});
Cant delete a record from the store.
My model
Ext.define('touch.model.FilesModel', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.identifier.Uuid'
],
config: {
identifier: 'uuid',
idProperty: 'iD',
fields: [
{ name: 'iD', type: 'auto' },
{ name: 'fileName', type: 'auto' }
]
}
});
and this is my SessionStorage
Ext.define('touch.store.FilesStore', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.SessionStorage'
],
config: {
storeId: 'FilesStore',
autoLoad: true,
model: 'touch.model.FilesModel',
proxy: {
type: 'sessionstorage',
id: 'FilesStore-store-unique'
},
sorters: [{
property: 'created',
direction: 'DESC'
}]
}
});
I am trying to remove a record from the store, and it doesnt work.
i tried:
var filesStore = Ext.getStore('FilesStore');
filesStore.remove(filesStore.getAt(index)); // fails on this line: "Uncaught TypeError: Cannot read property 'destroy' of null" remove from the store
filesStore.sync();
then i tried just to do
var filesStore = Ext.getStore('FilesStore');
filesStore.getAt(index).erase() // fails with: [ERROR][Anonymous] You are trying to erase a model instance that doesn't have a Proxy specified
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);
},
I'm having trouble trying to invoke getters/setters on a Model object that has an association with one other model. Here are the classes:
Category.js
Ext.define('Chapter05.model.Category', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' }
]
})
Product.js
Ext.define('Chapter05.model.Product', {
extend: 'Ext.data.Model',
requires: [
'Chapter05.model.Category'
],
fields: [
{ name: 'id', type: 'int' },
{ name: 'category_id', type: 'int' },
{ name: 'name', type: 'string' }
],
// we can use the belongsTo shortcut on the model to create a belongsTo association
associations: [
{ type: 'belongsTo', model: 'Chapter05.model.Category' }
]
})
Main.js
Ext.define('Chapter05.view.Main', {
extend: 'Ext.container.Container',
requires:[
'Ext.tab.Panel'
'Chapter05.model.Product',
'Chapter05.model.Category',
],
xtype: 'app-main',
layout: 'vbox',
items: [
{
xtype: 'button',
text: 'Category',
handler: function(evt) {
var product = new Chapter05.model.Product({
id: 100,
category_id: 20,
name: 'Sneakers'
});
product.getCategory(function(category, operation) {
// do something with the category object
alert(category.get('id')); // alerts 20
}, this);
}
}
]
});
The error occurs at the line where product.getCategory(...) is. I get the following message in Safari Web Inspector:
TypeError: 'undefined' is not a function (evaluating 'product.getCategory')
Am I forgetting to do something?
P.S.
The project(Chapter05) was generated using Sencha Cmd. Hence, the fully qualified names.
I've had a similar problem with a hasOne relation. It was solved by specifying the getters/setters and the associationKey yourself.
Something like:
belongsTo: {
model: 'Chapter05.model.Category',
getterName: 'getCategory',
setterName: 'setCategory',
associationKey: 'category_id'
}
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();
}
});