DataGrid Zend Framework - Manual
DataGrid Zend Framework - Manual
DataGrid
Zend
Framework
–
Manual
Please keep in mind that the most updated version of this document can be found at
http://petala-azul.com/blog/datagrid-full-manual/
Index
DataGrid Zend Framework – Manual............................................................................................................................................1
Index .............................................................................................................................................................................................2
Introduction ...................................................................................................................................................................................3
Titles ......................................................................................................................................................................................5
Eval........................................................................................................................................................................................6
Class......................................................................................................................................................................................6
searchType............................................................................................................................................................................6
Format ...................................................................................................................................................................................6
Extra Fields............................................................................................................................................................................7
Joins..........................................................................................................................................................................................8
Filters ........................................................................................................................................................................................9
Array ......................................................................................................................................................................................9
XML .....................................................................................................................................................................................10
CSV .....................................................................................................................................................................................10
JSON ...................................................................................................................................................................................11
Export......................................................................................................................................................................................11
CRUD ......................................................................................................................................................................................11
CRUD Operations................................................................................................................................................................12
Templates ...............................................................................................................................................................................13
Cache ......................................................................................................................................................................................14
Internationalization ..................................................................................................................................................................14
Introduction
My name is Bento Vilas Boas and Iʼm from Portugal. Iʼm not a senior developer, so you will find some code that needs to be
optimized (thatʼs why itʼs open-source).
Iʼve done my first work with ZF about six months ago, and my first disappointment was the lack of a DataGrid.
Meanwhile Iʼve been working on a new CMS (that will probably be open-source, but itʼs in a early stage) and I started this
DataGrid.
This is a beta version. You will find bugs, there are more than 11.000 lines of code, and I personally can't test all situations.
My main principle is to keep things simple, but not too simple (itʼs a quote, not sure the author).
A junior developer will have no problems using this DataGrid and a senior will be capable to extend and maximize it to fit its
needs.
The
DataGrid
The main file Datagrid.php will abstract the query result and return arrays corresponding to the parts that complete the
Datagrid (titles, sql expressions, filters, pagination, records, ....)
The
basics
You only need tree lines of code to deploy a DataGrid. You need to pass the db instance to the constructor.
$db = Zend_Registry::get("db");
$grid = new Bvb_Grid_Deploy_Table($db,'Document Title','temp/dir');
$grid->from('table');
$this->view->grid = $grid->deploy();
This piece of code will output something like the table we can see here http://petala-azul.com/grid/default/site/basic. It will
fetch all fields from the table and create a table with pagination, filters, order and exportation.
Of curse you can change this behavior. Let's imagine you have a table with 12 fields, but you only need 11, you don't want to
fetch the user's password. You can tell DataGrid to hide certain fields by just doing this:
$grid->hide(array('password'));
All others fields will be fetched, except the password one. You can also do other simple things like define the default order
with this code
$grid->order('id DESC');
$grid->where("id>5");
And if you don't want to give user's the ability to order the results add the following code
$grid->noOrder(1);
There is one more thing you can do on a DataGrid. Defining the limit. But remember. If you use it, the system pagination will
be disabled.
$grid->limit(5);
Or
$grid->limit(array(4,10));
Specifying fields and defining options
There are two methods for add fields to the Datagrid. One is more simple, the other is more "object way".
You can specify each field you want to display by using the following method:
$grid->addColumn('username');
$grid->addColumn('email');
With the above code, only two fields will be fetched and presented to the user. Now, the good part.
Titles
The most obvious is setting the field title. That can be accomplished using
With this code, the title will be " Username Title " (without the quotes).
Sql
Expressions
We may want to show the salaries average, the amount of money we make per year, etc.
$grid->addColumn('salary',array(sqlexp=>"AVG(salary)"));
$grid->groupBy('year');
Don't forget to define the groupBy, or you will get an error. You can find a result example here http://www.petala-
azul.com/grid/default/site/group
Hiding a field.
$grid->addColumn('id',array('hide'=>1));
But for what reason would I like to select a field and then not show him on the table? Good question that deserves a better
answer.
For this:
$grid->addColumn('username',array('title'=>"Username",'decorator'=>'<a
href="http://example.com/user/id/{{id}}"> {{username}}</a>'));
When used the index decorator, in options array, the field value will be replaced by the decorator value. Did you noticed the
{{username}} and {{id}} stuff? Yes? Great. You can call the value of any field by putting is name within {{}}.
Horizontal
Row
One cool option that you could also use is the horizontal row. When activated the horizontal row will produce something like
this http://www.petala-azul.com/grid/default/site/hrow.
$grid->addColumn('username',array('hRow'=>1));
Eval
As most of you already figured out, this code will be passed trough the php function eval. Note that even here you can use the
field's values using {{id}}, or any other field
$grid->addColumn('username',array('eval'=>"ucfirst('{{username}}') "));
Class
As the name implies, this will pass to the template the CSS class name to be applied.
$grid->addColumn('username',array('class'=>"red"));
searchType
This is used to help filters knowing which expression they will apply when searching. By default the LIKE option is used, but
you may want to use the "=" or any other.
$grid->addColumn('username',array('searchType'=>"!="));
Options available:
DataGrid SQL
like LIKE '%value%'
equal =
= =
rlike LIKE 'value%'
llike LIKE '%value'
>= >=
> >
!= !=
<> <>
<= <=
< <
Format
This index will call a class that has been previously added to the DataGrid
$grid->addColumn('amount',array('format'=>"number"));
Optionally you can set the format index as an array to pass optional arguments to the class constructor
$grid->addColumn('amount',array(format=>array('number',array('arg'=>1,'arg'=>2))));
The DataGrid will try to find a class with the name Bvb_Grid_Format_Number and with a method called 'format'
You can add your own formats by setting them after instantiate the grid
You can add as many as dir as you want. The DataGrid will try to find the class on reverse order. So, if you add this
The system will look first for a class named My_Grid_Formatter_Number and then for other called
Bvb_Grid_Formatter_Number
$grid = $this->grid ( 'table' );# The constructor argument is the field name
$grid->from ( 'Country' )
->order ( 'Name' )
->setPagination ( 20 );
Extra
Fields
You can add extra fields to the table on the left or on the right. Every extra field is an array. It looks something like this.
$grid->addExtraColumns($right,$left);
Joins
Working with joins isnʼt harder then working with simple tables.
$grid->table(array('v'=>'nr_user_visits','u'=>'nr_users'));
And, obviously, when naming fields we need to prefix them width the table name.
$grid->addColumn('u.username',array('title'=>'Username'));
$grid->addColumn('u.email',array('title'=>'Email'));
$grid->addColumn('v.month',array('title'=>'Month'));
$grid->addColumn('v.year',array('title'=>'Year'));
Example:
$grid->order ("u.id");
When hiding
$grid->hide(array('u.id','v.user_id','u.password','u.id'));
etc, etc,
SQL Expressions
The expression result will be presented before the pagination as a new table row (tr) and bellow to matching field
$grid->sqlexp (array('id'=>'COUNT','total'=>'SUM','sales'=>'AVG'));
The output:
Some examples:
SUM
MAX
AVG
Filters
Well, there isnʼt much to talk about filters, they are lonely people…
Be default filters are enable and to disable them we must use the following code (as stated before)
$grid->noFilters(1);
You can also create a dropdown menu with the values that user is allowed to filter
$grid->addFilters($filters);
$grid->filters=array('email'=>array('style'=>'width:75px;'),
'username'=>array('style'=>"width:175px; "));
A great option you can get is auto select the distinct values for every field on your table.
$grid->filters=array(u.username=>array('distinct'=>array('field'=>'u.id',
'name'=>'u.username')));
The previous code will fetch all distinct u.id values from the query and present them as a select menu. The value will be the
ʻfieldʼ index and the caption will be the name index.
Using Arrays, JSON, XML, CSV
Array
To create a datagrid using a array the array must have this format
$array = array(
array('name'=>'Jonh','age'=>'20','country'=>'England'),
array('name'=>'Santos','age'=>'25','country'=>'England'),
array('name'=>'Martin','age'=>'40','country'=>'Spain')
);
$grid->setDataFromArray($array);
The system will recognize the index's as titles, but you can change the name later.
How?
$grid->addColumn('age',array('title'=>'My Age'));
The method addColumn will not erase the previous params, instead it will append them using the array_merge function.
These 3 new methods are very useful when using foreign content (XML, CSV, JSON)
XML
To create a grid using XML use this function
//The first argument is the xml location, the second is the loop location and the third is the columns location
$grid->setDataFromXml( 'http://my_url.blogspot.com/feeds/posts/default?alt=rss' ,
'channel, item');
//The first argument is the xml location, the second is the loop location and the third is the columns location (optional)
//The second argument is the path to the loop. The data we want to fetch is inside the channel and item array. (check the XML
structure for confirmation)
CSV
More easy its impossible.
$grid->setDataFromCsv($file, $field = null, $separator = ',');
//Set field to 'true' if first line if the file isn't the columns name
$grid->setDataFromCsv('media/files/grid.csv');
JSON
It's also very easy to work with.
//1-the data
//3- The root to the loop (similar when using XML files)
Example
IMPORTANT: when using using Arrays, JSON, XML or CSV to create your datagrid, the filters, order and 90% of all other
methods still available. But there are some changes
When using filters and using distinct, you only need to do this
You cannot use the where clause, and CRUD operations. Everything else is available for db and foreign datagrid creation
Export
To allow results exportation the only thing you need to do is this
CRUD
It's easier than ever to add record to a table
If the field type is enum, the system will show a DropDown menu with the options set in the field and if the field is 'set' a multi
select will show up
The system will not validate or filter any data if not specified (except the one made by Zend_Db)
CRUD Operations
Example:
Add columns to the form
IMPORTANT: The datagrid will auto recognize the enum and set fields types, so you don't need to set any values, filters, or
validators for them, as the system will check itself. However, if you define the values they will override the ones set on the db field
Form example:
$fAdd = new Bvb_Grid_Form_Column ( 'firstname' );
$fAdd->title ( 'First name' )
->validators ( array ('EmailAddress' ) )
->description ( 'Insert you email address' );
Note: The default validators and filters are the ones that ship with Zend Framework. If you want to add your custom, you have
to define them after instantiate the datagrid
Templates
At this point only word, pdf and table templates are customizable.
The grid will have some default templates, but you may, and probably will, want to change them to fit your needs.
$grid->setTemplate('personal','table');
$grid->setTemplate('company','pdf');
The Datagrid will look for a file called personal at My/Template/Table/Personal.php and will expect a class with the name
My_Template_Table_Personal
CRITICAL: All templates MUST extend the ones that ship with the grid. So in this case will be:
<?php
class My_Template_Table_Personal extends Bvb_Grid_Template_Table_Table
{
}
Important: You need to inform the complete url for the images that appear on the table (for exportation).
$grid->imagesUrl = 'http://www.example.com/public/images/grid/';
There is no better explanation then look at the templates by you. They are pretty simple.
Cache
To use cache you only need the add the following line of code
$grid->cache = array('use'=>1,'instance'=>Zend_Registry::get('cache'),'tag'=>'grid');
Internationalization
Fields titles, fields descriptions and a bunch of other strings are translatable. All you have to do for make it happen is registry
in the Zend_Registry a translator instance with the name Zend_Translate
Bugs & Restrictions