Page 1 of 9 123 ... LastLast
Results 1 to 10 of 85

Thread: Retrieve columns and fields for grid from server

  1. #1
    Sencha User
    Join Date
    Aug 2007
    Posts
    100

    Default Retrieve columns and fields for grid from server

    Hi guys,

    I've spend all afternoon searching through the forums, but so far haven't found the right thread/ example to get me started.

    In my application I have set up a grid, derived from the samples page. This works fine, but having to define the columns and fields in my script makes it very inflexible.

    My situation is kind of like a database explorer (like browse in phpMyAdmin). I want a grid to show the content of a mysql database table. So if the table has 4 columns, I want the grid to have 4 columns as well. So basically I'm looking for a way to set up the columns dynamically based upon a Json call, maybe?

    I imagine this is possible with Ext. I've come across several threads about metadata and column models, but so far it didn't really help me understand. I'm really looking for a basic solutions. Nothing fancy with respect to formatting the columns etc.

    Can anyone point me to resources explaining this?

    Thanks a lot! -Michiel

  2. #2
    Ext User
    Join Date
    Jul 2007
    Location
    Florida
    Posts
    9,996

    Default

    I posted some code inside the autoGrid extension thread.

  3. #3
    Sencha User
    Join Date
    Aug 2007
    Posts
    100

    Default

    Hi mjlecomte,

    Thanks for your reply. I've read that entire thread, but it seem very complicated. I can't find the part that I'm looking for, and unfortunately the demo page appears to be offline.

    I've also found this thread: http://extjs.com/forum/showthread.php?t=57061, where this is suggested:

    Code:
    Ext.Ajax.request({
       url: 'foo',
       success: function(response){
           var cols = Ext.decode(response.responseText);
           myGrid.reconfigure(myGrid.getStore(), new Ext.grid.ColumnModel(cols));
       }
    });
    But don't really see how to implement this.

    Could you maybe provide a short example? Or do you know of a demo page. Learning from some working code, has always proved to be the best way for me.

    Anyway, thanks for the reply. I hope you could elaborate a bit for me.

    Michiel

  4. #4

    Default

    One workaround would be to let your Ext code be outputted by PHP, and defining the column-model in your PHP output. It's flexible (sort of), and you don't need to fool around in Ext.

  5. #5
    Ext User
    Join Date
    Jul 2007
    Location
    Florida
    Posts
    9,996

    Default

    I just threw this together quick. Here's what could be used as an extension. I also posted similar code as a plugin in the ux repository.

    PHP Code:
    Ext.ns('Ext.ux.grid');

    /**
     * Ext.ux.grid.MetaGrid Extension Class
     * Extension of Ext.grid.EditorGridPanel to handle metaData.
     *
     * @author Michael LeComte
     * @version 0.2
     * @date Feb 2, 2009
     *
     * @class Ext.ux.grid.MetaGrid
     * @extends Ext.grid.EditorGridPanel
     */
    Ext.ux.grid.MetaGrid Ext.extend(Ext.grid.EditorGridPanel, {

        
    initPreviewtrue,
        
        
    loadMask: {
            
    msg'Loading ...'
        
    },

        
    /**
         * @cfg {Boolean} true to mask the grid if there's no data to make 
         * it even more obvious that the grid is empty.  This will apply a 
         * mask to the grid's body with a message in the middle if there 
         * are zero rows - quite hard for the user to miss.
         */
        
    maskEmptytrue,
        
        
    /**
         * key number for new records (will be adjusted by new records)
         */
        
    newKey: -1,
        
        
    paging: {
            
    perPage25
        
    },
        
        
    /**
         * @cfg {String} primaryKey The database table primary key.
         */
        
    primaryKey'id',
        
        
    stripeRowstrue,

        
    trackMouseOvertrue,
        
        
    initComponent: function(){

            
    Ext.applyIf(this, {
                
    plugins: [],
                
    pagingPlugins: [],
                
    // customize view config
                
    viewConfig: {
                    
    emptyText'No Data',
                    
    forceFittrue
                
    }
            });

            if (
    this.filters) {
                
    this.filters = new Ext.grid.GridFilters({
                    
    filters:[]
                });  
                
    this.plugins.push(this.filters);  
                
    this.pagingPlugins.push(this.filters);
            }

            
    this.store = new Ext.data.Store({
                
    urlthis.url,
                
    // create reader (reader will be further configured through metaData sent by server)
                
    reader: new Ext.data.JsonReader(),
                
    baseParamsthis.baseParams,
                
    listeners: {
                    
    // register to the store's metachange event
                    
    metachange: {
                        
    fnthis.onMetaChange,
                        
    scopethis
                    
    },
                    
    loadexception: {
                        
    fn: function(proxyoptionsresponsee){
                            if (
    Ext.isFirebug) {
                                
    console.warn('store loadexception: 'arguments);
                            }
                            else {
                                
    Ext.Msg.alert('store loadexception: 'arguments);
                            }
                        }
                    },
                    
    scopethis
                
    }
            });

            
    // mask the grid if there is no data if so configured
            
    if (this.maskEmpty) {
                
    this.store.on(
                    
    'load', function() {
                        var 
    el this.getGridEl();
                        if (
    this.store.getTotalCount() == && typeof el == 'object') {
                            
    el.mask('No Data''x-mask');
                        }
                    }, 
    this
                
    );
            } 
            
            
    //Create Paging Toolbar      
            
    this.pagingToolbar = new Ext.PagingToolbar({
                
    id'pager',
                
    storethis.store,
                
    //pageSize: this.options.pageSize,//makes this global for all who need it
                
    pageFittrue,
                
    pageSizethis.pageSize || 25//default is 20
                
    pluginsthis.pagingPlugins,
                
    displayInfotrue,//default is false (to not show displayMsg)
                
    displayMsg'Displaying {0} - {1} of {2}',
                
    emptyMsg"No data to display",//display message when no records found
                
    items: [{
                    
    text'Change data',
                    
    scopethis
                
    }]
            });
            
            
    //Add a bottom bar      
            
    this.bbar this.pagingToolbar;
            
            
    /*
             * JSONReader provides metachange functionality which allows you to create
             * dynamic records natively
             * It does not allow you to create the grid's column model dynamically.
             */
            
    if (this.columns && (this.columns instanceof Array)) {
                
    this.colModel = new Ext.grid.ColumnModel(this.columns);
                
    delete this.columns;
            }
            
            
    // Create a empty colModel if none given
            
    if (!this.colModel) {
                
    this.colModel = new Ext.grid.ColumnModel([]);
            }
            
            
    /**
             * defaultSortable : Boolean
             * Default sortable of columns which have no sortable specified
             * (defaults to false)
             * Instead of specifying sorting permission by individual columns
             * can just specify for entire grid
             */
            
    this.colModel.defaultSortable true;
            
            
    Ext.ux.grid.MetaGrid.superclass.initComponent.call(this);

            var 
    params = { //this is only parameters for the FIRST page load,
                
    reconfiguretrue,
                
    start0//pass start/limit parameters for paging
                
    limitthis.paging.perPage
            
    };

            
    this.store.load({paramsparams});
            
        },

        
    /**
         * Configure the reader using the server supplied meta data.
         * This grid is observing the store's metachange event (which will be triggered
         * when the metaData property is detected in the returned json data object).
         * This method is specified as the handler for the that metachange event.
         * This method interrogates the metaData property of the json packet (passed
         * to this method as the 2nd argument ).  The local meta property also contains
         * other user-defined properties needed:
         *     fields
         *     defaultSortable
         *     id
         *     root
         *     start
         *     limit
         *     sortinfo.field
         *     sortinfo.direction
         *     successProperty
         *     totalProperty
         * @param {Object} store
         * @param {Object} meta The reader's meta property that exposes the JSON metadata
         */
        
    onMetaChange: function(storemeta){
        
            
    // avoid loading meta on store reload 
            
    delete (store.lastOptions.params.meta);
            
            var 
    columns = [], editorpluginsstoreCfglconvert;

            
    // set primary Key         
            
    this.primaryKey meta.id;

            
    // the metaData.fields property in the returned data packet will be used to:
            // 1. internally create a Record constructor using the array of field definitions:
            // this.recordType = Ext.data.Record.create(o.metaData.fields);
            // both the reader and the store will have a recordType property
            // 2. reconfigure the column model:
            
    Ext.each(meta.fields, function(col){
            
                
    // if plugin specified
                
    if (col.plugin !== undefined) {
                    
    columns.push(eval(col.plugin));
                    return;
                }
                
                
    // if header property is not specified do not add to column model
                
    if (col.header == undefined) {
                    return;
                }
                
                
    // if not specified assign dataIndex = name               
                
    if (typeof col.dataIndex == "undefined") {
                    
    col.dataIndex col.name;
                }
                
                
    //if using gridFilters extension
                
    if (this.filters) {
                    if (
    col.filter !== undefined) {
                        if ((
    col.filter.type !== undefined)) {
                            
    col.filter.dataIndex col.dataIndex;
                            
    this.filters.addFilter(col.filter);
                        }
                    }
                    
    delete col.filter;
                }
                
                
    // if renderer specified in meta data
                
    if (typeof col.renderer == "string") {
                
                    
    // if specified Ext.util or a function will eval to get that function
                    
    if (col.renderer.indexOf("Ext") < && col.renderer.indexOf("function") < 0) {
                        
    //                    col.renderer = this.setRenderer(col.renderer);
                        
    col.renderer this[col.renderer].createDelegate(this);
                    }
                    else {
                        
    col.renderer = eval(col.renderer);
                    }
                }
                
                
    /*
                 // if want to modify default column id
                 if(typeof col.id == "undefined"){
                 col.id = 'c' + i;
                 }
                 */
                // if listeners specified in meta data
                
    col.listeners;
                if (
    typeof l == "object") {
                    for (var 
    e in l) {
                        if (
    typeof e == "string") {
                            for (var 
    c in l[e]) {
                                if (
    typeof c == "string") {
                                    
    l[e][c] = eval(l[e][c]);
                                }
                            }
                        }
                    }
                }
                
                
    // if convert specified assume it's a function and eval it
                
    if (col.convert) {
                    
    col.convert = eval(col.convert);
                }

                
    editor col.editor;
                
                if (
    editor) {
                
                    switch (
    editor.xtype) {
                        case 
    'checkbox':
                            
    delete (col.editor);
                            
    delete (col.renderer);
                            
    col = new Ext.grid.CheckColumn(col);
                            
    col.editor Ext.ComponentMgr.create(editor'textfield');
                            
    col.init(this);
                            break;
                        case 
    'combo':
                            if (
    col.editor.store) {
                                
    storeCfg col.editor.store;
                                
    col.editor.store = new Ext.data[storeCfg.storeType](storeCfg.config);
                            }
                            
    col.editor Ext.ComponentMgr.create(editor'textfield');
                            break;
                        case 
    'datefield':
                            
    col.editor Ext.ComponentMgr.create(editor'textfield');
                            break;
                        default:
                            
    col.editor Ext.ComponentMgr.create(editor'textfield');
                            break;
                    }
                    
                    
    plugins editor.plugins;
                    
    delete (editor.plugins);
                    
                    
    //configure any listeners specified for this column's editor
                    
    editor.listeners;
                    if (
    typeof l == "object") {
                        for (var 
    e in l) {
                            if (
    typeof e == "string") {
                                for (var 
    c in l[e]) {
                                    if (
    typeof c == "string") {
                                        
    l[e][c] = eval(l[e][c]);
                                    }
                                }
                            }
                        }
                    }
                }
                
                if (
    plugins instanceof Array) {
                    
    editor.plugins = [];
                    
    Ext.each(plugins, function(plugin){
                        
    plugin.name plugin.name || col.dataIndex;
                        
    editor.plugins.push(Ext.ComponentMgr.create(plugin));
                    });
                }
                
                
    // add column to colModel config array            
                
    columns.push(col);
                
            }, 
    this); // end of columns loop        
            
    var cm = new Ext.grid.ColumnModel(columns);
            
            if (
    meta.defaultSortable != undefined) {
                
    cm.defaultSortable meta.defaultSortable;
            }
            
            
    // can change the store if we need to also, perhaps if we detect a groupField
            // config for example
            // meta.groupField or meta.storeCfg.groupField;
            
    var store this.store
            
            
    // Reconfigure the grid to use a different Store and Column Model. The View 
            // will be bound to the new objects and refreshed. 
            
    this.reconfigure(storecm);

            
    // to add a record, just get a reference to the recordType:
            // this.store.recordType
            // and then use it to create a new record:
            // var r = new s.recordType({
            //     value:4,
            //     displayField:"Last Week",
            //     total: 23
            // });
            // and then insert it into the store (updates the grid visually also):
            // this.store.insert(0, r);
            
            //update the store for the pagingtoolbar also
            
    var oldStore this.pagingToolbar.store;
            
    this.pagingToolbar.unbind(oldStore);
            
    this.pagingToolbar.bind(store);
            
            if (
    this.stateful) {
                
    this.initState();
            }
            
            if (!
    this.view.hmenu.items.containsKey('reset')) {
                
    this.view.hmenu.add({
                    
    id"reset",
                    
    text"Reset Columns",
                    
    cls"xg-hmenu-reset-columns"
                
    });
            }
        }
    });
    Ext.reg('meta-grid'Ext.ux.grid.MetaGrid); 

  6. #6
    Ext User
    Join Date
    Jul 2007
    Location
    Florida
    Posts
    9,996

    Default

    example usage

    PHP Code:
    Ext.apply(Ext, {
        
    isFirebug: (window.console && window.console.firebug)
    });

    Ext.BLANK_IMAGE_URL '../../resources/images/default/s.gif';

    Ext.ns('app');
    app.getMetaGrid = function(config){
        return new 
    Ext.ux.grid.MetaGrid(Ext.apply({
        
            
    baseParamsnull,
            
            
    /**
             * @cfg {String} url Specify the url to the data object (server side
             * script) from which to load data through the HttpProxy.
             */
            
    url'meta-data.txt',
            
            
    renderChange: function(val){
                if (
    val 0) {
                    return 
    '<span style="color:green;">' val '</span>';
                }
                else 
                    if (
    val 0) {
                        return 
    '<span style="color:red;">' val '</span>';
                    }
                return 
    val;
            },
            
            
    renderCombo: function(valmetadatarecordrowIndexcolIndexstore){
                var 
    data;
                
    /*
                 // the field name:
                 //var field = record.fields.items[colIndex].name; // unreliable since colIndex may be wrong
                 var field = this.colModel.getDataIndex(colIndex);
                 
                 // Use the Store Manager to get a reference to the ComboBox store.
                 // The store that is passed as one of arguments to this renderer
                 // function is the grid store.  We need to cross reference the data
                 // with the ComboBox store, not the grid store.
                 //Get a registered Store using the id of the Store
                 var storeId = field;
                 var comboStore = Ext.StoreMgr.lookup(storeId);
                 
                 if (!comboStore) {
                 comboStore = new App.ComboStore(storeId);
                 }
                 var comboRecord = comboStore.getById(val);
                 if (comboRecord) {
                 data = comboRecord.data.displayField;
                 }
                 else {
                 data = data;//'missing data';
                 }
                 */
                // return the value that should be rendered into the grid cell
                
    return data;
            },
            
            
    /** 
             * Date renderer function
             * Renders a date
             */
            
    renderDate: function(date){
                return 
    date date.dateFormat('M d, Y') : '';
            },
            
            
    renderDateTime: function(date){
                if (!
    date) {
                    return 
    '';
                }
                var 
    now = new Date();
                var 
    now.clearTime(true);
                var 
    notime date.clearTime(true).getTime();
                if (
    notime == d.getTime()) {
                    return 
    'Today ' date.dateFormat('g:i a');
                }
                
    d.add('d', -6);
                if (
    d.getTime() <= notime) {
                    return 
    date.dateFormat('D g:i a');
                }
                return 
    date.dateFormat('n/j g:i a');
            },
            
            
            
    /** 
             * Italic Custom renderer function
             * takes val and renders it in italics
             * @param {Object} val
             */
            
    renderItalic: function(datametadatarecordrowIndexcolumnIndexstore){
                return 
    '<i>' data '</i>';
            },
            
            
    /** 
             * Percent Custom renderer function
             * takes 'data' and renders it red or green with %
             */
            
    renderPctChange: function(datametadatarecordrowIndexcolumnIndexstore){
                var 
    = (parseFloat(data) * 100.0).toFixed(1);
                var 
    qtip '>';
                if (
    data >= 0) {
                    
    //meta.css = 'green-cls';
                    
    qtip " qtip='yeah'/>";
                    return 
    '<span style="color:green;"' qtip data '%</span>';
                }
                else 
                    if (
    data 0) {
                        
    //meta.css = 'red-cls';
                        
    qtip " qtip='woops'/>";
                        return 
    '<span style="color:red;"' qtip data '%</span>';
                    }
                
    //css:
                //.red-cls {color: red;}
                //.green-cls {color: green;}
                
    return data;
            },
            
            
    /** 
             * Red/Green Custom renderer function
             * takes val and renders it red if <0 otherwise renders it green
             * @param {Object} val
             */
            
    renderPosNeg: function(datametadatarecordrowIndexcolumnIndexstore){
            
                if (
    data >= 0) {
                    return 
    '<span style="color:green;">' data '</span>';
                }
                else 
                    if (
    data 0) {
                        return 
    '<span style="color:red;">' data '</span>';
                    }
                return 
    data;
            },
            
            
    /** 
             * Risk Custom renderer function
             * Renders according to risk level
             * @param {Object} val
             */
            
    renderRisk: function(datametadatarecordrowIndexcolumnIndexstore){
                switch (
    data) {
                    case 
    "high":
                        
    metadata.css "redcell";
                        return 
    "high";//display 'high' in the cell (could be
                    //we could display anything here
                    //"High","Hi","yup"...anything
                    
    case "medium":
                        return 
    "medium";
                    case 
    "low":
                        return 
    "low";
                    default:
                        return 
    data;
                }
            },
            
            
    /** 
             * Star Custom renderer function
             * Renders a picture according to value
             * @param {Object} val
             */
            
    renderStars: function(datametadatarecordrowIndexcolumnIndexstore){
                switch (
    data) {
                    case 
    "1":
                        
    metadata.css "stars1";
                        return 
    1;//returns text over the background image
                    
    case "2":
                        
    metadata.css "stars2";
                        return;
    //just shows the background image
                    
    case "3":
                        
    metadata.css "stars3";
                        return;case 
    "4":
                        
    metadata.css "stars4";
                        return;case 
    "5":
                        
    metadata.css "stars5";
                        return;default:
                        return 
    data;
                }
            }
        }, 
    config));
    };



    Ext.onReady(function(){
        var 
    win = new Ext.Window({
            
    layout'fit',
            
    closablefalse,
            
    plaintrue,
            
    height500,
            
    width700,
            
    items: [app.getMetaGrid({
                
    title'Meta Grid Example',
                
    borderfalse
            
    })]
        });
        
    win.show();
    }); 

  7. #7
    Ext User
    Join Date
    Jul 2007
    Location
    Florida
    Posts
    9,996

    Default

    The html file to wire it up.

    HTML Code:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    
    <title id="title">MetaGrid Example</title>
    
        <!-- Javascript includes (note the order is important) -->
        <!-- Libraries -->
        <script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="../../ext-all-debug.js"></script>
    
        <!-- Extensions - Grid -->
        <script type="text/javascript" src="MetaGrid.js"></script>
     
        <!-- Page Specific -->
        <script type="text/javascript" src="meta-example.js"></script>
    
    
        <!-- CSS includes -->
        <!-- Main Ext -->
        <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
    
        <!-- Page specific overrides (note referenced LAST) -->
        <link rel="stylesheet" type="text/css" href="overrides.css" />
    
    </head>
    <body>
    
        <!-- Take note of the empty body -->
    
    </body>
    </html>
    Some sample data:

    Code:
    {
       "total":30,
       "results":[
          {
             "companyID":"166",
             "company":"3m Company",
             "price":"44",
             "change":"0.02",
             "pctChange":"0.03",
             "lastChange":"2007-08-01 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"1",
             "check":"1",
             "tax":2.64
          },
          {
             "companyID":"1",
             "company":"Alcoa",
             "price":"23.33",
             "change":"0.42",
             "pctChange":"1.47",
             "lastChange":"2007-10-02 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"5",
             "check":"0",
             "tax":1.4
          },
          {
             "companyID":"144",
             "company":"Altria Group Inc",
             "price":"10",
             "change":"0.28",
             "pctChange":"0.34",
             "lastChange":"2007-02-02 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"4",
             "check":"1",
             "tax":0.6
          },
          {
             "companyID":"145",
             "company":"American Express Company",
             "price":"51",
             "change":"0.01",
             "pctChange":"0.02",
             "lastChange":"2007-10-26 00:00:00",
             "industryID":"4",
             "risk":"low",
             "stars":"2",
             "check":"1",
             "tax":3.06
          },
          {
             "companyID":"2034",
             "company":"American International Group, Inc.",
             "price":"10",
             "change":"0.31",
             "pctChange":"0.49",
             "lastChange":"2007-06-09 00:00:00",
             "industryID":"2",
             "risk":"high",
             "stars":"2",
             "check":"1",
             "tax":0.6
          },
          {
             "companyID":"146",
             "company":"AT&T",
             "price":"31.63",
             "change":"-0.48",
             "pctChange":"-1.54",
             "lastChange":"2007-12-25 00:00:00",
             "industryID":"8",
             "risk":"medium",
             "stars":"3",
             "check":"1",
             "tax":1.9
          },
          {
             "companyID":"2009",
             "company":"Boeing Co.",
             "price":"75.43",
             "change":"0.53",
             "pctChange":"0.71",
             "lastChange":"2007-08-01 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"3",
             "check":"1",
             "tax":4.53
          },
          {
             "companyID":"148",
             "company":"Caterpillar Inc.",
             "price":"67.27",
             "change":"0.92",
             "pctChange":"1.39",
             "lastChange":"2007-10-02 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"3",
             "check":"1",
             "tax":4.04
          },
          {
             "companyID":"2030",
             "company":"Citigroup",
             "price":"49.37",
             "change":"0.02",
             "pctChange":"0.04",
             "lastChange":"2007-10-05 00:00:00",
             "industryID":"3",
             "risk":"high",
             "stars":"3",
             "check":"0",
             "tax":2.96
          },
          {
             "companyID":"149",
             "company":"E.I. du Pont de Nemours and Company",
             "price":"10",
             "change":"0.51",
             "pctChange":"1.28",
             "lastChange":"2007-10-02 00:00:00",
             "industryID":"5",
             "risk":"low",
             "stars":"2",
             "check":"0",
             "tax":0.6
          }
       ],
       "success":true,
       "metaData":{
          "defaultSortable":true,
          "sortInfo":{
             "field":"id",
             "direction":"ASC"
          },
          "fields":[
             {
                "name":"id",
                "mapping":"companyID",
                "header":"ID",
                "align":"right",
                "width":40
             },
             {
                "name":"company",
                "editor":{
                   "xtype":"textfield",
                   "allowBlank":false
                },
                "fixed":false,
                "header":"Company",
                "hidden":false,
                "hideable":true,
                "locked":false,
                "mapping":"company",
                "sortable":true,
                "tooltip":"Click to sort",
                "width":170
             },
             {
                "name":"tax"
             },
             {
                "resizable":true,
                "name":"risk",
                "editor":{
                   "xtype":"combo",
                   "name":"risk",
                   "editable":false,
                   "forceSelection":true,
                   "lazyRender":true,
                   "listClass":"x-combo-list-small",
                   "mode":"local",
                   "triggerAction":"all",
                   "typeAhead":false
                },
                "fixed":false,
                "header":"Risk",
                "hidden":false,
                "hideable":true,
                "locked":false,
                "mapping":"risk",
                "renderer":"renderRisk",
                "sortable":true,
                "tooltip":"Click to sort",
                "width":70
             },
             {
                "name":"lastChange",
                "dateFormat":"Y-m-d H:i:s",
                "editor":{
                   "xtype":"datefield",
                   "allowBlank":false,
                   "selectOnFocus":true
                },
                "fixed":false,
                "header":"Last Change",
                "hidden":false,
                "hideable":true,
                "locked":false,
                "mapping":"lastChange",
                "renderer":"renderDateTime",
                "sortable":true,
                "tooltip":"Click to sort",
                "type":"date",
                "width":75
             }
          ],
          "id":"id",
          "root":"results",
          "start":0,
          "limit":10,
          "successProperty":"success",
          "totalProperty":"total"
       }
    }

  8. #8
    Ext User
    Join Date
    Jul 2007
    Location
    Florida
    Posts
    9,996

    Default

    Some day maybe I'll post my php backend that automates building the metaData on the backend.

    Here's a snippet from the php file:
    PHP Code:
    function getMeta() {
        
        
        
    // Define Collumns
        
    $readerRoot 'results';
        
    $readerId 'companyID'//update this dynamically since it will vary *************************
        
        
    $meta = array();
        
    $meta['defaultSortable'] = true;  //will be applied to column Model
        
    $meta['fields'] = getFields();
        
    $meta['id'] = $readerId;        
        
    $meta['root'] = $readerRoot;

        
    // You can optionally specify the column that the initially displayed grid is sorted on.  
        // If sortInfo is not specified, then whatever order the records are read into the store will
        // be the order it is displayed (so basically whatever order the server side sql query produces
        // will be the initial sort).
        // When configuring through meta data, sortInfo must be spent because it's reset by ext.
        
    $sortInfo = array('field'=>'company''direction'=>'ASC');
        
    $meta['sortInfo'] = $sortInfo;  

        
    $meta['successProperty'] = 'success';
        
    $meta['totalProperty'] = 'total';
        return 
    $meta;
    }

    function 
    getFields() {

        
    $fields = array();

        
    // ----------------------------------------------------------------------

        
    $fields[] = array(
            
    'name'=>'industryID',
            
    'align'=>'right',
            
    'editor'=>array(
                
    'xtype'=>'combo',
                
                
    //the underlying data field name to bind to this ComboBox (defaults to
                //undefined if mode = 'remote' or 'text' if transforming a select)
                
    'displayField'=>'industryName',//see store's 'fields' config property

                
    'editable'=>false,
                
    'forceSelection'=>true,
                
    //By enabling lazyRender this prevents the combo box from rendering until requested
                
                //this will keep the comboBox from reloading itself if it's already preloaded.
                
    'lazyRender'=>true,//should always be true for editor
                
                // Set mode to 'local' so that the ComboBox will think the data is local
                // instead of the default of 'remote' which will load data from the server
                // the first time the comboBox is selected.
                // A local store has the advantage that the first time the comboBox is selected
                // the data will already be there (there will not be any visual appearance of
                // waiting etc.).  This has the drawback however that the store will be loaded
                // even if the comboBox is never selected.  So you'll have to decide what situation
                // you like better. 
                
    'mode'=>'local',//default is 'remote'
                
                
    'sortInfo'=>array('field'=>'industryName''direction'=>'ASC'),

                
    //where to get the data for combobox
                
    'store'=>array(
                    
    'storeType'=>'SimpleStore',//will do new Ext.data.SimpleStore({}) on client
                    
    'config'=>array(
                        
    //id = the property within each row object that provides an ID for the record (optional)
                        //SimpleStore uses an ArrayReader. The ArrayReader uses this for the id (The subscript
                        //within row Array that provides an ID for the Record)
                        
    'id'=>0//array index of the record id.
                        
    'data'=>array(
                            array(
    1'Automotive'),
                            array(
    2'Computer'),
                            array(
    3'Finance'),
                            array(
    4'Food'),
                            array(
    5'Manufacturing'),
                            array(
    6'Medical'),
                            array(
    7'Retail'),
                            array(
    8'Services')
                        ),
                        
    //first item is valueField, second item is displayField
                        
    'fields'=>array('industryID''industryName'),
                        
                        
    //use the storeId to later reference this store using the StoreMgr
                        
    'storeId'=>'industry'
                    
    ), // end config
                
    ), // end editor
                
    'triggerAction'=>'all',
                
    //if we enable typeAhead it will be querying database
                //so we may not want typeahead consuming resources
                
    'typeAhead'=>false,

                
    //the underlying value field name to bind to this ComboBox
                
    'valueField'=>'industryID',//see store's 'fields' config property
            
    ),
            
    'filter'=>array(
                
    'type'=>'string'
            
    ),
            
    'header'=>'Industry',
            
    'hidden'=>false,
            
    'locked'=>false
            
    'renderer'=>'industry',
            
    'sortable'=>true,
            
    'resizable'=>true
            
    'tooltip'=>'comboBox is based on client side data (from html)'
            
    'type'=>'string'
            
    'width'=>70
        
    ); 

  9. #9
    Sencha User
    Join Date
    Aug 2007
    Posts
    100

    Default

    Excelent mjlecomte!! Thank you very much! This is exactly the working example I was looking for. I have your example running now, and I'm actually starting to understand the script, thanks to the very usefull comments.

    Time to integrate it into my application! I'm sure that will work

    Thanks again for helping me out here!

    -Michiel

  10. #10
    Sencha User
    Join Date
    Aug 2007
    Posts
    100

    Default

    I've almost got it working now. I've inserted the grid inside a tabpabanel in my application. I can get the data to load in the grid, but only after I hit the refresh button. Before that no data, and no colums are visible. Just the bottom bar .. FireBug shows the data is actually loaded though.

    Any trick to show the data instantly, without the need to refresh?

    Thanks!

Page 1 of 9 123 ... LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •