Zend Framework: creating your own grid helper

9 Feb

Grid is used in almost every application. So its better to create a gird view helper than to create a grid on each page where it needs.

In this article I am going to discuss how to create a helper for creating grid with a single line of code.

Although you can create view helper wherever you want and can use that helper only by adding path to that helper and than call that view helper in your view template, however here I am going to create a gird helper in the library/Zend/View/Helper directory where all the helper shipped with Zend reside.

So lets have a look.

First create Grid.php in library/Zend/View/Helper directory and place the following code in it.

<?php

require_once ‘Zend/View/Helper/Abstract.php’;

class Zend_View_Helper_Grid2 extends Zend_View_Helper_Abstract

{

 

public $view = null;

 

   public function setView(Zend_View_Interface $view)

    {

        $this->view = $view;

        return $this;

    }

   /* this constructor takes 4 args, name of the grid, header columns, paginator and the bool value sorting.

    public function grid ($name, $fields = null,$paginator=null,$sorting=false)

    {

 

// taking value of sort using Fron controller getRequest() method.

$sort = Zend_Controller_Front::getInstance()->getRequest()->getParam(‘sort’,’DESC’);

// checking and handling sorting.

if ($sort  ==  ‘ASC’) {

            $sort = ‘DESC’;

          }  else  {

            $sort = “ASC”;

         }

// start constructing the gird.

       $output=”<div id='”.$name.”‘>”;

        $output .= “<table class=’grid’>

                                                         <thead>

                                                                    <tr>”;

        // this foreach loop display the column header  in “th” tag.

foreach ($fields as $key => $value)  {

                            $output .= “<th>”;

                          // check if sorting is true, if so add link to the fields headers

 if          ($sorting){

                            $output .= “<a href='”.$this->view->url(array(‘sort’=>$sort,’by’=>$key)).”‘>”.$value.”</a>”;

                             }  else  {

                             $output .= $value;

                            }

              $output .= “</th>”;

                       }

                            $output .= “</tr>

                                   </thead>”;

                    // constructing the body that contain the records in rows and columns.

 $output .=”<tbody>”;

                      // this loop display the actual data.

foreach($paginator as $p) {

                        $output.=”<tr>”;

                            foreach($p as $record) {

                                             $output .= “<td>”.$record.”</td>”;

                                }

                          $output.=”</tr>”;

                    }

                   $output .= “</tbody>”;

                  // check if paginator is ture, if so then add paginator component to the table “tfoot”.

if($paginator) {

                           $output .=”<tfoot>”;

                           $output .=”<td align=’center’ colspan='”.count($fields).”‘>”;

            $output.= $this->view->paginationControl($paginator,

                             ‘Sliding’,

                             ‘pagination.phtml’);

                               $output .=”</tfoot>”;

                        }

        $output .=”</table><div>”;

           return $output;

    }

}

 

In the code above we first extend our helper form the Zend_View_Helper_Abstract class. All view helper classes extend this abstract class.

Next we define function setView(Zend_View_Interface $view). This function is necessary if you want to access variable assign to you view template in your helper class.

 The next method/constructor is the most important one. In constructor we are creating our gird.

The argument passed to this constructor are the name of the gird, fields array that will be displays as the column name of the grid.

The paginator variable is the object of paginator component.

In the fist lines we get the sort from the request if sent. Otherwise set its default value.

Next we create a table and check if paginator is set to true, if yes then we call paginator controller, passing it paginator instance, the type of the pagination, and the partial view helper.

That’s it, if you break the code you will easily understand what we are building.

 

After creating your helper class, its time to call it from your view template. Use the following code for this purpose.

<?

            $fields = array(

                        ‘id’ => ‘ID’,

                        ‘firstname’ => ‘First Name’,

                        ‘lastname’ => ‘Last Name’,

                        ’email’ => ‘Email’,

                        ‘username’ =>’Username’

            );

            echo $this->grid(

                                              ‘grd’,

                                                    $fields,

                                                              $this->paginator,

                                                                                                   true);

?>

 

 

cheers.

5 Responses to “Zend Framework: creating your own grid helper”

  1. Dmitri February 9, 2009 at 10:52 pm #

    Hello Faheem.
    Many thanks to you for your articles, they are very usefull and interesting to me.
    Small question: why do you create your class in library/Zend/View/Helper? Wouldn’t it be better to do it in your own branch like this: library/Mod/View/Helper, in order to keep your code aside from Zend?
    Then your class will look like this: Mod_View_Helper_Grid2.

  2. Faheem Abbas February 10, 2009 at 5:46 am #

    Yeah, you are right. actually If you make your own directory for helpers, you need to tell the view where helpers resides and in this article I was interested in telling that how can you make your own grid helper rather than a proper way of creating helpers in own directory structure.
    Anyway the thing you mention is recommended.
    However you will need to do a bit of more work in that case.
    Thanks.

  3. Jignesh December 22, 2009 at 6:55 am #

    Hi,

    Thanks for this articles. when i want to implement this grid view to my application to view the data in grid using Grid.php file then following fetal error occured.

    Fatal error: Uncaught exception ‘Zend_Loader_PluginLoader_Exception’ with message ‘Plugin by name ‘Grid’ was not found in the registry; used paths: Zend_View_Helper_: Zend/View/Helper/;./application/default/views\helpers/’ in C:\Program Files\Zend Source\library\Zend\Loader\PluginLoader.php:406

    My project structure is like this.

    C:/wamp/www/B4UProject/application/default/controller
    /models
    /views/helper/Grid.php
    /forms

    C:/wamp/www/B4UProject/application/default/controller
    /models
    /views
    /forms

    so how can i solve the error. please guide if i have to add code then where i have to add it.

    Regards,
    Jignesh

  4. Jignesh December 22, 2009 at 8:40 am #

    Hi,
    I have solve the above posted problem. now it will give an error of Warning: Invalid argument supplied for foreach() in C:\wamp\www\modular\application\default\views\helpers\Grid.php on line 66

    Please give solution for this..

    Regards,
    Jignesh

  5. Richard Jones February 10, 2011 at 6:59 pm #

    WordPress is eating your apostrophes. When I copy and pasted I then had to do a find and replace all the “Right single quotation mark”s with apostrophes. Not a huge deal on this small file, but still a pain. It might be a good idea to offer the code as a downloadable file. You could also bundle your entire library as a public project on github or google code and point readers to that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: