1. #31
    Sencha User
    Join Date
    Sep 2011
    Posts
    1
    Vote Rating
    0
    witali is on a distinguished road

      0  

    Default My solution in MVC applcation

    My solution in MVC applcation


    Load dependencies and create model

    Code:
    (function(){
        Ext.Loader.setConfig({
            enabled:true
        });
        
        Ext.Loader.setPath('App', '/assets/app');
    
        Ext.syncRequire([
            'App.model.EquipmentType',        
            'App.store.EquipmentTypes'
            ]);
    
    
        
        var eqStore = Ext.create('App.store.EquipmentTypes');
            
        eqStore.on('load', function(store, records) {
            var fields= [
            'id',
            'plan_type', 
            "equipment_requested",
            "equipment_approved",
            'network_id',
            'network_name'
            ];
    
            Ext.each(records, function(eqType) {
                var eqId = eqType.get('id');
                    
                fields.push({
                    name: 'equipment_requested_' + eqId,
                    mapping: 'equipment_requested[' + eqId + ']',
                    defaultValue: 0
                });
                    
                fields.push({
                    name: 'equipment_approved_' + eqId,
                    mapping: 'equipment_approved[' + eqId + ']',
                    defaultValue: 0
                });
            });
    
            Ext.define('App.model.Planning', {
                extend:'Ext.data.Model',
    
                fields: fields,
    
    
                proxy:{
                    url:'/planning.json',
    
                    type:'rest',
                    simpleSortMode:true,
                    reader:{
                        type:'json',
                        root:'items'
                    },
                    writer:{
                        type:'json',
                        root:"items",
                        encode:true,
                        writeAllFields:false
                    }
                }
    
            });    
    
        });
            
        eqStore.load();
        
        
        
    })();

  2. #32
    Ext GWT Premium Member
    Join Date
    Dec 2008
    Location
    Milwaukee
    Posts
    33
    Vote Rating
    3
    meyersd is on a distinguished road

      0  

    Default


    My MVC solution is to have an afterrender event on a grid to load dynamic columns, dynamic fields, and dynamic data/store.
    Code:
    onGridAfterRender: function(abstractcomponent, options) {
      var grid = this;
      if (grid != null && grid.store.data.items != null && grid.store.data.items[0] != null) {
          var rawData = grid.store.data.items[0].raw;
          var dynamicStore = new Ext.data.JsonStore({
              fields: rawData.fields,
              data : rawData.crossHoldingList
          });
          grid.reconfigure(dynamicStore, rawData.columns);
      }
    }
    The store on the grid was previously loaded with raw data. Here is the JSON
    Code:
    {
    "columns": [
      {"id":"ticker","header": "Ticker", "width": 160, "dataIndex": "ticker"},
      {"header": "Company", "width": 75, "dataIndex": "company"},
      {"header": "Dynamic Col 1", "dataIndex": "dynamicCol1"},            
      {"header": "Dynamic Col 2", "dataIndex": "dynamicCol2"}
      ],
    "fields": ["ticker","company","dynamicCol1","dynamicCol2"],
    "dataList": [
    {
      "company": "Red Hat",
       "ticker": "RHT",
        "dynamicCol1": "Some Data 1",
        "dynamicCol2": "Some Data 2"
     },
     {
        "company": "Intel",
        "ticker": "INTL",
        "dynamicCol1": "Other Data 1",
        "dynamicCol2": "Other Data 2"
      }
      ]
    }

  3. #33
    Sencha User
    Join Date
    Nov 2007
    Posts
    294
    Vote Rating
    0
    Sesshomurai is on a distinguished road

      0  

    Default


    Hi,
    Interesting thread and I was able to do this in Ext 3.x. Are there any new paradigms in Ext 4.x to facilitate doing this?

    I agree a lot of short-lived model class definitions is silly. I also agree that losing models entirely and putting the dynamic fields only on the store isn't the best option.

    A model that can be redefined on the fly (at the instance level) and a store that automatically changes with it is best.

    Any news?

  4. #34
    Sencha User
    Join Date
    Sep 2011
    Posts
    1
    Vote Rating
    0
    jaune162 is on a distinguished road

      0  

    Default Extjs 4 Dynamic Model user reader property metaData

    Extjs 4 Dynamic Model user reader property metaData


    See Ext.data.reader.Reader's property "metaData".
    See alse metaProperty.

    [code]
    request
    {
    metaData:{
    idProperty:'id',
    fields:['id','name','age']
    },
    success:true,
    roots:[some data]
    }



    Ext.data.reader.Json
    readRecords: function(data) { var me = this, meta; //this has to be before the call to super because we use the meta data in the superclass readRecords if (me.getMeta) { meta = me.getMeta(data); if (meta) { me.onMetaChange(meta); } } else if (data.metaData) { me.onMetaChange(data.metaData); } /** * @property {Object} jsonData * A copy of this.rawData. * @deprecated Will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead. */ me.jsonData = data; return me.callParent([data]); },

    Ext.data.reader.Reader
    /** * @private * Reconfigures the meta data tied to this Reader */ onMetaChange : function(meta) { var me = this, fields = meta.fields || me.getFields(), newModel, clientIdProperty; // save off the raw meta data me.metaData = meta; // set any reader-specific configs from meta if available me.root = meta.root || me.root; me.idProperty = meta.idProperty || me.idProperty; me.totalProperty = meta.totalProperty || me.totalProperty; me.successProperty = meta.successProperty || me.successProperty; me.messageProperty = meta.messageProperty || me.messageProperty; clientIdProperty = meta.clientIdProperty; if (me.model) { me.model.setFields(fields, me.idProperty, clientIdProperty); me.setModel(me.model, true); } else { newModel = Ext.define("Ext.data.reader.Json-Model" + Ext.id(), { extend: 'Ext.data.Model', fields: fields, clientIdProperty: clientIdProperty }); if (me.idProperty) { // We only do this if the reader actually has a custom idProperty set, // otherwise let the model use its own default value. It is valid for // the reader idProperty to be undefined, in which case it will use the // model's idProperty (in getIdProperty()). newModel.idProperty = me.idProperty; } me.setModel(newModel, true); } },

  5. #35
    Sencha User faruq's Avatar
    Join Date
    Feb 2008
    Posts
    5
    Vote Rating
    0
    faruq is on a distinguished road

      0  

    Default


    Hi,

    Thanks for your code which helped me alot to generate dynamic things. Could you please also share the code to generate records variable from database.

    I am trying from last 2 days to complete this task.

    Thanks in Advance.

    Regards,
    Faruq Shaik.
    faruq1256@gmail.com
    Quote Originally Posted by SenchaGuru View Post
    Hi all

    I am building an application where the user can generate tables on the fly. The description of these tables are stored at the back-end.

    I needed to generate models from these descriptions and be able to use data grid objects to manipulate the data (crud operations).

    I have looked in this forum for a solution to this as I had realized that the current ExtJS 4 does not support adding fields dynamically to a model or a store, .. but I had no luck finding something that works for what I needed (in Extjs4).

    Anyways, I came up with a solution using 'eval' that does exactly what I wanted , .. and I wanted to share it with you.

    Here it is,..

    Code:
    Ext.Loader.setConfig({
        enabled: true
    });
    Ext.Loader.setPath('Ext.ux', 'http://dev.sencha.com/deploy/ext-4.0.1/examples/ux');
    Ext.require([
        'Ext.form.*',
        'Ext.data.*',
        'Ext.grid.*',
        'Ext.ux.grid.FiltersFeature',
        'Ext.layout.container.Column'
        ]);
    
    // This data can be pulled off a back-end database
    // Used to generate a model and a data grid
    var records = [{
        data:{
            "dataIndex":"first",
            "name":"First Name",
            "type":"string"
        }
    },{
        data:{
            "dataIndex":"last",
            "name":"Last Name",
            "type":"String"
        }
    },{
        data:{
            "dataIndex":"email",
            "name":"Email",
            "type":"string"
        }
    }];
    
    // Lookup table (type => xtype)
    var type_lookup = new Object;
    type_lookup['int'] = 'numberfield';
    type_lookup['float'] = 'numberfield';
    type_lookup['string'] = 'textfield';
    type_lookup['date'] = 'datefield';
    type_lookup['boolean'] = 'checkbox';
    
    // Skeleton store
    var store_template = {
        autoLoad: true,
        autoSync: true,
        remoteFilter: false,
        
        // DATA is inserted here for the example to work on local drive (use proxy below)
        data:[{id:1,first:"Fred",last:"Flintstone",email:"fred@flintstone.com"},
              {id:2,first:"Wilma",last:"Flintstone",email:"wilma@flintstone.com"},
              {id:3,first:"Pebbles",last:"Flintstone",email:"pebbles@flintstone.com"},
              {id:4,first:"Barney",last:"Rubble",email:"barney@rubble.com"},
              {id:5,first:"Betty",last:"Rubble",email:"betty@rubble.com"},
              {id:6,first:"BamBam",last:"Rubble",email:"bambam@rubble.com"}],
        proxy: {
            type: 'rest',
            url: 'http://dev.sencha.com/deploy/ext-4.0.1/examples/restful/app.php/users',
            reader: {
                type: 'json',
                root: 'data'
            },
            writer: {
                type: 'json'
            }
        }
    };
    
    // Skeleton grid (_PLUGINS_ & _STORE_, are placeholders)
    var grid_template = {
        columnWidth: 1,
        plugins: '_PLUGINS_',
        height: 300,
        store: '_STORE_'
    }
    
    // Skeleton window (_ITEMS_ is a placeholder)
    var window_template = {
        title: 'Dynamic Model / Window',
        height: 400,
        width: 750,
        layout: 'fit',
        items: '_ITEMS_'
    }
    
    // Generate a model dynamically, provide fields
    function modelFactory(name,fields){
        model =  {
            extend: 'Ext.data.Model',
            fields: fields
        };
        eval("Ext.define('"+name+"',"+Ext.encode(model)+");");
    }
    
    // Generate a dynamic store
    function storeFactory(name,template,model){
        template.model = model;
        eval(name+" = Ext.create('Ext.data.Store',"+Ext.encode(template)+");");
    }
    
    // Generate a dynamic grid, .. store name is appended as a string because otherwise, Ext.encode
    // will cause 'too much recursion' error (same for plugins)
    function gridFactory(name,template,store,plugins){
        script =  name+" = Ext.create('Ext.grid.Panel', "+Ext.encode(template)+");";
        script = script.replace("\"_STORE_\"", store);
        script = script.replace("\"_PLUGINS_\"", plugins);
        eval(script);
    }
    // Generate a dynamic window, .. items are appended as a string to avoid Ext.encode error
    function windowFactory(winName,winTemp,items){
        script += winName+" = Ext.create('Ext.window.Window',"+Ext.encode(winTemp)+").show();";
        script = script.replace("\"_ITEMS_\"", items);
        eval(script);
    }
    
    // Generate a model, a store a grid and a window dynamically from a record list!
    function generateDynamicModel(records){
        
        fields = [{
            name: 'id',
            type: 'int',
            useNull:true
        }];
    
        columns = [{
            text: 'ID',
            sortable: true,
            dataIndex: 'id'
        }];
    
        for (var i = 0; i < records.length; i++) {
    
            fields[i+1] =  {
                name: records[i].data.dataIndex,
                type: records[i].data.type
            };
    
            columns[i+1] = {
                text: records[i].data.name,
                sortable: true,
                dataIndex: records[i].data.dataIndex,
                field:  {
                    xtype: type_lookup[records[i].data.type]
                }
            };
        }
    
        grid_template.columns = columns;
    
        modelFactory('myModel',fields);
        storeFactory('myStore',store_template,'myModel');
        gridFactory('myGrid',grid_template,'myStore','[rowEditing]');
        windowFactory('myWindow',window_template,'[myGrid]');
    
        // Direct access to the store created above 
        myStore.load();
    }
    
    Ext.onReady(function(){
        rowEditing = Ext.create('Ext.grid.plugin.RowEditing');
        generateDynamicModel(records);
    });
    I never used 'eval' to such an extend, but it works surprisingly well,..

    You can also download the working example (attached).

    Cheers

    Adnan

  6. #36
    Sencha User faruq's Avatar
    Join Date
    Feb 2008
    Posts
    5
    Vote Rating
    0
    faruq is on a distinguished road

      0  

    Default


    Hi,

    Could you please suggest me on adding the toolbar with handler. I am able to add the toolbar to that grid but handler is not working. Here is my sample code.

    Code:
    var grid_template = {
        columnWidth: 1,
        plugins: '_PLUGINS_',
        height: 300,
        store: '_STORE_',
        tbar: toolbar,
        bbar: [{
            	xtype: 'button',
    //        	align:'right',
            	iconCls:'icon-save',
            	tooltip: 'Click to save all changes to the database',
            	text: 'Save',
            	handler : function() {
                   alert("alert me...");
                }
              }]
    }
    Thanks in Advance.

    Faruq Shaik.

  7. #37
    Sencha User
    Join Date
    Nov 2013
    Posts
    1
    Vote Rating
    0
    Sherell is on a distinguished road

      0  

    Default


    Hello everyone, I'm new here, and a lot of attention

  8. #38
    Sencha User faruq's Avatar
    Join Date
    Feb 2008
    Posts
    5
    Vote Rating
    0
    faruq is on a distinguished road

      0  

    Default


    Hi All,

    At last I found the solution to add a toolbars to Dynamic Grid. Below is the code:

    Add Toolbar function as below:

    Code:
    var toolbar = Ext.create('Ext.toolbar.Toolbar', { 
    dock: 'bottom', 
    items: [{text:'button text',
              handler : function(btn) {
                   alert("alert me...");
                }
    
    
    }] 
    });
    Then call this function after generateDynamicModel(record_data); as

    Code:
    myGrid.addDocked(toolbar);
    Regards,
    Faruq Shaik.

  9. #39
    Sencha User
    Join Date
    Aug 2009
    Posts
    3
    Vote Rating
    0
    jmCodinach is on a distinguished road

      0  

    Default


    Hello,
    I appreciate very much if sombody could tell me how should I add a renderer function call in the columns definition.


    In your example:


    .....
    "columns": [
    {"id":"ticker","header": "Ticker", "width": 160, "dataIndex": "ticker","renderer":"myRenderFunction"},
    {"header": "Company", "width": 75, "dataIndex": "company"},
    {"header": "Dynamic Col 1", "dataIndex": "dynamicCol1"},
    {"header": "Dynamic Col 2", "dataIndex": "dynamicCol2"}
    ],
    ......

    of course the double quotes are for a string not for a function call.


    Many thanks in advance.


    JMC

    By the way, the following link helps me a lot in my implementation:
    http://www.learnsomethings.com/2012/...olumn-headers/

  10. #40
    Sencha User olecom's Avatar
    Join Date
    Oct 2011
    Location
    Republic of Belarus
    Posts
    40
    Vote Rating
    2
    olecom is on a distinguished road

      0  

    Default


    Quote Originally Posted by jmCodinach View Post
    Hello,I appreciate very much if sombody could tell me how should I add a renderer function call in the columns definition.
    My way is to extend `Ext.grid.column.Column` with anything i need: renderer, filters, onTriggerClick(ExtJS 4), complex items, etc. Then to set that `xtype` in columns definition sent with `metaData` to reconfigure model/grid.
    PHP Code:
    Ext.define('App.shoesupro.view.GridColumnCurrency',{
        
    extendApp.shoesupro.view.GridColumnFilter,// NOTE: this is extent of extent
        
    xtype'so_gridColumnCurrency',
        
    renderer: function (v){
            return 
    Ext.util.Format.currency(v)
        }
    })

    // column def:

    var columns = [{
          
    dataIndex"ps_ret"
        
    text"ps_ret"
        
    width100
        
    xtype"so_gridColumnCurrency"
        
    editor"textfield"
    }]