July 15, 2010

DataGrid Control V2

I’ve been working on a series of “Control Objects” to include in my usual projects, and I thought I’d post one of the completed ones up here. Basically it mimcs the use of the DataGrid control in Visual Studio but in a way I find a lot easier and more in-tune with PHP. After creating the DataGrid, you define a “source”. The Source is essentially a multi-dimensional array that you could assign with a simple

while($r[] = mysql_fetch_array($resource)){}

you would then pass $r as the source to the DataGrid. You have the ability to set some options (like specifying specific style sheets, JS libraries for AJAX editing or defining and renaming visible columns) and then a single build(); command will output the table. Of course, you can also build(true); to return the table incase you’re using some sort of theme system.

$data = array(
  array('id'=>0,'f_name'=>'Angelo','l_name'=>'Rodrigues'), 
  array('id'=>1,'f_name'=>'Darth','l_name'=>'Vader'),
  array('id'=>2,'f_name'=>'Luke','l_name'=>'Skywalker'),
  array('id'=>3,'f_name'=>'Han','l_name'=>'Solo'),
);
 
$DataGrid = new DataGrid(); 
$DataGrid->configure(
  array(
    'primary_key' => 'id', 
    'sortable' => true, 
    'striped' => true,
    'even_row' => null, 
    'odd_row' => 'striped'
    )
);
 
// This not only defines display fields, but the order as well 
$fields = array( 
  'f_name' => 'First Name',
  'l_name' => 'Last Name',
);
$DataGrid->setDisplayFields($fields);
$headers = $DataGrid->Headers();
echo $headers['css']; 
echo $headers['js']['object'];
echo $headers['js']['function'];
 
 
$DataGrid->source($data); 
$DataGrid->build();

The code can be further simplified by using a new class called ControlObjectManager (or COM for short). COM can be used to instantiate multiple Controls at once and even assign shortcuts to commonly used Controls. For example, if you need DataGrids a lot, you can initiate them via a simple call like $COM->init(array('dg')) and as long as you set up that dg means DataGrid in the configuration for COM, you’re good to go.

I’ll post up some more on the COM when it’s done, but for now, here’s a link to the latest iteration of DataGrid v2.

View on Pastebin – Just note that this is the debug version of the script, so there are tons of comments and explanations.

The original DataGrid actually tied in to MySql directly and required the MySqlAdapter control to even function. This latest iteration removes all ties to any database instead focusing on a simple multi-dimensional array of data. As well it drops the code-base down quite a bit and condenses a lot of functionality. For example: originally you would have had to set the display columns and then order them, but by compressing them into a single function it not only makes MORE sense, but is easier to read.