PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » Structures » Structures_DataGrid » Manual

Structures_DataGrid is a class for building, manipulating and rendering a tabular structure of data. It has the ability to allow you to render a datagrid in HTML format as well as many other formats such as an XML Document, an Excel Spreadsheet, an XUL Document and more. It also offers paging and sorting functionality to limit the data that is presented. This concept is based on the .NET Framework DataGrid control and works very well with database and XML result sets.

Introduction and Features

Introduction

Introduction – What can I do with Structures_DataGrid?

Description

Structures_DataGrid is a package with the purpose of rendering a data set into a tabular structure in a specific output format. Possible output formats are (X)HTML, XML, XUL, Excel .xls spreadsheets, CSV, or console tables.

The input data format is independent of the underlying data storage layer: It does not matter if the data has been selected from a database, has been harvested from plain text files or converted from a web service call. The data can be sorted and paged, and each cell of the table can have a custom look by using CSS for the HTML output.

Where to start

So to begin, you will want to find a datasource, commonly you might use a Database like MySQL or an XML document. You can then easily bind this datasource to the datagrid, to do so you have 3 options. The first, is to fetch your data into a 2 dimension array and pass it into the bind method. The second way is to bind a record set that is not already an array, such as a DB_DataObject or a DB_Result object. To do so, you can use the bindDataSource method by creating a DataSource object. The third way is to loop through your record set and add each record individually, this practice is the least efficient.

If you bind the datagrid to a datasource that is an object such as a DB_DataObject, you do not need to fetch the data as the DataGrid will handle that for you.

Render the output

Once your datagrid has been populated with your records, you have many options on how to manipulate what is to be shown. You can sort the data, choose to show only a certain amount of data per page and also choose what format the data should be rendered into. You can render the datagrid in many formats including HTML.

FAQ

FAQ – Answers to most Frequently Asked Questions

Description

This document is based on questions asked on PEAR general mailing list and other mailing lists and forums.

Structures_DataGrid FAQ

  1. I'm using the HTML_Table Renderer. How can I use multiple grids on the same page?
  2. Which DataSource drivers are recommended?
  3. I'd like to add row numbers to my DataGrid. How can I do this?
  4. I'm using the Excel Renderer and would like to have the € sign in the resulting Excel file, but I always get only a box or some funny characters. How can I get the right € sign?
  5. Streaming is a nice feature. Why isn't streaming the default behaviour?
  6. I have used $renderer->toHtml(); with older versions of Structures_DataGrid, but this does not work anymore. How can I fix my code?
  7. All the rows are displayed on one page. Why isn't it paging the data?
  8. Sorting doesn't work with MDB2 DataSource driver if I have column names in uppercase letters. Why?
I'm using the HTML_Table Renderer. How can I use multiple grids on the same page?

The setRequestPrefix() method is the solution for this problem. Each DataGrid for the page needs such a prefix that is internally used before the GET parameters for sorting and paging. An example of the usage:

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

$datagrid1 = new Structures_DataGrid();
$datagrid2 = new Structures_DataGrid();

$datagrid1->setRequestPrefix('trade_');
$datagrid2->setRequestPrefix('stock_');

$datagrid1->bind('SELECT * FROM trade', array('dsn' => DSN));
$datagrid2->bind('SELECT * FROM stock', array('dsn' => DSN));

$datagrid1->render();
$datagrid2->render();
?>

You need to call setRequestPrefix() before calling bind().

Which DataSource drivers are recommended?

Currently there are five DataSource drivers that are recommended in the sense of efficiency:

  • DB_DataObject
  • DB_Table
  • DBQuery
  • MDB2
  • PDO

These four drivers will only fetch the needed records from the database. For example, if you have a row limit of 15 records per page, they will only fetch (up to) 15 records.

All other DataSource drivers can, of course, also be used. But there is no logic implemented (better said: implementable) to avoid fetching (or keeping in memory) unneeded records.

I'd like to add row numbers to my DataGrid. How can I do this?

You need a formatter for the new column that should hold the row number. The first parameter that is passed to such a formatter function contains a currRow value with the row number per page. For calculating the row number relative to the whole table, you need to take also the getCurrentRecordNumberStart() method into account.

The following code snippet shows you how to define the formatter function and how to add the column (with # as the column label and right aligned values):

<?php
function formatRowNumber($params, $recordNumberStart)
{
    return $params['currRow'] + $recordNumberStart;
}

$datagrid->addColumn(
    new Structures_DataGrid_Column(
        '#',
        null,
        null,
        array('style' => 'text-align: right;'),
        null,
        'formatRowNumber',
        $datagrid->getCurrentRecordNumberStart()
    ));
?>
I'm using the Excel Renderer and would like to have the € sign in the resulting Excel file, but I always get only a box or some funny characters. How can I get the right € sign?

Instead of using an encoding like ISO-8859-15, you need to use Windows-1252.

Streaming is a nice feature. Why isn't streaming the default behaviour?

Streaming support in Structures_DataGrid is intended to be used with large datasets. But it can also be used with very small datasets without loss of performance.

As always, there is an exception to this rule: When you're using one of the DataSource drivers that fetch data from a database and you have queries that need a lot of time for computation of the results, you should not use streaming, as running such a complex query multiple times will need even more time, of course.

I have used $renderer->toHtml(); with older versions of Structures_DataGrid, but this does not work anymore. How can I fix my code?

If you just want to output the HTML code, use the following line of code:

<?php
$datagrid->render()
?>

If you want to get the generated HTML code, e.g. for using it within a template, use the following line of code:

<?php
$html = $datagrid->getOutput();
?>
All the rows are displayed on one page. Why isn't it paging the data?

Don't forget to pass the number of rows per page to the constructor:

<?php
$datagrid =& new Structures_DataGrid(10); // 10 rows per page
?>
Sorting doesn't work with MDB2 DataSource driver if I have column names in uppercase letters. Why?

This is caused by MDB2's portability settings that are enabled by default. The MDB2_PORTABILITY_FIX_CASE setting is set to CASE_LOWER, resulting in lowercased letters for all column names. Disable this or all portability settings of MDB2 to avoid sorting problem with Structures_DataGrid.

Installation

Installation – How to install the core and drivers packages

Introduction

If you are not familiar with PEAR, we recommend that you first read the PEAR general installation instructions

Structures_DataGrid uses drivers that are provided separately. It means that installing the core package named Structures_DataGrid is not enough to get something working.

Installation steps

You will at least need one DataSource driver, for handling the input, and one Rendering driver (or Renderer), for the output.

The following commands will install the core package, as well as the MDB2 DataSource (for binding SQL queries), HTML_Table Renderer and the Pager renderer (for paging links). That should cover your most common needs.

$ pear install -o Structures_DataGrid
$ pear install -o Structures_DataGrid_DataSource_MDB2
$ pear install -o Structures_DataGrid_Renderer_HTMLTable
$ pear install -o Structures_DataGrid_Renderer_Pager
  

If you get an error message like Failed to download pear/Structures_DataGrid within preferred state "stable", latest release is [...], you can simply append -beta to the package name, for example:

$ pear install -o Structures_DataGrid-beta
   

Of course, you may want to use other input/output formats, such as XML, MS Excel, DB_DataObject, XUL, etc... Just install the corresponding drivers.

Advanced installation

It is possible to install all DataSource drivers or all Renderer drivers at once. The following two commands will install Structures_DataGrid and either all DataSource or all Renderer drivers at once.

$ pear install Structures_DataGrid-beta#datasources
$ pear install Structures_DataGrid-beta#renderers
   

Please note that the individual drivers will be installed only if the requirements are fulfilled. That means that the MDB2 DataSource won't be installed if you don't have MDB2 installed. The same holds for the Excel Renderer if you don't have Spreadsheet_Excel_Writer installed.

Of course, the same holds for the uninstallation. For example:

$ pear uninstall Structures_DataGrid-beta#datasources
$ pear uninstall Structures_DataGrid-beta#renderers
   

DataSources

DataSources – What is a DataSource driver?

Description

A DataSource has a rather self-explanatory name; however, a DataSource driver in context to the DataGrid can become a very essential key to your software. A DataSource driver will interact with your data source directly, such as a DB_DataObject or a MDB2 query and handle all of the paging and sorting code for you, resulting in very few lines of code that you will need to write.

How to use the drivers

There are two methods intended to be used for binding a DataSource driver: bind() and bindDataSource().

The bind() method is able to autodetect the right driver in many cases. For example, you can pass DB_Table or DB_DataObject instances to it. Strings can't be autodetected because they could contain CSV or XML data, for example. In such cases, you can specify the type as the third parameter in the bind() method call (e.g. 'CSV' or 'XML').

If you are building your own custom DataSource driver, using bindDataSource() is the method of choice. Just instantiate your DataSource class and pass this instance to the bindDataSource() method.

Currently available DataSource drivers

A list with the currently available DataSources can be found on the overview page.

Please also note the following FAQ entry: Which DataSource drivers are recommended?

Rendering the output

Rendering the output – What formats can I render the output?

Description

The DataGrid offers the ability to build out your data in a grid format in an HTML table, which is the most common method due to the nature of PHP. However, the DataGrid offers many other ways of outputting the tabular data structure such as an Excel spreadsheet or an XML document.

How do I change the renderer?

To use a different renderer other than the HTML_Table renderer, you can specify the name of the renderer (e.g. 'CSV', 'Pager' or 'XML') as the first parameter of the fill(), getOutput(), and render() methods. Another possibility is to use setRenderer() method. The old way of using the third parameter of the constructor to define the renderer is deprecated since version 0.7.0.

Currently available renderers

A list with the currently available renderers can be found on the overview page.

Streaming

Streaming – How to stream large recordsets

Description

Large recordsets can exceed PHP's memory limit. Structures_DataGrid offers streaming support with many DataSource drivers and some Renderer drivers to avoid problems with the memory limit.

How do I use streaming?

Streaming can be enabled by calling the enableStreaming() method of the Structures_DataGrid object. An optimal parameter allows to set the number of records that should be read and written on each stream iteration. The default buffer size is 500 records.

Once streaming is enabled, only up to the number of records specified in the buffer size records will be fetched and rendered. This will be repeated until this was done for all records.

Enabling streaming with buffer size of 1,000 records

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

// Instantiate the DataGrid
$datagrid =& new Structures_DataGrid();

// Enable streaming and set buffer size to 1,000 records
$datagrid->enableStreaming(1000);

// ... e.g. bind(), render() calls as usual
?>

Driver support for streaming

Although streaming can be used with every DataSource driver, only the following drivers support streaming in a meaningful way: DataObject, DBQuery, DB_Table and MDB2. Streaming support is planned to be added also to the CSV and XML DataSources.

Streaming support is also compatible with every Renderer driver but can currently be used only with CSV and XML Renderers in a meaningful way. Other Renderers might be rewritten in the future for streaming support.

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',
                                   null, null, 'printLink')
);
$dg->addColumn(
    new Structures_DataGrid_Column('Description', 'description',
                                   'description', null, null,
                                   '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:

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.

Example - Quick

Example - Quick – Quickly retrieve data from a database table

Description

Binding an SQL query

To retrieve the data that the datagrid will display you can begin by passing a simple SQL statement to the bind() method.

Using an SQL query as datasource

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

// Instantiate the DataGrid
$datagrid =& new Structures_DataGrid();

// Setup your database connection
$options = array('dsn' => 'mysql://user:password@host/db_name');

// Bind a basic SQL statement as datasource
$test = $datagrid->bind('SELECT * FROM my_table', $options);

// Print binding error if any
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

// Print the DataGrid with the default renderer (HTML Table)
$test = $datagrid->render();

// Print rendering error if any
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

?>

If you are familiar with the SQL language you'll certainly find many ways to adapt the above example to your needs, using more complex queries.

You can also page through your dataset with the automatic paging feature as shown below. This feature transparently adds LIMIT clauses to your SQL statement, providing optimized database access.

Automatic paging

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

// 10 records per page
$datagrid =& new Structures_DataGrid(10);

// Setup your datasource
$options = array('dsn' => 'mysql://user:password@host/db_name');
$test = $datagrid->bind("SELECT * FROM my_table", $options);
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

// Print the DataGrid with the default renderer (HTML Table)
$test = $datagrid->render();
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

// Print the HTML paging links
$test = $datagrid->render(DATAGRID_RENDER_PAGER);
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

?>

Example - Complex

Example - Complex – How to build a datagrid using many of the features

Description

An interface to a User Management System

This example will show you how to create an interface to a User Management System using the DB_DataObject package to handle the database aspects of this example.

User Management System Example

<?php
require_once 'Structures/DataGrid.php';
require_once 'HTML/Table.php';
require_once 'myclasses/User.php';

// Instantiate the DataObject; that's our DataSource container
$user = new User_DataObject();

// Create the DataGrid
$datagrid =& new Structures_DataGrid(20); // Display 20 records per page

// Specify how the DataGrid should be sorted by default
$datagrid->setDefaultSort(array('lname' => 'ASC'));

// Bind the DataSource container 
$test = $datagrid->bind($user);
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}

// Define columns
$datagrid->addColumn(new Structures_DataGrid_Column(null, null, null, array('width' => '10'), null, 'printCheckbox()'));
$datagrid->addColumn(new Structures_DataGrid_Column('Name', null, 'lname', array('width' => '40%'), null, 'printFullName()'));
$datagrid->addColumn(new Structures_DataGrid_Column('Username', 'username', 'username', array('width' => '20%')));
$datagrid->addColumn(new Structures_DataGrid_Column('Role', null, null, array('width' => '20%'), null, 'printRoleSelector()'));
$datagrid->addColumn(new Structures_DataGrid_Column('Edit', null, null, array('width' => '20%'), null, 'printEditLink()'));

// Define the Look and Feel
$tableAttribs = array(
    'width' => '100%',
    'cellspacing' => '0',
    'cellpadding' => '4',
    'class' => 'datagrid'
);
$headerAttribs = array(
    'bgcolor' => '#CCCCCC'
);
$evenRowAttribs = array(
    'bgcolor' => '#FFFFFF'
);
$oddRowAttribs = array(
    'bgcolor' => '#EEEEEE'
);
$rendererOptions = array(
    'sortIconASC' => '&uArr;',
    'sortIconDESC' => '&dArr;'
);

// Create a HTML_Table
$table = new HTML_Table($tableAttribs);
$tableHeader =& $table->getHeader();
$tableBody =& $table->getBody();

// Ask the DataGrid to fill the HTML_Table with data, using rendering options
$test = $datagrid->fill($table, $rendererOptions);
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}


// Set attributes for the header row
$tableHeader->setRowAttributes(0, $headerAttribs);

// Set alternating row attributes
$tableBody->altRowAttributes(0, $evenRowAttribs, $oddRowAttribs, true);

// Output table and paging links
echo $table->toHtml();

// Display paging links
$test = $datagrid->render(DATAGRID_RENDER_PAGER);
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}


function printCheckbox($params)
{
    extract($params);
    return '<input type="checkbox" name="idList[]" value="' . $record['id'] . '">';
}
function printFullName($params)
{
    extract($params);
    return $record['fname'] . ' ' . $record['lname'];
}
function printRoleSelector($params)
{
    global $roleList;

    extract($params);
    
    $html = '<select name="role_id">';
    foreach ($roleList as $roleId => $roleName) {
        $html .= "<option value=\"$roleId\">$roleName</option>\n";
    }
    $html .= '</select>';
    
    return $html;
}
function printEditLink($params)
{
    extract($params);
    return '<a href="edit.php?id=' . $record['id'] . '">Edit</a>';
}
?>

Custom DataSources

Custom DataSources – How to write your own DataSource driver.

Introduction

Writing your own DataSource driver is the way to go when none of the existing driver suit your needs. It is actually pretty easy, and allows for great flexibility.

Of course, if you're trying to fetch data from an exotic source, writing your own driver is required. But, sometimes it's also the best way to achieve the best optimization, especially (but not only) with databases.

This document will present you the DataSource interface, and how to implement it.

Definitions

A DataSource driver is a descendent of the Structures_DataGrid_DataSource class, which implements the DataSource interface.

DataSource is a synomym for DataSource driver.

The DataSource interface consists in a set of methods that drivers must or may overload and protected properties that drivers can use, as well as recommended practices.

A DataSource container is a constant or a variable of any type (string, array, object, etc...) that either contains data or describes how to retrieve data.

Every DataSource driver is specific to, and knows how to handle, a given DataSource container type.

The DataSource interface

Properties available to drivers

array $_options - Data binding options as an associative array. You can read the content of this property but you shouldn't change it directly.

Methods that must or may be implemented in drivers

constructor ( void )

The constructor must set default options, if any, and call the parent constructor. This method is optional.

object bind ( mixed container , array options )

bind() is reponsible for loading a DataSource container into the driver, according to some binding options. This method is optional. It must return a PEAR_Error object in case of failure.

object count ( void )

count() must return the total number or records found in the container. This method is required, and is always called before fetch(). It must return a PEAR_Error object in case of failure.

object sort ( mixed sortSpec , array sortDir )

sort() must sort the data according to sortSpec and the optional sortDir. This method is required, and is always called before fetch(). It must return a PEAR_Error object in case of failure.

mixed fetch ( integer offset , integer len )

fetch() must return a 2-dimension array of data, starting from record offset, containing len records..This method is required It must return a PEAR_Error object in case of failure.

Protected methods that drivers can use

void _addDefaultOptions ( array options )

_addDefaultOptions() is used to declare the driver-specific options, if any, as well as their default values. It must be called from the constructor.

void setOptions ( array options )

setOptions() is a public method used to set options. If they ever need to change options, drivers should use this method.

A simple driver

Let's start with a very simple driver. It is rather readable and you shouldn't have much trouble understanding it. It is not extremely useful to write a custom driver for a such simple SQL query, but it should get you started.

A simple SQL adaptor

<?php
require 'Structures/DataGrid/DataSource.php';
require_once 'DB.php';

class MyDataSource extends Structures_DataGrid_DataSource {
 
    var $db;
    var $orderBy = '';
 
    function MyDataSource() {
        $dsn = 'mysql://someuser:apasswd@localhost/thedb';
        $this->db =& DB::connect($dsn);
    }

    function count() {
        $query = "SELECT COUNT(*) FROM animals WHERE species='cat'";
        return $this->db->getOne($query);
    }

    function sort($sortSpec, $sortDir = 'ASC') {
        $this->orderBy = "ORDER BY $sortSpec $sortDir"; 
    }

    function fetch($offset = 0, $len = null) {
        
        $limit = is_null($len) ? "LIMIT $offset,18446744073709551615" 
                               : "LIMIT $offset,$len";
    
        $query  = "SELECT * FROM animals WHERE species='cat' ";
        $query .= $this->_orderBy . " $limit";

        return $this->db->getAll($query);
    }
}

?>

Testing your driver

Before going live, it is very recommended to test your driver with the dump() method.

Testing with dump()

<?php
$datasource = new MyDataSource();

$count = $datasource->count();
echo "There are $count cats in the farm\n\n";

$datasource->sort('weight');

echo "Here are the 5 lightest ones: \n";

// dump() accepts the same $offset and $len argument as fetch()
$datasource->dump(0,5);
?>

That should output a nicely formated ascii table like:

     
     
There are 23 cats in the farm.

Here are the 5 lightest ones:
+---------+---------+-----------+--------+
| name    | species | birthDate | weight |
+---------+---------+-----------+--------+
| sarge   | cat     | 20021220  | 1.8    |
| etch    | cat     | 20000509  | 2.5    |
| potato  | cat     | 19980128  | 3.8    |
| sid     | cat     | 20011101  | 4.1    |
| woody   | cat     | 19970712  | 6.0    |
+---------+---------+-----------+--------+
     

Using your new driver

Okay, so you have written a driver that's tailored to your needs, and tested it. It is now time to connect it to Structures_DataGrid.

For this purpose we're going to use the bindDataSource() method.

Binding a custom datasource

<?php

$datagrid =& new Structures_DataGrid(); 

$datasource = new MyDataSource();

$datagrid->bindDataSource($datasource);

$datagrid->render();
?>

That should output a sortable HTML table.

Of course, the usual features of Structures_DataGrid are now available to you: paging, other output formats as XML, MS-Excel, etc...

Custom Renderers

Custom Renderers – How to write your own Rendering driver.

Introduction

Writing your own Renderer allows you to fine tune every aspect of Structures_DataGrid output.

You may need to output the datagrid in a completely unsupported format. Then writing your own Renderer is the only option

But you may also need a unsupported variant of an existing renderer, say, for example, a very specific HTML output. In this case, you generally have two options : either writing a Rendering driver from scratch, or customizing (subclassing) an existing one.

This document will present you the Rendering driver interface, and how to implement it. You will certainly see how flexible Structures_DataGrid can become with custom Renderers, but also how easy we have to tried to make this process.

Definitions

A Rendering driver is a descendent of the Structures_DataGrid_Renderer class, which implements the Renderer interface.

Renderer is a synomym for Rendering driver.

The Renderer interface consists in a set of methods that drivers must or may overload and protected properties that drivers can use, as well as recommended practices.

A Rendering container is either an object that contain a sort of rendering engine, or a variable of any type (string, array, object, etc...) that can contain the output of a Renderer.

A Renderer with Container Support driver is specific to, and knows how to handle, a given type of Rendering container.

A driver is said to provide Container Support when it is able to handle a given type of Rendering container. Drivers with Container Support must implement the setContainer() and getContainer() public methods. They must be able to use a Rendering container provided by the user with setContainer(). They must also be able to create and intialize a Rendering container if the user does not provide any.

A driver is said to provide Output Buffering when it buffers the output that it generates, implements the flatten() method and is able to return the generated output from flatten().

A Direct Rendering driver is the simplest form of Renderer. It directs all of its output to standard output. By definition, a such driver neither provide Container support nor Output Buffering

The Renderer interface

Protected properties available to drivers

All of the following properties are read-only : drivers can access their content but must not change it directly.

array $_options -Common and driver-specific options

array $_columns - Columns fields names and labels

int $_columnsNum - Number of columns

array $_records - Records content

int $_recordsNum - Number of records in the current page

int $_totalRecordsNum - Total number of records as reported by the datasource

int $_firstRecord - First record number (starting from 1), in the current page

int $_lastRecord - Last record number (starting from 1), in the current page

int $_page - Current page number (starting from 1)

int $_pageLimit - Number of records per page

int $_pagesNum - Number of pages

string $_requestPrefix - GET/POST/Cookie parameters prefix

array $_currentSort - Fields/directions the data is currently sorted by

array $_sortableFields - Which fields the datagrid may be sorted by

Methods that must or may be implemented in drivers

All of the following methods are optional.

constructor ( void )

The constructor must set default options via _addDefaultOptions(), if any, and call the parent constructor.

object setContainer ( mixed container )

setContainer() is responsible for attaching a rendering container provided by the user. It must return a PEAR_Error object in case of failure.

object getContainer ( void )

getContainer() must return a reference to the container used by the driver. It must return a PEAR_Error object in case of failure.

void init ( void )

init() must initialize the rendering process. This method is also responsible for creating the container if it has not already been provided with setContainer().

void buildHeader ( array columns )

buildHeader() must build the header. $columns is a convenient reference to the $_columns property.

Protected methods that drivers can use

void _addDefaultOptions ( array options )

_addDefaultOptions() is used to declare the driver-specific options, if any, as well as their default values. It must be called from the constructor.

void setOptions ( array options )

setOptions() is a public method used to set options. If they ever need to change options, drivers should use this method.

A simple driver

Soon

Testing your driver

Soon

Using your new driver

Soon

Class Structures_DataGrid

constructor Structures_DataGrid::Structures_DataGrid

constructor Structures_DataGrid::Structures_DataGrid() – Constructor

Synopsis

require_once 'Structures/DataGrid.php';

void constructor Structures_DataGrid::Structures_DataGrid ( string $limit = null , int $page = null , string $rendererType = null )

Description

Builds the DataGrid class. The Core functionality and Renderer are separated for maintainability and to keep cohesion high.

Parameter

string $limit

The number of records to display per page.

integer $page

The current page viewed. In most cases, this is useless. Note: if you specify this, the "page" GET variable will be ignored.

string $rendererType

The type of renderer to use. You may prefer to use the $type argument of render() , fill() or getOutput()

Throws

throws no exceptions thrown

Examples

Instantiation

<?php
// Don't forget the ampersand
$datagrid =& new Structures_DataGrid();
?>

Note

This function can not be called statically.

Structures_DataGrid::addColumn

Structures_DataGrid::addColumn() – Add a column, with optional position

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::addColumn ( &$column , string $position = 'last' , string $relativeTo = null , object $column )

Description

This package is not documented yet.

Parameter

&$column
string $position

One of: "last", "first", "after" or "before" (default: "last")

string $relativeTo

The name (label) or field name of the relative column, if $position is "after" or "before"

object $column

The Structures_DataGrid_Column object (reference to)

Return value

returns PEAR_Error on failure, void otherwise

Throws

throws no exceptions thrown

Examples

Adding a simple column

<?php
$datagrid =& new Structures_DataGrid();
$column = new Structures_DataGrid_Column('Title', 'title', 'title', array('align' => 'center'), 'N/A', null);
$datagrid->addColumn($column);
?>

Note

This function can not be called statically.

Structures_DataGrid::attachRenderer

Structures_DataGrid::attachRenderer() – Attach an already instantiated Rendering driver

Synopsis

require_once 'Structures/DataGrid.php';

mixed& Structures_DataGrid::attachRenderer ( &$renderer , object $renderer )

Description

This package is not documented yet.

Parameter

&$renderer
object $renderer

Driver object, subclassing Structures_DataGrid_Renderer

Return value

returns Renderer instance or a PEAR_Error object

Throws

throws no exceptions thrown

See

see Structures_DataGrid::setRenderer()

Note

This function can not be called statically.

Structures_DataGrid::bind

Structures_DataGrid::bind() – A simple way to add a record set to the datagrid

Synopsis

require_once 'Structures/DataGrid.php';

bool Structures_DataGrid::bind ( mixed $container , array $options = array() , string $type = null )

Description

This package is not documented yet.

Parameter

mixed $container

The record set in any of the supported data source types

array $options

Optional. The options to be used for the data source

string $type

Optional. The data source type

Return value

returns True if successful, otherwise PEAR_Error.

Throws

throws no exceptions thrown

Examples

Bind an SQL query

<?php
// Setup your database connection
$options = array('dsn' => 'mysql://user:password@host/db_name');

// Bind a basic SQL statement as datasource
// Note: ORDER BY and LIMIT clause are automatically added
$test = $datagrid->bind('SELECT * FROM my_table', $options);

// Print binding error if any
if (PEAR::isError($test)) {
    echo $test->getMessage();
}
?>

Bind a DB_DataObject

<?php
$person = new DataObjects_Person;

$person->hair = 'red';
$person->has_glasses = 1;

$datagrid->bind($person);
?>

Note

This function can not be called statically.

Structures_DataGrid::bindDataSource

Structures_DataGrid::bindDataSource() – Bind an already instantiated DataSource driver

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::bindDataSource ( mixed &$source )

Description

This package is not documented yet.

Parameter

mixed &$source

The data source driver object

Return value

returns True if successful, otherwise PEAR_Error

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::build

Structures_DataGrid::build() – Build the datagrid

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::build ( )

Description

This package is not documented yet.

Return value

returns Either true or a PEAR_Error object

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::dataSourceFactory

Structures_DataGrid::dataSourceFactory() – Datasource driver Factory

Synopsis

require_once 'Structures/DataGrid.php';

Structures_DataGrid_DataSource|PEAR_Error& Structures_DataGrid::dataSourceFactory ( mixed $source , array $options = array() , string $type = null )

Description

A clever method which loads and instantiate data source drivers.

Can be called in various ways:

Detect the source type and load the appropriate driver with default options:

<?php
$driver =& Structures_DataGrid::dataSourceFactory($source);
?>

Detect the source type and load the appropriate driver with custom options:

<?php
$driver =& Structures_DataGrid::dataSourceFactory($source, $options);
?>

Load a driver for an explicit type (faster, bypasses detection routine):

<?php
$driver =& Structures_DataGrid::dataSourceFactory($source, $options, $type);
?>

Parameter

mixed $source

The data source respective to the driver

array $options

An associative array of the form: array(optionName => optionValue, ...)

string $type

The data source type constant (of the form DATAGRID_SOURCE_*)

Return value

returns driver object or PEAR_Error on failure

Throws

throws no exceptions thrown

See

see Structures_DataGrid::_detectSourceType()

Note

This function can not be called statically.

Structures_DataGrid::dump

Structures_DataGrid::dump() – Method used for debugging purposes only. Displays a dump of the DataGrid object.

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::dump ( )

Description

This package is not documented yet.

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::enableStreaming

Structures_DataGrid::enableStreaming() – Enable streaming support for reading from DataSources and writing with Renderers and set the buffer size (number of records)

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::enableStreaming ( integer $bufferSize = 500 )

Description

This package is not documented yet.

Parameter

integer $bufferSize

Number of records that should be buffered

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::fill

Structures_DataGrid::fill() – Fill a rendering container with data

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::fill ( object &$container , array $options = array() , string $type = null )

Description

This package is not documented yet.

Parameter

object &$container

A rendering container of any of the supported types (example: an HTML_Table object, a Spreadsheet_Excel_Writer object, etc...)

array $options

Options for the corresponding rendering driver

string $type

Explicit type in case the container type can't be detected

Return value

returns Either true or a PEAR_Error object

Throws

throws no exceptions thrown

Examples

Filling a Pager object

<?php

require_once 'Pager/Pager.php';

// Create a Pager object with your own options
$pager =& Pager::factory($options);

// fill() sets the $pager object up, according to your data and settings
$datagrid->fill($pager);

// Render the paging links
echo $pager->links;

// Or a select field if you like that
echo $pager->getpageselectbox();

?>

Fill a form with sort fields

<?php
require_once 'HTML/QuickForm.php';

// Create an empty form with your settings
$form = new HTML_QuickForm('myForm', 'POST');

// Customize it, add a header, text field, etc..
$form->addElement('header', null, 'Search & Sort Form Example');
$form->addElement('text', 'my_search', 'Search for:');

// Let the datagrid add sort fields, radio style
$options = array('directionStyle' => 'radio');
$datagrid->fill($form, $options, 'HTMLSortForm');

// You must add a submit button. fill() never does this
$form->addElement('submit', null, 'Submit');

// Use the native HTML_QuickForm::display() to print your form
$form->display();

?>

Note

This function can not be called statically.

Structures_DataGrid::generateColumns

Structures_DataGrid::generateColumns() – Generate columns from a fields list

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::generateColumns ( array $fields = array() )

Description

This is a shortcut for adding simple columns easily, instead of creating them manually and calling addColumn() for each.

The generated columns are appended to the current column set.

Parameter

array $fields

Fields and labels. Array of the form: array(field => label, ...) The default is an empty array, which means: all fields fetched from the datasource

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getColumnByField

Structures_DataGrid::getColumnByField() – Find a column by field name

Synopsis

require_once 'Structures/DataGrid.php';

object Either& Structures_DataGrid::getColumnByField ( string $fieldName )

Description

This package is not documented yet.

Parameter

string $fieldName

The field name of the column to look for

Return value

returns the column object (reference to) or false if there is no such column

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getColumnByName

Structures_DataGrid::getColumnByName() – Find a column by name (label)

Synopsis

require_once 'Structures/DataGrid.php';

object Either& Structures_DataGrid::getColumnByName ( string $name )

Description

This package is not documented yet.

Parameter

string $name

The name (label) of the column to look for

Return value

returns the column object (reference to) or false if there is no such column

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getColumnCount

Structures_DataGrid::getColumnCount() – Returns the number of columns

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getColumnCount ( )

Description

This package is not documented yet.

Return value

returns the number of columns

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getColumns

Structures_DataGrid::getColumns() – Return the current columns

Synopsis

require_once 'Structures/DataGrid.php';

array Structures_DataGrid::getColumns ( )

Description

This package is not documented yet.

Return value

returns Structures_DataGrid_Column objects (references to). This is a numerically indexed array (starting from 0).

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getCurrentPage

Structures_DataGrid::getCurrentPage() – Retrieves the current page number when paging is implemented

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getCurrentPage ( )

Description

This package is not documented yet.

Return value

returns the current page number

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getCurrentRecordNumberEnd

Structures_DataGrid::getCurrentRecordNumberEnd() – Returns the number of the last record of the current page

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getCurrentRecordNumberEnd ( )

Description

This package is not documented yet.

Return value

returns the number of the last record currently shown

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getCurrentRecordNumberStart

Structures_DataGrid::getCurrentRecordNumberStart() – Returns the number of the first record of the current page

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getCurrentRecordNumberStart ( )

Description

This package is not documented yet.

Return value

returns the number of the first record currently shown, or: 0 if there are no records, 1 if there is no row limit

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getDataSource

Structures_DataGrid::getDataSource() – Get the currently loaded DataSource driver

Synopsis

require_once 'Structures/DataGrid.php';

object DataSource& Structures_DataGrid::getDataSource ( )

Description

Retrieves the DataSource object as a reference

Return value

returns object reference or null if no driver is loaded

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getOutput

Structures_DataGrid::getOutput() – Return the datagrid output

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::getOutput ( int $type = null , array $options = array() )

Description

This package is not documented yet.

Parameter

integer $type

Renderer type (optional)

array $options

An associative array of the form: array(optionName => optionValue, ...)

Return value

returns The datagrid output (Usually a string: HTML, CSV, etc...) or a PEAR_Error

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getPageCount

Structures_DataGrid::getPageCount() – Returns the total number of pages

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getPageCount ( )

Description

This package is not documented yet.

Return value

returns the total number of pages or 1 if there are no records or if there is no row limit

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getRecordCount

Structures_DataGrid::getRecordCount() – Returns the total number of records

Synopsis

require_once 'Structures/DataGrid.php';

int Structures_DataGrid::getRecordCount ( )

Description

This package is not documented yet.

Return value

returns the total number of records

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::getRenderer

Structures_DataGrid::getRenderer() – Get the current or default Rendering driver

Synopsis

require_once 'Structures/DataGrid.php';

object Renderer& Structures_DataGrid::getRenderer ( )

Description

Retrieves the renderer object as a reference

Return value

returns object reference

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::removeColumn

Structures_DataGrid::removeColumn() – Remove a column

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::removeColumn ( &$column , object $column )

Description

This package is not documented yet.

Parameter

&$column
object $column

The Structures_DataGrid_Column object (reference to)

Throws

throws no exceptions thrown

Examples

Remove an unneeded column

<?php
$datagrid =& new Structures_DataGrid();

// Replace this with your database access informations:
$bindOptions['dsn'] = "mysql://foo:bar@host/world";

// The City table contains 5 fields: ID, Name, CountryCode, District and Population
$datagrid->bind("SELECT * FROM City ORDER BY Population", $bindOptions);

// We want to remove the ID field, so we retrieve a reference to the Column:
$column =& $datagrid->getColumnByField('ID');

// And we drop that column:
$datagrid->removeColumn($column);

// This will only render 4 fields: Name, CountryCode, District and Population:
$datagrid->render();
?>

Note

This function can not be called statically.

Structures_DataGrid::render

Structures_DataGrid::render() – Render the datagrid

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::render ( mixed $renderer = null , array $options = array() )

Description

You can call this method several times with different renderers.

Parameter

mixed $renderer

Renderer type or instance (optional)

array $options

An associative array of the form: array(optionName => optionValue, ...)

Return value

returns True or PEAR_Error

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setCurrentPage

Structures_DataGrid::setCurrentPage() – Define the current page number.

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setCurrentPage ( mixed $page )

Description

This method is used when paging is implemented

Parameter

mixed $page

The current page number (as string or int).

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setDataSourceOption

Structures_DataGrid::setDataSourceOption() – Set a single datasource option

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setDataSourceOption ( string $name , mixed $value )

Description

This package is not documented yet.

Parameter

string $name

Option name

mixed $value

Option value

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setDataSourceOptions

Structures_DataGrid::setDataSourceOptions() – Set multiple datasource options

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setDataSourceOptions ( array $options )

Description

This package is not documented yet.

Parameter

array $options

An associative array of the form: array("option_name" => "option_value",...)

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setDefaultSort

Structures_DataGrid::setDefaultSort() – Set default sorting specification

Synopsis

require_once 'Structures/DataGrid.php';

mixed Structures_DataGrid::setDefaultSort ( array $sortSpec )

Description

If there is no sorting query in the HTTP request, and if the sortRecordSet() method is not called, then the specification passed to setDefaultSort() will be used.

This is especially useful if you want the data to already be sorted when a user first see the datagrid.

This method needs to be called before bind().

Parameter

array $sortSpec

Sorting specification Structure: array(fieldName => direction, ...)

Return value

returns Either true or a PEAR_Error object

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setRenderer

Structures_DataGrid::setRenderer() – Set Renderer

Synopsis

require_once 'Structures/DataGrid.php';

mixed& Structures_DataGrid::setRenderer ( string $type , array $options = array() )

Description

Defines which renderer to be used by the DataGrid based on given $type and $options. To attach an existing renderer instance, use attachRenderer() instead.

Parameter

string $type

The defined renderer string

array $options

Rendering options

Return value

returns Renderer instance or PEAR_Error

Throws

throws no exceptions thrown

See

see Structures_DataGrid::attachRenderer()

Note

This function can not be called statically.

Structures_DataGrid::setRendererOption

Structures_DataGrid::setRendererOption() – Set a single renderer option

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setRendererOption ( string $name , mixed $value , bool $common = false )

Description

This package is not documented yet.

Parameter

string $name

Option name

mixed $value

Option value

boolean $common

Whether to use this option for all renderers (TRUE) or only for the current one (FALSE)

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setRendererOptions

Structures_DataGrid::setRendererOptions() – Set multiple renderer options

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setRendererOptions ( array $options , bool $common = false )

Description

This package is not documented yet.

Parameter

array $options

An associative array of the form: array("option_name" => "option_value",...)

boolean $common

Whether to use these options for all renderers (TRUE) or only for the current one (FALSE)

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setRequestPrefix

Structures_DataGrid::setRequestPrefix() – Set the global GET/POST variables prefix

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setRequestPrefix ( string $prefix )

Description

If you need to change the request variables, you can define a prefix. This is extra useful when using multiple datagrids.

This method needs to be called before bind().

Parameter

string $prefix

The prefix to use on request variables;

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid::setUrlFormat

Structures_DataGrid::setUrlFormat() – Enable and configure URL mapping

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::setUrlFormat ( mixed $format , string $prefix = null , string $scriptname = null )

Description

If this is set, it will be parsed instead of GET/POST. This is only supported on PHP5, as it depends on Net_URL_Mapper.

There are three possible placeholders, :pager, :orderBy and :direction. :page or (:orderBy and :direction) can be used alone.

It is possible to use multipe DataGrid instances on one page with different prefixes.

Instead of a format string you might also pass a Net_URL_Mapper instance to this method, in which case $prefix and $scriptname will be ignored. This instance must be properly set up, connected to url patterns, etc... This is especially useful when you've already configured URL mapping globally for your application and want Structures_DataGrid to integrate.

Parameter

mixed $format

The URL format string or a Net_URL_Mapper instance

string $prefix

Sets the url prefix

string $scriptname

Set the scriptname if mod_rewrite not available

See

see http://pear.php.net/Net_URL_Mapper

Throws

throws Net_URL_Mapper_InvalidException

Examples

configure a url format

<?php

// identical, for example /page/5/foo/ASC
$datagrid->setUrlFormat('/page/:page/:orderBy/:direction');
$datagrid->setUrlFormat('/:page/:orderBy/:direction', 'page');

// without /page, for example /5/foo/ASC
$datagrid->setUrlFormat('/:page/:orderBy/:direction');

// without paging, for example /sort/foo/ASC
$datagrid->setUrlFormat('/:orderBy/:direction', 'sort');

// with scriptname, for example /index.php/5/foo/ASC
$datagrid->setUrlFormat('/:page/:orderBy/:direction', 'page', 'index.php');

?>

Note

This function can not be called statically.

Structures_DataGrid::sortRecordSet

Structures_DataGrid::sortRecordSet() – Sorts the records by the defined field.

Synopsis

require_once 'Structures/DataGrid.php';

void Structures_DataGrid::sortRecordSet ( array $sortSpec , string $direction = 'ASC' )

Description

Do not use this method if data is coming from a database as sorting is much faster coming directly from the database itself.

Parameter

array $sortSpec

Sorting specification Structure: array(fieldName => direction, ...)

string $direction

Deprecated. Put the direction(s) into $sortSpec

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Class Structures_DataGrid_Column

Class Summary Structures_DataGrid_Column

Class Summary Structures_DataGrid_Column – Structures_DataGrid_Column Class

Structures_DataGrid_Column Class

This class represents a single column for the DataGrid.

Class Trees for Structures_DataGrid_Column

constructor Structures_DataGrid_Column::Structures_DataGrid_Column

constructor Structures_DataGrid_Column::Structures_DataGrid_Column() – Constructor

Synopsis

require_once 'Structures/DataGrid/Column.php';

void constructor Structures_DataGrid_Column::Structures_DataGrid_Column ( string $label , string $field = null , string $orderBy = null , array $attributes = array() , string $autoFillValue = null , mixed $formatter = null , array $formatterArgs = array() )

Description

Creates default table style settings

Parameter

string $label

The label of the column to be printed

string $field

The name of the field for the column to be mapped to

string $orderBy

The field or expression to order the data by

array $attributes

The attributes for the XML or HTML TD tag; form: array(name => value, ...)

string $autoFillValue

The value to use for the autoFill

mixed $formatter

Formatter callback. See setFormatter()

array $formatterArgs

Associative array of arguments passed as second argument to the formatter callback

Throws

throws no exceptions thrown

See

see Structures_DataGrid_Column::setFormatter()

see Structures_DataGrid::addColumn()

see http://www.php.net/manual/en/language.pseudo-types.php

Note

This function can not be called statically.

Structures_DataGrid_Column::format

Structures_DataGrid_Column::format() – Choose a format preset

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::format ( $type , mixed $type,... )

Description

EXPERIMENTAL: the behaviour of this method may change in future releases.

This method allows to associate an "automatic" predefined formatter to the column, for common needs as formatting dates, numbers, ...

The currently supported predefined formatters are :

Parameter

$type
mixed $type,...

Predefined formatter name, followed by formatter-specific parameters

Throws

throws no exceptions thrown

Examples

Common formats

<?php

// Format UNIX timestamps as english dates:
$column->format('dateFromTimestamp', 'm/d/y');

// Format MySQL DATE, DATETIME or TIMESTAMP strings as french dates:
$column->format('dateFromMysql', 'd/m/y');

// Format numbers with 3 decimals and no thousands separator:
$column->format('number', 3, '.', '');

// Format numbers with 2 decimals:
$column->format('number', 2);

// Format using a printf expression:
$column->format('printf', 'Number of potatoes: %d');

// Format an HTML link using a printf expression with url-encoding:
$column->format('printfURL', '<a href="edit.php?key=%s">Edit</a>'); 

?>

Note

This function can not be called statically.

Structures_DataGrid_Column::formatter

Structures_DataGrid_Column::formatter() – Formatter

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::formatter ( $record , $row , $col )

Description

This method is not meant to be called by user-space code.

Calls a predefined function to develop custom output for the column. The defined function can accept parameters so that each cell in the column can be unique based on the record. The function will also automatically receive the record array as a parameter. All parameters passed into the function will be in one array.

Parameter

$record
$row
$col

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getAttributes

Structures_DataGrid_Column::getAttributes() – Get the column XML/HTML attributes

Synopsis

require_once 'Structures/DataGrid/Column.php';

array Structures_DataGrid_Column::getAttributes ( )

Description

Return the attributes applied to all cells in this column. This only makes sense for HTML or XML rendering

Return value

returns Attributes; form: array(name => value, ...)

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getAutoFillValue

Structures_DataGrid_Column::getAutoFillValue() – Get auto fill value

Synopsis

require_once 'Structures/DataGrid/Column.php';

string Structures_DataGrid_Column::getAutoFillValue ( )

Description

Returns the value to be printed if a cell in the column is null.

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getDefaultDirection

Structures_DataGrid_Column::getDefaultDirection() – Return the default direction to order this column by

Synopsis

require_once 'Structures/DataGrid/Column.php';

string Structures_DataGrid_Column::getDefaultDirection ( $str )

Description

This package is not documented yet.

Parameter

$str

Return value

returns "ASC" or "DESC"

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getField

Structures_DataGrid_Column::getField() – Get name of the field for the column to be mapped to

Synopsis

require_once 'Structures/DataGrid/Column.php';

string Structures_DataGrid_Column::getField ( )

Description

Returns the name of the field for the column to be mapped to

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getLabel

Structures_DataGrid_Column::getLabel() – Get column label

Synopsis

require_once 'Structures/DataGrid/Column.php';

string Structures_DataGrid_Column::getLabel ( )

Description

The label is the text rendered into the column header.

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::getOrderBy

Structures_DataGrid_Column::getOrderBy() – Get the field name to order the data by

Synopsis

require_once 'Structures/DataGrid/Column.php';

string Structures_DataGrid_Column::getOrderBy ( )

Description

This package is not documented yet.

Return value

returns field name

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setAttributes

Structures_DataGrid_Column::setAttributes() – Set the column XML/HTML attributes

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setAttributes ( array $attributes )

Description

Set the attributes to be applied to all cells in this column. This only makes sense for HTML or XML rendering

Parameter

array $attributes

form: array(name => value, ...)

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setAutoFillValue

Structures_DataGrid_Column::setAutoFillValue() – Set auto fill value

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setAutoFillValue ( string $str )

Description

Defines a value to be printed if a cell in the column is null.

Parameter

string $str

The value to use for the autoFill

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setDefaultDirection

Structures_DataGrid_Column::setDefaultDirection() – Set the default direction to order this column by

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setDefaultDirection ( string $str )

Description

This package is not documented yet.

Parameter

string $str

"ASC" or "DESC"

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setField

Structures_DataGrid_Column::setField() – Set name of the field for the column to be mapped to

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setField ( string $str )

Description

Defines the name of the field for the column to be mapped to

Parameter

string $str

The name of the field for the column to be mapped to

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setFormatter

Structures_DataGrid_Column::setFormatter() – Set Formatter Callback

Synopsis

require_once 'Structures/DataGrid/Column.php';

mixed Structures_DataGrid_Column::setFormatter ( mixed $formatter , array $arguments = array() )

Description

Define a formatting callback function with optional arguments for this column.

The callback function receives the following array as its first argument:

<?php
array(
   'record' => associative array of all fields values for this record,
   'fieldName' => the field name of this column,
   'columnName' => the label (header) of this column,
   'orderBy' => the field name to sort this column by,
   'attribs' => this column's attributes,
   'currRow' => zero-based row index,
   'currCol' => zero-based column index,
 );
?>

If you pass the optional $arguments parameter to setFormatter(), the callback function will receive it as its second argument.

Parameter

mixed $formatter

Callback PHP pseudo-type (Array or String)

array $arguments

Associative array of parameters passed to as second argument to the callback function

Return value

returns PEAR_Error on failure

Throws

throws no exceptions thrown

See

see http://www.php.net/manual/en/language.pseudo-types.php

Note

This function can not be called statically.

Structures_DataGrid_Column::setLabel

Structures_DataGrid_Column::setLabel() – Set column label

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setLabel ( string $str )

Description

The label is the text rendered into the column header.

Parameter

string $str

Column label

Throws

throws no exceptions thrown

Note

This function can not be called statically.

Structures_DataGrid_Column::setOrderBy

Structures_DataGrid_Column::setOrderBy() – Set the field name to order the data by

Synopsis

require_once 'Structures/DataGrid/Column.php';

void Structures_DataGrid_Column::setOrderBy ( string $str )

Description

This package is not documented yet.

Parameter

string $str

field name

Throws

throws no exceptions thrown

Note

This function can not be called statically.

DataSource drivers

Structures_DataGrid_DataSource_Array

Structures_DataGrid_DataSource_Array – Array Data Source Driver

Description

This class is a data source driver for a 2D array

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

General notes

This driver expects an array of the following form:

$data = array(0 => array('col0' => 'val00', 'col1' => 'val01', ...),
              1 => array('col0' => 'val10', 'col1' => 'val11', ...),
              ...
             );

The first level of this array contains one entry for each row. For every row entry an array with the data for this row is expected. Such an array contains the field names as the keys. For example, 'val01' is the value of the column with the field name 'col1' in the first row. Row numbers start with 0, not with 1.

Structures_DataGrid_DataSource_CSV

Structures_DataGrid_DataSource_CSV – Comma Separated Value (CSV) Data Source Driver

Description

This class is a data source driver for a CSV File. It will also support any other delimiter.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
delimiter string Field delimiter ','
enclosure string Field enclosure '"'
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
header bool Whether the CSV file (or string) contains a header row false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

Structures_DataGrid_DataSource_DataObject

Structures_DataGrid_DataSource_DataObject – PEAR::DB_DataObject Data Source Driver

Description

This class is a data source driver for a PEAR::DB::DB_DataObject object

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting yes
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
fields_order_property string The name of a property that you can set within your DataObject. It will be used to set the order in which fields are displayed, as long as you're not configuring this by adding/generating columns. Also requires the fields_property to be set. null
fields_property string The name of a property that you can set within your DataObject. This property is expected to contain the same kind of information as the 'fields' option. If the 'fields' option is set, this one will not be used. 'fb_fieldsToRender'
formbuilder_integration bool DEPRECATED: use link_level and fields_order_property instead. For BC, Setting this to true is equivalent to setting link_level to 3 and fields_order_property to 'fb_preDefOrder'. false
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
labels_property string The name of a property that you can set within your DataObject. This property should contain the same kind of information as the 'labels' option. If the 'labels' option is set, this one will not be used. 'fb_fieldLabels'
link_keep_key bool Set this to true when you want to keep the original values (usually foreign keys) of fields which are being replaced by their linked values. The record will then contain additional keys with "__key" prepended. This option only makes sense with link_level higher than 0. Example: if the country_code original value is 'FR' and this is replaced by "France" from the linked country table, then setting link_keep_key to true will keep the "FR" value in country_code__key. false
link_level int The maximum link display level. If equal to 0 the links will not be followed. 0
link_property string The name of a property you can set within a linked DataObject. This property should contain a array of field names that will be used to display a string out of this linked DataObject. Has no effect when link_level is 0. 'fb_linkDisplayFields'
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null
raw_count bool If true: query all the records in order to count them. This is needed when records are grouped (GROUP BY, DISTINCT, etc..), but might be heavy. If false: perform a smart count query with DB_DataObject::count(). false
return_objects bool If true, the returned records will consists of clones of the dataobject instead of associative arrays. This is especially useful when used in conjunction with the smarty renderer for example, to directly access the dataobject properties and methods from your templates. false
sort_property string The name of a property that you can set within your DataObject. This property should contain an array of the form: array("field1", "field1 DESC", ...) If the data is already being sorted then this this property's content will be appended to the current ordering. 'fb_linkOrderFields'

Examples

Bind a DB_DataObject to Structures_DataGrid

<?php
$person = new DataObjects_Person;

$person->hair = 'red';
$person->has_glasses = 1; 

$datagrid->bind($person);
?>

Structures_DataGrid_DataSource_DB

Structures_DataGrid_DataSource_DB – PEAR::DB Data Source Driver

Description

This class is a data source driver for the PEAR::DB::DB_Result object

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

Structures_DataGrid_DataSource_DBQuery

Structures_DataGrid_DataSource_DBQuery – PEAR::DB SQL Query Data Source Driver

Description

This class is a data source driver for the PEAR::DB object

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting yes
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
count_query string Query that calculates the number of rows. See below for more information about when such a count query is needed. ''
db_options array Options for the created database object. This option is only used when the 'dsn' option is given. array()
dbc object A PEAR::DB instance that will be used by this driver. Either this or the 'dsn' option is required. null
dsn string A PEAR::DB dsn string. The DB connection will be established by this driver. Either this or the 'dbc' option is required. null
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

General notes

You need to specify either a DB instance or a DB compatible dsn string as an option to use this driver.

If you use complex queries (e.g. with complex joins or with aliases), $datagrid->getRecordCount() might return a wrong result. For the case of GROUP BY, UNION, or DISTINCT in your queries, and for the case of subqueries, this driver already has special handling. However, if you observe wrong record counts, you need to specify a special query that returns only the number of records (e.g. 'SELECT COUNT(*) FROM ...') as an additional option 'count_query' to the bind() call.

You can specify an ORDER BY statement in your query. Please be aware that this sorting statement is then used in *every* query before the sorting options that come from a renderer (e.g. by clicking on the column header when using the HTML_Table renderer which is sent in the HTTP request). If you want to give a default sorting statement that is only used if there is no sorting query in the HTTP request, then use $datagrid->setDefaultSort().

Structures_DataGrid_DataSource_DBTable

Structures_DataGrid_DataSource_DBTable – PEAR::DB_Table Data Source Driver

Description

This class is a data source driver for the PEAR::DB_Table object

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting yes
Insert, update and delete records yes

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
params array Placeholder parameters for prepare/execute array()
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null
view string The view from $sql array in your DB_Table object. This option is required. null
where string A where clause for the SQL query. null

General notes

If you use aliases in the select part of your view, the count() method from DB_Table and, therefore, $datagrid->getRecordCount() might return a wrong result. To avoid this, DB_Table uses a special query for counting if it is given via a view that needs to be named as '__count_' followed by the name of the view that this counting view belongs to. (For example: if you have a view named 'all', the counting view needs to be named as '__count_all'.)

To use update() and delete() methods, it is required that the indexes are properly defined in the $idx array in your DB_Table subclass. If you have, for example, created your database table yourself and did not setup the $idx array, you can use the 'primaryKey' option to define the primary key field.

Examples

Bind a DB_Table class to Structures_DataGrid

<?php
// basic guestbook class that extends DB_Table
class GuestBook_Table extends DB_Table
{
    var $col = array(
        // unique row ID
        'id' => array(
            'type'    => 'integer',
            'require' => true
        ),
        // first name
        'fname' => array(
            'type'    => 'varchar',
            'size'    => 32
        ),
        // last name
        'lname' => array(
            'type'    => 'varchar',
            'size'    => 64
        ),
        // email address
        'email' => array(
            'type'    => 'varchar',
            'size'    => 128,
            'require' => true
        ),
        // date signed
        'signdate' => array(
            'type'    => 'date',
            'require' => true
        )
    );
    var $idx = array();  // indices don't matter here
    var $sql = array(
        // multiple rows for a list 
        'list' => array( 
            'select' => 'id, signdate, CONCAT(fname, " ", lname) AS fullname',
            'order'  => 'signdate DESC'
        )
    );
}

// instantiate the extended DB_Table class
// (using an existing database connection and the table name 'guestbook')
$guestbook =& new GuestBook_Table($db, 'guestbook');

// Options for the bind() call
// (using the predefined query 'list' from the $sql array and a where
// condition)
$options = array('view' => 'list', 'where' => 'YEAR(signdate) = 2100');

// bind the guestbook object
// (if you don't generate any column yourself before rendering, three
// columns will be generated: id, signdate, fullname)
$test = $datagrid->bind($guestbook, $options);

// print binding error if any
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}
?>

Structures_DataGrid_DataSource_Excel

Structures_DataGrid_DataSource_Excel – Excel Spreadsheet Data Source Driver

Description

This class is a data source driver for an Excel spreadsheet.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
header bool Whether the Excel file contains a header row false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

General notes

Spreadsheet_Excel_Reader ("PHP-ExcelReader") is not available as a PEAR package. It is available on SourceForge.net: http://sourceforge.net/projects/phpexcelreader/

This class expects the file reader.php in the directory Spreadsheet/Excel/.

Please note that the current version (2i) of Spreadsheet_Excel_Reader contains a die() statement in the read() method in reader.php (line 171). This makes a reasonable PEAR error handling for the "file not found" error impossible.

It is therefore recommended that you replace the die() statement by something like this:

return PEAR::raiseError('The filename ' . $sFileName . ' is not readable');

This class is optimized for the changed code (but will work also with the die() in the reader class, of course), and provides then a reasonable error handling.

Structures_DataGrid_DataSource_MDB2

Structures_DataGrid_DataSource_MDB2 – PEAR::MDB2 SQL Query Data Source Driver

Description

This class is a data source driver for the PEAR::MDB2 object

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting yes
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
count_query string Query that calculates the number of rows. See below for more information about when such a count query is needed. ''
db_options array Options for the created database object. This option is only used when the 'dsn' option is given. array()
dbc object A PEAR::MDB2 instance that will be used by this driver. Either this or the 'dsn' option is required. null
dsn string A PEAR::MDB2 dsn string. The MDB2 connection will be established by this driver. Either this or the 'dbc' option is required. null
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

General notes

You need to specify either a MDB2 instance or a MDB2 compatible dsn string as an option to use this driver.

If you use complex queries (e.g. with complex joins or with aliases), $datagrid->getRecordCount() might return a wrong result. For the case of GROUP BY, UNION, or DISTINCT in your queries, and for the case of subqueries, this driver already has special handling. However, if you observe wrong record counts, you need to specify a special query that returns only the number of records (e.g. 'SELECT COUNT(*) FROM ...') as an additional option 'count_query' to the bind() call.

You can specify an ORDER BY statement in your query. Please be aware that this sorting statement is then used in *every* query before the sorting options that come from a renderer (e.g. by clicking on the column header when using the HTML_Table renderer which is sent in the HTTP request). If you want to give a default sorting statement that is only used if there is no sorting query in the HTTP request, then use $datagrid->setDefaultSort().

Structures_DataGrid_DataSource_PDO

Structures_DataGrid_DataSource_PDO – PDO SQL Query Data Source Driver

Description

This class is a data source driver for PHP Data Objects

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting yes
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
count_query string Query that calculates the number of rows. See below for more information about when such a count query is needed. ''
db_options array Options for the created database object. This option is only used when the 'dsn' option is given. array()
dbc object A PDO instance that will be used by this driver. Either this or the 'dsn' option is required. null
dsn string A PDO dsn string. The PDO connection will be established by this driver. Either this or the 'dbc' option is required. null
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
password string Password for the crated PDO connection. Only needed in conjunction with 'dsn' option. null
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null
username string Username for the created PDO connection. Only needed in conjunction with 'dsn' option. null

General notes

You need to specify either a PDO instance or a PDO compatible dsn string as an option to use this driver.

If you use complex queries (e.g. with complex joins or with aliases), $datagrid->getRecordCount() might return a wrong result. For the case of GROUP BY, UNION, or DISTINCT in your queries, and for the case of subqueries, this driver already has special handling. However, if you observe wrong record counts, you need to specify a special query that returns only the number of records (e.g. 'SELECT COUNT(*) FROM ...') as an additional option 'count_query' to the bind() call.

You can specify an ORDER BY statement in your query. Please be aware that this sorting statement is then used in *every* query before the sorting options that come from a renderer (e.g. by clicking on the column header when using the HTML_Table renderer which is sent in the HTTP request). If you want to give a default sorting statement that is only used if there is no sorting query in the HTTP request, then use $datagrid->setDefaultSort().

Structures_DataGrid_DataSource_RSS

Structures_DataGrid_DataSource_RSS – RSS data source driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null

Structures_DataGrid_DataSource_XML

Structures_DataGrid_DataSource_XML – XML DataSource driver

Description

This class is a DataSource driver for XML data. It accepts strings and filenames. An XPath expression can be specified to extract a subset from the given XML data.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Multiple field sorting no
Insert, update and delete records no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
fieldAttribute string Which attribute of the XML source should be used as column field name (only used if the XML source has attributes). null
fields array Which data fields to fetch from the datasource. An empty array means: all fields. Form: array(field1, field2, ...) array()
generate_columns bool Generate Structures_DataGrid_Column objects with labels. See the 'labels' option. DEPRECATED: use Structures_DataGrid::generateColumns() instead false
labelAttribute string Which attribute of the XML source should be used as column label (only used if 'generate_columns' is true and the XML source has attributes). null
labels array Data field to column label mapping. Only used when 'generate_columns' is true. Form: array(field => label, ...) DEPRECATED: use Structures_DataGrid::generateColumns() instead array()
natsort boolean Whether the array should be sorted naturally (e.g. example1, Example2, test1, Test2) or not (e.g. Example2, Test2, example1, test1; i.e. capital letters will come first). false
primaryKey array Name(s), or numerical index(es) of the field(s) which contain a unique record identifier (only use several fields in case of a multiple-fields primary key) null
xpath string XPath to a subset of the XML data. ''

Examples

Bind a simple XML string

<?php
$xml = <<<XML
<records>
  <record>
    <firstname>Olivier</firstname>
    <lastname>Guilyardi</lastname>
    <city>Paris</city>
    <country>France</country>
  </record>
  <record>
    <firstname>Mark</firstname>
    <lastname>Wiesemann</lastname>
    <city>Aachen</city>
    <country>Germany</country>
  </record>
</records>
XML;

// Options for the bind() call (empty in this example)
$options = array();

// Bind the XML string
$test = $datagrid->bind($xml, $options, 'XML');

// Print binding error if any
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}
?>

Bind a more complex XML string (using 'xpath' option)

<?php
$xml = <<<XML
<response>
  <date>today</date>
  <server>localhost</server>
  <records>
    <record>
      <firstname>Olivier</firstname>
      <lastname>Guilyardi</lastname>
      <city>Paris</city>
      <country>France</country>
    </record>
    <record>
      <firstname>Mark</firstname>
      <lastname>Wiesemann</lastname>
      <city>Aachen</city>
      <country>Germany</country>
    </record>
  </records>
</response>
XML;

// Options for the bind() call
$options = array('xpath' => '/response/records');

// Bind the XML string
$test = $datagrid->bind($xml, $options, 'XML');

// Print binding error if any
if (PEAR::isError($test)) {
    echo $test->getMessage(); 
}
?>

Renderer drivers

Structures_DataGrid_Renderer_CheckableHTMLTable

Structures_DataGrid_Renderer_CheckableHTMLTable – HTML table rendering driver with a checkbox for each row of the grid

Availability

This driver is experimental and has not been officially released yet. It is only available from SVN.

Description

Driver for rendering the DataGrid as an HTML table with a checkbox for each row

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
classASC string A CSS class name for TH elements to define that sorting is currently ascending. ''
classDESC string A CSS class name for TH elements to define that sorting is currently descending. ''
columnAttributes array Column cells attributes. This is an array of the form: array(fieldName => array(attribute => value, ...) ...) This option is only used by XML/HTML based drivers. array()
convertEntities bool Whether or not to convert html entities. This calls htmlspecialchars(). true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
emptyRowAttributes array An associative array containing the attributes for empty rows. array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
evenRowAttributes array An associative array containing each attribute of the even rows. array()
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
form object Instance of a HTML_QuickForm object. null
formRenderer object Instance of a HTML_QuickForm_Renderer_QuickHtml object. null
headerAttributes array Attributes for the header row. This is an array of the form: array(attribute => value, ...) array()
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
inputName string The HTML_QuickForm element name for the checkboxes. 'checkedItems'
numberAlign bool Whether to right-align numeric values. true
oddRowAttributes array An associative array containing each attribute of the odd rows. array()
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
primaryKey string The name of the primary key. This value is used for the checkboxes. 'id'
selfPath string The complete path for sorting and paging links. $_SERVER['PHP_SELF']
sortIconASC string The icon to define that sorting is currently ascending. Can be text or HTML to define an image. ''
sortIconDESC string The icon to define that sorting is currently descending. Can be text or HTML to define an image. ''
sortingResetsPaging bool Whether sorting HTTP queries reset paging. true

General notes

This driver puts a checkbox for each row of the table into the first column. By default, a new column with the value of the 'inputName' option is added for the checkboxes. If you want to customize this column, you can add a column yourself as it is shown in the example.

Examples

Basic usage

<?php
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/Renderer/QuickHtml.php';
require_once 'Structures/DataGrid.php';

// prepare the form and the QuickHtml renderer
$form =& new HTML_QuickForm();
$renderer =& new HTML_QuickForm_Renderer_QuickHtml();

// add action selectbox and submit button to the form
$form->addElement('select', 'action', 'choose',
                  array('delete' => 'Delete',
                        'move'   => 'Move to archive'));
$form->addElement('submit', 'submit', 'Save');

// prepare the DataGrid
$dg =& new Structures_DataGrid();
if (PEAR::isError($dg)) {
   die($dg->getMessage() . '<br />' . $dg->getDebugInfo());
}

// bind some data (e.g. via a SQL query and MDB2)
$error = $dg->bind('SELECT * FROM news',
                   array('dsn' => 'mysql://user:password@server/database'));
if (PEAR::isError($error)) {
   die($error->getMessage() . '<br />' . $error->getDebugInfo());
}

// the renderer adds an auto-generated column for the checkbox by default;
// it is also possible to add a column yourself, for example like in the
// following four lines:
$column = new Structures_DataGrid_Column('checkboxes', 'idList', null,
                                         array('width' => '10'));
$dg->addColumn($column);
$dg->generateColumns();

$rendererOptions = array('form'         => $form,
                         'formRenderer' => $renderer,
                         'inputName'    => 'idList',
                         'primaryKey'   => 'id'
                        );

// use a template string for the form
$tpl = '';

// generate the HTML table and add it to the template string
$tpl .= $dg->getOutput('CheckableHTMLTable', $rendererOptions);
if (PEAR::isError($tpl)) {
   die($tpl->getMessage() . '<br />' . $tpl->getDebugInfo());
}

// add the HTML code of the action selectbox and the submit button to the
// template string
$tpl .= $renderer->elementToHtml('action');
$tpl .= $renderer->elementToHtml('submit');

// we're now ready to output the form (toHtml() adds the <form> / </form>
// pair to the template)
echo $renderer->toHtml($tpl);

// if the form was submitted and the data is valid, show the submitted data
if ($form->isSubmitted() && $form->validate()) {
    var_dump($form->getSubmitValues());
}
?>

Structures_DataGrid_Renderer_Console

Structures_DataGrid_Renderer_Console – Console Table Rendering Driver

Description

This renderer generates nicely formatted and padded ASCII tables.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true

Structures_DataGrid_Renderer_CSV

Structures_DataGrid_Renderer_CSV – CSV Rendering Driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support no
Output Buffering yes
Direct Rendering yes
Streaming yes
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
delimiter string Field delimiter ','
enclosure string Field enclosure '"'
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
filename string Filename of the generated CSV file; boolean false means that no filename will be sent false
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
lineBreak string The character(s) to use for line breaks '\n'
numberAlign bool Whether to right-align numeric values. true
saveToFile boolean Whether the output should be saved on the local filesystem. Please note that the 'filename' option must be given if this option is set to true. false
targetEncoding string If set, the content will be converted from encoding to targetEncoding. A BOM will also be added, if relevant. See PHP mbstring documentation for encoding names. Tip: for Excel use 'UTF-16LE'. ''
useQuotes mixed Whether or not to encapsulate the values with the enclosure value. true: always, false: never, 'auto': when needed 'auto'
writeMode string The mode that is used in the internal fopen() calls. Useful e.g. when you want to append to existing file. C.p. the fopen() documentation for the allowed modes. 'wb'

Structures_DataGrid_Renderer_Flexy

Structures_DataGrid_Renderer_Flexy – Flexy Rendering Driver

Availability

This driver is experimental and has not been officially released yet. It is only available from SVN.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
assocColumns bool Whether or not to build the column header as an associate array. true
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
columnAttributes array Column cells attributes. This is an array of the form: array(fieldName => array(attribute => value, ...) ...) This option is only used by XML/HTML based drivers. array()
columnNames array The set of column names to use for the column header. array()
convertEntities bool Whether or not to convert html entities. This calls htmlspecialchars(). true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
evenRowAttribute string The css class to be used for the even row listings. 'even'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
formatter array The callback array for a column header formatter method. array($this,'defaultHeaderFormatter')
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
oddRowAttribute string The css class to be used for odd row listings. 'odd'
onMove string Name of a Javascript function to call on onClick/onSubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
pagerOptions array The custom options to be sent to the Pager renderer.  
resultsFormat string The format of the results message in sprintf format. 'You have %s results in %s pages'
selfPath string The complete path for sorting and paging links. $_SERVER['PHP_SELF']
sortingResetsPaging bool Whether sorting HTTP queries reset paging. true

General notes

This driver does not support the render() method, it only is able to be attached setting the container to a current Flexy instance. Options to the renderer must also be passed using the setOptions() method.

Flexy output is buffered using the DataGrid getOutput() method.

This driver assigns the following Flexy template variables: - columnSet: array of columns' labels and sorting links - columnHeader: object of columns' labels and sorting links - recordSet: associate array of records values - numberedSet: numbered array of records values - currentPage: current page (starting from 1) - recordLimit: number of rows per page - pagesNum: number of pages - columnsNum: number of columns - recordsNum: number of records in the current page - totalRecordsNum: total number of records - firstRecord: first record number (starting from 1) - lastRecord: last record number (starting from 1)

This driver also register a Smarty custom function named getPaging that can be called from Smarty templates with {getPaging} in order to print paging links. This function accepts any of the Pager::factory() options as parameters.

Dynamic Template example, featuring sorting and paging:

<!-- Show paging links using the custom getPaging function -->
{getPaging():h}

<p>Showing records {firstRecord} to {lastRecord}
from {totalRecordsNum}, page {currentPage} of {pagesNum}</p>

<table cellspacing="0">
   <!-- Build header -->
   <tr>
       <th>
           {foreach:columnSet,column}
               <td><a href="{column[link]:h}">{column[label]:h}</a></td>
           {end:}
       </th>
   </tr>

   <!-- Build body -->
   <tr class="{getRowCSS()}" flexy:foreach="numberedSet,k,row">
       {foreach:row,field}
           <td>{field}</td>
       {end:}
   </tr>
</table>

Static Template example, featuring sorting and paging:

<table cellspacing="0">
   <!-- Build header -->
   <tr>
       <th>
           <td>
               <a href="{columnHeader.name[link]:h}">{columnHeader.field1[label]:h}</a>
           </td>
           <td>
              <a href="{columnHeader.surname[link]:h}">{columnHeader.field2[label]:h}</a>
           </td>
       </th>
   </tr>

   <!-- Build body -->
   <tr class="{getRowCSS()}" flexy:foreach="recordSet,k,row">
       <td>{row[field1]}</td>
       <td>{row[field2]}</td>
   </tr>
</table>
require_once 'HTML/Template/Flexy.php';
require_once 'Structures/DataGrid.php';
require_once 'Structures/DataGrid/Renderer/Flexy.php';

$tpl = new HTML_Template_Flexy($config['HTML_Template_Flexy']);
$dg =& new Structures_DataGrid($_GET['setPerPage'] ? $_GET['setPerPage']
                                                   : 10,$_GET['page']
                                                   ? $_GET['page'] : 1);
$dg->bind($dataObject);
$renderer = new Structures_DataGrid_Renderer_Flexy();
$renderer->setContainer($tpl);
$renderer->setOptions($config['Structures_DataGrid']);
$dg->attachRenderer($renderer);
$this->tpl->compile($template);
echo $dg->getOutput();

Structures_DataGrid_Renderer_HTMLEditForm

Structures_DataGrid_Renderer_HTMLEditForm – HTML form to edit a record

Availability

This driver is experimental and has not been officially released yet. It is only available from SVN.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
textSubmit string Label for the submit button 'Submit'

Examples

Basic usage

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

$datagrid =& new Structures_DataGrid();
$datagrid->bind(...);  // bind your data here

$datagrid->setRenderer('HTMLEditForm');

$datagrid->render();
?>

Usage with tableless renderer and DHTMLRules

<?php
// don't forget to include the stylesheet to get a reasonable layout

require_once 'Structures/DataGrid.php';
require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
require_once 'HTML/QuickForm/Renderer/Tableless.php';

$datagrid =& new Structures_DataGrid();
$datagrid->bind(...);  // bind your data here

// create the form object, using DHTMLRules
$form = new HTML_QuickForm_DHTMLRulesTableless('editform', null, null,
                                               null, null, true);
$form->removeAttribute('name');  // for XHTML validity

// to get a legend for the fieldset, we add a header element
$form->addElement('header', 'header', 'EditForm example');

// fill() makes the renderer to generate the needed form elements
$datagrid->fill($form, null, 'HTMLEditForm');

// we have to add a submit button ourselves
$form->addElement('submit', null, 'Submit');

// to show the DHTMLRules functionality, we add a required rule
// (we assume that there is an element with name 'id')
$form->addRule('id', 'Please enter the ID.', 'required', null, 'client');

// to get validation onChange/onBlur events, we need the following call
$form->getValidationScript();

// instantiate the tableless renderer and output the form
$renderer =& new HTML_QuickForm_Renderer_Tableless();
$form->accept($renderer);
echo $renderer->toHtml();
?>

Structures_DataGrid_Renderer_HTMLSortForm

Structures_DataGrid_Renderer_HTMLSortForm – Multiple fields sorting form rendering driver

Description

This driver renders a form (using HTML_QuickForm) so that the user can select several fields and directions to sort the datagrid by.

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
directionStyle string Whether to render the direction form elements as 'select' or 'radio' elements 'select'
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
sortFieldsNum int How many fields the user will be able to sort by. This has no effect if the backend does not support sorting by multiple fields. 3
textAscending string Label for the ASC direction 'Ascending'
textChoose string What to display in the select box when no field is selected (first option) 'Choose...'
textDescending string Label for the DESC direction 'Descending'
textSortBy string Label for the first field 'Sort by:'
textSubmit string Label for the submit button 'Submit'
textThenBy string Label for the second and following fields 'Then by:'

Examples

Fill a form with sort fields

<?php
require_once 'HTML/QuickForm.php';

// Create an empty form with your settings
$form = new HTML_QuickForm('myForm', 'POST');

// Customize it, add a header, text field, etc..
$form->addElement('header', null, 'Search & Sort Form Example');
$form->addElement('text', 'my_search', 'Search for:');

// Let the datagrid add sort fields, radio style
$options = array('directionStyle' => 'radio');
$datagrid->fill($form, $options, 'HTMLSortForm');

// You must add a submit button. fill() never does this
$form->addElement('submit', null, 'Submit');

// Use the native HTML_QuickForm::display() to print your form
$form->display();

?>

Structures_DataGrid_Renderer_HTMLTable

Structures_DataGrid_Renderer_HTMLTable – HTML Table Rendering Driver

Description

Driver for rendering the DataGrid as an HTMLTable

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
classASC string A CSS class name for TH elements to define that sorting is currently ascending. ''
classDESC string A CSS class name for TH elements to define that sorting is currently descending. ''
columnAttributes array Column cells attributes. This is an array of the form: array(fieldName => array(attribute => value, ...) ...) This option is only used by XML/HTML based drivers. array()
convertEntities bool Whether or not to convert html entities. This calls htmlspecialchars(). true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
emptyRowAttributes array An associative array containing the attributes for empty rows. array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
evenRowAttributes array An associative array containing each attribute of the even rows. array()
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
headerAttributes array Attributes for the header row. This is an array of the form: array(attribute => value, ...) array()
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
oddRowAttributes array An associative array containing each attribute of the odd rows. array()
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
selfPath string The complete path for sorting and paging links. $_SERVER['PHP_SELF']
sortIconASC string The icon to define that sorting is currently ascending. Can be text or HTML to define an image. ''
sortIconDESC string The icon to define that sorting is currently descending. Can be text or HTML to define an image. ''
sortingResetsPaging bool Whether sorting HTTP queries reset paging. true

Examples

Simple AJAX support using the Prototype framework

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

$datagrid =& new Structures_DataGrid(10);

$options['dsn'] = 'mysql://username@localhost/mydatabase';
$datagrid->bind("SELECT * FROM mytable", $options);

// Set the javascript handler function for onclick events
$datagrid->setRendererOption('onMove', 'updateGrid', true);

if (isset($_GET['ajax'])) {
    // Handle table AJAX requests 
    if ($_GET['ajax'] == 'table') {
        $datagrid->render();
    }
    // Handle pager AJAX requests 
    if ($_GET['ajax'] == 'pager') {
        $datagrid->render('Pager');
    }
    exit();
}

// No AJAX request, render the initial content..
?>
<html>

<head>
<!-- Require the Prototype JS framework from http://www.prototypejs.org -->
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function updateGrid(info) 
{
    var url = '<?php echo $_SERVER['PHP_SELF']; ?>';
    var pars = 'page=' + info.page;
    if (info.sort.length > 0) {
        pars += '&orderBy=' + info.sort[0].field + '&direction=' + info.sort[0].direction;
    }
        
    new Ajax.Updater( 'grid', url, { method: 'get', parameters: pars + '&ajax=table' });
    new Ajax.Updater( 'pager', url, { method: 'get', parameters: pars + '&ajax=pager' });

    // Important: return false to avoid href links
    return false;
}
</script>
</head>

<body>
Pages: <span id="pager"><?php $datagrid->render('Pager'); ?></span>
<div id="grid"><?php $datagrid->render(); ?></div>
</body>

</html>

Structures_DataGrid_Renderer_Pager

Structures_DataGrid_Renderer_Pager – Pager rendering driver

Description

This driver provides generic paging. This driver has full container support. You can use the Structures_DataGrid::fill() method with it. It buffers output, you can use Structures_DataGrid::getOutput()

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
pagerOptions array Options passed to Pager::factory(). Basic defaults are: mode: Sliding, delta: 5, separator: "|", prevImg: "&lt;&lt;" (<<), nextImg: "&gt;&gt;" (>>). The extraVars and excludeVars options are populated according to the Renderer common extraVars and excludeVars options. You may also specify some variables to be added or excluded here. The totalItems, perPage, urlVar, and currentPage options are set accordingly to the data statistics reported by the DataGrid and DataSource. You may overload these values here if you know what you are doing.  

Structures_DataGrid_Renderer_Smarty

Structures_DataGrid_Renderer_Smarty – Smarty Rendering Driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving yes

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
associative bool By default the column set and the records are numerically indexed arrays. By setting this option to true the keys will be field names instead. false
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
columnAttributes array Column cells attributes. This is an array of the form: array(fieldName => array(attribute => value, ...) ...) This option is only used by XML/HTML based drivers. array()
convertEntities bool Whether or not to convert html entities. This calls htmlspecialchars(). true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
selfPath string The complete path for sorting and paging links. $_SERVER['PHP_SELF']
sortingResetsPaging bool Whether sorting HTTP queries reset paging. true
varPrefix string Prefix for smarty variables and functions assigned by this driver. Can be used in conjunction with Structure_DataGrid::setRequestPrefix() for displaying several grids on a single page. ''

General notes

To use this driver you need the Smarty template engine from http://smarty.php.net

This driver does not support the render() method, it is only able to:

Either fill() a Smarty object by assigning variables and registering the {getPaging} smarty function. It's up to you to call Smarty::display() after the Smarty object has been filled.

Or return all variables as a PHP array from getOutput(), for maximum flexibility, so that you can assign them the way you like to your Smarty instance.

This driver assigns the following Smarty variables:

- $columnSet:       array of columns specifications
                    structure:
                         array (
                             0 => array (
                                 'name'       => field name,
                                 'label'      => column label,
                                 'link'       => sorting link,
                                 'attributes' => attributes string,
                                 'direction'  => 'ASC', 'DESC' or '',
                                 'onclick'    => onMove call
                             ),
                             ...
                         )
- $recordSet:       array of records values
- $currentPage:     current page (starting from 1)
- $nextPage:        next page
- $previousPage:    previous page
- $recordLimit:     number of rows per page
- $pagesNum:        number of pages
- $columnsNum:      number of columns
- $recordsNum:      number of records in the current page
- $totalRecordsNum: total number of records
- $firstRecord:     first record number (starting from 1)
- $lastRecord:      last record number (starting from 1)
- $currentSort:     array with column names and the directions used for sorting
- $datagrid:        a reference that you can pass to {getPaging}

This driver registers a Smarty custom function named getPaging that can be called from Smarty templates with {getPaging} in order to print paging links. This function accepts the same parameters as the pagerOptions option of Structures_DataGrid_Renderer_Pager.

{getPaging} accepts an optional "datagrid" parameter which you can pass the $datagrid variable, to display paging for an arbitrary datagrid (useful with multiple dynamic datagrids on a single page).

Object Records : this drivers preserves object records if provided. This means that if your datasource provides objects instead of associative arrays as records, you can access their properties and methods in your smarty template, with something like: {$recordSet[col]->getSomeInformation()}.

Examples

Using the Smarty renderer

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

$datagrid =& new Structures_DataGrid(10);
$options = array('dsn' => 'mysql://username@localhost/mydatabase');
$datagrid->bind("SELECT * FROM mytable", $options);

$smarty = new Smarty();
$datagrid->fill($smarty);
$smarty->display('smarty-simple.tpl');
?>

Smarty template with sorting and paging (smarty-simple.tpl)

<?php
<!-- Show paging links using the custom getPaging function -->
{getPaging prevImg="<<" nextImg=">>" separator=" | " delta="5"}

<p>Showing records {$firstRecord} to {$lastRecord} 
from {$totalRecordsNum}, page {$currentPage} of {$pagesNum}</p>

<table cellspacing="0">
    <!-- Build header -->
    <tr>
        {section name=col loop=$columnSet}
            <th {$columnSet[col].attributes}>
                <!-- Check if the column is sortable -->
                {if $columnSet[col].link != ""}
                    <a href="{$columnSet[col].link}">{$columnSet[col].label}</a>
                    <!-- Show the current ordering with an arrow -->
                    {if $columnSet[col].direction == "ASC"}
                      &darr;
                    {elseif $columnSet[col].direction == "DESC"}
                      &uarr;
                    {/if}
                {else}
                    {$columnSet[col].label}
                {/if}
            </th>
        {/section}
    </tr>
    
    <!-- Build body -->
    {section name=row loop=$recordSet}
        <tr {if $smarty.section.row.iteration is even}bgcolor="#EEEEEE"{/if}>
            {section name=col loop=$recordSet[row]}
                <td {$columnSet[col].attributes}>{$recordSet[row][col]}</td>
            {/section}
        </tr>
    {/section}
</table>
?>

Structures_DataGrid_Renderer_XLS

Structures_DataGrid_Renderer_XLS – Excel Spreadsheet Rendering Driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support yes
Output Buffering no
Direct Rendering not really, see below
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
bodyFormat mixed The format for body cells (either 0 [= "no format"] or a Spreadsheet_Excel_Writer_Format object) Please see the NOTE ABOUT FORMATTING below. 0
border int Border drawn around the whole datagrid: 0 => none, 1 => thin, 2 => thick (NOT IMPLEMENTED YET) 0
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
filename string The filename of the spreadsheet 'spreadsheet.xls'
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
headerBorder int Border between the header and body: 0 => none, 1 => thin, 2 => thick (NOT IMPLEMENTED YET) 0
headerFormat mixed The format for header cells (either 0 [= "no format"] or a Spreadsheet_Excel_Writer_Format object) Please see the NOTE ABOUT FORMATTING below. 0
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
sendToBrowser bool Should the spreadsheet be send to the browser? (true = send to browser, false = write to a file) true
startCol int The Worksheet column number to start rendering at 0
startRow int The Worksheet row number to start rendering at 0
tempDir string A temporary directory to be used by Spreadsheet_Excel_Writer (cp. "General Notes" section). null
version int If you don't pass a worksheet object to this renderer, you can set the BIFF version with this option. The only accepted value by Spreadsheet_Excel_Writer is 8 (for usage of the BIFF8 format). All other values will lead to the older format (which is needed if you get errors in Excel, e.g. about a broken file). 8
worksheet object Optional reference to a Spreadsheet_Excel_Writer_Worksheet object. You can leave this to null except if your workbook contains several worksheets and you want to fill a specific one. null

General notes

This driver does not support the flatten() method. You can not retrieve its output with DataGrid::getOutput(). You can either render it directly to the browser or save it to a file. See the "sendToBrowser" and "filename" options.

This driver has container support. You can use Structures_DataGrid::fill() with it; that's even recommended.

If PHP's safe_mode is enabled, Spreadsheet_Excel_Writer sometimes fails to generate the Excel file. You can avoid this problem by setting the 'tempDir' option to a (temporary) directory that is writable by PHP.

NOTE ABOUT FORMATTING:

You can specify some formatting with the 'headerFormat' and 'bodyFormat' options, or with setBodyFormat() and setHeaderFormat().

But beware of the following from the Spreadsheet_Excel_Writer manual: "Formats can't be created directly by a new call. You have to create a format using the addFormat() method from a Workbook, which associates your Format with this Workbook (you can't use the Format with another Workbook)."

What this means is that if you want to pass a format to this driver you have to "derive" the Format object out of the workbook used in the driver.

The easiest way to do this is:

// Create a workbook
$workbook = new Spreadsheet_Excel_Writer();

// Specify that spreadsheet must be sent the browser
$workbook->send('test.xls');

// Create your format
$format_bold =& $workbook->addFormat();
$format_bold->setBold();

// Fill the workbook, passing the format as an option
$options = array('headerFormat' => &$format_bold);
$datagrid->fill($workbook, $options);

Structures_DataGrid_Renderer_XML

Structures_DataGrid_Renderer_XML – XML Rendering Driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support no
Output Buffering yes
Direct Rendering yes
Streaming yes
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
columnAttributes array Column cells attributes. This is an array of the form: array(fieldName => array(attribute => value, ...) ...) This option is only used by XML/HTML based drivers. array()
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fieldAttribute string The name of the attribute for the field name. null stands for no attribute null
fieldTag string The name of the tag for each field inside a row, without brackets. The special value '{field}' is replaced by the field name. '{field}'
filename string Filename of the generated XML file; boolean false means that no filename will be sent false
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
labelAttribute string The name of the attribute for the column label. null stands for no attribute null
numberAlign bool Whether to right-align numeric values. true
outerTag string The name of the tag for the datagrid, without brackets 'DataGrid'
rowTag string The name of the tag for each row, without brackets 'Row'
saveToFile boolean Whether the output should be saved on the local filesystem. Please note that the 'filename' option must be given if this option is set to true. false
useXMLDecl bool Whether the XML declaration string should be added to the output. The encoding attribute value will get set from the common "encoding" option. If you need to further customize the XML declaration (version, etc..), then please set "useXMLDecl" to false, and add your own declaration string. true
writeMode string The mode that is used in the internal fopen() calls. Useful e.g. when you want to append to existing file. C.p. the fopen() documentation for the allowed modes. 'wb'

Structures_DataGrid_Renderer_XUL

Structures_DataGrid_Renderer_XUL – XUL Rendering Driver

Supported operations modes

This driver supports the following operation modes:

Supported operations modes of this driver
Mode Supported?
Container Support no
Output Buffering yes
Direct Rendering no
Streaming no
Object Preserving no

Options

This driver accepts the following options:

Options for this driver
Option Type Description Default Value
buildFooter bool Whether to build the footer. true
buildHeader bool Whether to build the header. true
defaultCellValue string What value to put by default into empty cells. null
defaultColumnValues array Per-column default cell value. This is an array of the form: array(fieldName => value, ...). array()
encoding string The content encoding. If the mbstring extension is present the default value is set from mb_internal_encoding(), otherwise it is ISO-8859-1. 'ISO-8859-1'
excludeVars array Variables to be removed from the generated HTTP queries. array()
extraVars array Variables to be added to the generated HTTP queries. array()
fillWithEmptyRows bool Ensures that all pages have the same number of rows. false
hideColumnLinks array By default sorting links are enabled on all columns. With this option it is possible to disable sorting links on specific columns. This is an array of the form: array(fieldName, ...). This option only affects drivers that support sorting. array()
numberAlign bool Whether to right-align numeric values. true
onMove string Name of a Javascript function to call on onclick/onsubmit events when the user is either paging or sorting the data. This function receives a single object argument of the form: { page: <page>, sort: [{field: <field>, direction: <direction>}, ...], data: <user_data> }. Remark: setting this option doesn't remove the href attribute, you should return false from your handler function to void it (eg: for AJAX, etc..). null
onMoveData string User data passed in the "data" member of the object argument passed to onMove. No JSON serialization is performed, this is assigned as a raw string to the "data" attribute. It's up to you to add quotes, slashes, etc... ''
selfPath string The complete path for sorting links $_SERVER['PHP_SELF']

General notes

This renderer class will render a XUL listbox. For additional information on the XUL Listbox, refer to this url: http://www.xulplanet.com/references/elemref/ref_listbox.html

You have to setup your XUL document, just as you would with an HTML document. This driver will only generated the <listbox> element and content.

Examples

Using the XUL renderer

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

$datagrid =& new Structures_DataGrid(10);
$options = array('dsn' => 'mysql://username@localhost/mydatabase');
$datagrid->bind("SELECT * FROM mytable", $options);

header('Content-type: application/vnd.mozilla.xul+xml'); 
 
echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
echo "<?xml-stylesheet href=\"myStyle.css\" type=\"text/css\"?>\n";

echo "<window title=\"MyDataGrid\" 
       xmlns=\"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\">\n";
       
$datagrid->render('XUL');

echo "</window>\n";
?>