Tuesday, 18 March 2014

Extjs 4 : Converting treestore into store using associations.

Extjs doesn't support updating tree by keeping nodes in its own hierarchy. treestore.sync90 function only sends updated nodes to the server as individual models. But sometimes we may need to send tree structure in the form of tree to the server(Ofcourse only updated nodes).

For example consider following tree,
Parent1
  • Child1
  • Child2
  • Child3
Parent2
  • Chld4
  • Child5
 If  child2 and child5 are dirty records and if we fire treestore.sync(), it only sends child2 and child5 models as data. We loose the context of parent. We may not know for which parent this child belongs to. In such a case you can use following model and code snippet to convert your tree into model with associated models.

Each node will have subtree models as associated model and using following function, you can convert modified tree nodes into associated-model store. This store is a plain store with associated models. Now you can send this model to the server
(For more info on sending updated model associations to the server viz following blog post
http://balu-learnings.blogspot.in/2014/03/extjs-4-sending-updated-models-to.html ).

model :

Ext.define('App.model.treegridsample', {
    extend : 'Ext.data.Model',
    fields : [ {
        name : 'id',
        useNull : true,
        defaultValue : ''
    }{
        name : 'text'
    }{
        name : 'leaf',
        persist : false
    }],

    associations : [ {
        type : 'hasMany',
        model : 'App.model.treegridsample',
        name : 'children'
    }
});


CustomTree.js
  
Ext.define('App.view.common.CustomTree', {
 extend : 'Ext.tree.Panel',
 convertToStore : function(model) {
  if (this.getStore() === null) {
   return null;
  }
  var rootNode = this.getStore().getRootNode();
  model = model || Ext.getClassName(this.getStore().getRootNode());
  dataStore = this.convertNodeToStore(rootNode, model);
  return dataStore.childrenStore;
 },
convertNodeToStore : function(rootNode, model) {
 var record = Ext.create(model);
 record.data = rootNode.data;
 if (record.childrenStore === null || typeof record.childrenStore === 'undefined') {
  record.childrenStore = Ext.create('Ext.data.Store', {
   model : model
  });
 }
 for (var i = 0; i < rootNode.childNodes.length; i++) {
  var cNode = rootNode.childNodes[i];
  var child = this.convertNodeToStore(cNode, model);
  if (cNode.dirty || cNode.phantom) {
   record.childrenStore.add(child);
   rootNode.setDirty();
  }
 }
 return record;
}


Source can be found@ https://github.com/Balagangadhar/ExtJS4-Misc/blob/master/CustomTree.js

No comments:

Post a Comment