Column Formatter

Column Formatter – What can I do with the column formatter?

Description

The column formatter method can be a very powerful solution to a very common need. The need is to customize the output for a cell in the grid such as a link for a form element. This can be easily done by specifying a "callback" function. This function will then return the string that is needed to be printed.

Using the column formatter

<?php
require_once 'Structures/DataGrid.php';

$dg =& new Structures_DataGrid();
$result $dg->bind('http://pear.php.net/feeds/pkg_structures_datagrid.rss');
if (
PEAR::isError($result)) {
    die(
'An error occured while fetching the RSS information.');
}

$dg->addColumn(
    new 
Structures_DataGrid_Column('Release''title''title',
                                   
nullnull'printLink')
);
$dg->addColumn(
    new 
Structures_DataGrid_Column('Description''description',
                                   
'description'nullnull,
                                   
'printDesc', array('length' => 15))
);
$dg->addColumn(
    new 
Structures_DataGrid_Column('Date''dc:date''dc:date')
);
$dg->render();

function 
printLink($params$args = array())
{
    
extract($params);
    
extract($args);

    return 
'<a href="' $record['link'] . '">' $record['title'] . '</a>';
}

function 
printDesc($params$args = array())
{
    
extract($params);
    
extract($args);

    if (
strlen($record[$fieldName]) > $length) {
        return 
nl2br(substr($record[$fieldName], 0$length)) . '...';
    } else {
        return 
nl2br($record[$fieldName]);
    }
}
?>

Each callback function needs to accept at least one parameter ($params in the example above). This parameter will contain various information:

  • 'record': An array containing the complete current record

  • 'fieldName': The field name of the current column

  • 'columnName': The column name of the current column

  • 'orderBy': The 'orderBy' argument of the current column

  • 'attribs': The attributes of the current column

  • 'currRow': The number of the current row

  • 'currCol': The number of the current column

An optional second parameter ($args in the example) allows you to pass additional information to the callback functions. In the example above, an array with length information is passed when the callback function printDesc() is called for the description column. Please note that this second parameter is only passed when you specify something in the column constructor. Therefore, it is a good practice to use $args = array() in the parameter list of your callback functions.