Re: [PHP-PEAR] HTML_Table.php
[email protected] ("clayton collie") Fri, 9 Mar 2001 17:32:38 -0500
| Newsgroups | php.pear |
|---|---|
| Message-ID | <[email protected]> |
Bertrand,
i dont know if you're thinking in this direction, but a useful subclass
would be one tha is populated (attributes included) via user space
callbacks. you can then specialize and grab data from multidimensional
arrays and db's, all from the same code.
as an example, we can have callbacks for table, row, and cell, once we
specify the number of columns we want to create.
An example follows :
// userland function to fetch table row data and attributes
function doOnTableRow(&$table, $row_num, $userData) {
$row = mysql_fetch_array( $userData );
if (!$row) return false;
if ( ($row['balance'] > 0) && ($row['overdue_days'] > 30) ) {
$attrs = "class=\"overdue\"";
// or maybe $this->row_attrs["bgColor"] = "red" etc
} else {
global $color_table;
$bgColor = $color_table[$row_num % count($color_table)]
$attrs = "bgColor=$bgColor"
}
return ($row,$attrs); // row becomes the data passed to
callback below
}
// userland function to return table cell data and attributes
function doOnTableCell(&$table, $row_num, $col_num, $row_data,
$userData) {
$align = ( is_numeric($row_data[$col_num]) ) ? "right" : "";
if ($col_num == 4) {
switch ($row_data['paid_by']) {
case "MC" : $img = "mc.jpg"; break;
case "AMEX" : $img = "amex.jpg"; break;
case "PayPal" : $img = "pp.gif"; break;
}
$img = "<img src=\"/images/$img\" border=0>"
$result = $img
} else {
$result = $row_data[$row_num];
}
$attrs = $align;
return ($result, $attrs);
}
pseudo code for table creation is
function HTML_TableEx::getRow( $row_num, $row_data) {
$row = "";
$td = array();
$cell_func = $this->options["onTD"];
for ($i = 0; $i < $this->colCount; $i++) {
$td = $cell_func($this, $row_num, $row_data, $this->userData);
$attrs = $td[0];
$data = $td[1];
$row .= "\t<TD $attrs>\n\t$data\n\t</TD>\n";
}
return $row;
}
function HTML_TableEx::getRows( ) {
$row_num = 0;
$row_data = "";
$result = "";
$td = array();
$row_func = $this->options["onTR"];
$row_data = $row_func($this, $row_num, $this->userData);
while ( is_array($row_data) ) {
$attrs = $row_data[0];
$data = $row_data[1];
$row = getRow( $row_num++, $data ) ;
$result .= "<TR $attrs>$row\n</TR>\n";
}
return $row;
}
function HTML_TableEx::render() {
echo "<table {$this->tableAttrs}>\n";
echo getRows();
echo "</table>";
}
-- sample use
$sql = "select lastname, firstname, balance, overdue_days, paid_by from
invoices";
$handle = mysql_connect( .... );
$html_table = new HTML_TableEx( array("colCount"=>5, "onTR" =>
"doOnTableRow", "onTD" => "doOnTableCell") )
$html_table->userData = $handle
$html_table->render()