ext js 6 pass dynamic id from grid panel to model - javascript

How to passing id from gridpanel to model ?
here my grid panel code:
{
text : 'Tindakan',
xtype: 'actioncolumn',
minWidth: 130,
sortable: false,
menuDisabled: true,
items: [{
icon: 'images/view.png', // Use a URL in the icon config
tooltip: 'Lihat',
handler : function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
alert("Lihat - " + rec.get('id'));
}]
}
Here is my model code:
Ext.define('Kds.model.ProfilView', {
extend: 'Ext.data.Store',
alias: 'model.profilView',
fields: [
'name',
'ic_no',
'address',
],
pageSize : 20,
proxy: {
type: 'rest',
url : 'http://localhost/kds-rest/web/index.php/people/view/'+id,
useDefaultXhrHeader : false,
withCredentials: false,
reader: {
type: 'json',
rootProperty: 'data',
//totalProperty: 'totalItems'
}
},
autoLoad: 'true',
});

How do you use that model? If you create or use that each time, you can try this:
handler : function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
//Create or get model to use
var model = Ext.create('Kds.model.ProfilView', {
// then give the record id to model
recordId: rec.get('id') // edited
});
}
// to use in model
Ext.define('Kds.model.ProfilView', {
extend: 'Ext.data.Store',
alias: 'model.profilView',
fields: [
'name',
'ic_no',
'address'
],
pageSize : 20,
autoLoad: 'true',
initComponent: function() {
var me = this;
me.proxy = {
type: 'rest',
url : 'http://localhost/kdsrest/web/index.php/people/view/'+me.recordId, // or this.up().recordId,
................
} // iniComponent
me.callParent();
Edit: How to load model dynamically: fiddle: https://fiddle.sencha.com/#fiddle/11g9
Ext.define('model.instance', {
extend: 'Ext.data.Model',
fields: ['name', 'city', 'country'],
proxy: {
type: 'ajax',
url: 'info',
reader: {
type: 'json',
rootProperty: 'records'
}
}
});
var fn = function getSelectedRow(gridView, rowIndex, colIndex, column, e,direction) {
var me = this;
var store = gridView.getStore();
var record = store.getAt(rowIndex);
var inst = Ext.create('model.instance', {
name: record.get('name')
});
inst.load({
scope: this,
success: function(rec) {
console.log(rec);
}
});
}
var store1 = Ext.create('Ext.data.Store', {
fields: ['name', 'surname'],
data: [{
name: 'Rick',
surname: 'Donohoe'
}, {
name: 'Jane',
surname: 'Cat'
}]
});
var grid = Ext.create('Ext.grid.Panel', {
columns: [{
dataIndex: 'name'
}, {
dataIndex: 'surname'
}, {
xtype: 'actioncolumn',
text: 'Select',
icon: '/image',
handler: Ext.bind(fn, this)
}],
store: store1,
renderTo: Ext.getBody()
});

Related

Creating dependent extjs grids

I just started to study extjs 6.
How it is possible to implement dependent grids when the main displays data from the table, when clicked on, in the second grid, the dependent entries from the second table are displayed.
What I realized at the moment:
I created a grid, I get the records from the "Operation" table, I call it using the CRUD. In the "Operation" table, all entries are associated with the second table (numoperation) in the code field.
It is required to me that at pressing on record of the main grid which is already created, to receive dependent records from the table numoperation in the second grid.
How can this be implemented in general?
I would be glad if you share useful links, tips or examples.
Thank you in advance.
Below is the code for the client part of the application:
Ext.onReady(function () {
Ext.define('Operation', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
'date_op',
'code',
'status',
'type'
]
});
var urlRoot = 'data?model=Operation&method=';
var registrStore = Ext.create('Ext.data.Store', {
model: 'Operation',
pageSize: 10,
proxy: {
type: 'jsonp',
noCache: false,
api: {
create: urlRoot + 'Create',
read: urlRoot + 'Read',
update: urlRoot + 'Update',
destroy: urlRoot + 'Destroy'
},
reader: {
type: 'json',
metaProperty: 'meta',
root: 'data',
idProperty: 'id',
totalProperty: 'meta.total',
successProperty: 'meta.success'
},
writer: {
type: 'json',
encode: true,
writeAllFields: true,
root: 'data',
allowSingle: false,
}
}
});
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: 2,
autoCancel: false,
listeners: {
edit: function (editor, context) {
var emp = registrStore.getProxy();
var con = context.record;
emp.setExtraParam("id", con.data['id']);
emp.setExtraParam("date_operation", con.data['date_operation']);
emp.setExtraParam("code", con.data['code']);
emp.setExtraParam("status", con.data['status']);
emp.setExtraParam("type", con.data['type']);
}
}
});
var textField = {
xtype: 'textfield'
};
// Определение столбцов
var columns = [
{
header: 'ID',
dataIndex: 'id',
sortable: true,
width: 35
},
{
header: 'Дата',
dataIndex: 'date_op',
sortable: true,
editor: textField
},
{
header: 'Код',
dataIndex: 'code',
sortable: true,
editor: textField
},
{
header: 'Статус',
dataIndex: 'status',
sortable: true,
editor: textField
},
{
header: 'Тип',
dataIndex: 'type',
sortable: true,
editor: textField
}
];
var pagingToolbar = {
xtype: 'pagingtoolbar',
store: registrStore,
displayInfo: true,
items: [
'-',
{
text: 'Save Changes',
handler: function () {
registrStore.sync();
}
},
'-',
{
text: 'Reject Changes',
handler: function () {
// Отмена изменений в stoe
registrStore.rejectChanges();
}
},
'-'
]
};
var onDelete = function () {
var selected = grid.selModel.getSelection();
Ext.MessageBox.confirm(
'Confirm delete',
'Are you sure?',
function (btn) {
if (btn == 'yes') {
var nn = selected[0].get('id')
var emp = registrStore.getProxy();
emp.setExtraParam("id", nn)
grid.store.remove(selected);
grid.store.sync();
}
}
);
};
var onInsertRecord = function () {
var selected = grid.selModel.getSelection();
rowEditing.cancelEdit();
var newEmployee = Ext.create("Operation");
registrStore.insert(selected[0].index, newEmployee);
rowEditing.startEdit(selected[0].index, 0);
};
var doRowCtxMenu = function (view, record, item, index, e) {
e.stopEvent();
if (!grid.rowCtxMenu) {
grid.rowCtxMenu = new Ext.menu.Menu({
items: [
{
text: 'Insert Operation',
handler: onInsertRecord
},
{
text: 'Delete Operation',
handler: onDelete
}
]
});
}
grid.selModel.select(record);
grid.rowCtxMenu.showAt(e.getXY());
};
var grid = Ext.create('Ext.grid.Panel', {
title: 'Таблица операций',
items: grid,
columns: columns,
store: registrStore,
loadMask: true,
bbar: pagingToolbar,
plugins: [rowEditing],
stripeRows: true,
selType: 'rowmodel',
viewConfig: {
forceFit: true
},
listeners: {
itemcontextmenu: doRowCtxMenu,
destroy: function (thisGrid) {
if (thisGrid.rowCtxMenu) {
thisGrid.rowCtxMenu.destroy();
}
}
},
renderTo: Ext.getBody()
});
registrStore.load();
});
What you probably want to do is to add a listener on the main grid that listens for the event: select.
https://docs.sencha.com/extjs/6.5.3/modern/Ext.grid.Grid.html#event-select
listeners: {
select: "onSelectMainGrid",
},
then you want to have a function called onSelectMainGrid or something similar
var onSelectMainGrid : function(grid, selectedItem) {
. . .
}
and in this function, you want to get the store from the dependent grids and you want to call the .load() function on them. For your dependent grid's store's proxy, use the config extraParams: {}
https://docs.sencha.com/extjs/6.5.3/modern/Ext.data.Connection.html#cfg-extraParams and bind the selection from the main grid to the extraParams of the dependent grids. Then call the method .load() on the dependent grid's store. The store of your dependent grid will look something like
var dependentGridStore = Ext.create('Ext.data.Store', {
model: 'OperationDependent',
pageSize: 10,
proxy: {
type: 'jsonp',
noCache: false,
extraParams: { // <==THIS IS NEW
valueFromMainGrid: '{selectedValueFromMainGrid}'
}
api: {
create: urlRoot + 'Create',
read: urlRoot + 'Read',
update: urlRoot + 'Update',
destroy: urlRoot + 'Destroy'
},
reader: {
type: 'json',
. . .
. . .
});
I noticed that you have all the code in the same file. It is strongly advised that you separate your code into views, viewModels, and viewControllers.
One last thing, If you don't make use of a viewModel for databinding, alternatively in the onSelectMainGrid function, since you are passing the selectedItem parameter, you can just get the dependent grid, then get its store, then get its proxy, and then set the extraParams to the selectedItem passed as parameter to the function.
Let me know if you need any clarification.
I did so (shortened the code for better perception):
Ext.define('Operation', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
'date_operation',
'code',
'status',
'type',
'mesto_hraneniya',
'contragent',
'sum_operation',
'rezerv',
'cnt_doc',
'stellag'
]
});
var urlRoot = 'data?model=Operation&method=';
// Хранилище для данных таблицы Registr
var registrStore = Ext.create('Ext.data.Store', {
model: 'Operation',
pageSize: 10,
proxy: {
type: 'jsonp',
noCache: false,
api: {
create: urlRoot + 'Create',
read: urlRoot + 'Read',
update: urlRoot + 'Update',
destroy: urlRoot + 'Destroy'
},
reader: {
type: 'json',
metaProperty: 'meta',
root: 'data',
idProperty: 'id',
totalProperty: 'meta.total',
successProperty: 'meta.success'
},
writer: {
type: 'json',
encode: true,
writeAllFields: true,
root: 'data',
allowSingle: false,
}
}
});
Ext.define('Tovary', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
'name',
'code',
'prise',
'unit'
]
});
var urlRootTv = 'data?model=Tovary&method=';
var TovaryGridStore = Ext.create('Ext.data.Store', {
model: 'Tovary',
pageSize: 10,
proxy: {
type: 'jsonp',
noCache: false,
extraParams: {
inclProps: '{code_tv}'
},
api: {
create: urlRootTv + 'Create',
read: urlRootTv + 'Read',
update: urlRootTv + 'Update',
destroy: urlRootTv + 'Destroy'
},
reader: {
type: 'json',
metaProperty: 'meta',
root: 'data',
idProperty: 'id',
totalProperty: 'meta.total',
successProperty: 'meta.success'
},
writer: {
type: 'json',
encode: true,
writeAllFields: true,
root: 'data',
allowSingle: false,
}
}
});
......
// Grid панель
var grid = Ext.create('Ext.grid.Panel', {
title: 'Таблица операций',
items: grid,
columns: columns,
store: registrStore,
loadMask: true,
bbar: pagingToolbar,
plugins: [rowEditing],
stripeRows: true,
selType: 'rowmodel',
viewConfig: {
forceFit: true
},
listeners: {
itemcontextmenu: doRowCtxMenu,
destroy: function (thisGrid) {
if (thisGrid.rowCtxMenu) {
thisGrid.rowCtxMenu.destroy();
}
},
select: function(grid, selectedItem) {
TovaryGridStore.proxy.extraParams = {'code_tv' : selectedItem.id.code};
TovaryGridStore.load();
}
},
renderTo: Ext.getBody()
});
registrStore.load();
When I click on a row in the grid, the browser console displays an error:
GET http://127.0.0.1:8000/hello_extjs/data?model=Tovary&method=Read&code_tv=&page=1&start=0&limit=10&callback=Ext.data.JsonP.callback2 500 (Internal Server Error)
What is the cause of this error? Whether correctly I understand that now I need to deduce the second Ext.grid.Panel what to display in it the data of model "Tovary"?

ExtJS: Is possible to state if else condition for bind in grid panel?

Inside the ViewModel I've defined 2 stores and I'm using a gridpanel as view. Is there any chance to state if else condition for bind property inside gridpanel?
ViewModel:
stores: {
dataStore: {
model: 'MyApp.first.Model',
autoLoad: true,
session: true
},
listStore: {
model: 'MyApp.second.Model',
autoLoad: true,
session: true,
},
and on grid panel I want to do this condition;
Ext.define('MyApp.base.Grid', {
extend: 'Ext.grid.Panel',
// Currently binds directly to listStore
bind: '{listStore}',
// but I'm trying to implement a proper adjustment such as this;
// bind: function () {
// var username = localStorage.getItem('username');
// if (username === 'sample#adress.com') {'{dataStore}';} else {'{listStore}'}
// },
You can't use conditional expressions with bind, however, you can use ViewModel's formulas to select which store to use with grid. Here is example of such formula:
conditionalStore: function (get) {
var param = get('param');
if (param === 1) {
return get('simpsonsStore');
}
return get('griffinsStore');
}
And here is working fiddle, which you can play with: https://fiddle.sencha.com/#view/editor&fiddle/2eq2
You can use bindStore method of grid.
In this FIDDLE, I have created a demo using grid. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
//defining store 1
Ext.define('Store1', {
extend: 'Ext.data.Store',
alias: 'store.store1',
autoLoad: true,
fields: ['name', 'email', 'phone'],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: ''
}
}
});
//defining store 2
Ext.define('Store2', {
extend: 'Ext.data.Store',
alias: 'store.store2',
autoLoad: true,
fields: ['name', 'email', 'phone'],
proxy: {
type: 'ajax',
url: 'data2.json',
reader: {
type: 'json',
rootProperty: ''
}
}
});
//defining view model
Ext.define('MyViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myvm',
stores: {
gridStore1: {
type: 'store1'
},
gridStore2: {
type: 'store2'
}
}
});
//creating grid
Ext.create({
xtype: 'grid',
title: 'Example of bind the store',
renderTo: Ext.getBody(),
viewModel: {
type: 'myvm'
},
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Email',
dataIndex: 'email',
flex: 1
}, {
text: 'Phone',
dataIndex: 'phone'
}],
tbar: [{
text: 'Load Store1',
handler: function (btn) {
var grid = this.up('grid');
grid.bindStore(grid.getViewModel().getStore('gridStore1'))
}
}, {
text: 'Load Store2',
handler: function (btn) {
var grid = this.up('grid');
grid.bindStore(grid.getViewModel().getStore('gridStore2'))
}
}]
});
}
});

Web service returning JSON but not rendering

I have a SharePoint web service that retrieves documents from a farm. The call is a successful 200 and when I open it I can validate the JSON fine.
However it is not rendering on the page. Instead throwing a:
SyntaxError: missing ; before statement[Learn More] getTopics:1:8
getTopics is part of the Visual studio wsp project which compiles, deploys, and successfully retrieves the data. Is there something I'm missing here?
Code
var title = 'List';
var gridHeight = 400;
var uniqueId = 'topics';
var url = '/_vti_bin/MetaDataDoc/MetaDoc.svc/getTopics/?folder=/general_documents/';
var dSort = 'modified';
var dSortOrder = 'DESC';
buildGrid(uniqueId,title,gridHeight,url,dSort,dSortOrder)
function buildGrid(divId, title, gridHeight, url, dSort, dSortOrder) {
Ext.define('gridModel', {
extend: 'Ext.data.Model',
fields: [
{ name: "name", mapping: "name", sortable: true, convert: Ext.util.Format.trim },
{ name: "upcase_name", mapping: "name", convert: Ext.util.Format.uppercase },
{ name: "upcase_desc", mapping: "para", convert: Ext.util.Format.uppercase },
{ name: "url", mapping: "url", sortable: true},
{ name: "modified", mapping: "date", sortable: true, type: "date", dateFormat: "n/j/Y g:i A" },
{ name: "type", mapping: "type", sortable: true },
{ name: "size", mapping: "size", sortable: true, type: 'int'},
{ name: "desc", mapping: "para" },
{ name: "doclist", mapping: "doclist", convert: nestedData },
{ name: "title", mapping: "title" }
]
});
function toggleDetails(btn, pressed) {
grid[divId].columns[1].renderer = pressed ? renderNameDetails : renderName;
grid[divId].columns[0].renderer = pressed ? renderTypeDetails : renderType;
grid[divId].getView().refresh();
}
var gridStore = Ext.create('Ext.data.Store', {
model: 'gridModel',
proxy: {
type: 'jsonp',
url: url,
reader: {
type: 'json',
record: 'doc',
root: 'doclist'
}
}
});
if (dSort) {
gridStore.sort(dSort, dSortOrder);
}
var searchField = new SearchField({ store: gridStore, width: 300 });
var toggleButton = new Ext.Button({
enableToggle: true,
border: true,
text: 'View Details',
toggleHandler: toggleDetails,
pressed: false
});
grid[divId] = Ext.create('Ext.grid.Panel', {
renderTo: divId,
store: gridStore,
enableColumnHide: false,
enableColumnMove : false,
height: gridHeight,
tbar: ['Filter: ', ' ', searchField, { xtype: 'tbfill' }, toggleButton],
columns: [
{text: 'Type', width: 50, dataIndex: 'type',renderer: renderType},
{text: 'Document Name', flex: 1, dataIndex: 'name', renderer: renderName},
{text: 'Modified', width: 90, dataIndex: 'modified', xtype:'datecolumn', format:'m/d/Y'}
]
});
var loadMask = new Ext.LoadMask(divId, {message: "Loading"});
gridStore.load();
}
getTopics from the web service
public content getTopics(string foldername)
{
content returnContent = new content();
returnContent = getDocs2(foldername);
return returnContent;
}
Add that missing semicolon here (line 8):
buildGrid(uniqueId,title,gridHeight,url,dSort,dSortOrder);

Grid not updating when new record is added to his store

I have a gridpanel who is not being updated when a record is inserted on his store.
Model:
Ext.define('S1.model.Ciot', {
extend: 'Ext.data.Model',
requires: 'S1.proxy.Ciot',
proxy: 'ciot',
associations: [
{
type: 'belongsTo',
model: 'S1.model.Person',
associatedName: 'owner',
primaryKey: 'id',
foreignKey: 'owner_id',
associationKey: 'owner',
setterName: 'setOwner',
getterName: 'getOwner'
}
],
fields: [
{name: 'id', type: 'int', useNull: true},
{name: "owner_id", type: 'int', useNull: true},
{name: "number", type: 'int', useNull: true},
{name: "status", type: 'int', useNull: true},
{name: "product", type: 'string', useNull: true}
]
});
Store:
Ext.define('S1.store.Ciot', {
autoLoad: true,
extend: 'Ext.data.Store',
requires: 'S1.proxy.Ciot',
model: 'S1.model.Ciot',
proxy: 'ciot',
remoteSort: true,
remoteFilter: true,
remoteGroup: true,
pageSize: 40
});
Controller:
Ext.define('S1.controller.Ciot', {
extend: 'Ext.app.Controller',
stores: [
'Ciot'
],
models: [
'Ciot'
],
views: [
'ciot.Window',
'ciot.Grid',
'ciot.EditWindow',
'ciot.Form'
],
init: function () {
var me = this;
me.control({
'ciotgrid button[name=new]': {
click: me.onNewButtonClick
},
'ciotgrid': {
itemdblclick: me.onGridItemDblClick
},
'ciotform button[name=save]': {
click: me.onButtonSaveClick
}
});
},
onNewButtonClick: function (bt) {
var record = Ext.create('S1.model.Ciot'),
grid = bt.up('grid');
this.openEditWindow(record, grid);
},
onGridItemDblClick: function (v, record) {
this.openEditWindow(record, v);
},
openEditWindow: function (record, grid) {
var w = Ext.create('S1.view.ciot.EditWindow');
w.setGrid(grid || null);
w.show();
w.down('form').loadRecord(record);
},
onButtonSaveClick: function (bt) {
var form = bt.up('form'),
record = form.getRecord();
if (!record) {
return false;
}
if (!form.getForm().isValid()) {
return false;
}
form.updateRecord();
record.save({
success: this.onSaveSuccess,
failure: this.onSaveFailure,
scope: form
});
},
onSaveSuccess: function (r, op) {
var w = this.up('cioteditwindow'),
grid = w.getGrid(),
rs = op.getResultSet();
grid.getStore().insert(0, rs.records[0]);
w.close();
},
onSaveFailure: function (record, op) {
// ...
}
});
The callback onSaveSuccess successfully add the new record to the grid, but nothing happens on the frontend.
The record returned from the backend is OK.
Looks like the grid that I am inserting the new record, is not the same grid rendered.
What am I doing wrong here?
Thank you.
ps: the code was shortened for demonstration purposes.
Try to refresh the grid:
onSaveSuccess: function (r, op) {
var w = this.up('cioteditwindow'),
grid = w.getGrid(),
rs = op.getResultSet();
grid.getStore().insert(0, rs.records[0]);
--> grid.getView().refresh();
w.close();
},
The problem was in my record.
There was a "record.getOwner()" in the grid column renderer and the owner property was not being set.
I don't know why that method was not returning an error.
Grid:
Ext.define('S1.view.ciot.Grid', {
extend: 'Ext.grid.Panel',
alias: 'widget.ciotgrid',
store: 'Ciot',
columns: [
{
header: 'Empresa',
dataIndex: 'owner_id',
renderer: function (v, md, record) {
var owner = record.getOwner();
if (owner instanceof S1.model.Person) {
v = owner.get('name');
}
return v;
},
flex: 1
},
{header: 'Número', dataIndex: 'number', flex: 1},
{header: 'CIOT', dataIndex: 'ciot', flex: 1},
{header: 'Produto', dataIndex: 'product', flex: 1},
{header: 'Status', dataIndex: 'status', flex: 1}
]
});

Accessing Android phone contacts with phonegap and Sencha Touch

please I'm trying to get a list of all the contacts on my phone with the following code.
var App = new Ext.Application({
name: 'SmsthingyApp',
useLoadMask: true,
launch: function () {
Ext.data.ProxyMgr.registerType("contactstorage",
Ext.extend(Ext.data.Proxy, {
create: function(operation, callback, scope) {
},
read: function(operation, callback, scope) {
},
update: function(operation, callback, scope) {
},
destroy: function(operation, callback, scope) {
}
})
);
Ext.regModel("contact", {
fields: [
{name: "id", type: "int"},
{name: "givenName", type: "string"},
{name: "familyName", type: "string"},
{name: "emails", type: "auto"},
{name: "phoneNumbers", type: "auto"}
]
});
Ext.regStore('contacts',{
model: "contact",
proxy: {
type: "contactstorage",
read: function(operation, callback, scope) {
var thisProxy = this;
navigator.contacts.find(
['id', 'name', 'emails', 'phoneNumbers', 'addresses'],
function(deviceContacts) {
//loop over deviceContacts and create Contact model instances
var contacts = [];
for (var i = 0; i < deviceContacts.length; i++) {
var deviceContact = deviceContacts[ i ];
var contact = new thisProxy.model({
id: deviceContact.id,
givenName: deviceContact.name.givenName,
familyName: deviceContact.name.familyName,
emails: deviceContact.emails,
phoneNumbers: deviceContact.phoneNumbers
});
contact.deviceContact = deviceContact;
contacts.push(contact);
}
//return model instances in a result set
operation.resultSet = new Ext.data.ResultSet({
records: contacts,
total : contacts.length,
loaded : true
});
//announce success
operation.setSuccessful();
operation.setCompleted();
//finish with callback
if (typeof callback == "function") {
callback.call(scope || thisProxy, operation);
}
},
function (e) { console.log('Error fetching contacts'); },
{multiple: true}
);
}
}
});
Ext.regModel('Sms', {
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
{ name: 'date', type: 'date', dateFormat: 'c' },
{ name: 'title', type: 'string' },
{ name: 'message', type: 'string' }
],
validations: [
{ type: 'presence', field: 'id' },
{ type: 'presence', field: 'title', message: 'Please select a contact for this sms.' }
]
});
Ext.regStore('SmsStore', {
model: 'Sms',
sorters: [{
property: 'date',
direction: 'DESC'
}],
proxy: {
type: 'localstorage',
id: 'sms-app-localstore'
},
getGroupString: function (record)
{
if (record && record.data.date)
{
return record.get('date').toDateString();
}
else
{
return '';
}
}
});
SmsthingyApp.views.ContactsList = new Ext.List({
id: 'ContactsList',
layout: 'fit',
store:'contacts',
itemTpl: '{givenName} {familyName}',
listeners: {'render': function (thisComponent)
{
SmsthingyApp.views.ContactsList.getStore().load();
}
},
onItemDisclosure: function (record) {
//Ext.dispatch({
// controller: SmsthingyApp.controllers.contacts,
// action: 'show',
// id: record.getId()
//});
}
});
SmsthingyApp.views.contactsListContainer = new Ext.Panel({
id: 'contactsListContainer',
layout: 'fit',
html: 'This is the sms list container',
items: [SmsthingyApp.views.ContactsList],
dockedItems: [{
xtype: 'toolbar',
title: 'Contacts'
}]
});
SmsthingyApp.views.smsEditorTopToolbar = new Ext.Toolbar({
title: 'Edit SMS',
items: [
{
text: 'Back',
ui: 'back',
handler: function () {
SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
}
},
{ xtype: 'spacer' },
{
text: 'Save',
ui: 'action',
handler: function () {
var smsEditor = SmsthingyApp.views.smsEditor;
var currentSms = smsEditor.getRecord();
// Update the note with the values in the form fields.
smsEditor.updateRecord(currentSms);
var errors = currentSms.validate();
if (!errors.isValid())
{
currentSms.reject();
Ext.Msg.alert('Wait!', errors.getByField('title')[0].message, Ext.emptyFn);
return;
}
var smsList = SmsthingyApp.views.smsList;
var smsStore = smsList.getStore();
if (smsStore.findRecord('id', currentSms.data.id) === null)
{
smsStore.add(currentSms);
}
else
{
currentSms.setDirty();
}
smsStore.sync();
smsStore.sort([{ property: 'date', direction: 'DESC'}]);
smsList.refresh();
SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
}
}
]
});
SmsthingyApp.views.smsEditorBottomToolbar = new Ext.Toolbar({
dock: 'bottom',
items: [
{ xtype: 'spacer' },
{
text: 'Send',
handler: function () {
// TODO: Send current sms.
}
}
]
});
SmsthingyApp.views.smsEditor = new Ext.form.FormPanel({
id: 'smsEditor',
items: [
{
xtype: 'textfield',
name: 'title',
label: 'To',
required: true
},
{
xtype: 'textareafield',
name: 'narrative',
label: 'Message'
}
],
dockedItems:[
SmsthingyApp.views.smsEditorTopToolbar,
SmsthingyApp.views.smsEditorBottomToolbar
]
});
SmsthingyApp.views.smsList = new Ext.List({
id: 'smsList',
store: 'SmsStore',
grouped: true,
emptyText: '<div style="margin: 5px;">No notes cached.</div>',
onItemDisclosure: function (record)
{
var selectedSms = record;
SmsthingyApp.views.smsEditor.load(selectedSms);
SmsthingyApp.views.viewport.setActiveItem('smsEditor', { type: 'slide', direction: 'left' });
},
itemTpl: '<div class="list-item-title">{title}</div>' +'<div class="list-item-narrative">{narrative}</div>',
listeners: {'render': function (thisComponent)
{
thisComponent.getStore().load();
}
}
});
SmsthingyApp.views.smsListToolbar = new Ext.Toolbar({
id: 'smsListToolbar',
title: 'Sent SMS',
layout: 'hbox',
items:[
{xtype:'spacer'},
{
id:'newSmsButton',
text:'New SMS',
ui:'action',
handler:function()
{
var now = new Date();
var smsId = now.getTime();
var sms = Ext.ModelMgr.create({ id: smsId, date: now, title: '', narrative: '' },'Sms');
SmsthingyApp.views.smsEditor.load(sms);
SmsthingyApp.views.viewport.setActiveItem('smsEditor', {type: 'slide', direction: 'left'});
}
}
]
});
SmsthingyApp.views.smsListContainer = new Ext.Panel({
id: 'smsListContainer',
layout: 'fit',
html: 'This is the sms list container',
dockedItems: [SmsthingyApp.views.smsListToolbar],
items: [SmsthingyApp.views.smsList]
});
SmsthingyApp.views.viewport = new Ext.Panel({
fullscreen: true,
layout: 'card',
cardAnimation: 'slide',
items:[
SmsthingyApp.views.contactsListContainer,
SmsthingyApp.views.smsListContainer,
SmsthingyApp.views.smsEditor
]
});
}
})
I'm using eclipse and LogCat tab keeps marking this red
02-08 11:11:58.741: E/Web Console(13886): Uncaught TypeError: Cannot read property 'contacts' of undefined at file:///android_asset/www/app.js:35
I'm guessing this has something to with why I can't see the contacts in the contactsListContainer.
Any help please?
I'm not a Sencha expert but I do know that this line:
var App = new Ext.Application({
will cause problems with PhoneGap as we also declare a variable called App. It would be better to change that line to be something like:
var myApp = new Ext.Application({
to avoid the name conflict.
If that doesn't resolve your problem I suggest you read over my post on searching contacts. I'd make sure I could successfully search for contacts before adding in Sencha.

Categories

Resources