extjstreestore

ExtJs Tree Panel, Tree Store from Json API


I am trying to make a tree representation in ExtJS. I have a service return this Json File.

Json File

can u help me in building the Model , Store and view to build the tree? thanks in advance.


Solution

  • first of all, you must modify your JSON to the structure which will accept the tree. In your JSON there is property id for each object. this id property must be unique, in your case you have group id:1 and device id:1. this must be changed during data modification.

    here we are creating models and modifying JSON recursively to achieve desired data structure.

    NOTE mType property which will define a model for node. see fiddle, also documentation for treepanel

    Ext.define('Root', {
        extend: 'Ext.data.TreeModel',
        childType: 'Group',
        fields: [{
            name: 'text',
            mapping: 'name'
        }]
    });
    Ext.define('Group', {
        extend: 'Ext.data.TreeModel',
        fields: [{
            name: 'text',
            mapping: 'name'
        }]
    });
    Ext.define('Device', {
        extend: 'Ext.data.TreeModel',
        fields: [{
            name: 'text',
            mapping: 'name'
        }]
    });
    
    var normilizeData = function (json) {
        var node = {};
        Ext.Object.each(json, function (k, v) {
            if(v.id){
             v.id = k+":"+v.id;
            }
    
            if (k == 'group') {
                Ext.apply(node, v);
                node.mType = 'Group';
            } else if (k == 'children') {
                if (v.length) {
                    node.children = [];
                    Ext.each(v, function (a) {
                        node.children.push(normilizeData(a));
                    })
                } else {
                    node.leaf = true;
                }
            } else if (k == 'device') {
                Ext.apply(node, v);
                node.mType = 'Device';
            } else {
                if (!node.children) {
                    node.children = [];
                }
                node.children.push(normilizeData(v));
            }
        });
        return node;
    }