Viewing file: class.datagrid.php (65.45 KB) -rw-rw-r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
/** * A class used to display data resulted from a MySQL query or from an array, in an accessible way for the end-user * * Some of the highlights: * * - the class executes a given SQL query and generates a template driven HTML code that displays the query results * - automatically provides means of navigation trough pages and lets user decide how many rows to be displayed on each page * - automatically let user sort by available columns - or you can restrict this feature for specific columns * - if requested, it can automatically display a "selector" column - a column to let users mark specific rows * as selected * - you set what columns from the query result to be displayed * - you can alter the content of a column's fields on the fly by creating callback functions * - you can add JavaScript actions for when user clicks on displayed rows or on specific column's cells * - you can extend the functionality of the data grid by adding custom columns - columns whose content is not * generated by the query but added by you - you can add any HTML and/or JavaScript to perform any action * - everything is template driven * - multi-language support * * See the documentation for more info. * * Read the LICENSE file, provided with the package, to find out how you can use this PHP script. * * If you don't find this file, please write an email to noname at nivelzero dot ro and you will be sent a copy of the license file * * For more resources visit {@link http://stefangabos.blogspot.com} * * @name dataGrid * @package dataGrid * @version 1.0 (last revision: May 20, 2007) * @author Stefan Gabos <[email protected]> * @copyright (c) 2006 - 2007 Stefan Gabos */
error_reporting(E_ALL);
class dataGrid {
/** * When set to TRUE, a navigation tab will be displayed at the top of the table * * default is TRUE * * @var boolean */ var $showTopNavigation; /** * When set to TRUE, a navigation tab will be displayed at the bottom of the table * * default is TRUE * * @var boolean */ var $showBottomNavigation; /** * The page to starts showing records from. * * default is 1 * * @var integer */ var $defaultPage; /** * When set to TRUE, a custom tab will be displayed at the top of the table (underneath the top navigation tab) * * Use {@link addToCustomTab} method to add items to the custom tab * * default is TRUE * * @var boolean */ var $showTopCustomTab; /** * When set to TRUE, a custom tab will be displayed at the bottom of the table (above the bottom navigation tab) * * Use {@link addToCustomTab} method to add items to the custom tab * * default is TRUE * * @var boolean */ var $showBottomCustomTab; /** * The maximum number of pages to be shown at once in the navigation tab * * default is 10 * * @var integer */ var $maxNavigationPages; /** * The selected page from which to start scrolling the pages in the navigation tab * (i.e suppose you have 20 pages. at first, pages from 1 through 10 are shown in the navigation tab * (if $maxNavigationPages is set to 10) but when you click on page 7 then pages from 2 to 12 will * be shown in the navigation tab - that is, if $scrollNavigationPagesFromPage is set to 5) * * default is 5 * * @var integer */ var $scrollNavigationPagesFromPage; /** * The default number of rows to be displayed on a single page * * <b>Note that if the value of this property doesn't exists in {@link recordsOnPageArray}, it's value * be lost upon the first submit and will revert to the first value in {@link recordsOnPageArray}</b> * * default is 15 * * @var integer */ var $rowsOnPage; /** * Array of items to be shown in "records on page" select box in the navigation tab * * default is array(5, 10, 15, 20, 25, 50, 100) * * @var array */ var $recordsOnPageArray; /** * The data grid uses POST which is not SEO friendly but might suit some of the implementations. * * If you want the data grid to be SEO friendly you should set this property to TRUE and set the {@link URLa} property to a value * of your choice, representing the prefix of the page you're currently on, in the data grid. This value will then be appended to the * URL where the data grid is shown. * * So if you have your data grid at * * <i>http://www.mysite.com/example.php</i> * * ...and you set {@link URLa} to "?page=", upon navigating to another page of the data grid, the URL will become * * <i>http://www.mysite.com/example.php?page=X</i> (where X is the current page in the data grid) * * ...while setting it to "/" will make the URL look like * * <i>http://www.mysite.com/example.php/X</i> (where X is the current page in the data grid) * * Default is FALSE * * @var boolean */ var $useSEO;
/** * The data grid uses POST which is not SEO friendly but might suit some of the implementations. * * If you want the data grid to be SEO friendly you should set the {@link useSEO} property to TRUE and set this property to a value * of your choice, representing the prefix of the page you're currently on, in the data grid. This value will then be appended to the * URL where the data grid is shown. * * So if you have your data grid at * * <i>http://www.mysite.com/example.php</i> * * ...and you set this property's value to "?page=", upon navigating to another page of the data grid, the URL will become * * <i>http://www.mysite.com/example.php?page=X</i> (where X is the current page in the data grid) * * ...while setting it to "/" will make the URL look like * * <i>http://www.mysite.com/example.php/X</i> (where X is the current page in the data grid) * * <b>Note that this only work if the {@link useSEO} property is set to TRUE</b> * * Default is '?page=' (without the quotes) * * @var string */ var $URLa;
/** * Message to display if there are no records to display * * By default, the strLang_noRecords message is displayed from the language file * * If this property is anything else than an empty string, it will be used as the message for when there are no records to display * * Default is "" (an empty string) * * @var string */ var $noDataMsg; /** * Where should the grid go upon submit * * <b>this is a read-only property</b> * * @var string */ var $formAction;
/** * The form name is automatically generated every time. * * Read this property to find out what is the form's generated name * * <b>this is a read-only property</b> * * @var string */ var $formName; /** * Initializes the grid * * @param string $source a SELECT SQL to be used to generate grid data * * <i>OR</i> * * an associative array you wish to display in the grid, where the keys of the array will be * the column names * * <b>Notes</b> * * <i>If you are passing a MySQL SELECT query, you must not use ORDER BY and LIMIT * statements in it as they are appended automatically!</i> * * @param string &$db a reference to an instantiated "Zebra PHP Framework MySQL Database Wrapper" object. * you should use this approach for logging and debugging purposes but the class will work * even if you don't specify this reference. in this case the class <b>will assume that there * is already a connection to a MySQL database</b> * * <b>Notes</b> * * <i>In case {@link source} is an array or you simply don't want to use * use Zebra's MySQL Database Wrapper, this argument must still be a variable! So, instead of * passing an empty string, you should pass something like $void</i> * * @param string $formAction (optional) Where should the grid go upon submit * * Default is an empty string and is interpreted as the current path * * <b>Notes</b> * * <i>You should leave this like it is unless you know what you're doing!</i> * * @return void */ function dataGrid($source, &$db, $formAction = "") { // default values to properties $this->showTopNavigation = true;
$this->showBottomNavigation = true;
$this->defaultPage = 1;
$this->showTopCustomTab = true;
$this->showBottomCustomTab = true;
$this->maxNavigationPages = 10;
$this->scrollNavigationPagesFromPage = 5;
$this->rowsOnPage = 15;
$this->recordsOnPageArray = array(5, 10, 15, 20, 25, 50, 100,1000);
$this->secondarySortColumns = "";
$this->useSEO = false;
$this->URLa = "?page=";
$this->noDataMsg = ""; $this->forceHeaderHTML = false; $this->forceFooterHTML = false;
$this->formName = "";
$this->template = "default";
$this->formAction = $formAction == "" ? $_SERVER["REQUEST_URI"] : $formAction;
$this->javaScriptCode = "";
// get the absolute path of the class. any further includes rely on this // and (on a windows machine) replace \ with / $this->absolutePath = preg_replace("/\\\/", "/", dirname(__FILE__)); // get the relative path of the class. ( by removing $_SERVER["DOCUMENT_ROOT"] from the it) // any HTML references (to scripts, to stylesheets) in the template file should rely on this $this->relativePath = preg_replace("/" . preg_replace("/\//", "\/", $_SERVER["DOCUMENT_ROOT"]) . "/i", "", $this->absolutePath); // if $db is specified and is an object and is a "database" object if (@is_object($db) && @get_class($db) == "database") { // set the dbRefference property $this->dbRefference = $db; } // set the query property $this->source = $source; // define an array to hold the column titles specified by the user $this->columnsToShow = array(); // define an array to hold the items in the custom tab $this->customTabItems = array(); // generate an 8 char long random name to use as form name $this->formName = ""; for ($i = 0; $i < 8; $i++) { $this->formName .= chr(rand(97,122)); }
// if the xtemplate class is not already included if (!class_exists("XTemplate") && !class_exists("xtemplate")) {
// include the xtemplate class require_once $this->absolutePath . "/includes/class.xtemplate.php"; } $this->setTemplate("default");
$this->setLanguage("english");
} /** * Ads an user-defined javascript code block (javascript function or stand-alone commands) that will be outputted * with the grid and that can be called by the grid's methods * * <b>Do not specify <script></script> headers as they will be automatically added!</b> * * You can call this method as many times as you want. Previously set code will not be overwritten */ function addJavaScript($script) {
$this->javaScriptCode .= $script . "\n\n";
}
/** * Adds an HTML block (refered to as 'item') to the <b>custom tab</b> * * See also {@link showTopCustomTab} and {@link showBottomCustomTab} * * @param string $HTMLBlock HTML code block to add (this will be further refered to as 'item') * * @param integer $position (optional) by default items are added from left to right. * if you want your item in a specific position, specify it here. * (this is 0 based index - position 0 will be the first item in the custom tab * therefore the leftmost) * * @return void * */ function addToCustomTab($HTMLBlock, $position = "") {
// count the total items in the $customTabItems array $totalItems = count($this->customTabItems);
// if $position was specified if (strlen($position) != 0) {
// validate $position $position =
// if $position is a negative number intval($position) < 0 ?
// make it 0 0 :
// if $position is greater than the available items (remember that this is 0 based index!) (intval($position) > ($totalItems - 1) ?
// make the $position the last element in the index $position = $totalItems :
// if no errors, leave it as it is $position = $position
);
// move all elements in the array, that are greater than $position // to the right (thus, making place to insert $item at $position) for ($i = $totalItems - 1; $i >= $position; $i--) {
$this->customTabItems[$i + 1] = $this->customTabItems[$i];
}
// add $item at $position $this->customTabItems[$position] = $HTMLBlock;
// if $position was not specified } else {
// insert $item into array $this->customTabItems[] = $HTMLBlock;
}
}
/** * Disables sorting possibility for column (by default all columns are sortable) * * <i>This method is also available for custom columns</i> * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method, for which to disable sorting * * <b>Notes</b> * * <i>This argument can also be an array, if you want to disable sorting for * multiple columns at once</i> * * @return void */ function disableSorting($columnName) {
// if $columnName is an array if (is_array($columnName)) {
// iterate through the array foreach ($columnName as $column) {
// disable sorting for the column $this->columnsToShow[$column]["disableSorting"] = true;
}
// $columnName not an array } else {
// disable sorting $this->columnsToShow[$columnName]["disableSorting"] = true;
}
}
/** * Enables sorting for a column on which sorting was previously disabled by using the {@link disableSorting} method * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method, for which to enable sorting * * <b>Notes</b> * * <i>This argument can also be an array, if you want to enable sorting for * multiple columns at once</i> * * @return void */ function enableSorting($columnName) {
// if $columnName is an array if (is_array($columnName)) {
// iterate through the array foreach ($columnName as $column) {
// enable sorting $this->columnsToShow[$column]["disableSorting"] = false;
}
// if $columnName is not an array } else {
// enable sorting $this->columnsToShow[$columnName]["disableSorting"] = false;
}
}
/** * Outputs the grid * * @return boolean TRUE on success or FALSE on failure */ function render($toVar = false) {
// before anything, remove from the columnsToShow array the values that are not supposed to be there // (i.e. a column that was never set through the show or the showCustomColumn methods but has a // callback function or other properties set) foreach ($this->columnsToShow as $originalName=>$column) {
if (!isset($column["name"])) {
unset($this->columnsToShow[$originalName]);
}
}
// the number of records to be shown on one page if (isset($_POST["dataGrid_recordsOnPage"])) {
$this->rowsOnPage = $_POST["dataGrid_recordsOnPage"];
}
// if acting as SEO friendly if ($this->useSEO) {
// check if form action URL contains information about the current page if (preg_match_all("/" . quotemeta($this->URLa) . "([0-9]*)?" . "/", $this->formAction, $matches) > 0) {
// if does, use that as current page $this->currentPage = $matches[1];
// if no information about the current page could be found in form action URL } else {
// take the default page as current page $this->currentPage = $this->defaultPage;
}
// if not acting as SEO friendly } else {
// get the current page $this->currentPage = isset($_POST["dataGrid_page"]) ? $_POST["dataGrid_page"] : $this->defaultPage;
}
// get the field to sort by $this->sortField = isset($_POST["dataGrid_sortfield"]) ? $_POST["dataGrid_sortfield"] : "";
// get the direction of sorting $this->sortDirection = isset($_POST["dataGrid_sortdirection"]) ? $_POST["dataGrid_sortdirection"] : "";
// if current page is smaller than 1 if ($this->currentPage < 1) {
// set the current page to 1 $this->currentPage = 1;
}
// if data to display comes from an array if (is_array($this->source)) {
// count the total records to be displayed $this->totalRecords = count($this->source);
// if there are any records at all if ($this->totalRecords > 0) {
// iterate through the records foreach ($this->source as $key => $row) {
// iterate through each column of a row foreach ($row as $columnTitle => $columnValue) {
// and save data into it's column (this is used later for sorting the data) ${"zebraDataGrid_" . $columnTitle}[$key] = $columnValue;
}
}
// if the data needs to be sorted if ($this->sortField != "") {
// sort the array array_multisort(${"zebraDataGrid_" . $this->sortField}, strtolower($this->sortDirection) == "desc" ? SORT_DESC : SORT_ASC, $this->source);
}
// delete from the array the records that are not displayed on the current page for ($i = 0; $i < ($this->currentPage - 1) * $this->rowsOnPage; $i++) {
unset($this->source[$i]);
}
// delete from the array the records that are not displayed on the current page for ($i = (($this->currentPage - 1) * $this->rowsOnPage) + $this->rowsOnPage; $i < $this->totalRecords; $i++) {
unset($this->source[$i]);
}
// move the internal pointer to the top reset($this->source);
}
// if data come from an SQL } else {
// if the data needs to be sorted if ($this->sortField != "") {
// append the sort string to the SQL $this->source .= " ORDER BY " . $this->sortField . (strtolower($this->sortDirection) == "desc" ? " DESC" : "" ) . (trim($this->secondarySortColumns) != "" ? ", " . (trim(substr($this->secondarySortColumns, 0, 1)) == "," ? substr(trim($this->secondarySortColumns), 1) : trim($this->secondarySortColumns)) : "");
}
// add the LIMIT statement to the query $this->source .= " LIMIT " . (($this->currentPage - 1) * $this->rowsOnPage) . ", " . $this->rowsOnPage . " ";
// execute the query // if there is a reference to a "database" object if (isset($this->dbRefference)) {
// execute the query through the "database" object $this->sourceResult = $this->dbRefference->query($this->source);
// get the total number of records in the result (ignoring the LIMIT) $this->totalRecords = $this->dbRefference->foundRows;
// if there is no reference to a "database" object then // assume that there is a connection to a database } else {
// if SQL_CALC_FOUND_ROWS string is not found in query append it // (we do this trick to get the numbers of records that would've been returned if there was no LIMIT applied) if (strtolower(substr(ltrim($this->source), 0, 6)) == "select" && strpos($this->source, "SQL_CALC_FOUND_ROWS") === false) {
// add the 'SQL_CALC_FOUND_ROWS' parameter to the query $this->source = preg_replace("/SELECT/i", "SELECT SQL_CALC_FOUND_ROWS", $this->source, 1);
}
// execute the query using standard php function $this->sourceResult = mysql_query($this->source)or die(mysql_error() . "<br /><br />" . $this->source);
// get the total number of records in the result (ignoring the LIMIT) $foundRows = mysql_fetch_assoc(mysql_query("SELECT FOUND_ROWS()"));
$this->totalRecords = $foundRows["FOUND_ROWS()"];
}
}
// continue only if data comes from an array or executing the SQL returned a valid result if (is_array($this->source) || @is_resource($this->sourceResult)) {
// assign relative path to the template folder // any HTML references (to scripts, stylesheets) in the template file should rely on this $this->xtpl->assign("templatePath", $this->relativePath . "/templates/" . $this->template . "/");
// assign the form's name $this->xtpl->assign("formName", $this->formName);
// assign the form's action $this->xtpl->assign("formAction", $this->formAction);
// if there are records to display if ($this->totalRecords > 0) {
// assign some values to be used in the template // the number of total records $this->xtpl->assign("totalRecords", $this->totalRecords);
// showing records from $showRecordsFrom = (($this->currentPage - 1) * $this->rowsOnPage) + 1;
$this->xtpl->assign("showingRecordsFrom", $showRecordsFrom);
// showing records to $showRecordsTo = (($this->currentPage - 1) * $this->rowsOnPage) + $this->rowsOnPage;
if ($showRecordsTo > $this->totalRecords) {
$showRecordsTo = $this->totalRecords;
}
$this->xtpl->assign("showingRecordsTo", $showRecordsTo);
// create the options for the "records on page" select $options = "";
for ($i = 0; $i < count($this->recordsOnPageArray); $i++) {
$options .= "<option value='" . $this->recordsOnPageArray[$i] . "' " . ($this->rowsOnPage == $this->recordsOnPageArray[$i] ? "selected" : "") . ">" . $this->recordsOnPageArray[$i] . "</option>";
}
$this->xtpl->assign("options", $options);
// if we have custom javascript code to show if (isset($this->javaScriptCode)) {
$this->xtpl->assign("javaScript", $this->javaScriptCode);
}
// if we have custom HTML at header if (isset($this->headerHTML)) {
$this->xtpl->assign("HTML", $this->headerHTML);
$this->xtpl->parse("main.headerHTML");
}
// if we have custom HTML at footer if (isset($this->footerHTML)) {
$this->xtpl->assign("HTML", $this->footerHTML);
$this->xtpl->parse("main.footerHTML");
}
// compute the total number of pages $this->totalPages = ceil($this->totalRecords / $this->rowsOnPage);
$this->xtpl->assign("totalPages", $this->totalPages);
if ($this->useSEO) {
$this->xtpl->assign("URLa", $this->URLa);
$this->xtpl->assign("qmURLa", quotemeta($this->URLa));
$this->xtpl->parse("main.useSEO");
}
// colspan $this->xtpl->assign("totalColspan", count($this->columnsToShow));
// if a navigation bar is to be displayed at the top or on the bottom of the table if ($this->showTopNavigation || $this->showBottomNavigation) {
// enable navigation only if there are more than 1 pages if ($this->totalPages > 1) {
// if there are more pages than the number of pages to be displayed at once in the navigation tab if ($this->totalPages > $this->maxNavigationPages) {
// set the page number from which to show the page numbers in the navigation tab $maxNavigationPagesFrom =
$this->currentPage < $this->scrollNavigationPagesFromPage ?
1 :
(($this->currentPage - $this->scrollNavigationPagesFromPage + 1) + $this->maxNavigationPages < $this->totalPages ?
($this->currentPage - $this->scrollNavigationPagesFromPage + 1) :
($this->totalPages - $this->maxNavigationPages));
// if there are less pages than the number of pages to be displayed at once in the navigation tab } else {
// set to 1 the page number from which to show the page numbers in the navigation tab $maxNavigationPagesFrom = 1;
}
// compute the maximum page number to be shown in the navigation tab $showPageTo =
$maxNavigationPagesFrom + $this->maxNavigationPages > $this->totalPages ?
$this->totalPages :
($maxNavigationPagesFrom + $this->maxNavigationPages);
// if current page number is greater than 1 if ($this->currentPage > 1) {
// enable the "previous page" button // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.previous_page_link");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.previous_page_link");
}
// if current page is 1 } else {
// disable the "previous page" button // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.previous_page_link_disabled");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.previous_page_link_disabled");
}
}
// show page numbers in the navigation tab for ($i = $maxNavigationPagesFrom; $i <= $showPageTo; $i++) {
$this->xtpl->assign("page", $i); // if the page number currently to be displayed is the current page
if ($i == $this->currentPage) {
// parse accordingly // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.item.selected");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.item.selected");
}
// if the page number currently to be displayed is not the current page } else {
// parse accordingly // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.item.selectable");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.item.selectable");
}
}
// wraps up page number display // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.item");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.item");
}
}
// if current page number is less than the total available pages if ($this->currentPage < $this->totalPages) {
// enable the "next page" button // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.next_page_link");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.next_page_link");
}
// if current page number is equal total available pages } else {
// disable the "next page" button // on the top navigation bar if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation.next_page_link_disabled");
}
// on the bottom navigation bar if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation.next_page_link_disabled");
}
}
}
// wraps up navigation tab display // on top if ($this->showTopNavigation) {
$this->xtpl->parse("main.top_navigation");
}
// and on the bottom if ($this->showBottomNavigation) {
$this->xtpl->parse("main.bottom_navigation");
}
}
// show column titles // iterates through columns to display foreach ($this->columnsToShow as $originalName=>$column) {
// create the action for the onlick event $this->xtpl->assign("originalName", $originalName);
$this->xtpl->assign("column", $column["name"]);
// if there are special properties for this column's title if (isset($column["titleHTMLProperties"])) {
$this->xtpl->assign("titleHTMLProperties", $column["titleHTMLProperties"]);
} else {
$this->xtpl->assign("titleHTMLProperties", "");
}
// if sorting is not set to "disabled" if (
!isset($column["disableSorting"]) || (
isset($column["disableSorting"]) &&
!$column["disableSorting"]
)
) {
// if the data is sorted by this field if ($this->sortField == $originalName) {
// if the sort direction is ascending if ($this->sortDirection == "") {
// show the ascending image $this->xtpl->parse("main.column.title.sorted_asc");
// if the sort direction is descending } else {
// show the descending image $this->xtpl->parse("main.column.title.sorted_desc");
}
}
// parse as sortable $this->xtpl->parse("main.column.title.sortable");
// if sorting is disabled } else {
// parse as not sortable $this->xtpl->parse("main.column.title.not_sortable");
}
// wraps up column title display $this->xtpl->parse("main.column.title");
}
// wraps up column header display $this->xtpl->parse("main.column");
$counter = 0;
// iterates through all the rows in the query result while ((is_array($this->source) ? (list($key, $value) = each($this->source)) : ($row = mysql_fetch_assoc($this->sourceResult)))) {
if (is_array($this->source)) {
$row = $value;
}
$counter++;
// iterates through the fields in the row foreach ($this->columnsToShow as $field=>$properties) { // if it's a custom field we're talking about if (isset($properties["custom"])) {
$row[$field] = "";
}
// if there is a callback function specified for records in current column and function exists if (
isset($this->columnsToShow[$field]["callback"]) &&
$this->columnsToShow[$field]["callback"] != "" &&
function_exists($this->columnsToShow[$field]["callback"])
) {
// run the callback function on the current value eval("\$value = " . $this->columnsToShow[$field]["callback"] . "('" . preg_replace("/\'/", "\\'", $row[$field]) . "', \$row);");
} else {
// get the value of the field (and allow field identifiers of form tablename.field) $value = $row[(strpos($field, ".") ? substr($field, strpos($field, ".") + 1) : $field)]; //$value.="-".$field;
} if ($field=="puntuacion"){ $cortada=0; $numeroestrellas=intval($value); if ($numeroestrellas==0){ $estrellas="<small>sin votos</small>"; }else{ $estrellas=''; for($g=0;$g<=$numeroestrellas;$g++){ if ($g>0)$estrellas.="<img src='estrellita.gif'>"; } $cortada=$numeroestrellas-floatval($value); } //echo "value=$value,nuerroestrellas=$numeroestrellas,cortada=$cortada"; if ($cortada!=0)$estrellas.="<img src='estrellita_cortada.gif'>"; $this->xtpl->assign("value",$estrellas); }elseif ($field=='autor'){ // buscamos premio nobel //echo "select autor from papyr225_papyre.autores_nobel where autor like '%".$field."%'"; $rox=@mysql_fetch_array(mysql_query("select autor from papyr225_papyre.autores_nobel where autor like '%".trim($value)."%'")); if ($rox){ $this->xtpl->assign("value", $value."<img src='nobel.gif'>"); }else{ $this->xtpl->assign("value", $value); } }else{ $this->xtpl->assign("value", $value); }
// if there is an action function specified for records in current column if (isset($this->columnsToShow[$field]["action"]) && $this->columnsToShow[$field]["action"] != "") {
// run the callback function on the current value eval("\$action = " . $this->columnsToShow[$field]["action"] . "('" . preg_replace("/\'/", "\\'", $row[(strpos($field, ".") ? substr($field, strpos($field, ".") + 1) : $field)]) . "', \$row);");
} else {
$action = "";
}
$this->xtpl->assign("action", $action);
// if there are special properties for this column's fields if (isset($this->columnsToShow[$field]["fieldHTMLProperties"])) {
$this->xtpl->assign("fieldHTMLProperties", $this->columnsToShow[$field]["fieldHTMLProperties"]);
// if no special properties } else {
// we empty fieldHTMLProperties or else it will have any previously set fieldHTMLProperties $this->xtpl->assign("fieldHTMLProperties", "");
}
// if we're on an even row if ($counter % 2 == 0) {
// parse the field accordingly $this->xtpl->parse("main.row.even_row.field");
// if we're on an odd row } else {
// parse the field accordingly $this->xtpl->parse("main.row.odd_row.field");
}
}
// if we're on an even row if ($counter % 2 == 0) {
// parse the row accordingly $this->xtpl->parse("main.row.even_row");
// if we're on an odd row } else {
// parse the row accordingly $this->xtpl->parse("main.row.odd_row"); }
// wraps up row display $this->xtpl->parse("main.row");
}
// if top and/or bottom custom tabs are to be shown and there are elements to be shown in the custom tab if (
($this->showTopCustomTab || $this->showBottomCustomTab) &&
isset($this->customTabItems) &&
is_array($this->customTabItems) &&
!empty($this->customTabItems)
) {
// iterate through the available items foreach ($this->customTabItems as $item) {
// parse items $this->xtpl->assign("item", $item);
// if required if ($this->showTopCustomTab) {
// show top custom tab $this->xtpl->parse("main.top_action_tab.item");
}
// if required if ($this->showBottomCustomTab) {
// show bottom custom tab $this->xtpl->parse("main.bottom_action_tab.item");
}
}
// wrap up custom tab display // if required if ($this->showTopCustomTab) {
// top custom tab $this->xtpl->parse("main.top_action_tab");
}
// if required if ($this->showBottomCustomTab) {
// bottom custom tab $this->xtpl->parse("main.bottom_action_tab");
}
}
// if there are no records to display } else {
// if custom message is to be displayed instead of the message from the language file if ($this->noDataMsg != "") {
// display the custom message $this->xtpl->assign("noDataMsg", $this->noDataMsg);
// if message from the language file needs to be displayed } else {
// display the message from the language file $this->xtpl->assign("noDataMsg", $this->languageStrings["strLang_noRecords"]);
}
$this->xtpl->parse("main.no_data");
// if we have custom HTML at header and needs to be displayed even if there are no records if (isset($this->headerHTML) && $this->forceHeaderHTML) {
$this->xtpl->assign("HTML", $this->headerHTML);
$this->xtpl->parse("main.headerHTML");
}
// if we have custom HTML at footer and needs to be displayed even if there are no records if (isset($this->footerHTML) && $this->forceFooterHTML) {
$this->xtpl->assign("HTML", $this->footerHTML);
$this->xtpl->parse("main.footerHTML");
}
}
// wraps up the grid $this->xtpl->parse("main");
if ($toVar) {
// display return $this->xtpl->text("main");
} else {
// display $this->xtpl->out("main");
}
// if query did not return a valid result } else {
// return false return false;
}
}
/** * Binds to a column an user defined PHP function that <b>returns</b> the javascript to be run whenever the onclick * event occurs on any of column's fields * * <i>The user defined function takes as parameter the value of the field where the onclick event occurred and, * optionally, an array containing all the available fields and their respective values for that particular row</i> * * By calling this method you will unset any previously set actions by the {@link setRowActionFunction} method for the * specified column * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method * * @param string $actionFunctionName name of the user defined function * * @return void */ function setActionFunction($columnName, $actionFunctionName) {
// set the action function for this column's fields $this->columnsToShow[$columnName]["action"] = $actionFunctionName;
}
/** * Sets a callback function to be run on each value of a specific column before displaying it * * <i>The user defined function takes as parameter the value of the field where the onclick event occurred and, * optionally, an array containing all the available fields and their respective values for that particular row</i> * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method * * <b>Notes</b> * * <i>This argument can also be an array, if you want to set the same callback * function for multiple columns at once</i> * * @param string $callbackFunctionName name of the user defined function * * @return void */ function setCallBackFunction($columnName, $callbackFunctionName) {
// if $columnName is an array if (is_array($columnName)) {
// iterate through all the given columns foreach ($columnName as $column) {
// set the callback function for each one of the columns $this->columnsToShow[$column]["callback"] = $callbackFunctionName;
}
// if $columnName is not an array } else {
// set the callback function for this column $this->columnsToShow[$columnName]["callback"] = $callbackFunctionName;
}
}
/** * Sets HTML attributes for specific column * * <i>The properties must be valid HTML markup for the <td> element (or whatever element you are using in the template)</i> * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method * * <b>Notes</b> * * <i>This argument can also be an array, if you want to set the attributes for * multiple columns at once</i> * * @param string $HTMLProperties HTML attributes * * @return void */ function setColumnHTMLProperties($columnName, $HTMLProperties) {
// if $columnName is an array if (is_array($columnName)) {
// iterate through all the columns foreach ($columnName as $column) {
// sets HTML properties to each one of the columns $this->columnsToShow[$column]["fieldHTMLProperties"] = $HTMLProperties;
}
// if $columnName is not an array } else {
// sets HTML properties $this->columnsToShow[$columnName]["fieldHTMLProperties"] = $HTMLProperties;
}
}
/** * Sets the default column to sort the records by, and the direction of sorting * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or {@link showCustomColumn} * by which to sort the data initially * * @param string $sortDirection the direction of sorting. possible values are "ASC" and "DESC" * default is "ASC" * */ function setDefaultSortColumn($columnName, $sortDirection = "ASC") {
// this property is applied only if there was no sorting done by the user if (!isset($_POST["dataGrid_sortfield"])) {
$_POST["dataGrid_sortfield"] = $columnName;
$_POST["dataGrid_sortdirection"] = ($sortDirection == "ASC" ? "" : "DESC");
// call this method for the new values in $_POST to show up in the template $this->xtpl->scan_globals();
}
}
/** * Alias of {@link setColumnHTMLProperties} * * @deprecated This method is deprecated - please use {@link setColumnHTMLProperties} instead * * @return void */ function setFieldHTMLProperties($columnName, $HTMLProperties) {
$this->setColumnHTMLProperties($columnName, $HTMLProperties);
}
/** * Sets the HTML code to be displayed after the rendering of the table but INSIDE the form * * @param string $HTML HTML code to be displayed * * @param boolean $showIfNoData Instructs the class whether to show the footer HTML code if there's no data to display * * Default is false * * @return void */ function setFooterHTML($HTML, $showIfNoData = false) {
$this->footerHTML = $HTML; $this->forceFooterHTML = $showIfNoData;
}
/** * Sets the HTML code to be displayed before the rendering of the table but INSIDE the form * * @param string $HTML HTML code to be displayed * * @param boolean $showIfNoData Instructs the class whether to show the header HTML code if there's no data to display * * Default is false * * @return void */ function setHeaderHTML($HTML, $showIfNoData = false) {
$this->headerHTML = $HTML;
$this->forceHeaderHTML = $showIfNoData;
}
/** * Sets a new language * * <i>Default language of the data grid is english</i> * * @param string $language The name of the php language file you wish to use from the /languages folder must be specified * Without the extension! (i.e. "german" for the german language not "german.php") * * @var string * * @return void */ function setLanguage($languageFile) {
// include the language file require_once $this->absolutePath . "/languages/" . $languageFile . ".php";
// assign all the values from the language file $this->xtpl->assign("languageStrings", $this->languageStrings);
}
/** * Specifies a user defined PHP function that <b>returns</b> the javascript to be run whenever the onclick * event occurs on <b>any</b> field of <b>any</b> row * * After calling this method you can still set specific actions for individual column fields by calling the * {@link setActionFunction} method. * * <i>The user defined function takes as parameter the value of the field where the onclick event occurred and, * optionally, an array containing all the available fields and their respective values for that particular row</i> * * @param string $actionFunctionName name of the user defined function * * @return void */ function setRowActionFunction($actionFunctionName) {
// iterate through available columns foreach ($this->columnsToShow as $columnName=>$properties) {
// if column is not blocked (see unsetActionFunction) if (!isset($this->columnsToShow[$columnName]["blockAction"])) {
// set the action function for all the columns to show $this->columnsToShow[$columnName]["action"] = $actionFunctionName;
}
}
}
/** * If you need additional sorting columns, after the primary sort column, use this method to set them * * The column set with {@link setDefaultSortColumn} or at run-time by the user is known as "the primary sorting column" * * @param string $columnNames Identifier names of columns you wish to further order the results by (and optionally ASC or DESC - * as you would normally use when writing MySQL ORDER BY clauses), separated by commas */ function setSecondarySortColumns($columnNames) {
$this->secondarySortColumns = $columnNames;
}
/** * Sets a new template to be used * * <i>Default template of the data grid is "default"</i> * * @param string $template The folder of the template you wish to use. Inside the folder * there <b>must</b> be a <b>template.xtpl</b> file which will be automatically used * * @var string * * @return void */ function setTemplate($template) {
// if template object was not already created if (!isset($this->xtpl)) {
// create a new XTemplate object using the specified template $this->xtpl = new XTemplate($this->absolutePath . "/templates/" . $template . "/template.xtpl");
// if template object was already created } else {
// restart it using the specified template $this->xtpl->restart($this->absolutePath . "/templates/" . $template . "/template.xtpl");
}
$this->template = $template;
// if language was already set if (isset($this->languageStrings)) {
// reassign all the values from the language file $this->xtpl->assign("languageStrings", $this->languageStrings);
}
}
/** * Sets HTML attributes for specific column's title * * <i>The properties must be valid HTML markup for the <td> element (or whatever element is used in the template)</i> * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or * {@link showCustomColumn} method * * <b>Notes</b> * * <i>This argument can also be an array, if you want to set the attributes for * multiple column titles at once</i> * * @param string $HTMLProperties HTML attributes * * @return void */ function setTitleHTMLProperties($columnName, $HTMLProperties) {
// if $columnName is an array if (is_array($columnName)) {
// iterate through all the given columns foreach ($columnName as $column) {
// sets HTML properties to each one of the columns $this->columnsToShow[$column]["titleHTMLProperties"] = $HTMLProperties;
}
// if $columnName is not an array } else {
// sets HTML properties $this->columnsToShow[$columnName]["titleHTMLProperties"] = $HTMLProperties;
}
}
/** * Sets a column for displaying in the grid (none are displayed by default) * * @param string $columnName name of an existing column * * <b>Notes</b> * * <i>If data source is an SQL, you can also refer to column names as <tablename.columnname></i> * * <i>All methods that require you to specify the "identifier name of the column" as parameter * refer to this property!</i> * * @param string $title (optional) text to be displayed instead of the column name * * @return void */ function showColumn($columnName, $title = "") { // adds column to the array of columns specified by the user $this->columnsToShow[$columnName] = array("name"=>($title == "" ? $columnName : $title), "disableSort"=>false); } /** * Specifies a custom column to be shown * * A custom column is a column whose data is not found in the data source * * The content of a custom column is generated by using the {@link setCallBackFunction} method * * @param string $columnName a name for the column * * <b>Notes</b> * * <i>All methods that require you to specify the "identifier name of the column" as parameter * refer to this property!</i> * * @param string $title (optional) text to be displayed instead of the column name * * @return void */ function showCustomColumn($columnName, $title = "") {
// adds column to the array of columns specified by the user $this->columnsToShow[$columnName] = array("name"=>($title == "" ? $columnName : $title), "custom"=>true);
} /** * Enables a "selector" column - a column with checkboxes enabling the user to mark specific rows as selected * * @param string $columnName string to be displayed as column title * * @param string $controlName a unique name to identify the checkbox controls array * * <b>Notes</b> * * <i>All methods that require you to specify the "identifier name of the column" as parameter * refer to this property!</i> * * <i>Each checkbox's ID will be $controlName + underscore + specific value;</i> * * <i>So, if the control's name is "checkbox" and $valueSeed's first value's is 1, the first checkbox's * ID will be "checkbox_1"</i> * * @param string $valueSeed the identifier name of a column in data source to be used for values for each checkbox * * <b>Notes</b> * * <i>this column must be a column that holds data that uniquely identifies data from each row</i> * * @return void */ function showSelectorColumn($columnName, $controlName, $valueSeed) { // adds column to the array of columns specified by the user $this->showCustomColumn("%dataGrid_selectorColumn%", $columnName); // unsets any action for this column and blocks any further settings of actions for this column $this->unsetActionFunction("%dataGrid_selectorColumn%", true); // disables sorting for this column $this->disableSorting("%dataGrid_selectorColumn%"); // the function that will generate the content for the cell $functionString = " function _selector(\$data, \$rowData) { return ' <input type=\"checkbox\" style=\"margin:-2px;font-size:0px;\" name=\"" . $controlName . "[]\" id=\"" . $controlName . "_'.@\$rowData[\"" . $valueSeed . "\"].'\" value=\"'.@\$rowData[\"" . $valueSeed . "\"].'\" class=\"grid-row-selector-checkbox\" onclick=\"if (this.checked == false) {this.parentNode.parentNode.className = this.parentNode.parentNode.id} else {this.parentNode.parentNode.className = \'grid-row-selected\'}\"> '; } "; // registers the function eval ($functionString); // and sets it as the callback function for the column $this->setCallBackFunction("%dataGrid_selectorColumn%", "_selector"); // adds the javascript function to handle 'check all', 'uncheck all' and 'invert selection' calls $this->addJavaScript(" function setChkBoxGroupState(formName, controlName, action) { if (document.forms[formName].elements[controlName].length) { for (i=0;i<document.forms[formName].elements[controlName].length;i++) { document.forms[formName].elements[controlName][i].checked = (action == 'invert' ? 1 - Math.abs(document.forms[formName].elements[controlName][i].checked) : (action == 'none' ? false : true)); if (document.forms[formName].elements[controlName][i].checked == false) { document.forms[formName].elements[controlName][i].parentNode.parentNode.className = document.forms[formName].elements[controlName][i].parentNode.parentNode.id; } else { document.forms[formName].elements[controlName][i].parentNode.parentNode.className = 'grid-row-selected'; } } } else { document.forms[formName].elements[controlName].checked = (action == 'invert' ? 1 - Math.abs(document.forms[formName].elements[controlName].checked) : (action == 'none' ? false : true)); if (document.forms[formName].elements[controlName].checked == false) { document.forms[formName].elements[controlName].parentNode.parentNode.className = document.forms[formName].elements[controlName].parentNode.parentNode.id; } else { document.forms[formName].elements[controlName].parentNode.parentNode.className = 'grid-row-selected'; } } } ");
// adds the 'check all', 'uncheck all' and 'invert selection' items to the custom tab
$this->xtpl->assign("action", "javascript:setChkBoxGroupState('" . $this->formName . "', '" . $controlName . "[]', 'all');return false");
$this->xtpl->assign("caption", $this->languageStrings["strLang_checkAll"]);
$this->xtpl->parse("main.check_all");
$this->addToCustomTab($this->xtpl->text("main.check_all"));
$this->xtpl->reset("main.check_all"); $this->xtpl->assign("action", "javascript:setChkBoxGroupState('" . $this->formName . "', '" . $controlName . "[]', 'none');return false");
$this->xtpl->assign("caption", $this->languageStrings["strLang_uncheckAll"]);
$this->xtpl->parse("main.uncheck_all");
$this->addToCustomTab($this->xtpl->text("main.uncheck_all"));
$this->xtpl->reset("main.uncheck_all");
$this->xtpl->assign("action", "javascript:setChkBoxGroupState('" . $this->formName . "', '" . $controlName . "[]', 'invert');return false");
$this->xtpl->assign("caption", $this->languageStrings["strLang_invertSelection"]);
$this->xtpl->parse("main.invert_selection");
$this->addToCustomTab($this->xtpl->text("main.invert_selection"));
$this->xtpl->reset("main.invert_selection");
} /** * Unsets the action function * * By calling this method you will unset any previously set actions by the {@link setRowActionFunction} or the * {@link setActionFunction} methods for the specified column * * @param string $columnName identifier name of a column previously set with the {@link showColumn} or {@link showCustomColumn} * method * * <b>Notes</b> * * <i>This argument can also be an array, if you want to unset the action for multiple columns at once</i> * * @param string $block if set to true, further calling of the {@link setRowActionFunction} function will * have no effect on the $columnName column. you can still set an action to this * column by calling the {@link setActionFunction} method explicitly for $columnName * * @return void */ function unsetActionFunction($columnName, $block = false) { // if $columnName is an array if (is_array($columnName)) {
// iterate through all the given columns foreach ($columnName as $column) {
// unset the action function for this column's fields unset($this->columnsToShow[$column]["action"]);
// if block if ($block) {
// set a special flag for this column $this->columnsToShow[$column]["blockAction"] = true;
} } // if $columnName is not an array } else {
// unset the action function for this column's fields unset($this->columnsToShow[$columnName]["action"]);
// if block if ($block) {
// set a special flag for this column $this->columnsToShow[$columnName]["blockAction"] = true;
}
} } } ?>
|