ddragos
ddragos

Reputation: 81

Extjs tree store set leaf property value based on children property

I am using a TreeStore to load data that looks like this:

{ "categories": [{ "text": "Ext JS", "expanded": "true", "categories": [{ "text": "app", "categories": [{ "text": "Application.js", "categories": "null" }] }, { "text": "button", "expanded": "true", "categories": [{ "text": "Button.js", "categories": "null" }, { "text": "Cycle.js", "categories": "null" }, { "text": "Split.js", "categories": "null" }] } ] }] }

What I want is to set the leaf property to true or false if the categories property is null or not. My model looks like this :

Ext.define('TestTree.model.MyModel', {
extend: 'Ext.data.Model',
requires: [
    'Ext.data.field.Boolean'
],
fields: [
    {
        name: 'text'
    },
    {
        type: 'boolean',
        name: 'leaf'
    }
]

});

The idea was to use the calculate config of the leaf field for that but if I try to use data.get('categories') I get Field leaf depends on undefined field get and if I try to define the field categories in my model an use data.categories, nothing happens. I don't know what I am missing! My store looks like this:

Ext.define('TestTree.store.MyTreeStore', {
extend: 'Ext.data.TreeStore',
requires: [
    'TestTree.model.MyModel',
    'Ext.data.proxy.Ajax',
    'Ext.data.reader.Json'
],
constructor: function(cfg) {
    var me = this;
    cfg = cfg || {};
    me.callParent([Ext.apply({
        storeId: 'MyTreeStore',
        autoLoad: true,
        model: 'TestTree.model.MyModel',
        proxy: {
            type: 'ajax',
            url: 'resources/data/treeData.json',
            reader: {
                type: 'json',
                rootProperty: 'categories'
            }
        }
    }, cfg)]);
}

});

Thank you!

Upvotes: 1

Views: 2352

Answers (2)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

I used calculate instead of convert.

From the doc

Using calculate is the simplest and safest way to define a calculated field.

So the code becomes

Ext.define("Files", {
    extend : "Ext.data.Model",
    fields : [{
         name: 'categories'
    },{
        name: 'leaf',
        calculate : function(data) {
            return data.categories === null;
        },
        depends: ['categories']
    }]
});

Upvotes: 0

Guilherme Lopes
Guilherme Lopes

Reputation: 4760

Create your model with the following init method:

Ext.define("Files", {
    extend : "Ext.data.Model",
    fields : [{
         name: 'categories'
    },{
        name: 'leaf',
        convert : function(value, record) {
            return record.get('categories') == 'null';
        }
    }]
});

This should fix your issue, and here is a fiddle so you can take a look: https://fiddle.sencha.com/#fiddle/gq8

Upvotes: 2

Related Questions