Re: Structures_DataGrid question - do I need to use DB_DataObject?

From: Date: Fri, 18 Nov 2005 13:40:48 +0000
Subject: Re: Structures_DataGrid question - do I need to use DB_DataObject?
References: 1  Groups: php.pear.general 
Request: Send a blank email to pear-general+get-21987@lists.php.net to get a copy of this message
Interesting indeed, I didn't know that you could assign object to smarty and call their method right from the template. What I did could be merged with yours as I did not make much for the pager. Here's the Array renderer I wrote and how I use it. The main limitation is you can't use columns that have an empty or null 'name' property Sorry if some comments mismatch the context, most of them come from Structures_DataGrid_Renderer_HTML_Table The renderer class saved under Array.php : <?php class Structures_DataGrid_Renderer_Array {
    /**
     * Wether or not to reset paging on sorting request
     * @var bool
     */
    var $sortingResetsPaging = true;
    /**
     * The complete path for the sorting links.  If not defined, PHP_SELF is
     * used.
     * @var string
     */
    var $path;
    /**
     * The icon to define that sorting is currently Ascending.  Can be text or
     * HTML to define an image.
     * @var string
     */
     var $sortIconASC;
    /**
     * The icon to define that sorting is currently Descending.  Can be text or
     * HTML to define an image.
     * @var string
     */
     var $sortIconDESC;
    /**
     * The HTML::Pager object that controls paging logic.
     * @var object Pager
     */
    var $pager;
    /**
     * The structures_datagrid object
     * @var object Structures_DataGrid
     */
    var $_dg;
    /**
     * The array containing headers and rows
     * @var array
     */
    var $_Array;
    /**
     * A switch to determine the state of the table
     * @var bool
     */
    var $_rendered = false;
    /**
     * Variables to be added to the generated links
     * @var array
     */
    var $_extraVars = array();
    /**
     * Constructor
     *
     * Build default values
     *
     * @param   object Structures_DataGrid  $dg     The datagrid to render.
     * @access  public
     */
    function Structures_DataGrid_Renderer_Array(&$dg)
    {
        $this->_dg =& $dg;
        $this->_Array = array();
    }
    function toArray(){
        $this->getArray();
    	return $this->_Array;
    }
    /**
     * Gets the array for the DataGrid
     *
     * @access  public
     * @return  void
     */
    function getArray()
    {
        $dg =& $this->_dg;
        if (!$this->_rendered) {
            /*
            // Get the data to be rendered
            if (PEAR::isError($result = $dg->fetchDataSource())) {
                return $result;
            }
            */
            // Check to see if column headers exist, if not create them
            // This must follow after any fetch method call
            $dg->_setDefaultHeaders();
            // Define Array['Header']
            if ($this->header) {
                $this->_buildArrayHeader();
            }
            // Build Array['Data']
            $this->_buildArrayBody();
            $this->_rendered = true;
        }
    }
    /**
     * Sets the rendered status.  This can be used to "flush the cache" in case
     * you need to render the datagrid twice with the second time having changes
     *
     * @access  public
     * @params  bool        $status     The rendered status of the DataGrid
     */
    function setRendered($status)
    {
        $this->_rendered = (bool)$status;
    }
    /**
     * Handles building the header of the DataGrid
     *
     * @access  private
     * @return  void
     * @todo    Redesign/Rework the header URL building.
     */
    function _buildArrayHeader()
    {
        $cnt = 0;
        foreach ($this->_dg->columnSet as $column) {
            //Define Content
            if (!is_null ($column->orderBy)) {
                // Determine Direction
                if ($this->_dg->sortArray[0] == $column->orderBy &&
                    $this->_dg->sortArray[1] == 'ASC') {
                    $direction = $this->_dg->_requestPrefix . 'direction=DESC';
                } else {
                    $direction = $this->_dg->_requestPrefix . 'direction=ASC';
                }
                // Build URL -- This needs much refinement :)
                $get = array();
                if (isset($_SERVER['QUERY_STRING'])) {
                    $qString = explode('&', $_SERVER['QUERY_STRING']);
                    $i = 0;
                    $prefix = $this->_dg->_requestPrefix;
                    foreach($qString as $element) {
                        if ($element != '') {
                            $list = explode ('=', $element);
                            $key = $list[0];
                            switch ($key) {
                                case $prefix . 'orderBy' :
                                    $get[] = $prefix . 'orderBy=' .
                                                   $column->orderBy;
                                    $orderByExists = true;
                                    break;
                                case $prefix . 'direction' :
                                    $get[] = $direction;
                                    break;
                                case $prefix . 'page' :
                                    $get[] = $prefix . 'page=1';
                                    break;
                                default:
                                    if (!in_array ($key, array_keys ($this->_extraVars))) {
                                        $get[] = $element;
                                    }
                            }
                        }
                    }
                    if (!isset($orderByExists)) {
                        $get[] = $this->_dg->_requestPrefix . 'orderBy=' .
                                 $column->orderBy;
                        $get[] = $direction;
                    }
                } else {
                    $get[] = $this->_dg->_requestPrefix . 'orderBy=' .
                             $column->orderBy;
                    $get[] = $direction;
                }
                foreach ($this->_extraVars as $key => $val) {
                    $val = urlencode ($val);
                    $get[] = "$key=$val";
                }
                if (isset($this->path)) {
                    $url = $this->path . '?';
                } else {
                    $url = $_SERVER['PHP_SELF'] . '?';
                }
                $url .= join ('&amp;', $get);
                $str = '<a href="' . $url . '">' . $column->columnName;
                $iconVar = "sortIcon" .
                           ($this->_dg->sortArray[1] ? $this->_dg->sortArray[1] : 'ASC');
                if (($this->$iconVar != '') &&
                    ($this->_dg->sortArray[0] == $column->orderBy)) {
                    $str .= ' ' . $this->$iconVar;
                }
                $str .= '</a>';
            } else {
                $str = $column->columnName;
            }
            // Print Content to HTML_Table
            $this->_Array['headers'][$column->columnName]=$str;
            $cnt++;
        }
    }
    /**
     * Handles building the body of the DataGrid
     *
     * @access  private
     * @return  void
     */
    function _buildArrayBody()
    {
        if ($this->_dg->recordSet) {
            if (!isset($this->_dg->rowLimit)) {
                $this->_dg->rowLimit = count($this->_dg->recordSet);
            }
            // Determine looping values
            if ($this->_dg->rowLimit >= count($this->_dg->recordSet)) {
                $begin = 0;
                $end = $this->_dg->rowLimit;
            } else {
                if ($this->_dg->page > 1) {
                    $begin = ($this->_dg->page - 1) * $this->_dg->rowLimit;
                    $end = $this->_dg->page * $this->_dg->rowLimit;
                } else {
                    $begin = 0;
                    if ($this->_dg->rowLimit == null) {
                        $end = count($this->_dg->recordSet);
                    } else {
                        $end = $this->_dg->rowLimit;
                    }
                }
            }
            // Begin loop
            $rowCnt = 0;
            for ($i = $begin; $i < $end; $i++) {
                if (isset($this->_dg->recordSet[$i])) {
                    $cnt = 0;
                    $row = $this->_dg->recordSet[$i];
                    foreach ($this->_dg->columnSet as $column) {
                        // Build Content
                        if (isset($column->formatter)) {
                            //Use Formatter
                            $content = $column->formatter($row);
                        } elseif (!isset($column->fieldName)) {
                            if ($column->autoFillValue != '') {
                                // Use AutoFill
                                $content = $column->autoFillValue;
                            } else {
                                // Use Column Name
                                $content = $column->columnName;
                            }
                        } else {
                            // Use Record Data
                            $content = htmlentities($row[$column->fieldName]);
                            if (($content == '') &&
                                ($column->autoFillValue != '')) {
                                // Use AutoFill
                                $content = $column->autoFillValue;
                            }
                        }
                        // Set Content in Data
                        $this->_Array['Data'][$rowCnt][$column->columnName]=$content;
                        $cnt++;
                    }
                    $rowCnt++;
                }
            }
        }
        $this->_Array['Pager']=$this->getPaging();
    }
    /**
     * Handles the building of the page list for the DataGrid in HTML.
     * This method uses the HTML::Pager class
     *
     * @access  public
     * @param   string $mode        The mode of pager to use
     * @param   string $separator   The string to use to separate each page link
     * @param   string $prev        The string for the previous page link
     * @param   string $next        The string for the forward page link
     * @param   string $delta       The number of pages to display before and
     *                              after the current page
     * @param   array $attrs        Additional attributes for the Pager class
     * @return  string              The HTML for the page links
     * @see     HTML::Pager
     */
    function getPaging($mode = 'Sliding', $separator = '|', $prev = '<<',
                       $next = '>>', $delta = 5, $attrs = null)
    {
        require_once 'Pager/Pager.php';
        // Generate Paging
        $options = array('mode' => $mode,
                         'delta' => $delta,
                         'separator' => $separator,
                         'prevImg' => $prev,
                         'nextImg' => $next);
        if (is_array($attrs)) {
            $options = array_merge($options, $attrs);
        }
        if (isset ($options['extraVars'])) {
            $options['extraVars'] = array_merge ($options['extraVars'], $this->_extraVars);
        } else {
            $options['extraVars'] = $this->_extraVars;
        }
        $this->_buildPaging($options);
        // Return paging html
        return $this->pager->links;
    }
    /**
     * Handles generating the paging object
     *
     * @param   array        $options        Array of HTML::Pager options
     * @access  private
     * @return  void
     */
    function _buildPaging($options)
    {
        if ($this->_dg->_dataSource != null) {
            $count = $this->_dg->_dataSource->count();
        } else {
            $count = count($this->_dg->recordSet);
        }
        $defaults = array('totalItems' => $count,
                          'perPage' => is_null($this->_dg->rowLimit) ?
                                            $count : $this->_dg->rowLimit,
                          'urlVar' => $this->_dg->_requestPrefix . 'page',
                          'currentPage' => $this->_dg->page);
        $options = array_merge($defaults, $options);
        $this->pager =& Pager::factory($options);
    }
    /**
     * Add custom GET variables to the generated links
     *
     * This method adds the provided variables to the paging and sorting
     * links. The variable values are automatically url encoded.
     *
     * @param   array   $vars   Array of the form (key => value, ...)
     * @access  public
     * @return  void
     */
    function setExtraVars ($vars)
    {
        $this->_extraVars = $vars;
    }
} ?> How I use it : <?php $cdg=new houseContactDg(10);// Subclass of Structures_DataGrid that makes the columns I need $cdg->setRenderer("Array","classes/");// (depending on where you put the Array.php file $cdg->bind(&$dataobject); $smarty->assign("data",$cdg->renderer->toArray()); ?> And the smarty template : <table> <tr> <th>Order by : </th> <th>{$data.headers.Name}</th> <th>{$data.headers.Date}</th> <th>&nbsp;</th> </tr> {foreach item=sec key=i from=$data.Data} <tr> <td>{html_image file=$sec.Filename}</td> <td>{$sec.Name}<br /> Message sent on : {$sec.Date}<br /> {$sec.Message} </td><td>{$sec.editlink}</td> </tr> {/foreach} </table> {$data.Pager}

« previous php.pear.general (#21987) next »