October 11, 2010

DataGrid V2

Some of you may remember a post that I made a little while ago outlining that I had migrated the MySqlDataGrid class that I was working on to a single DataGrid which accepts a multi-dimensional array as a data source. I’ve further updated that class (while dropping a bit of functionality sadly) but I think I’ve made it a lot easier to work with and also added some pretty neat features.

– Update –
The full code is now packaged and been accepted on PHP Classes. From there you can download the files, view the examples and even post any bugs or questions you might have. You do not require an account to download the files, but I would recommend getting one anyways. PHPClasses really does have a lot of useful things on it, but a lot of users stick with the default “must be a member to download files” option for a lot of them.

The class allows you to create a simple table, and purely by providing a few configuration options, you can create a standards compliant HTML table. So say you have an array that looks like this:

<?php
$data = array(
    array(
        'uid' => 0,
        'username' => 'Angelo',
        'password' => 'mypass2',
    ),
    array(
        'uid' => 1,
        'username' => 'Rodrigues',
        'password' => 'dd9j2v2v',
    ),
);?>

And have it display the data in a tabular format. You can control what columns are displayed, in what order, and you can even insert new columns before or after any other one. It even supports the idea of “hashes”. Basically, by including {uid} as the value for an added column you reference the particular UID of that row. It’s a little confusing in words, but by example it makes a lot more sense.

What I’m doing below is simple setting the data source for the DataGrid to our $data array defined above. I am then going to tell it that I want to display the fields UID and username, but I am going to change the name that is being displayed. As in, insteadof uid in lower case, I am going to call the column “User ID”. I am then going to add a column after the username field, with an edit button.

<?php 
$dg = new DataGrid(); 
$dg->dataSource($data); 
$dg->fields(
    array(
        'uid' => 'User ID',
        'username' => 'User Name'
    )
);
$dg->addField('Actions','actions','<a href="index.php?uid={uid}">Edit</a>',array('after'=>'username'));
 
$dg->render(); ?>

That will do all that I mentioned above and then create and display the table. You can play a column before or after any other column, but you must provide a display name, a “safe name” (no spaces or special characters), a value for the new field and the position (before or after). Render will directly create and display the table, but a call to build() will just create the HTML and pass it back to you for you to use as well.

http://www.phpclasses.org/package/6542-PHP-Display-data-listings-in-an-HTML-table.html

Leave a Reply