Sencha Touch 1.1.1 nested JSON Store load - json

Hi guys I hope someone can help me with this I´m really stuck although it´s some damned beginner question that has already been answered and I assure you I read all of the answer Posts but still can´t get it to work.
I´m using Sencha Touch 1.1.1 and try to get this Store loaded with nested JSON data. Here´s the code:
Ext.regModel("UserData", {
hasMany : [{
name : "id",
type : "integer",
},{
name : "username",
type : "string",
},{
name : "password",
type : "string",
}]
});
var userdata =
{"users": [
{
"id": 16,
"username": "bla#bla.com",
"password": "bla",
}, {
"id": 17,
"username": "bla#bla.com",
"password": "bla",
}
]
};
var myStore = new Ext.data.Store({
model : 'UserData',
data : userdata,
proxy : {
type : 'ajax',
reader : {
type : 'json',
root : 'users' // not working
}
}
});
var myList = new Ext.List ({
fullscreen : true,
store : myStore,
grouped : false,
itemTpl : '<div>{username}</div>'
});
Returns Uncaught Type Error: Arguments list has wrong type. When I rewrite the JSON with an outer Array wrapper, it works, but with wrong root (not users) I definitly saw examples where this worked with the root:'' value.
var userdata =
[ {"users": [
{
"id": 16,
"username": "bla#bla.com",
"password": "bla",
}, {
"id": 17,
"username": "bla#bla.com",
"password": "bla",
}
]
} ];
What am I missing?

If I am not mistaken, in your "UserData" model, it should be fields instead of hasMany.
And try putting your json data in a separate json file and locate the path in your store's proxy.
var myStore = new Ext.data.Store({
model: 'UserData',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'test.json',
reader: {
type: 'json',
root: 'users'
}
}
});
I tested it and it's working fine here. Here is my full code.
Ext.regModel("UserData", {
fields: [
{name: 'id', type:'int'},
{name: 'username', type:'string'},
{name: 'password', type:'string'}
]
});
var myStore = new Ext.data.Store({
model: 'UserData',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'test.json',
reader: {
type: 'json',
root: 'users'
}
}
});
var app = new Ext.Application({
name: 'TestApp',
useLoadMask: true,
launch: function() {
TestApp.views.listToolbar = new Ext.Toolbar({
title: 'Foo Bar',
layout: 'hbox'
});
TestApp.views.list = new Ext.List({
id: 'list',
store: myStore,
emptyText: 'Nothing',
itemTpl: '<div class="username">{username}</div>',
});
TestApp.views.container = new Ext.Panel({
layout: 'fit',
html: 'this is the container',
dockedItems: [TestApp.views.listToolbar],
items: [TestApp.views.list]
});
TestApp.views.viewport = new Ext.Panel({
fullscreen: true,
layout: 'card',
cardAnimation: 'slide',
items: [
TestApp.views.container
]
});
}
});

Related

Parse nested json with a proxy in a Sencha Touch 2 store using rootProperty

I have a JSON response that is nested like the following (simplified, but same format):
{
"response":{
"v":"1.0",
"users":[
{
"firstName":"Nicole",
"LastName":"A",
},
{
"firstName":"John",
"LastName":"B",
},
{
"firstName":"Bob",
"LastName":"C",
}
],
}
}
Here is the model:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
name: 'firstName'
},
{
name: 'lastName'
}
]
}
});
I am starting from the sencha architect tutorial for CityBars, so most of the code should be quite basic, and I am just trying to get the users from the json response loaded. Here is the controller:
Ext.define('MyApp.controller.User', {
extend: 'Ext.app.Controller',
launch: function() {
var me = this;
Ext.Viewport.setMasked({ message: 'Loading Attendees...' });
me.getUsers(function (store) {
me.getDataList().setStore(store);
});
},
getUsers: function(callback) {
var store = Ext.data.StoreManager.lookup('UserStore'),
url = 'http://urltogetjsonresponse'
store.getProxy().setUrl(url);
store.load(function() {
callback(store);
});
},
});
Here is the store:
Ext.define('MyApp.store.UserStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.User',
'Ext.data.proxy.JsonP',
'Ext.data.reader.Json'
],
config: {
model: 'MyApp.model.User',
storeId: 'UserStore',
proxy: {
type: 'jsonp',
reader: {
type: 'json',
rootProperty: 'response.user'
}
}
}
});
I tried 'response.user' but it did not work for me. I have already looked all over and know that using rootProperty: 'user' would work, if the users attribute were at the same level as "response" instead of nested under it. I have also tried adding record: 'users' but that did not seem to work either.
If anybody knows if this is doable and has an easy solution to this, that would be great. I don't actually understand how the proxy works, so if anybody can explain a bit about that, it would be helpful too. Thanks.
Taken from Sencha's documentation about the JSON reader :
{
"count": 1,
"ok": true,
"msg": "Users found",
"users": [{
"userId": 123,
"name": "Ed Spencer",
"email": "ed#sencha.com"
}],
"metaData": {
"idProperty": 'userId',
"rootProperty": "users",
"totalProperty": 'count',
"successProperty": 'ok',
"messageProperty": 'msg'
}
}
The rootProperty here is 'users', so you'll need to specify users (which is the name of the array containing your instances of model) and not user .

Trouble loading JSON data into a ExtJS datastore

I've tried every combination I can think of in terms of how to configure my ExtJS datastore to read my incoming JSON data. I'm getting this JSON data in:
[{ "data_type": {"attribute1" : "value1",
"attribute2" : "value2",
"attribute3" : "value3"
}
},
{ "data_type": {"attribute1": "value4",
"attribute2" : "value5",
"attribute3" : "value6"
}
}
]
I don't want to parse the JSON and reformat it in order to make ExtJS happy because it seems redundant. What I want to end up with is a datastore which would allow me to do:
Ext.create('Ext.container.Container',
{
id: 'junk',
renderTo: 'slider',
width: 960,
height:600,
layout: 'vbox',
items: [
{
xtype: 'grid',
title: 'foobar',
height: 400,
width: 700,
store: my_store,
viewConfig: { emptyText: 'No data' },
columns: [
{
text: 'column1',
dataIndex: 'attribute1'
},{
text: 'column2',
dataIndex: 'attribute2'
},{
text: 'column3',
dataIndex: 'attribute3'
}
]
}
]
}
I know ExtJS knows how to parse this JSON, because I can do:
var foo = Ext.decode(data);
var good_data = foo[0].data_type.attribute1
And that returns 'value1' as I would expect. Can anyone help me understand the magical incantation to get a datamodel and store to do that?
Thanks!
First of all you should create model:
Ext.define('SomeModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'attribute1'},
{name: 'attribute2'},
{name: 'attribute3'}
]
});
Then you can configure store to support your data format by setting record property to data_type:
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
data : data,
model: 'SomeModel',
proxy: {
type: 'memory',
reader: {
type: 'json',
record: 'data_type'
}
}
});
Working sample: http://jsfiddle.net/lolo/WfXK6/1/

Sencha Touch: How to get data from complex JSON objects

I am not able retrieve records from complex json objects but i am able to get the data when using an TPL.
Please see the below example codes:
JSON:
{
"lists": [
{
"title": "Groceries",
"id": "1",
"items": [
{
"text": "contact solution - COUPON",
"listId": "1",
"id": "4",
"leaf": "true"
},
{
"text": "Falafel (bulk)",
"listId": "1",
"id": "161",
"leaf": "true"
},
{
"text": "brita filters",
"listId": "1",
"id": "166",
"leaf": "false"
}
]
}
]
Model:
Ext.regModel("TopModel",
{
fields: [
{ name: 'title', type: 'string' },
{ name: 'id', type: 'string' },
],
hasMany: [
{ model: 'SubModel', name: 'items' }
],
proxy: {
type: 'ajax',
url : 'test/lists.json',
actionMethods: {
create: 'POST',
destroy: 'POST',
read: 'POST',
update: 'POST'
},
reader: {
type: 'json',
root: function(data) {
return data.lists || [];
}
}
}
});
Ext.regModel("SubModel",
{
fields: [
{ name: 'text', type: 'string'},
{ name: 'listId', type: 'string'},
{ name: 'id', type: 'string'},
{ name: 'leaf', type: 'string'}
]
});
In my View file, i have defined the store as below.
this.stores = new Ext.data.Store({
clearOnPageLoad: false,
autoLoad:true,
model:'TopModel',
getGroupString: function(record) {
return record.get('leaf');
}
});
});
I am not able to retrieve the values for record.get('leaf') as this refers to the child model items. When I tried to print it, it prints as undefined.
How to access the child attributes? Here 'items' is listed as an array.
I tried to display the data using list as below. All the records are displayed but the problem is that it is picked as one whole item instead of separate list for each item.
var list = new Ext.List({
cls: 'big-list',
grouped : true,
emptyText: '<div>No data found</div>',
itemTpl: ['<div><tpl for="items">',
'<div>',
'{id} {text}',
'</div>',
'</tpl></div>',
],
store: this.stores,
listeners: {
itemtap: this.onListItemTap,
scope: this
}
});
Kindly help me on how to get the list items to be displayed as individual records.
you can use online json parser(http://json.parser.online.fr/) to parse json xml from parser data you easily seprate objects and arrays and you get all data which are require for you..i hope this help you

Dojo grid nested json

I'd like to have a dojo grid which connects to a server url which outputs the following json :
{identifier : "id"
items : [ { id: "1", name: "John", university : { name: "XXX", address: "YYY" } }].
Basically I have a nested json. I would like to represent the university name and University address as separate columns in the grid.
I tried using the dojox.grid.DataGrid object and creating a gird layout, but do not know how to refer to the nested elments and university.name and university.address don't seem to work.
I am using dojo 1.6.1.
Does anybody have any pointers?
This is the js code I use :
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.addOnLoad(function(){
// our test data store for this example:
var jsonStore = new dojo.data.ItemFileReadStore({
url: '/MainDeployer/ajax/users/get.json'
});
var layoutUsers = [
[{
field: "name",
name: "Name",
width: 10
},
{
field: "university.name",
name: "University Name",
width: 10
},
{
field: "university.address",
name: "University Address",
width: 'auto'
}]];
// create a new grid:
var grid = new dojox.grid.DataGrid({
query: {},
store: jsonStore,
clientSort: true,
rowSelector: '20px',
structure: layoutUsers
},
document.createElement('div'));
dojo.byId("usersTable").appendChild(grid.domNode);
grid.startup();
});
Thanks,
Cristian
What kind of store are you using? Have a look at the dojo.data.ItemFileReadStore documentation, there is an example with a situation like yours:
http://dojotoolkit.org/reference-guide/dojo/data/ItemFileReadStore.html#item-structure
This would help you fetching all the items with a single call to the method "fetch". If for some reasons it doesn't work due to the different json structure, you can continue using ItemFileReadStore , and create a function that loops over all the objects in your json and uses the loadItem method for adding items one by one in this way (it's not beautiful but it works):
var myData = {"items" : []};
var myStore = new dojo.data.ItemFileWriteStore({data: myData});
var myLayout = [{
field: 'name',
name: 'Name',
width: '200px'
},
{
field: 'universityName',
name: 'University Name',
width: '100px'
},
{
field: 'universityAddress',
name: 'University Address',
width: '60px'
}];
var myGrid;
dojo.addOnLoad(function(){
myGrid = new dojox.grid.DataGrid({
store: myStore,
structure: myLayout
}, document.createElement('div'));
dojo.byId("myGridContainer").appendChild(myGrid.domNode);
myGrid.startup();
dojo.xhrGet({
url: myURL,
handleAs: "json",
headers: {
"Content-Type": "application/json; charset=uft-8",
"Accept" : "application/json"
},
load: function(responseObject, ioArgs) {
myList = responseObject;
dojo.forEach(myList.items, function(element) {
myStore.newItem({"name": element.name,
"universityName": element.university.name,
"universityAddress": element.university.address});
});
})
});
}
se a formatter:
var nameFormatter = function(value, rowIdx){
return value.name;
};
var addressFormatter = function(value, rowIdx){
return value.address;
};
var layoutUsers = [
[{
field: "name",
name: "Name",
width: 10
},
{
field: "university",
name: "University Name",
width: 10,
formatter: nameFormatter
},
{
field: "university",
name: "University Address",
width: 'auto',
formatter: addressFormatter
}]];

Store's metadata won't load

I try to load fields config to json store via metadata. The json is:
{
"rows":[
{
"datev":"02.01.2011",
"w1":"100",
"w2":"200"
},
{
"datev":"02.01.2011",
"w1":"300",
"w2":"50"
},
{
"datev":"03.01.2011",
"w1":"10",
"w2":"450"
}
],
"metaData":{
"fields":[
{
"name":"datev"
}
],
"root":"rows"
}
}
and my store is:
var test = new Ext.data.JsonStore({
url: 'test.php'
});
test.load();
The metadata doesn't load. What is wrong with the code?
I think you need to add a JSON reader
var reader = new Ext.data.JsonReader({
fields: []
});
var store = new Ext.data.Store({
nocache : true,
reader : reader,
autoLoad : true,
remoteSort : true,
proxy : new Ext.data.HttpProxy({
url : '/getjson?queryable=featureType&featureType=Electronic%20Device',
method : 'GET'
})
or maybe
var store = new Ext.data.JsonStore({
url: 'somewhere',
fields: []
});
You are not specifying the Id Property, and neither the Root property. this is my code i hope this help
var EStore = new Ext.data.JsonStore
({
api: { read: 'getAssignedJobs',
create: 'createAssignedJobs',
update: 'updateAssignedJobs'
},
root: 'jobData',
idProperty: 'Id',
autoSave: true,
batch: false,
successProperty: 'success',
writer: new Ext.data.JsonWriter({ encode: true, writeAllFields: true }),
fields: [
{ name: 'Id', type: 'int' },
{ name: 'ResourceId', mapping: 'fitter_id', type: 'int' },
{ name: 'StartDate', type: 'date', format: 'd/m/Y G:i' },
{ name: 'EndDate', type: 'date', format: 'd/m/Y G:i' },
{ name: 'status', type: 'int' },
{ name: 'job_id', type: 'int' }
]
});