Zend Framework + Doctrine + jQuery Grid

Today i will show you how to put together: Zend Framework, Doctrine and simple jQuery Grid in easy way. All i want to do is to get some data from database with doctrine, format that data and send it to the template with Zend_Json:) Really nothing special.

Ok. Let’s start. First of all we need to create database schema.yml. It is realy easy country table:


Country:
  tableName: country
  columns:
    id:
      primary: true
      autoincrement: true
      type: integer(10)
    name: string(50)
    description: string(255)

We also have to set up the database configuration in the config.ini:

type       = “mysql”     // database adapter
dbname = “doctrine_grid”  // database name
host       = “localhost”  // host
username = “user”
password = “pass”

Then we must create database, generate models and sql, create tables and load simple data fixtures.

From the command line in the main application directory we call the following code:

1) php doctrine-cli.php create-db

2) php doctrine-cli.php generate-models-yaml

3) php doctrine-cli.php generate-sql //it is not necessary

4) php doctrine-cli.php create-tables

or simply: php doctrine-cli.php build-all

Now we need some data for testing.

Create data.yml file in directory: data/fixtures


Country:
  Country_1:
    name: 'Poland'
    description: 'Description for Poland'
  Country_2:
    name: 'Germany'
    description: 'Description for Germany'
  Country_3:
    name: 'Brzail'
    description: 'Description for Brazil'
  Country_4:
    name: 'USA'
    description: 'Description for USA'
  Country_5:
    name: 'Ireland'
    description: 'Description for Ireland'
  Country_6:
    name: 'Canada'
    description: 'Description for Canada'
  Country_7:
    name: 'India'
    description: 'Description for India'
  Country_8:
    name: 'Italy'
    description: 'Description for Italy'
  Country_9:
    name: 'Spain'
    description: 'Description for Spain'
  Country_10:
    name: 'Portugal'
    description: 'Description for Portugal'
  Country_11:
    name: 'Argentina'
    description: 'Description for Argentina'
  Country_12:
    name: 'Estonia'
    description: 'Description for Estonia'
  Country_13:
    name: 'Bulgaria'
    description: 'Description for Bulgaria'
  Country_14:
    name: 'France'
    description: 'Description for France'
  Country_15:
    name: 'Belgium'
    description: 'Description for Belgium'
  Country_16:
    name: 'Austria'
    description: 'Description for Austria'
  Country_17:
    name: 'Australia'
    description: 'Description for Australia'
  Country_18:
    name: 'Japan'
    description: 'Description for Japan'
  Country_19:
    name: 'Russia'
    description: 'Description for Russia'
  Country_20:
    name: 'Slovakia'
    description: 'Description for Slovakia'
  Country_21:
    name: 'Ireland'
    description: 'Description for Ireland'

And we call:

php doctrine-cli.php load-data

to import data to the database.

Next step is to download jQuery Flexi grid (yesterday i had some problem because site was suspended) and put it into public/js/ (js files I put into js/ and css files into /css folder). We also need to download latest jQuery version.

Now we can take care of php scripts. We can simply create new controller, for example GridController and one action: indexAction.


class GridController extends Core_Controller_Action
{
    public function indexAction(){

    }
}
?>

We don’t need to put any code in the indexAction. Zend will automatic call the index.tpl template where we have to put the following code:


<h1> Testing jQuery FlexiGrid </h1>

<table id="myGrid"> </table>
	<!-- updated to work with IE -->

{literal}

<link rel="stylesheet" type="text/css" href="public/css/flexigrid/flexigrid.css">
<script type="text/javascript" src="public/js/jquery-1.2.6.js"></script>
<script type="text/javascript" src="public/js/flexigrid/flexigrid.js"></script>

<script language="javascript" type="text/javascript">

$("#myGrid").flexigrid({
  url: 'grid/list',
  dataType: 'json',
  colModel : [
    {display: 'Id', name : 'id', width : 40, sortable : true, align: 'center'},
    {display: 'Name', name : 'name', width : 100, sortable : true, align: 'left'},
    {display: 'Description', name : 'description', width : 200, sortable : true, align: 'center'}
  ],
  buttons : [
    {name: 'Add', bclass: 'add', onpress : test},
    {name: 'Delete', bclass: 'delete', onpress : test},
    {separator: true}
  ],
  searchitems : [
    {display: 'Name', name : 'name'}
  ],
  sortname: "name",
  sortorder: "asc",
  usepager: true,
  title: 'List',
  useRp: true,
  rp: 10,
  showTableToggleBtn: true,
  width: 700,
  height: 200
});

function test(com, grid){

  $(".trSelected > td:first-child > div:first-child").each( function(index, element){

  alert($(element).html());

}
);

}

</script>

{/literal}

I have created the empty div for my flexi grid, then imported javascript libaries and called flexigrid method on div element. I just set the most important options (unfortunately there is realy small documentation about flexigrid, so sometimes we need to read the library code).

One of the required option is url. Flexi grid needs that url for retrieving data from the database - for example: sorting and pagination. We need to create function listAction where we put code responsible for getting data, sorting and pangination.


public function listAction(){

    # We don't want to render Layout
    $this->_helper->layout()->disableLayout();

    # rendering view is also not necessary
    $this->_helper->viewRenderer->setNoRender();

    $req = $this->getRequest();

    # Pagination parameters
    $currentPage 	= $req->getPost('page', 1);
    $resultsPerPage = $req->getPost('rp', 10);

    # Sorting parameters
    $orderBy 		= $req->getPost('sortname', 'name');
    $orderType 	= $req->getPost('sortorder', 'ASC');

    # Query parameters - for Searching
    $query 			= $req->getPost('query', '');
    $qtype 			= $req->getPost('qtype', 'name');

    # Creating Doctine pager object
    $pager = new Doctrine_Pager(
      Doctrine_Query::create()
      ->from( 'Country' )
      ->addWhere("$qtype LIKE ?", "%$query%")
      ->orderby( "$orderBy $orderType" ),
    $currentPage, // Current page of request
    $resultsPerPage // (Optional) Number of results per page. Default is 10
    );

    $items = $pager->execute();

    $elements = array();
    # We also have to format our data array that flexifrid could retrieve itt
    foreach($items as $item){

        $elements[] = array(
          'id'	=>	$item->id,
          'cell'	=>	array_values($item->toArray())
        );
    }

    echo Zend_Json::encode(array(
        'page'	=>	$currentPage,
        'total'	=>	$pager->getNumResults(),
        'rows'	=>	$elements
    ));

}
?>

That’s all. We can test our grid calling for example http://your-domain.com/grid/

You should see something like that:

flexi grid

You can also check my example on: www.test.adryjanek.eu/grid

40 Responses to “Zend Framework + Doctrine + jQuery Grid”


  1. 1 Lesmono

    Can u please be more specific. Please show me your directory structure and your index.php

  2. 2 Kamil Adryjanek

    You can find my directory structure (already integrated with Doctrine) here: http://blog.adryjanek.eu/2008/11/24/zend-framework-integracja-z-doctrine-orm/

  3. 3 Lesmono

    can u please send me the demo application from your http://www.test.adryjanek.eu/grid

  4. 4 Kamil Adryjanek

    I can send youm my code in the evening as soon as i get back home.

  5. 5 sdc888

    Great post! would love to see the code for the demo also!

    Thanks!

  6. 6 Kamil Adryjanek

    I just send you my source code on your e-mail.

  7. 7 Lesmono

    Hi…adry, have you send me the source code. Because I didn’t recieve any email from you.

  8. 8 Kamil Adryjanek

    Yes, I did but there was some problem with your e-mail address. I send it again today in the morning.

  9. 9 Michael

    Hey Kamil,

    I just wanted to say thanks, this worked great, I was able to intigrate it into an existing ZF/Doctrine project I am working on with out any issues.

    Thanks!!!!!
    Michael

  10. 10 Yusri

    hi.nice code. can you send to me the source code.
    thank you

  11. 11 Kamil Adryjanek

    No problem. Check your e-mail box.
    Cheers.

  12. 12 Kamil Adryjanek

    I have updated my code and test version on test.adryjanek.eu to work better with Internet Explorer. There were some problems with displaying data using div element.

  13. 13 Yenski Ronsha

    Hi nice code, can you send the code to my email address?

  14. 14 Kamil Adryjanek

    Hi, no prob. Enjoy :)

  15. 15 Cristian

    Hi all .. ok ok .. it’s nice .. but how do you implement jquery form validator in flexigrid ?

    some kaind of .. if form is valid, subit else not.

  16. 16 Amarnath

    Hi, Can you please send me the code to my email address.

  17. 17 Kamil Adryjanek

    Check your e-mail box. Cheers.

  18. 18 Mondy

    Hi, can you send me the code to my email address too?

    Thanks a lot.

  19. 19 Kamil Adryjanek

    Sent, greetings.

  20. 20 Comet

    Hi, can you send me the code to my email address too? (thanhhuyen2001vn@yahoo.com)
    Thanks a lot.

  21. 21 Robert

    It’s a nice code. Pls, send your demo code to me. Thank in advance.

  22. 22 Kamil Adryjanek

    @Comet,sent.
    @Robert, i need your e-mail.

  23. 23 Niko

    Hi,
    Very interest and usefully, but can you send me the code to my email address too?

    Thanks a lot.

  24. 24 Kamil Adryjanek

    No problem, sent.

  25. 25 andrey

    Hi, can you send me the code to my email address too? (awean@rambler.ru). Only begining learn zf to need examples.
    Thanks a lot.

  26. 26 thomas

    Perfect code + Perfect tutorial = Top of tutorial .

    Possible to have a zip ?

    Thx,

  27. 27 Kamil Adryjanek

    Hi, Thank you for your comment.
    Check your e-mail, i just send you sample application code.
    Cheers

  28. 28 pss

    Hello,
    can you send me the code too?

    Thanks

  29. 29 Chris

    Hi,
    Great stuff. I appreciate it.
    Could you send me the code as well?
    Thanks in advance

  30. 30 maddog

    Hi!

    How adding to this code one form with search parameters?

  31. 31 Kamil Adryjanek

    @Chris: sent.
    @maddog: what do you mean exactly? Some dialog?

  32. 32 maddog

    Idea?
    Steps:
    1. User open page. There is form with some inputs, button submit and empty grid.
    2. User fill inputs and send data.
    3. Next starts zend validation. If validation on requesting data is ok, datas are sending to grid.

  33. 33 Kamil Adryjanek

    And what is the problem?? You just want to add a record to database? You can create simple form and add ajax submit handler to it to send data from your form via AJAX. For example:
    $(’#yourForm’).submit(function() {
    $.ajax({
    type: ‘POST’,
    url: ‘yourAjaxHandlerUrl’,
    data: formData,
    error: function() {

    }
    success: function() {

    }
    });

    In success action you sholud reload the grid and reset the form. In error handler you can display some errors from PHP validation (you can also add JS validation).
    It should help.

  34. 34 maddog

    That’s another problem.
    I want connect flexigrid and my search form / no internal flexigrid search/. Flexigrid should reload only when i pushed send button from my valided search form.

  35. 35 Shahab

    @Kamil Adryjanek: could you please send me the code on my id shahab_qadeer@hotmail

  36. 36 karimulla

    can you send me the source code please!

  37. 37 thantang

    You can send me your’s code,plz.
    I need it !
    Thanks.

  38. 38 Adriano

    Good day! My frendy I need your help, I sorry my english I m Brazilian…

    I need of your exemple for studante moore !!

  39. 39 Kamil Adryjanek

    Send, enyoj!

  40. 40 Adriano

    Thank’s save my life in my service …

  1. 1 Symfony + flexiGrig | Projektant - Programista PHP
  2. 2 Zend Framework v. 1.9.3 i Doctrine 1.1.4 | Moje zmagania ze światem informatyki.
  3. 3 Robo47.net

Leave a Reply

Podgląd komentarza:




About me:

  • PHP programmer
  • Symfony developer
  • Zend framework developer

Categories: