EXTJS 5: Load child Nodes from the server on expand(TreePanel, load on demand) - extjs5

I have a tree, which only loads 3 level at a time.
So when a user click on expand on a node, extjs will call a service and populate with the leaf nodes of that node. How can I acchieve this? For now, i'm only able to load all of the nodes at once, which is a huge performance hit if there is lot of nodes.
Model:
Ext.define("TreePanelResult", {
extend: 'Ext.data.TreeModel',
fields: [
{ name: "orgId", type: "int"},
{ name: "orgName", type: "string"},
{ name: "OrgShortName", type : "string"},
{ name: "iconCls", type: "string"},
{ name: "leaf", type: "bool" }
],
idProperty:'orgId'
});
ViewModel:
Ext.define('SampleViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.sampleTreeModel',
stores: {
treeStore: {
type: 'tree',
model:TreePanelResult,
root: {
text: 'Org',
id:'src',
expanded: true,
orgId: -1
},
paramNode:'orgId',
proxy: {
type: 'ajax',
url: 'services/admin/getHirerachy',
reader : {
type : 'json',
rootProperty : 'systemChildNodes'
}
},
listeners: {
beforeload: function(store, operation, eOpts) {
operation.params.node = operation.node.get("orgId");
store.getProxy().setExtraParams("orgId", operation.node.get("orgId"));
}
}
}
}
});
JSON Stucture:
{
"status": true,
children:null,
"systemChildNodes": [
{
"orgId": "234334",
"orgParentId": "0",
"OrgShortName": "csdsdsd",
"iconCls": "",
"leaf": false,
"systemChildNodes": [
{
"orgId": "2345446",
"orgParentId": "234334",
"OrgShortName": "sdewew",
"iconCls": "",
"leaf": false,
"systemChildNodes": []
}
{
"orgId": "2345446",
"orgParentId": "234334",
"OrgShortName": "sdewew",
"iconCls": "",
"leaf": false,
"systemChildNodes": []
}
]
}]
}
Any suggestions would be appreciated.
Thanks in Advance,
Sankar.

Related

ExtJS model associations with jsonapi specification

We are creating a new version our API (v2) adopting the JSON:API specification (https://jsonapi.org/). I'm not being able to port the ExtJS model associations (belongs_to) to the new pattern.
The ExtJS documentation only shows how to use a nested relation in the same root node (https://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.association.Association).
v1 data (sample):
{
"data": [
{
"id": 1,
"description": "Software Development",
"area_id": 1,
"area": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
},
],
"meta": {
"success": true,
"count": 1
}
}
v2 data (sample):
{
"data": [
{
"id": "1",
"type": "maint_service_nature",
"attributes": {
"id": 1,
"description": "Software Development",
"area_id": 1
},
"relationships": {
"area": {
"data": {
"id": "1",
"type": "area"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "area",
"attributes": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
}
],
"meta": {
"success": true,
"count": 1
}
}
My model:
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [
{ desc: "Id", name: 'id', type: 'int', useNull: true },
{ desc: "Area", name: 'area_id', type: 'int', useNull: true },
{ desc: "Description", name: 'description', type: 'string', useNull: true, tableIdentification: true }
],
associations: [
{
type: 'belongsTo',
model: 'Suite.model.Area',
foreignKey: 'area_id',
associationKey: 'area',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea',
reader: {
type: 'json',
root: false
}
}
],
proxy: {
type: 'rest',
url: App.getConf('restBaseUrlV2') + '/maint_service_natures',
reader: {
type: 'json',
root: 'data',
record: 'attributes',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors'
}
}
});
Any ideias on how to setup the association to work with the v2 data?
I'm honestly taking a stab at this one... I haven't used Ext JS 4 in years, and I wouldn't structure my JSON like JSON:API does, but I think the only way you can accomplish this is by rolling your own reader class. Given that you have generic properties for your data structure, this reader should work for all scenarios... although, I'm not too familiar with JSON:API, so I could be totally wrong. Either way, this is what I've come up with.
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myReader',
root: 'data',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors',
/**
* #override
*/
extractData: function (root) {
var me = this,
ModelClass = me.model,
length = root.length,
records = new Array(length),
dataConverter,
convertedValues, node, record, i;
for (i = 0; i < length; i++) {
node = root[i];
var attrs = node.attributes;
if (node.isModel) {
// If we're given a model instance in the data, just push it on
// without doing any conversion
records[i] = node;
} else {
// Create a record with an empty data object.
// Populate that data object by extracting and converting field values from raw data.
// Must pass the ID to use because we pass no data for the constructor to pluck an ID from
records[i] = record = new ModelClass(undefined, me.getId(attrs), attrs, convertedValues = {});
// If the server did not include an id in the response data, the Model constructor will mark the record as phantom.
// We need to set phantom to false here because records created from a server response using a reader by definition are not phantom records.
record.phantom = false;
// Use generated function to extract all fields at once
me.convertRecordData(convertedValues, attrs, record, me.applyDefaults);
if (me.implicitIncludes && record.associations.length) {
me.readAssociated(record, node);
}
}
}
return records;
}
});
Ext.define('Suite.model.Area', {
extend: 'Ext.data.Model',
fields: [{
name: 'type',
type: 'string'
}]
});
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [{
desc: "Id",
name: 'id',
type: 'int',
useNull: true
}, {
desc: "Area",
name: 'area_id',
type: 'int',
useNull: true
}, {
desc: "Description",
name: 'description',
type: 'string',
useNull: true,
tableIdentification: true
}],
associations: [{
type: 'belongsTo',
model: 'Suite.model.Area',
associatedName: 'Area',
foreignKey: 'area_id',
associationKey: 'relationships.area.data',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea'
}],
proxy: {
type: 'rest',
url: 'data1.json',
reader: {
type: 'myReader'
}
}
});
Suite.model.MaintServiceNature.load(null, {
callback: function (record) {
console.log(record.getData(true));
}
});
}
});

Extjs, can't read a simple json inside a treepanel

I am in trouble trying to load a very simple json where nodes are nested inside "data" as showed below. I expect to get two nodes with text AAA and BBB, but I only get a tree with a couple of empty nodes with infinite children (each children with a single sub children).
test_lrymgr.json
{
"data": [
{
"text": ".",
"children": [
{
"nodename": "AAA",
"isvisible": true,
"expanded": false
},
{
"nodename": "BBB",
"isvisible": true,
"expanded": false
}
]
}
],
"metadata": { "success":true, "msg":"", "totalCount":1, "totalPages":1, "prevLink":"", "nextLink":""}
}
test_lrymgr.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="ext/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css" />
<script type="text/javascript" src="ext/ext-all-debug.js"></script>
</head>
<body>
<script type="text/javascript">
Ext.onReady(function () {
try {
//define model
Ext.define('MyDataModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'nodename', mapping: 'nodename' },
{ name: 'isvisible', mapping: 'isvisible' }
],
});
//define store
Ext.define('MyStore', {
extend: 'Ext.data.TreeStore',
storeId: 'idStoreLryManager',
model: 'MyDataModel',
proxy: {
type: 'ajax',
url: 'test_lrymgr.json',
reader: {
type: 'json',
root: 'data',
metaProperty: 'metadata',
totalProperty: 'metadata.totalCount',
successProperty: 'metadata.success',
messageProperty: 'metadata.msg'
},
}
});
//define tree panel
Ext.define('MyTreePanel', {
extend: 'Ext.tree.Panel',
alias: 'widget.myTreePanel',
store: 'MyStore',
rootVisible: false,
columns: [
{
xtype: 'treecolumn',
dataIndex: 'nodename',
sortable: false,
flex: 2,
header: ''
},
{
xtype: 'checkcolumn',
dataIndex: 'isvisible',
sortable: false,
width: 55,
header: 'Visible'
}
]
});
//create tree view
var storeInstance = Ext.create('MyStore');
Ext.createWidget('window', {
title: 'test',
layout: 'fit',
autoShow: true,
height: 360,
width: 200,
items: {
xtype: 'myTreePanel',
store: storeInstance,
border: false
}
});
//load
storeInstance.load({
scope: storeInstance,
callback: function (records, operation, success) {
try {
}
catch (ex) {
Ext.Msg.alert("", "callback error: " + ex);
}
}
});
}
catch (ex)
{
Ext.Msg.alert("", ex)
}
});
</script>
</body>
</html>
Any idea about what's wrong?...
Your json over here is wrong.Root mentioned in the store is "data".So
your json should be something like this:
{
"data": [{
"nodename": "child1",
"data": [{
"nodename": "subChild1",
"expanded": false,
"leaf": true
}, {
"nodename": "subChild2",
"expanded": false,
"leaf": true
}]
}],
"metadata": {
"success": true,
"msg": "",
"totalCount": 1,
"totalPages": 1,
"prevLink": "",
"nextLink": ""
}
}
For the tree to read nested data, the Ext.data.reader.Reader must be configured with a root property, so the reader can find nested data for each node (if a root is not specified, it will default to 'children'). This will tell the tree to look for any nested tree nodes by the same keyword, i.e., 'children'. If a root is specified in the config make sure that any nested nodes with children have the same name. Note that setting defaultRootProperty accomplishes the same thing.
You can see the simples possible tree configuration here: http://extjs.eu/ext-examples/#tree-simplest

Sencha Touch 2.2 load store from JSON, data goes to raw column

I'm trying to load a store from JSON received from webservices. But all the data from the JSON goes under the 'raw' column of the items in the store...
I can't figure out why, my code seems correct.
Any help is welcome.
My Model :
Ext.define('App.model.Node', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'version', type: 'int' },
{ name: 'user_id', type: 'int' },
{ name: 'tstamp', type: 'date' },
{ name: 'changeset_id', type: 'int' },
{ name: 'tags', type: 'string' },
{ name: 'geom', type: 'string'}
],
idProperty: 'id'
}
});
My Store :
Ext.define('App.store.NodeStore', {
extend: 'Ext.data.Store',
xtype: 'nodestore',
requires: [
'Ext.data.proxy.Rest'
],
config: {
model: 'App.model.Node',
storeId: 'nodeStore',
autoLoad: true,
proxy: {
type:'rest',
url:'http://localhost/server/nodes',
reader: {
type:'json',
rootProperty: 'nodes'
},
noCache: false,
limitParam: false,
headers: {
'Accept' : 'application/json'
}
}
}
});
My JSON :
{
"nodes": [
{
"id": "454467",
"version": 6,
"user_id": 52015,
"tstamp": "2008-12-27 21:38:45",
"changeset_id": "634766",
"tags": "",
"geom": "0101000020E6100000409CD1A0B29321405455682096804740"
},
{
"id": "454468",
"version": 8,
"user_id": 52015,
"tstamp": "2009-12-23 20:47:15",
"changeset_id": "3437205",
"tags": "",
"geom": "0101000020E6100000357C0BEBC69321409EC02ACD9C804740"
},
{
"id": "454469",
"version": 7,
"user_id": 52015,
"tstamp": "2009-12-23 20:47:15",
"changeset_id": "3437205",
"tags": "",
"geom": "0101000020E6100000347914F8D4932140B8BBBD5AA4804740"
}
]
}
And when I do a
var nodeStore = Ext.getStore('nodeStore');
nodeStore.load();
console.log(nodeStore.getData());
we can see the following object, with my data in the raw column under items...
I figured it out, my code is correct and the only thing missing is a callback in the load() function :
nodeStore.load({
callback: function(records, operation, success) {
console.log(records);
console.log(nodeStore.getCount());
nodeStore.each(function(element) {
console.log(element.data.id);
});
},
scope: this,
});
The problem was I was trying to access the store before it loaded the data. Now I'm waiting that all the data is loaded to access it, and it works.

Using json data how to create form in sencha

I want to read json data from file - content of the json file shown below
{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username",
"constrain": "5-10",
"value": ""
},
{
"field":"textfield",
"name": "password",
"constrain": "5-10",
"value": ""
},
{
"field":"datepickerfield",
"name": "Birthday",
"constrain": "5-10",
"value": "new Date()"
},
{
"field":"selectfield",
"name": "Select one",
"options":[
{"text": "First Option", "value": 'first'},
{"text": "Second Option", "value": 'second'},
{"text": "Third Option", "value": 'third'}
]
},
]
}
}
Model
Ext.define('dynamicForm.model.Form', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'field', type: 'string'},
{name: 'name', type: 'string'},
{name: 'constrain', type: 'string'},
{name: 'value', type: 'string'}
],
hasMany: {model: 'dynamicForm.model.SelectOption', name: 'options'}
}
});
Ext.define('dynamicForm.model.SelectOption', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'text', type: 'string'},
{name: 'value', type: 'string'}
]
}
});
store
Ext.define('dynamicForm.store.FormStore', {
extend : 'Ext.data.Store',
storeId: 'formStore',
config : {
model : 'dynamicForm.model.Form',
proxy : {
type : 'ajax',
url : 'form.json',
reader : {
type : 'json',
rootProperty : 'form.fields'
}
},
autoLoad: true
}
});
This what i tried so for.
var fromval = Ext.create('dynamicForm.store.FormStore');
fromval.load(function (){
console.log(fromval);
// i added register view which having form panel with id "testForm"
Ext.Viewport.add({
xtype : 'register'
});
for(i=0; i< fromval.getCount(); i++) {
console.log("------");
Ext.getCmp('testForm').add({
xtype: fromval.getAt(i).data.field,
label: fromval.getAt(i).data.name,
value: fromval.getAt(i).data.value,
options: [
{text: "First Option", value: "first"},
{text: "Second Option", value: "second"},
{text: "Third Option", value: "third"}
]
});
}
});
two text fileds and date are woking good, but i don't know how to get options for select field from store, just heard coded now.
over all Based on the above json data, i need to create sencha form dynamically.
Better to follow MVC structure:
Create a model:
Ext.define('MyApp.model.FormModel', {
extend: 'Ext.data.Model',
config: {
fields: ["field","name"]
}
});
A store with proxy:
Ext.define('MyApp.store.FormStore',{
extend: 'Ext.data.Store',
config:
{
model: 'MyApp.model.FormModel',
autoLoad:true,
proxy:
{
type: 'ajax',
url : 'FormData.json', //Your file containing json data
reader:
{
rootProperty:'form.fields'
}
}
}
});
The formData.json file:
{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username"
},
{
"field":"textfield",
"name": "password"
},
]
}
}
And then use the FormStore to fill the form data as you need.
Ext.define('MyApp.view.LoginPage', {
extend: 'Ext.form.Panel',
config: {
items:{
xtype:'fieldset',
layout:'vbox',
items:[{
flex:1,
xtype:'textfield',
id:'namefield',
placeHolder:'Username'
},{
flex:1,
xtype:'passwordfield',
id:'passwordfield',
placeHolder:'Password'
}]
},
listeners:{
painted:function()
{
var store=Ext.getStore('FormStore');
while(!store.isLoaded())
{
console.log("loading...");
}
var record=store.getAt(0);
Ext.getCmp('namefield').setValue(record.data.name);
Ext.getCmp('passwordfield').setValue(record.data.password);
}
}
}
});
{
"data":[
{
"xtype":"textfield",
"title":"UserName",
"name": "username"
},
{
"xtype":"textfield",
"title":"password",
"name": "password"
},
{
"xtype":"textfield",
"title":"phone no",
"name": "birthday"
},
{
"xtype":"textarea",
"title":"address",
"name": "address"
}
]
}
Ext.define('dynamicForm.model.FormModel', {
extend: 'Ext.data.Model',
fields: ['field', 'name']
});
Ext.define('dynamicForm.store.FormStore', {
extend : 'Ext.data.Store',
model : 'dynamicForm.model.FormModel',
proxy :
{
type : 'ajax',
url : 'data/user.json',
reader :
{
type : 'json',
rootProperty:'data'
},
autoLoad: true
}
});
Ext.define('dynamicForm.view.DynaForm',{
extend:'Ext.form.Panel',
alias:'widget.df1',
items:[]
});
Ext.application({
name:'dynamicForm',
appFolder:'app',
controllers:['Users'],
launch:function(){
Ext.create('Ext.container.Viewport',{
items:[
{
xtype:'df1',
items:[]
}
]
});
}
});
Ext.define('dynamicForm.controller.Users',{
extend:'Ext.app.Controller',
views:['DynaForm'],
models:['FormModel'],
stores:['FormStore'],
refs:[
{
ref:'form1',
selector:'df1'
}
],
init:function(){
console.log('in init');
this.control({
'viewport > panel': {
render: this.onPanelRendered
}
});
},
onPanelRendered: function() {
var fromval=this.getFormStoreStore();
var form=this.getForm1();
fromval.load({
scope: this,
callback: function(records ,operation, success) {
Ext.each(records, function(rec) {
var json= Ext.encode(rec.raw);
var response=Ext.JSON.decode(json);
for (var i = 0; i < response.data.length; i++) {
form.add({
xtype: response.data[i].xtype,
fieldLabel: response.data[i].title,
name: response.data[i].name
});
}
//form.add(Ext.JSON.decode(json).data);
form.doLayout();
});
}
});
}
});
It will be done automatically if you insert it into any extjs component content :
var jsonValues = "{
"form": {
"fields" : [
{
"field":"textfield",
"name": "username"
},
{
"field":"textfield",
"name": "password"
},
]
}
}";
var panel = new Ext.Panel({
id : 'myPanel',
items : [jsonValues]
});
panel.show();

Sencha touch - display child elements of nested JSON data

I am new to Sencha touch and need your help to resolve the issue. I am trying to display the list of children text using following JSON and Sencha touch code. I looked thorough the API and found that the Child data can be accessed, but then I am not sure how I can send that back to Panel/Store to display the list as
Child 21
Child 22
I have nested JSON data as follows:
{
"items":[
{
"id":"1",
"text": "Parent 1",
"leaf": false,
"items": [
{
"id":1,
"text": "child 1",
"leaf": true
},
{
"id":2,
"text": "child 2",
"leaf": true
}
]
},
{
"id":"2",
"text": "Parent 2",
"leaf": false,
"items": [
{
"id":3,
"text": "child 21",
"leaf": true
},
{
"id":4,
"text": "Child 22",
"leaf": true
}
]
}
]
}
Now my sencha touch code is as follows:
Ext.ns('MyApp');
MyApp.Child= Ext.regModel(Child, {
fields: ['id','text','day','date'],
belongsTo: 'Parent',
idProperty:'id',
proxy: {
type: 'rest',
url: 'test.json'
}
});
MyApp.Parent = Ext.regModel('Parent', {
fields: [
{name: 'id', type: 'int'},
{name: 'text', type: 'string'}
] ,
associations: [
{ type: 'hasMany', model: 'Child', name: 'items'}
],
proxy: {
type: 'ajax',
url: 'test.json'
}
});
MyApp.parentStore = new Ext.data.Store({
model : 'Parent',
proxy: {
type: 'rest',
url: 'test.json',
reader: {
type: 'json',
root : 'items'
}
},
autoLoad:true
});
MyApp.parentStore.filter('id','2');
// Do something here to get the list of child items.
// MyApp.childStore = ?
MyApp.appList = new Ext.Panel ({
fullscreen : true,
dockedItems : [
{
xtype : 'toolbar',
title : 'Applications',
dock : 'top'
}
],
items: [{
xtype: 'list',
store: MyApp.childStore, // ??????
itemTpl: '<div class="contact"><strong>{text}</strong></div>'
}]
});
From what I understand what you need to do is a NestedList
Have a look at these links:
http://www.sencha.com/learn/intro-to-the-nested-list-component/
https://github.com/nelstrom/Sencha-Touch-nested-list-demo