How to create multiple rooted JSON for ExtJS store? - json

I want to create a JSON string on server side with 2 root. I am using ExtJS 3.2. I want to use first root for load data to grid and the second one is to fill a form with different data.
I am creating JSON string on server side like this;
{
metaData: {
"idProperty": "reportID",
"root": "data",
"successProperty": "success"
},
"success": true,
"data": [
{
"ID": 1,
"name": "Jon",
"surname": "Doe"
}]
}
Let's assume second root name is summary and second idProperty is summaryID. How can I implement this and where can I add summary data?
Thx all.

There is no automagic for you are willing to do.i had the same issue on this project and i figured out how to create multiple stores automatically from a JSON response.put the following code before your grids are loaded.in extjs4,i put the following code in app.js so the stores will be created when the app is initialized.The stores will be created automatically,dependent on what the JSON returns:
Ext.Ajax
.request({
url : './account/getadminstores',
callback : function(options, success, response) {
var json = Ext.decode(response.responseText);
var adminStores = new Array();
// setup and intitialize on the fly stores
for ( var key1 in json) {
var storeFields = new Array();
for ( var key2 in json[key1]) {// if
// (i==1){break;}
// console.log(key2);
for ( var key3 in json[key1][key2]) {
storeFields.push(key3);
}
break;
}
;
Ext.define('MA.store.' + key1, {
extend : 'Ext.data.Store',
fields : storeFields,
storeId : key1,
id : 'MA.store.' + key1,
data : json[key1],
proxy: {
type: 'ajax',
url : './account/getadminstores',
reader: {
type: 'json',
root: key1
}
},
autoLoad: true
});
Ext.create('MA.store.' + key1);
}
;
Created stores for your case would be MA.store.root1and MA.store.root2which MA is your apps namespace(and you should change it to whatever your app namespace is).This code is for extjs4 and you might need some modifications to make it work in older versions.Hope it helps.

Related

extjs error on filling store

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

Collection - Model usage for JSON response?

Regarding the pattern Backbone uses for Collections and Models , I am not sure if what I am trying to achieve is possible.
I am wanting the Collection to act as a constructor by making a AJAX POST request to fetch JSON. Using that JSON response it will instantiate multiple models and add them to an array.
Each object has the attributes which will be stored in my model e.g.
define([
'underscore',
'backbone'
], function (_, Backbone)
{
'use strict';
var Employee= Backbone.Model.extend({
defaults: {
name: '',
skill: '',
latitude : 0,
longitude : 0
},
});
return Employee;
});
JSON Response
[
{
"name" : "bob",
"skill" : "project manager",
"latitude" : 12512.25,
"longitude" : 95952.26
},
{
"name" : "sarah",
"skill" : "software dev",
"latitude" : 89432.25,
"longitude" : 1205.26
},
{
"name" : "tom",
"skill" : "evil sys admin",
"latitude" : 1215,
"longitude" : 92325
}
]
Collection
define([
'underscore',
'backbone',
'models/employee'
], function (_, Backbone, Store, Employee) {
'use strict';
var Employees = Backbone.Collection.extend({
// Reference to this collection's model.
model: Employee,
});
return new Employees();
});
Code
emps = new Employees();
emps.url("/testURL"); //
emps.sync();
emps.model[0]; //undefined !!!
So from that I can conclude that the Collection is not smart enough to instantiate an array of Employee models from the JSON response.
How can I do this?
The function you're looking for is fetch. Fetch uses sync to fetch data, and then instantiates models accordingly.
If your API doesn't respond to a GET /someurl then what you need to override is the sync method. Read the source to see how it works.
Also, you're not using url properly. It should be a string, or a function that returns a string.
var employees = new Employees();
employees.url = '/my/testurl';
// note that fetch is async
employees.fetch().done(function () {
console.log(employees.length);
});
Right now your collection constructor code is getting undefined as its input array, and thus remains empty.
You want to pass your collection into your Employees constructor, like
var emps = new Employees(arrayOfEmployees, {model: Employee});
Also, that last part (re-specifying the model) is likely not necessary.

Not able to perform CURD operations properly in my Extjs app using Json-Server

I am using Json-server to test CURD operations in my extjs grid. I have put some dummy data on json-server and I am able to read, delete, update and edit that data.
But When I create data using my extjs app, I am not able to delete or edit that data cause auto generated Id is "nameOfMyModel + autoIncrementNumber".
My Store is:
Ext.define('ThemeApp.store.peopleStore', {
extend: 'Ext.data.Store',
model: 'ThemeApp.model.peopleModel',
storeId: 'peopleStore',
pageSize: 500,
autoLoad: true,
autoSync: true
});
Model is:
Ext.define('ThemeApp.model.peopleModel', {
extend: 'Ext.data.Model',
fields: [ 'id' ,'title','body'],
proxy: {
type: 'rest',
//format: 'json',
limitParam:"",
filterParam: "",
startParam:'',
pageParam:'',
url:'http://localhost:3000/posts',
api: {
read : 'http://localhost:3000/db',
create: 'http://localhost:3000/posts',
update : 'http://localhost:3000/posts' ,
destroy : 'http://localhost:3000/posts'
},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
rootProperty:'posts'
},
writer: {
type: 'json'
}
}
});
And I am Adding user like:
var UserStore = Ext.getStore('peopleStore');
var user = Ext.create('ThemeApp.model.peopleModel',{title: "Test", body: "Testing" });
user.save(); //POST /users
UserStore.load();
And For Deletion:
var grid = button.up('gridpanel');
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (selection) {
UserStore.remove(selection);
UserStore.load();
}
Can anyone tell me why I am not able to delete/update records which I generate via extjs app?
The Id of simple post is like
http://localhost:3000/posts/(number like 1 or 2)
and of app generated record is
http://localhost:3000/posts/ThemeApp.model.peopleModel-1
And I can see app generated record in database.json but browser is saying that this url doesn"t exist.
Kindly point out my mistake
Reason you can't delete them is because they are not created properly. First of all to generate sequential ids use
identifier: 'sequential' in your model, than it will generate numeric id's
You can read it in detail here Model identifier
After doing this generate new objects and see if you can handle them properly.

How to make a store with jsonreader using metadata in Extjs 4?

Is it possible to create a store that will read json, and use fields specified in the metadata in the json as a model?
I want to say something like:
var store = new Ext.data.Store({
autoLoad: {
params: {
metaNeeded: true
}
},
reader: new Ext.data.JsonReader({fields:[]}),
proxy: new Ext.data.HttpProxy({
api: {
url: 'php/chart-data.php'
}
})
});
I've tried a number of combinations however I cannot seem to get it to work.
I currently get the error "Cannot call method 'indexOf' of undefined". I've had others including "object has no read method".
The json I am sending is:
{
metadata:{
root:"rows",
sortInfo:{
field:"date",
direction:"ASC"
},
fields:[ {
name:"date"
}, {
name:"flow"
},{
name:"limit"
}
],
idProperty:"date"
},
success:true,
rows: << snip >>
}
Is it possible to have the store's model configured by the data that it receives, so I could use the same store later with different fields (e.g. date, flow, limit and temperature)?
I have gotten it to work with the following:
var store = new Ext.data.Store({
proxy: {
type: 'ajax',
url: 'php/chart-data2.php',
reader: new Ext.data.JsonReader({
fields:[]
})
}
});
And the php that sends the json:
'{"metaData":{
"root":"rows",
"fields": [
{"name":"date",
"type":"number",
"convert": function(val, rec) {
return val*1000
} },
{"name":"flow"},
{"name":"limit"}
]
},
"totalCount":'.count($chart).',
"success":true,
"rows":' . json_encode($chart) . '
}'
This now allows the server to specify the data (that's getting displayed in a chart), and can add in series dynamically. I don't know if it is good, but it works. I am kind of disappointed in the lack of documentation about this.

loading data from json in sencha

I am creating an application where i have created a list and populated the data in the list using a data store.
data.js
Ext.regModel('Contact', {
fields: ['firstName', 'lastName', 'DOB', 'group']
});
iPolis.ListStore = new Ext.data.Store({
model: 'Contact',
sorters: 'lastName',
getGroupString : function(record) {
return record.get('group');
},
data: [
{ firstName: "Domino", lastName: "Derval" , DOB: "28May2008", group:"Personalize"},
]
});
This part of the code runs fine where i get the data and display it. Now what i require is a connection to the database and retriving the data in the data.js using a json file.
Any suggestions on how thats possible?
iPolis.ListStore = new Ext.data.Store({
model : 'Contact',
proxy : {
type : 'ajax',
url : 'js/person_list.json',
reader : {
type : 'json',
//root : 'results',
// totalCount : 'total'
}
},
autoLoad : true
});
used this for getting the data but it gives me an error sayin XMLHttprequest cannot load data in file.json
Go through the Ext.data.Proxy in Sencha API and also check the examples of store in API docs.
Just replace the url property of reader to the php file.
return proper JSON