5,693,062 members and growing! (20,575 online)
Email Password   helpLost your password?
Web Development » Client side scripting » General License: The Code Project Open License (CPOL)

Dynamic bound DataGrid with ExtJS

By Paul Coldrey

Changing Datagrid bound data on the fly
Javascript, CSS, HTML, XHTML, Ajax, ASP, ASP.NET

Posted: 23 Jul 2008
Updated: 23 Jul 2008
Views: 8,064
Bookmarked: 4 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
3 votes for this Article.
Popularity: 1.59 Rating: 3.33 out of 5
1 vote, 33.3%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
1 vote, 33.3%
4
1 vote, 33.3%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

ExtJS is really cool library generating fancy looking GUI apps in Javascript. I started using ExtJS for a bunch of database frontends and found that I needed to have a DataGrid that would change its contents based on and AJAX call that filtered data based on some search parameters.

Notionally this was easy enough and it appeared there may be many ways to make this happen. As it turns out there is one right way and many - seemingly plausible - options that don't work.

After extracting this functionality from a few posting that were doing far more impressive things and trawling through the documentation I figured it might be helpful to post a bare-bones example of this funcationality to make it easy for the next ExtJS newb who finds themselves wanting to do the same thing.

Using the code

The Javascript/ExtJS portion looks like this:

Ext.onReady(function(){
    Ext.QuickTips.init();

    var proxy = new Ext.data.HttpProxy({
        url: 'demo.data.php',
    method: 'post'
    });

    var dstore = new Ext.data.JsonStore({
    url: 'demo.data.php',
    proxy: proxy,
    fields: ['id', 'data'],
    totalProperty: 'totalCount',
    root: 'matches'
    });
    dstore.load();

    var grid = new Ext.grid.GridPanel({
    store: dstore,
        columns: [
        {id:'id', header: "Id", width: 60,  sortable: true, dataIndex: 'id'},
        {id: 'data', header: "Data", width: 200, sortable: true, dataIndex: 'data'}
        ],
        stripeRows: true,
        autoExpandColumn: 'data',
        height:350,
        width: 500,
        title:'Demo Data'
    });

    var search = new Ext.FormPanel({
        labelWidth: 150, 
        frame:true,
        title: 'Search Demo Data',
        bodyStyle:'padding:5px 5px 0',
        width: 500,
        defaults: {width: 230},
        defaultType: 'textfield',
        items: 
    [{
            fieldLabel: 'Search regular expression',
            name: 'pattern',
        id: 'pattern'
    }],
    buttons: [{
            text: 'Search',
        handler: function() {
        dstore.load({
            params: {
            pattern: document.getElementById('pattern').value
            }});
        
        }
        }]
    });

    search.render('search_form');
    grid.render('search_results');
});

The backend datasource (which happens to be from PHP) looks like this:

<?php
$items = Array(Array('id'=>1, 'data' => 'the first item'),
           Array('id'=>2, 'data' => 'the second item'),
           Array('id'=>3, 'data' => 'one fish'),
           Array('id'=>4, 'data' => 'two fish'),
           Array('id'=>5, 'data' => 'red fish'),
           Array('id'=>6, 'data' => 'blue fish')
           );

$matches = Array();

if(!isset($_REQUEST['pattern']) || $_REQUEST['pattern'] == '') {
  $matches = $items;
} else {
  foreach ($items as $item) {
    if (eregi($_REQUEST['pattern'], $item['data'])) {
      $matches[] = $item;
    }
  }
}

echo json_encode(Array('totalCount' => count($matches),
             'matches' => $matches
             )
           );

?> 

The HTML file (that really is just the standard stuff) is included in the ZIP file.

Points of Interest

MySQL/PHP backend data source

For those looking to load database data (probably MySQL for PHP folk) into and ExtJS JSONStore, the PHP file supplies most of what you need to know. Basically you want an array of data that you then encode with json_encode(...). For MySQL building the data would look a bit like:

$data = Array(); 
$qry = mysql_query("SELECT id, description FROM ...");
while ($vals = mysql_fetch_array($qry)) {
  $data[] = Array('id' => $vals['id'], 'description' => $vals['description'];
} 
echo  json_encode($data); 

Paging control on DataGrid

If you are using a paging control on the grid then you will want the parameters that are sent to the DataStore to persist between calls (ie for when they press the paging buttons to retrieve the next page of data). To do this you need to set the baseParams property on the datastore rather than sending parameters via the params object of the load(...) call. A real world example is shown below:

function search_submit() {
  dstore.baseParams = {
      number: document.getElementById('number').value,
      title: document.getElementById('title').value,
      keywords: document.getElementById('keywords').value,
      typeid: document.getElementById('typeid').value,
      allversions: (document.getElementById('allversions').checked) ? 1 : 0,
    };
  dstore.load({
    params:  {
      start: 0,
      limit: 25
    }
  });
} 

HIstory

24-Jul-2008 - PJC - First posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Paul Coldrey


Paul runs his own business providing software design and development services. By choice he would live in a Linux world but a large proportion of his work is done using Microsoft technologies.
Occupation: Software Developer (Senior)
Company: Lumient
Location: Australia Australia

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralNice articlememberanil_mane21:49 28 Jul '08  
GeneralRe: Nice articlememberPaul Coldrey22:03 28 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jul 2008
Editor:
Copyright 2008 by Paul Coldrey
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project