datagrid zend framework 0.1.2

Upload: patricio-cardenas-garay

Post on 17-Oct-2015

38 views

Category:

Documents


0 download

TRANSCRIPT

  • 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............................................................................................................................................1Index .............................................................................................................................................................................................2Introduction ...................................................................................................................................................................................3The DataGrid ................................................................................................................................................................................4The basics ....................................................................................................................................................................................4

    Specifying fields and defining options .......................................................................................................................................5Titles ......................................................................................................................................................................................5Sql Expressions.....................................................................................................................................................................5Hiding a field. .........................................................................................................................................................................5Horizontal Row ......................................................................................................................................................................6Eval........................................................................................................................................................................................6Class......................................................................................................................................................................................6searchType............................................................................................................................................................................6Format ...................................................................................................................................................................................6Extra Fields............................................................................................................................................................................7

    Joins..........................................................................................................................................................................................8SQL Expressions ......................................................................................................................................................................8Filters ........................................................................................................................................................................................9Export ........................................................................................................................................................................................9CRUD......................................................................................................................................................................................10

    CRUD Operations................................................................................................................................................................10Add columns to the form......................................................................................................................................................10

    Templates ...............................................................................................................................................................................11Cache......................................................................................................................................................................................12Internationalization ..................................................................................................................................................................12Bugs & Restrictions.................................................................................................................................................................12

  • 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.

  • 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, ....)

    You only need tree lines of code to deploy a DataGrid. You need to pass the db instance to the constructor.

    $db = Zend_Reg is t r y : :ge t ( "db " ) ; $g r id = new Bvb_Gr id_Dep loy_Tab le ($db , 'Document T i t l e ' , ' t emp /d i r ' ) ; $g r id -> f rom( ' t ab le ' ) ; $ th i s ->v iew->gr id = $g r id ->dep loy ( ) ;

    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:

    $g r id ->h ide (a r ray ( ' 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

    $g r id ->o rde r ( ' i d DESC' ) ;

    You can also define the where clause like this

    $g r id ->where ( " id>5" ) ;

    If you wan to omit the filters just use this code

  • $gr id ->noF i l t e rs (1 ) ;

    And if you don't want to give user's the ability to order the results add the following code

    $g r id ->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.

    $g r id -> l im i t (5 ) ;

    Or

    $g r id -> l im i t (a r ray (4 ,10 ) ) ;

    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:

    $g r id ->addCo lumn( 'use rname ' ) ; $g r id ->addCo lumn( 'ema i l ' ) ;

    With the above code, only two fields will be fetched and presented to the user. Now, the good part.

    Defining field's options.

    The most obvious is setting the field title. That can be accomplished using

    $g r id ->addCo lumn( 'use rname ' ,a r ray ( ' t i t l e '=>"Username T i t l e " ) ) ;

    With this code, the title will be " Username Title " (without the quotes).

    We may want to show the salaries average, the amount of money we make per year, etc.

    $g r id ->addCo lumn( ' sa la ry ' , a r ray (sq lexp=>"AVG(sa la ry ) " ) ) ; $g r id ->g roupBy( ' yea r ' ) ;

    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

    $gr id ->addCo lumn( ' i d ' , a r ray ( ' h ide '=>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 id ->addCo lumn( 'use rname ' ,a r ray ( ' t i t l e '=>"Username" , ' deco ra to r '=> ' { {use rname} }< /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 {{}}.

    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.

    $g r id ->addCo lumn( 'use rnam e ' ,a r ray ( ' hRow '=>1) ) ;

    Please note the case sensitive index.

    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

    $g r id ->addCo lumn( 'use rname ' ,a r ray ( ' eva l ' =>"uc f i r s t ( ' { {use rname} } ' ) " ) ) ;

    As the name implies, this will pass to the template the CSS class name to be applied.

    $g r id ->addCo lumn( 'use rname ' ,a r ray ( ' c lass '=>" red" ) ) ;

    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.

    $g r id ->addCo lumn( 'use rname ' ,a r ray ( ' sea rchType '=>" != " ) ) ;

    Options available:

    DataGrid SQL like LIKE '%value%' equal = = = rlike LIKE 'value%' llike LIKE '%value' >= >= > > != != "number " ) ) ;

    Optionally you can set the format index as an array to pass optional arguments to the class constructor

    $g r id ->addCo lumn( 'amoun t ' , a r ray ( fo rma t=>ar ray ( ' number ' , a r ray ( ' a rg '=>1 , ' a rg '=>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

    $g r id = new Bvb_Gr id_Dep loy_Tab le ( ) ; $g r id ->addFormat te rD i r ( 'Bvb /Gr id /Fo rmat te r ' , 'Bvb_Gr id_Format te r ' ) ;

    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

    $g r id = new Bvb_Gr id_Dep loy_Tab le ( ) ; $g r id ->addFormat te rD i r ( 'Bvb /Gr id /Fo rmat te r ' , 'Bvb_Gr id_Format te r ' ) ; $g r id ->addFormat te rD i r ( 'My /Gr id /Format te r ' , 'My_Gr id_Format te r ' ) ;

    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 id = $ th i s ->g r id ( ' t ab le ' ) ; # The cons t ruc to r a rgumen t i s t he f i e ld name $g r id -> f rom ( 'Coun t ry ' ) ->o rde r ( 'Name ' ) ->se tPag ina t i on ( 20 ) ;

    $cap = new Bvb_Gr id_Co lumn ( 'Name ' ) ; $cap-> t i t l e ( 'Coun t ry (Cap i ta l ) ' ) ->decora to r ( ' ( { { Name} } )< /em> ' ) ;

    $con t inen t = new Bvb_Gr id_Co lumn ( 'Con t inen t ' ) ; $con t inen t -> t i t l e ( 'Con t inen t ' ) ;

    $popu la t i on = new Bvb_Gr id_Co lumn ( 'Popu la t i on ' ) ; $popu la t i on -> t i t l e ( 'Popu la t i on ' ) ->c lass ( 'w id th_80 ' ) ;

    $ l i f eExpec ta t i on = new Bvb_Gr id_Co lumn ( ' L i f eExpec tancy ' ) ; $ l i f eExpec ta t i on -> t i t l e ( ' L i f e E . ' ) ->c lass ( 'w id th_50 ' ) ;

    $g r id ->addCo lumns ( $cap , $con t inen t , $popu la t i on , $ l i f eExpec ta t i on ) ;

    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 gh t = new Bvb_Gr id_Ex t raCo lumns ( ) ; $ r i gh t ->pos i t i on ( ' r i gh t ' ) ->name( 'R igh t ' ) ->decora to r ( "< inpu t c lass= ' i npu t_p ' t ype= ' tex t ' va lue= \ " { {L i f eExpec tancy } } \ " s i ze= \ "3 \ " name= 'number [ ] ' > " ) ;

  • $ le f t = new Bvb_Gr id_Ex t raCo lumns ( ) ; $ l e f t ->pos i t i on ( ' l e f t ' ) ->name( 'Le f t ' ) ->decora to r ( "< inpu t t ype= 'checkbox ' name= 'number [ ] ' > " ) ;

    $g r id ->addEx t raCo lumns ($ r igh t ,$ le f t ) ;

    The extra fields can't be filtered or ordered.

    Working with joins isnt harder then working with simple tables.

    But there are some aspects that need your attention.

    $g r id -> f rom( "n r_users u INNER JOIN n r_user_v i s i t s v ON u . id = v .use r_ id " ) ;

    And we MUST declare the tables in use

    $g r id -> tab le (a r ray ( ' v '=> 'n r_user_v is i t s ' , ' u '=> 'n r_users ' ) ) ;

    And, obviously, when naming fields we need to prefix them width the table name.

    $g r id ->addCo lumn( 'u .use rname ' ,a r ray ( ' t i t l e '=> 'Username ' ) ) ; $g r id ->addCo lumn( 'u .ema i l ' , a r ray ( ' t i t l e '=> 'Ema i l ' ) ) ; $g r id ->addCo lumn( ' v .mon th ' , a r ray ( ' t i t l e '=> 'Mon th ' ) ) ; $g r id ->addCo lumn( ' v . yea r ' , a r ray ( ' t i t l e '=> 'Year ' ) ) ;

    Example:

    When setting the order

    $g r id ->o rde r ( "u . i d " ) ;

    When hiding

    $g r id ->h ide (a r ray ( ' u . i d ' , ' v .use r_ id ' , ' u .password ' , ' u . i d ' ) ) ;

    etc, etc,

    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

    $g r id ->sq lexp (a r ray ( ' i d '=> 'COUNT ' , ' t o ta l ' => 'SUM' , ' sa les '=> '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

    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)

    $g r id ->noF i l t e rs (1 ) ;

    You can also create a dropdown menu with the values that user is allowed to filter

    $ f i l t e rs = new Bvb_Gr id_F i l t e rs ( ) ; $ f i l t e rs ->addF i l t e r ( ' ema i l ' ) ->addF i l t e r ( ' use rname ' ,a r ray ( ' va lues '=>$va lues ) ) ;

    $g r id ->addF i l t e rs ($ f i l t e rs ) ;

    $values is the result of

    $va lues = $db-> fe tchA l l ( "SELECT username AS name, ema i l AS va lue FROM users " ) ;

    Important: The fields output names must be name and value.

    We can also apply a style to the filter input form

    $g r id -> f i l t e rs=ar ray ( ' ema i l ' =>a r ray ( ' s t y le '=> 'w id th :75px ; ' ) , ' use rname '=>ar ray ( ' s t y le '=>"w id th :175px ; " ) ) ;

    A great option you can get is auto select the distinct values for every field on your table.

    $g r id -> f i l t e rs=ar ray (u .use rname=>ar ray ( ' d i s t i nc t '=>ar ray ( ' f i e ld '=> 'u . i d ' , ' name '=> 'u .use rname ' ) ) ) ;

    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.

    To allow results exportation the only thing you need to do is this

    $g r id ->expor t = a r ray ( ' pd f ' , 'wo rd ' , 'wo rdx ' , ' exce l ' , ' p r i n t ' , ' ods ' , ' od t ' ) ; # o r j us t pd f and word

    Or choose the formats you want.

  • 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)

    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:

    $ fo rm = new Bvb_Gr id_Form ( ) ; $ fo rm->add ( 1 ) ->bu t ton ( 1 ) ->de le te ( 1 ) -> onAddForce ( a r ray ( ' da te_added ' => da te ( 'Y -m-d H : i : s ' ) ) ) ->onEd i tFo rce ( a r ray ( ' da te_added ' => da te ( 'Y -m-d H : i : s ' ) ) ) ;

    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:

    $ fAdd = new Bvb_Gr id_Form_Co lumn ( ' f i r s tname ' ) ; $ fAdd-> t i t l e ( ' F i r s t name ' ) ->va l i da to rs ( a r ray ( 'Ema i lAddress ' ) ) ->desc r ip t i on ( ' I nse r t you ema i l add ress ' ) ;

    $ las tName = new Bvb_Gr id_Form_Co lumn ( ' l as tname ' ) ; $ las tName-> t i t l e ( ' Las t name ' ) ;

    $coun t ry = new Bvb_Gr id_Form_Co lumn ( ' coun t ry ' ) ; $coun t ry -> t i t l e ( 'Coun t ry ' ) ->desc r ip t i on ( 'Choose your Coun t ry ' ) ->va lues ( $coun t ry ) ;

    $coun t ry = $db -> fe tchCo l ( "SELECT DIST INCT(Name) FROM Coun t ry ORDER BY Name ASC " ) ;

    $ lang = new Bvb_Gr id_Form_Co lumn ( ' l anguage ' ) ; $ lang -> t i t l e ( ' Language ' ) ->desc r ip t i on ( 'Your l anguage ' ) ->va lues ( $ language ) ;

    $ language = $db -> fe tchCo l ( "SELECT DIST INCT(Language) FROM Coun t ryLanguage ORDER BY Language ASC" ) ;

    $ fo rm->addCo lumns ( $ fAdd , $ las tName, $coun t ry , $ lang ) ; $g r id ->addForm ( $ fo rm ) ;

    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

    $g r id ->addE lemen tD i r ( 'My /Va l i da te ' , 'My_Va l ida te ' , ' va l i da to r ' ) ; $g r id ->addE lemen tD i r ( 'My /F i l t e r ' , 'My_F i l t e r ' , ' f i l t e r ' ) ;

    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

    $g r id = new Bvb_Gr id_Dep loy_Tab le ($db , 'Document T i t l e ' ) ; $g r id ->addTemp la teD i r ( 'My /Temp la te /Tab le ' , 'My_Temp la te_Tab le ' , ' t ab le ' )

  • $gr id ->addTemp la teD i r ( 'My /Temp la te /P r in t ' , 'My_Temp la te_Pr in t ' , ' p r i n t ' ) $g r id ->addTemp la teD i r ( 'My /Temp la te /Pd f ' , 'My_Temp la te_Pd f ' ) ;

    And then assign the template

    $g r id ->se tTemp la te ( ' pe rsona l ' , ' t ab le ' ) ; $g r id ->se tTemp la te ( ' company ' , ' pd f ' ) ;

    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: