Vous êtes sur la page 1sur 12

DataGr|d 2end Iramework - Manua|

Please keep in mind that the most updated version of this document can be found at
http://petala-azul.com/blog/datagrid-full-manual/



DataGrid Zend Framework Manual............................................................................................................................................1
Index .............................................................................................................................................................................................2
Introduction...................................................................................................................................................................................3
The DataGrid ................................................................................................................................................................................4
The basics ....................................................................................................................................................................................4
Specifying fields and defining options .......................................................................................................................................5
Titles ......................................................................................................................................................................................5
Sql Expressions.....................................................................................................................................................................5
Hiding a field. .........................................................................................................................................................................5
Horizontal Row ......................................................................................................................................................................6
Eval........................................................................................................................................................................................6
Class......................................................................................................................................................................................6
searchType............................................................................................................................................................................6
Format ...................................................................................................................................................................................6
Extra Fields............................................................................................................................................................................7
Joins..........................................................................................................................................................................................8
SQL Expressions ......................................................................................................................................................................8
Filters ........................................................................................................................................................................................9
Export ........................................................................................................................................................................................9
CRUD......................................................................................................................................................................................10
CRUD Operations................................................................................................................................................................10
Add columns to the form......................................................................................................................................................10
Templates ...............................................................................................................................................................................11
Cache......................................................................................................................................................................................12
Internationalization..................................................................................................................................................................12
Bugs & Restrictions.................................................................................................................................................................12


Introduct|on

My name is Bento Vilas Boas and Im from Portugal. Im not a senior developer, so you will find some code that needs to be
optimized (thats why its open-source).
Ive done my first work with ZF about six months ago, and my first disappointment was the lack of a DataGrid.
Meanwhile Ive been working on a new CMS (that will probably be open-source, but its in a early stage) and I started this
DataGrid.
This is a beta version. You will find bugs, there are more than 8500 lines of code, and I personally can't test all situations.
My main principle is to keep things simple, but not too simple (its a quote, not sure the author).
A junior developer will have no problems using this DataGrid, but a senior will have tools to extend and maximize it to fit its
needs.
1he DataGr|d
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, ....)

1he bas|cs
You only need tree lines of code to deploy a DataGrid. You need to pass the db instance to the constructor.

$db = Zend_Regi st r y: : get ( " db" ) ;
$gr i d = new Bvb_Gr i d_Depl oy_Tabl e( $db, ' Document Ti t l e' , ' t emp/ di r ' ) ;
$gr i d- >f r om( ' t abl e' ) ;
$t hi s- >vi ew- >gr i d = $gr i d- >depl oy( ) ;

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:
$gr i d- >hi de( ar r ay( ' passwor d' ) ) ;
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
$gr i d- >or der ( ' i d DESC' ) ;
You can also define the where clause like this
$gr i d- >wher e( " i d>5" ) ;
If you wan to omit the filters just use this code
$gr i d- >noFi l t er s ( 1) ;
And if you don't want to give user's the ability to order the results add the following code
$gr i d- >noOr der ( 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.
$gr i d- >l i mi t ( 5) ;
Or
$gr i d- >l i mi t ( ar r ay( 4, 10) ) ;

Spec|fy|ng f|e|ds and def|n|ng opt|ons

There are two methods for add fields to the Datagrid. One is more simple, the other is more "object way".

The simple way:

You can specify each field you want to display by using the following method:
$gr i d- >addCol umn( ' user name' ) ;
$gr i d- >addCol umn( ' emai l ' ) ;
With the above code, only two fields will be fetched and presented to the user. Now, the good part.
Defining field's options.
1|t|es
The most obvious is setting the field title. That can be accomplished using
$gr i d- >addCol umn( ' user name' , ar r ay( ' t i t l e' =>" User name Ti t l e " ) ) ;
With this code, the title will be " Username Title " (without the quotes).
Sq| Lxpress|ons
We may want to show the salaries average, the amount of money we make per year, etc.
$gr i d- >addCol umn( ' sal ar y' , ar r ay( sql exp=>" AVG( sal ar y) " ) ) ;
$gr i d- >gr oupBy( ' 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

n|d|ng a f|e|d.
$gr i d- >addCol umn( ' i d' , ar r ay( ' hi de' =>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:
$gr i d- >addCol umn( ' user name' , ar r ay( ' t i t l e' =>" User name" , ' decor at or ' =>' <a
hr ef =" ht t p: / / exampl e. com/ user / i d/ { { i d} } " > { { user name} } </ 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 {{}}.

nor|zonta| kow
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.
$gr i d- >addCol umn( ' user name' , ar r ay( ' hRow' =>1) ) ;
Please note the case sensitive index.

Lva|
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
$gr i d- >addCol umn( ' user name' , ar r ay( ' eval ' =>" ucf i r st ( ' { { user name} } ' ) " ) ) ;

C|ass
As the name implies, this will pass to the template the CSS class name to be applied.
$gr i d- >addCol umn( ' user name' , ar r ay( ' cl ass' =>" r ed" ) ) ;

search1ype
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.
$gr i d- >addCol umn( ' user name' , ar r ay( ' sear chType' =>" ! =" ) ) ;
Options available:
DataGrid SQL
like LIKE '%value%'
equal =
= =
rlike LIKE 'value%'
llike LIKE '%value'
>= >=
> >
!= !=
<> <>
<= <=
< <

Iormat
This index will call a class that has been previously added to the DataGrid
$gr i d- >addCol umn( ' amount ' , ar r ay( ' f or mat ' =>" number " ) ) ;
Optionally you can set the format index as an array to pass optional arguments to the class constructor
$gr i d- >addCol umn( ' amount ' , ar r ay( f or mat =>ar r ay( ' number ' , ar r ay( ' ar g' =>1, ' ar g' =>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
$gr i d = new Bvb_Gr i d_Depl oy_Tabl e( ) ;
$gr i d- >addFor mat t er Di r ( ' Bvb/ Gr i d/ For mat t er ' , ' Bvb_Gr i d_For mat t er ' ) ;
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
$gr i d = new Bvb_Gr i d_Depl oy_Tabl e( ) ;
$gr i d- >addFor mat t er Di r ( ' Bvb/ Gr i d/ For mat t er ' , ' Bvb_Gr i d_For mat t er ' ) ;
$gr i d- >addFor mat t er Di r ( ' My/ Gr i d/ For mat t er ' , ' My_Gr i d_For mat t er ' ) ;
The system will look first for a class named My_Grid_Formatter_Number and then for other called
Bvb_Grid_Formatter_Number
If no match found, the field value will be returned.
The object way
$gr i d = $t hi s- >gr i d ( ' t abl e' ) ; # The const r uct or ar gument i s t he f i el d name
$gr i d- >f r om ( ' Count r y' )
- >or der ( ' Name' )
- >set Pagi nat i on ( 20 ) ;

$cap = new Bvb_Gr i d_Col umn ( ' Name' ) ;
$cap- >t i t l e ( ' Count r y ( Capi t al ) ' )
- >decor at or ( ' <em>( { { Name} } ) </ em>' ) ;

$cont i nent = new Bvb_Gr i d_Col umn ( ' Cont i nent ' ) ;
$cont i nent - >t i t l e ( ' Cont i nent ' ) ;

$popul at i on = new Bvb_Gr i d_Col umn ( ' Popul at i on' ) ;
$popul at i on- >t i t l e ( ' Popul at i on' )
- >cl ass ( ' wi dt h_80' ) ;

$l i f eExpect at i on = new Bvb_Gr i d_Col umn ( ' Li f eExpect ancy' ) ;
$l i f eExpect at i on- >t i t l e ( ' Li f e E. ' )
- >cl ass ( ' wi dt h_50' ) ;

$gr i d- >addCol umns ( $cap, $cont i nent , $popul at i on, $l i f eExpect at i on) ;

Lxtra I|e|ds
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.
$r i ght = new Bvb_Gr i d_Ext r aCol umns( ) ;
$r i ght - >posi t i on( ' r i ght ' )
- >name( ' Ri ght ' )
- >decor at or ( " <i nput cl ass=' i nput _p' t ype=' t ext ' val ue=\ " { { Li f eExpect ancy} } \ " si ze=\ " 3\ "
name=' number [ ] ' >" ) ;


$l ef t = new Bvb_Gr i d_Ext r aCol umns( ) ;
$ l ef t - >posi t i on( ' l ef t ' )
- >name( ' Lef t ' )
- >decor at or ( " <i nput t ype=' checkbox' name=' number [ ] ' >" ) ;


$gr i d- >addExt r aCol umns( $r i ght , $l ef t ) ;
The extra fields can't be filtered or ordered.
Io|ns

Working with joins isnt harder then working with simple tables.
But there are some aspects that need your attention.
$gr i d- >f r om( " nr _user s u I NNER JOI N nr _user _vi si t s v ON u. i d = v. user _i d" ) ;
And we MUST declare the tables in use
$gr i d- >t abl e( ar r ay( ' v' =>' nr _user _vi si t s' , ' u' =>' nr _user s' ) ) ;
And, obviously, when naming fields we need to prefix them width the table name.
$gr i d- >addCol umn( ' u. user name' , ar r ay( ' t i t l e' =>' User name' ) ) ;
$gr i d- >addCol umn( ' u. emai l ' , ar r ay( ' t i t l e' =>' Emai l ' ) ) ;
$gr i d- >addCol umn( ' v. mont h' , ar r ay( ' t i t l e' =>' Mont h' ) ) ;
$gr i d- >addCol umn( ' v. year ' , ar r ay( ' t i t l e' =>' Year ' ) ) ;
Example:
When setting the order
$gr i d- >or der ( " u. i d" ) ;
When hiding
$gr i d- >hi de( ar r ay( ' u. i d' , ' v. user _i d' , ' u. passwor d' , ' u. i d' ) ) ;
etc, etc,

SL Lxpress|ons

The expression result will be presented before the pagination as a new table row (tr) and bellow to matching field
Using SQL expressions is as easy as this
$gr i d- >sql exp ( ar r ay( ' i d' =>' COUNT' , ' t ot al ' =>' SUM' , ' sal es' =>' AVG' ) ) ;
The output:
Count all records from id field
Sum all records from total field
Calculate Average from sales field
Can be used all expressions like this
SELECT EXP(FIELD) FROM .
Some examples:
SUM
MAX
AVG

I||ters

Well, there isnt 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)
$gr i d- >noFi l t er s( 1) ;
You can also create a dropdown menu with the values that user is allowed to filter
$f i l t er s = new Bvb_Gr i d_Fi l t er s( ) ;
$f i l t er s- >addFi l t er ( ' emai l ' )
- >addFi l t er ( ' user name' , ar r ay( ' val ues' =>$val ues) ) ;

$gr i d- >addFi l t er s( $f i l t er s) ;
$values is the result of
$val ues = $db- >f et chAl l ( " SELECT user name AS name, emai l AS val ue FROM user s" ) ;
Important: The fields output names must be name and value.
We can also apply a style to the filter input form

$gr i d- >f i l t er s=ar r ay( ' emai l ' =>ar r ay( ' st yl e' =>' wi dt h: 75px; ' ) ,
' user name' =>ar r ay( ' st yl e' =>" wi dt h: 175px; " ) ) ;
A great option you can get is auto select the distinct values for every field on your table.
$gr i d- >f i l t er s=ar r ay( u. user name=>ar r ay( ' di st i nct ' =>ar r ay( ' f i el d' =>' u. i d' ,
' name' =>' u. user name' ) ) ) ;
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.
Lxport
To allow results exportation the only thing you need to do is this
$gr i d- >expor t = ar r ay( ' pdf ' , ' wor d' , ' wor dx' , ' excel ' , ' pr i nt ' , ' ods' , ' odt ' ) ; # or j ust pdf and
wor d
Or choose the formats you want.
CkUD
It's easier than ever to add record to a table
But before a little more how it's done
The way system treats records inserting
If there are not defined fields the system will automatically hide the auto-increment field, and show all the others
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)
CkUD Cperat|ons

Option Type Description
add 0|1 Gives user permission to add records to the table
delete 0|1 Gives user permission to delete records from the table
edit 0|1 Gives user permission to edit records from the table
button 0|1 This will place a small text before the form with a link to add a new record
double_tables 0|1 If you want to have the form and the grid on the same page, or if when you are adding or
editing results the datagrid is omitted
onAddForce array Insert values that are not part of the form. The most common example is when you want to
add the user id, the update date, etc.
Ex: $form-> onAddForce ( array ('date_added' => dat Ex: $fields->validators ( array
('EmailAddress' ) ) e ( 'Y-m-d H:i:s' ),'user_id'=>'1' ) );
onEditForce array The same that onAddForce
onDeleteAddWhere string This is used for security. Imagine that you only want to allow a user to remove is owns
records. You will have to do something like this:
Ex: $form-> onDeleteAddWhere(" user_id='1' ");
Instead of
DELETE FROM table WHERE id='34'
you will get
DELETE FROM table WHERE id='34' AND user_id='1'
onDeleteCascade array This option is used for delete records from another table that matches a value that is being
deleted from the table. Suppose you are removing a user from the users table. Probably
will also want to remove the user articles, images, etc, etc.
EX:$form-
>onDeleteCascade(array('table'=>articles,'parentField'=>'id','childField'=>user_id,
'operand'=>'='));
$form->onDeleteCascade(array('table'=>images,'parentField'=>'id','childField'=>user_id,
'operand'=>'='));
By default the parentField is the primary_key and the operand is =, so you can omit that
indexes

Example:
$f or m = new Bvb_Gr i d_For m ( ) ;
$f or m- >add ( 1 )
- >but t on ( 1 )
- >del et e ( 1 )
- > onAddFor ce ( ar r ay ( ' dat e_added' => dat e ( ' Y- m- d H: i : s' ) ) )
- >onEdi t For ce ( ar r ay ( ' dat e_added' => dat e ( ' Y- m- d H: i : s' ) ) ) ;

Add co|umns to the form

Option Type Description
title string The title for the field
description string The field description
validators array An array with validators for a given field
Ex: $fields->validators ( array ('EmailAddress' )
filters array An array with filters for a given field
Ex: $field->filters(array('StringToLower','Alpha','StringTrim'));
values array An array containing values that will appear on a select input

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:
$f Add = new Bvb_Gr i d_For m_Col umn ( ' f i r st name' ) ;
$f Add- >t i t l e ( ' Fi r st name' )
- >val i dat or s ( ar r ay ( ' Emai l Addr ess' ) )
- >descr i pt i on ( ' I nser t you emai l addr ess' ) ;

$l ast Name = new Bvb_Gr i d_For m_Col umn ( ' l ast name' ) ;
$l ast Name- >t i t l e ( ' Last name' ) ;

$count r y = new Bvb_Gr i d_For m_Col umn ( ' count r y' ) ;
$count r y- >t i t l e ( ' Count r y' )
- >descr i pt i on ( ' Choose your Count r y' )
- >val ues ( $count r y ) ;

$count r y = $db- >f et chCol ( " SELECT DI STI NCT( Name) FROM Count r y ORDER BY Name
ASC " ) ;

$l ang = new Bvb_Gr i d_For m_Col umn ( ' l anguage' ) ;
$l ang- >t i t l e ( ' Language' )
- >descr i pt i on ( ' Your l anguage' )
- >val ues ( $l anguage ) ;

$l anguage = $db- >f et chCol ( " SELECT DI STI NCT( Language) FROM Count r yLanguage
ORDER BY Language ASC" ) ;

$f or m- >addCol umns ( $f Add, $l ast Name, $count r y, $l ang ) ;
$gr i d- >addFor m ( $f or m ) ;
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
$gr i d- >addEl ement Di r ( ' My/ Val i dat e' , ' My_Val i dat e' , ' val i dat or ' ) ;
$gr i d- >addEl ement Di r ( ' My/ Fi l t er ' , ' My_Fi l t er ' , ' f i l t er ' ) ;
1emp|ates
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.
So, to add a new template we have to do this
$gr i d = new Bvb_Gr i d_Depl oy_Tabl e( $db, ' Document Ti t l e' ) ;
$gr i d- >addTempl at eDi r ( ' My/ Templ at e/ Tabl e' , ' My_Templ at e_Tabl e' , ' t abl e' )
$gr i d- >addTempl at eDi r ( ' My/ Templ at e/ Pr i nt ' , ' My_Templ at e_Pr i nt ' , ' pr i nt ' )
$gr i d- >addTempl at eDi r ( ' My/ Templ at e/ Pdf ' , ' My_Templ at e_Pdf ' ) ;
And then assign the template
$gr i d- >set Templ at e( ' per sonal ' , ' t abl e' ) ;
$gr i d- >set Templ at e( ' 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
cl ass My_Templ at e_Tabl e_Per sonal ext ends Bvb_Gr i d_Templ at e_Tabl e_Tabl e
{
}

Important: You need to inform the complete url for the images that appear on the table (for exportation).
You can do that with the following code
$gr i d- >i magesUr l = ' ht t p: / / www. exampl e. com/ publ i c/ i mages/ gr i d/ ' ;
There is no better explanation then look at the templates by you. They are pretty simple.

Cache

The cache use can be very useful, especially on large environments.
To use cache you only need the add the following line of code
$gr i d- >cache = ar r ay( ' use' =>1, ' i nst ance' =>Zend_Regi st r y: : get ( ' cache' ) , ' t ag' =>' gr i d' ) ;
When performing CRUD operations, the cache will be cleaned.
Internat|ona||zat|on

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

8ugs & kestr|ct|ons

Only tested with MySQL databases;
Its only possible add, edit or delete records from a single table and if it has a primary key defined

Vous aimerez peut-être aussi