Parsing json using model - Sencha - json

I am trying to parse a json but i having problem to create model so how can i create effiecient model for json below so i can access def-id just by doing record.get('def_id'):
I am creating my model as:
Ext.define('MyApp.model.TodaysWord', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.TodaysWordMenu'],
config: {
fields: [
{name: 'status', mapping: 'status'},
{name: 'message', mapping: 'message'},
{name:'data', mapping: 'data'},
{name: 'definitions', mapping: 'definitions.defintion'},
{name: 'ratings', mapping: 'definitions.rating'},
],
}
});
Ext.define('MyApp.model.TodaysWordMenu', {
extend: 'Ext.data.Model',
config: {
fields: [
'name',
'author',
'word_id',
'category',
'definitions',
'rating',
'def_id',
'example',
'author',
'is_favourite'
],
belongsTo: "MyApp.model.TodaysWord"
}
});
I am getting response my above model are incorrect and i am having hard time to solve it.
My json:
({
"accountInfo":{
"expire_date":"2014-07-24 22:44:14",
"subscribe_date":"2013-07-24 22:44:14",
"time_remain":" 323 Days 22 Hours 2 Minutes",
"status":"not expired"
},
"status":"TRUE",
"message":"Todays Word",
"data":[
{
"name":"paint",
"author":"admin",
"word_id":"1",
"category":"Business",
"definitions":[
{
"rating":"Green",
"defintion":"to put color to in something",
"def_id":"1",
"example":null,
"author":"admin",
"is_favourite":"yesStar"
},
{
"rating":"Red",
"defintion":"this is a new definition of word paint.",
"def_id":"42",
"example":null,
"author":"admin",
"is_favourite":"noStar"
}
]
}
]
})
Any help would be appreciated.

You could use Ext.JSON.decode() and pass to it function your responseText. It would create you your needed object.

Related

Extjs simple model and store

I have a simple model, let's say:
Ext.define('UserModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'firstname', type: 'string'},
{name: 'lastname', type: 'string'}
]
});
And a json file that looks like this:
{
"DatabaseInJSON": {
"Users": [
{
"KeyFirstName": "John",
"KeyLastName": "Doe"
},{
"KeyFirstName": "James",
"KeyLastName": "Howlett"
}
],
"OtherStuffWeDontCareAbout": [
...
]
}
}
My question is:
If I create a store like this, how can i map the attribute "firstname" from my model to "KeyFirstName" from my json ?
Ext.define('my.custom.Store', {
extend: 'Ext.data.Store',
model: 'UserModel',
proxy: {
type: 'ajax',
url: 'path/to/my/file.json',
reader: {
type: 'json',
rootProperty: 'DatabaseInJSON'
}
}
});
You need to either employ mapping or a convert function
Have a look at the demo here which demonstrates both in action.
For the sake of the demo I turned your store into a memory proxy store and you are I presume also accessing your rootProperty wrong as it should be rootProperty: 'DatabaseInJSON.Users'
Code:
Ext.application({
name: 'Fiddle',
launch: function() {
myData = {
"DatabaseInJSON": {
"Users": [{
"KeyFirstName": "John",
"KeyLastName": "Doe"
}, {
"KeyFirstName": "James",
"KeyLastName": "Howlett"
}],
"OtherStuffWeDontCareAbout": {}
}
};
Ext.define('UserModel', {
extend: 'Ext.data.Model',
fields: [{
name: 'firstname',
mapping: 'KeyFirstName',
type: 'string'
}, {
name: 'lastname',
convert: function(v, record) {
return record.data.KeyLastName;
},
type: 'string'
}]
});
Ext.define('my.custom.Store', {
extend: 'Ext.data.Store',
model: 'UserModel',
proxy: {
type: 'memory',
reader: {
type: 'json',
rootProperty: 'DatabaseInJSON.Users'
}
}
});
myStore = Ext.create('my.custom.Store', {
data: myData
});
console.log(myStore.getRange());
}
});
Generally your Json properties should match the same names of your fields so that the reader can read them properly, to map 'KeyFirstName' to 'firstname' I think your best option would be to create a mapping in the field definition on the model.
This would apply this globally for all requests and I believe it would reverse the mapping when it come to saving the data.
To use the mapping in your case, you would need something like:
Ext.define('UserModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'firstname', type: 'string', mapping: function(data) { return data.KeyFirstName; } },
{name: 'lastname', type: 'string', mapping: function(data) { return data.KeyLastName; } }
]
});
Other than changing the format of the JSON data, the only other way I can think of would be to override the read or getResponseData method of the JsonReader

Extjs 4 - create new empty Record from Store without Model

I have tried to create a new empty record without creating a model.
Accidentally I tried to run this:
new new storeComp.model()
and it actually works!
anyone know any solution for this or an answer to how is it working ?
Thanks!
Shalev
Stores that are not configured with a model will create an anonymous one implicitly. This is explained in the docs for the implicitModel private property (the store needs to know that because if it uses an implicit model, it must destroy it when it is itself destroyed).
In the end that means that you can safely expect any store to be backed with a model.
I faced the same problem for an associative store. For that i have used below JSON format to load project store. So automatically empty record is created in associative (project-resources) Store.
Store:
Ext.define('App.store.Projects', {
extend : 'Ext.data.Store',
model : 'App.model.Project'
});
Models:
Ext.define("App.model.Project", {
extend: 'Ext.data.Model',
idProperty : 'id',
uses : ['App.model.ProjectResource'],
fields: [
{ type: 'auto', name: 'id'},
{ type: 'number', name: 'customerid'},
{ type: 'string', name: 'projectcode'}
],
associations: [
{type: 'hasMany', model: 'App.model.ProjectResource', name: 'Resources', storeConfig: { remoteFilter: true }}
]
});
Ext.define("App.model.ProjectResource", {
extend: 'Ext.data.Model',
idProperty : 'id',
fields: [
{ type: 'number', name: 'id'},
{ type: 'string', name: 'name'},
{ type: 'number', name: 'projectid'},
{ type: 'auto', name: 'resourceid'}
],
associations : [
{type : 'belongsTo', model: 'App.model.Project'}
]
});
JSON Format:
[
{
"id": "105",
"customerid": "105",
"projectcode": "ALN01",
"Resources": {}
}
]
Loading store with empty object (like "Resources": {}) will create empty model.

How to display associated json data in grid in extjs4?

I am working in extjs4 mvc where I am getting stuck at a point. Actually I want to display associated json data in grid in extjs4. I tried and searched a lot but not yet get problem solved.
Here is my some code
my view file:
Ext.define('AM.view.user.List' ,{
extend: 'Ext.grid.Panel',
alias : 'widget.userlist',
title : 'All Users',
store: 'Users',
columns: [
{header: 'Name', dataIndex: 'name', flex: 1},
{header: 'Email', dataIndex: 'email', flex: 1},
{header:'title',dataIndex:'title',flex:1} //I tried
]
});
Controller file:
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['Users'],
models: ['User','Book'],
views: ['user.Edit', 'user.List'],
refs: [{
ref: 'usersPanel',
selector: 'panel'
}],
init: function() {
this.control({
'viewport > userlist dataview': {
itemdblclick: this.editUser
},
'useredit button[action=save]': {
click: this.updateUser
}
});
}
});
User model file:
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ['id', 'name', 'email'],
hasMany: {
model: 'AM.model.Book',
//model: 'Book',
foreignKey: 'userId',
name: 'books'
},
proxy: {
type: 'ajax',
api: {
read: 'data/users.json',
update: 'data/updateUsers.json'
},
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});
User store file :--
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true
});
Book model file:
Ext.define('AM.model.Book',{
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'title', type: 'string'}, //,mapping:'record[0].title' not working
{name: 'userId', type: 'int'}
]
});
json file:
{
"success": "true",
"users": [
{
"id": "1",
"name": "shilpa",
"email": "shilpa#sencha.com",
"books": [
{
"id": "10",
"title": "c++",
"userId": "1"
}
]
}
]
}
here is the screenshot:
please give me some suggestion to display associated data in grid.
You can access all the books in the column renderer and construct the string you need. It would be something like this:
{
text: 'Books',
renderer: function (val, meta, record) {
var books = '';
record.books().each(function(bookRecord, index, count) {
books = books + bookRecord.get('title') + ',';
});
return books;
}
}
http://jsfiddle.net/alexrom7/YQXC8/1/

Sencha store and model set up for use with Json

I've got a Json file......
[
{
"Title":"Package1",
"id":"1",
"POI":[
{
"Title":"POI1",
"LayerID":"1",
},
{
"Title":"POI2",
"LayerID":"1",
}
},
{
"Title":"Package2",
"id":"2",
"POI":[
{
"Title":"POI3",
"LayerID":"2",
},
{
"Title":"POI4",
"LayerID":"2",
}
}
]
populating a store.....
Ext.define('Murmuration.store.MyPackages', {
extend: 'Ext.data.Store',
xtype: 'myPackages',
config: {
model: 'Murmuration.model.PackagesModel',
proxy: {
type: 'ajax',
url : 'data/store.json',
reader: {
type: 'json'
}
},
autoLoad: true
}
});
with a model......
Ext.define('Murmuration.model.PackagesModel', {
extend: 'Ext.data.Model',
xtype: 'packagesModel',
config: {
fields: [
{name: 'Title', type: 'string'},
{name: 'id', type: 'int'}
]
}
});
for said list......
Ext.define('Murmuration.view.homeList', {
extend: 'Ext.List',
xtype: 'homeList',
fulscreen: true,
config: {
title:'Murmuration',
itemTpl: '<div>{Title}</div>',
store:'MyPackages',
fulscreen: true,
}
});
The list Items are successfully being populated with 'Package1' and 'Package2'. But for the life of me I can't successfully change the code to populate the list with the POI titles for the fist package........'POI1' and 'POI2'. How would I go about successfully implementing the following? Any help would be greatly appreciated.
The json you've given is nested so things little different here. First thing is, you need to specify a rootProperty in your reader. So you define a root element in your json and that element will be set to rootProperty.
Next part is, you have POI as array of objects. So you'd need a separate model for POI.
Model for POI can be defined -
Ext.define('Murmuration.model.POIModel',{
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'Title', type: 'string'},
{name: 'LayerID', type: 'int'}
],
belongsTo:'Murmuration.model.PackagesModel'
}
});
After a close look, you'll notice there's one extra config belongsTo. This represents many to one association with your PackageModel since there are many POI in each package.
After doing this, you'd need to change you PackageModel also to -
Ext.define('Murmuration.model.PackagesModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'Title', type: 'string'},
{name: 'id', type: 'int'}
]
},
hasMany:{
associationKey:'POI',
model:'Murmuration.model.POIModel',
name:'POI'
}
});
here, hasMany represents that this model is having multiple model instances of POI model. associationKey is the key POI from you json and model gives the model instance of POI model.
After doing that you'd need to change your reader in store to -
Ext.define('Murmuration.store.MyPackages', {
extend: 'Ext.data.Store',
config: {
model: 'Murmuration.model.PackagesModel',
proxy: {
type: 'ajax',
url : 'data/store.json',
reader: {
type: 'json',
rootProperty:'items'
}
},
autoLoad: true
}
});
rootProperty should be set to root of you json. I assumed it could be items here.
Finally in you view you can have template set up like this -
itemTpl: new Ext.XTemplate(['<div>Package Title => {Title}'+
'<tpl for="POI"><h6>POI title => {Title}</h6><h6>POI layer => {LayerID}</h6></tpl></div>'
]),
2 things I found in your code are not correct though -
Store and Model can not have a xtype.
All the config options should be inside config:{} only.

How to Display Nested Json data in EXTJS 4 Grids?

I am working on ExtJS 4.0 and I want to display nested JSON data in a grid. For this I use the example given in Ext.data.reader.Reader docs, "Loading Nested Data". It is good and simple but now I want to display this data in a grid. How do I set dataIndex?
This is my sample model and store:
Ext.define("data", {
extend: 'Ext.data.Model',
fields: ['year', 'state'],
hasMany: {
model: 'record',
name: 'record'
},
proxy: {
type: 'rest',
url: 'Column.json.php',
reader: {
type: 'json',
root: 'data'
}
}
});
Ext.define("record", {
extend: 'Ext.data.Model',
fields: ['id', 'autorization', 'expendture'],
belongsTo: 'User'
});
var store1 = new Ext.data.Store({
model: "data"
});
And my JSON:
{
"data": [{
"year": "2010",
"state": "MP",
"record": [{
"id": "auth",
"autorization": "9.201"
}, {
"id": "exp",
"expendture": "1.250"
}]
}]
}
I want to read autorization and expendture with id
You have to do it at the Model/Record level using the mapping confg in fields, so you'd do something like this:
Ext.define("record", {
extend: 'Ext.data.Model',
fields: [
'id',
{name: 'autorization', mapping: 'record[0].autorization'},
{name: 'expendture', mapping: 'record[1].expendture'}
],
belongsTo: 'User'
});
It's good to note that it is probably quicker to ask questions over on the Sencha Forums.
I want to point out that Store.loadData does not respect the field mapping
The issue is that the Sencha team changed loadData's behavior, AND it's not something that's documented in a way that is clear. So if you are using it, add the following to your code base (above your app code, but below ext-all.js):
Ext.override(Ext.data.Store, {
loadDataViaReader : function(data, append) {
var me = this,
result = me.proxy.reader.read(data),
records = result.records;
me.loadRecords(records, { addRecords: append });
me.fireEvent('load', me, result.records, true);
}
});
then use:
mystore.loadDataViaReader(data)