extjsextjs-stores

How do i modify a raw data object returned by an ExtJS AJAX proxy into a JSON object to be consumed by a Tree Store


In an effort to create a treepanel, i configure it with a treestore whose AJAX proxy url receives json data i have no control of. But using Ext.data.reader.Json's transform property invokable before readRecords executes, gives an option to modify the passed raw (deserialized) data object from the AJAX proxy into a modified or a completely new data object. The transform config, gives the code snippet below:

Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: {
            type: 'json',
            transform: {
                fn: function(data) {
                    // do some manipulation of the raw data object
                    return data;
                },
                scope: this
            }
        }
    },
});

I would please like an example on how to go about modifying the return JSON object

[
{
    "id": 3,
    "attributes":
    {},
    "name": "user_one",
    "login": "",
    "email": "user_one@ats",
    "phone": "0751223344",
    "readonly": false,
    "administrator": false,
    "password": null
},
{
    "id": 4,
    "attributes":
    {},
    "name": "user_two",
    "login": "",
    "email": "user_two@ats",
    "phone": "0751556677",
    "readonly": false,
    "administrator": false,
    "password": null
}
]

into a JSON object fit for a treestore.

The hierarchical tree is to be rendered to show which user is under which admin using a condition administrator==true from the returned JSON, then a second AJAX request that returns that admin's users shown here.

[
    {
        "user_id": 3,
        "admin_id": 1,
    },
    {
        "user_id": 4,
        "admin_id": 2,
    }
    ]

Solution

  • Is the data nested at all? Otherwise why use a treepanel instead of a grid? To your question though, it'll depend on how you configure your treepanel but it would probably be something like this:

            transform: {
                fn: function(data) {
                    var treeRecords = Ext.Array.map(data, function(i){
                        return {
                            text: i.name,
                            leaf: true
                            //any other properties you want
                        }
                    });
    
                    var treeData = {
                        root: {
                            expanded: true,
                            children: treeRecords
                        }
                    };
    
                    return treeData;
                },
                scope: this
            }