Zend Framework

Dojo grid in Zend Framework: Creating nice and cool grid in php using Zend Framework and Dojo

Posted by Faheem Abbas on January 8, 2009

“Create new version here”.http://zendgeek.blogspot.com/2009/07/create-dojo-grid-in-zend-framework-nice.html

About a month or two earlier when I used dojo calendar in my application and write article about the Zend Framework and dojo I was wondering why zend make collaboration with zend. But today when I created a grid using zend dojo I feel the real power of the dojo in Zend framework. In this article I am going to give a simple example and create a grid using Zend framework and dojo.

At the end of this tutorial we will have a grid like the following

Dojo Grid in Zend Framework

Dojo Grid in Zend Framework

So let’s feel the power of dojo in zend.

First execute the following query for creating a table.

CREATE TABLE ‘jobs’ (

‘id’ int(11) NOT NULL auto_increment,

‘title’ varchar(50) NOT NULL,

‘description’ text,

‘posted_date’ datetime default NULL,

PRIMARY KEY  (’id’)

)

This will create a table in your database.

Create a model in your models directory and write the following code in it

<?php

class Jobs extends Zend_Db_Table_Abstract

{

protected $_name=’jobs’;

public function getJobsData()

{

$select = $this->_db->select()

->from($this->_name);

$results = $this->getAdapter()->fetchAll($select);

return $results;

}

}

?>

and save this table as Jobs.php

In the code above, we first extend our model from Zend_Db_Table_Abstract, define its name and define our custom function getJobsData() that fetch all the rows in the jobs table. We return the results as an array.

Next create a controller JobsController in you controller’s directory and place the following code in it.

<?php

class JobsController extends Zend_Controller_Action

{

public function  viewAction()

{

}

public function  recordsAction()

{

$jobs = new Jobs();

$data= $jobs->getJobsData();

$dojoData= new Zend_Dojo_Data(’id’,$data,’id’);

echo $dojoData->toJson();

exit;

}

}

In the above code we create two action view and records. We have placed nothing in the view action. In the recordsAction, we create an instance of Jobs model class.and then call its getJobsData() method which will give us an array of records. Next we create an instance of Zend_Dojo_Data() and give the fetched data to it. And finally we echo the data converted it into the Json.

We don’t need to create a view for the records action because we have placed exit it the end of this action which will stop rendering of the view. As we will call this action form our grid view template page so no need to define phtml file for it.

However we will need to create template file for our viewAction. In scripts/views/ directory create view.phtml file and place the following code in it.

<?php

Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

$this->dojo()->setLocalPath(’http://localhost/Zend/js/dojo/dojo/dojo.js’)

->addStyleSheetModule(’dijit.themes.tundra’)

->addStylesheet(’http://localhost/Zend/js/dojo/dojox/grid/_grid/tundraGrid.css’);

echo $this->dojo();

?>

<script type=”text/javascript”>

dojo.require(”dojox.data.QueryReadStore”);

dojo.require(”dojox.grid.Grid”);

dojo.require(”dojo.parser”);

</script>

<body class=”tundra”>

<div dojoType=”dojox.data.QueryReadStore” jsId=”activeStore”, url=”records”></div>

<div dojoType=”dojox.grid.data.DojoData” jsId=”model” rowsPerPage=”20″ store=”activeStore”></div>

<table id=”activePastes” dojoType=”dojox.grid.Grid” model=”model” style=”height:300px; width:700px;”>

<thead>

<tr>

<th field=”id”>Id</th>

<th field=”title”>Title</th>

<th field=”description”>Description</th>

<th field=”posted_date”>Posted</th>

</tr>

</thead>

</table>

</body>

Keep in mind this is the main template file where we are creating our gird.

In the first statement I told zend to use declarative instead of programmatic behavior which is default. Next I set local path and add specific stylesheets. Then in the javascript code I used statement

Dojo.requre(’dojox.data.’) etc

To include specific dojo js modules.

In the body tag I specify a class “tundra”. This is important for the stylesheet I have added.

Next tow div’s and table are  the main code for creating grid.

The first div fetch the records from the url specified. This url may be different if you fetch records form the other controller or source. Please specify valid url otherwise you will not get what you want.

The next div act as a bridge between our first div and the table. This div take data from the first div and give it to the table for display purposes.

Keep in mind that all the attributes of the div’s and table are compulsory. Removing any of the attribute may result in unvalid records or empty page. So define everything that I have defined. Once you become able to display your records, you can play with these attributes.

39 Responses to “Dojo grid in Zend Framework: Creating nice and cool grid in php using Zend Framework and Dojo”

  1. [...] Framework and dojo-grid sorting example In my previous post “dojo-grid-in-zend-framework-creating-nice-and-cool-grid-in-php-using-zend-framework-and-dojo” I discuss how to creat nice and cool gird using Zend framework and [...]

  2. Greg said

    Edits: your div tag is unterminated
    <div dojoType=”dojox.grid.data.DojoData” ...
    and you misspelled your closing thead tag.

  3. Todd said

    Thank you very much. I spent hours tinkering with Zend and dojo today. With the help of this post I finally got over the hump. I see a grid!

  4. saurabh said

    i can see only the headings..i.e id title description posted when i go to localhost/jobs/view URL..and i am not able to see any records..wot things should i check?

  5. Faheem Abbas said

    I’ve seen most of the time that if we don’t use “store” properly, we only see headings. For example “QueryReadStore” in this example. you should check your paths, e.g
    dojo.require(”dojox.data.QueryReadStore”);

    Important: Check your path to local dojo.js file.
    Keep in mind that if path to dojo.js file is not properly set, you may not be able to get the dojo grid.

  6. girish said

    Hi Faheem Abbas,
    You are simply gr8. I searched all the web (except this page) for short & simple tut on grid.
    I now i finally have a grid on my page.
    thx a ton.

    keep posting such good tuts.

  7. saurabh said

    still the problem isnt solved.!for the above tutorial are there any settings required in bootstrap,layout? or is this the complete working tutorial?i have modified bootstrap,layout as per your “zend framework and dojo” tutorial.please reply

  8. Faheem Abbas said

    Yes, you will need to make some configuration setting for using dojo in you Zend Framework application. please read the following article before creating grid with dojo.
    http://zendguru.wordpress.com/2008/10/27/zend-framework-and-dojo/

  9. saurabh said

    i have followed exactly according to this tutorial and http://zendguru.wordpress.com/2008/10/27/zend-framework-and-dojo/ for configuring dojo grid…still i cant see any grid..now i get “dojo loaded” message twice in my browser(i have put alert(’dojo loaded’)in dojo.js) ..i think first is from view.phtml(job controller’s view action) and other is comming from layout.phtml..so how can i solve this problem?

  10. Faheem Abbas said

    congrats for loading dojo successfully. Now make sure that your other js files like QueryReadStore.js etc are also properly loaded. And I’ll suggest you carefully read and follow my article. If problem doesn’t solve, gemme some explanation and I’ll try to solve your problem.

  11. Jim said

    Saurabh

    I had to do this in my controllers action that the datastore’s url referenced …

    // this has no associated renderer
    $this->_helper->viewRenderer->setNoRender();
    // this has no associated layout
    $this->_helper->getHelper(’layout’)->disableLayout();

    I ultimately ended up creating base class controller for my async actions. Once I setup the above, the grid worked as I expected.

    Without the above, I was getting firebug message about SyntaxError … very generic, not helpful and I checked in to the response, and found it was not what I was expecting .. which led me to try the above to disable layouts and rendering for asynchronous calls (ie – just echo’ing results on requests)

  12. saurabh said

    Jim,
    Can u please elaborate..do u mean i should add the 2 lines u said in
    1)public function recordsAction() or
    2)view.phtml
    NOTE:my browser doesnt show any errors but neither i see grid with records…

  13. Jim said

    Saurabh

    What I did was something like this

    class MyAsyncController extends Zend_Controller_Action
    {
    public function init()
    {
    // this has no associated renderer
    $this->_helper->viewRenderer->setNoRender();
    // this has no associated layout
    $this->_helper->getHelper(’layout’)->disableLayout();
    }
    }

    then, I created my “asynchronous handlers” deriving from that controller ..

    class MyHandlerController extends MyAsyncController
    {
    public function recordsAction()
    {
    public function recordsAction()
    {
    $model = new ModelObject();
    $data = $model->getMyData();
    $dojoData = new Zend_Dojo_Data(’MyID’, $data, ‘Mylabel’);
    echo $dojoData->toJson();
    }
    }
    }

    A thing to note, is that the grid has display issues (and retrieval of additional records) if you dont encode ‘numRows’ => totalrecords into it. It isn’t required for datasets that return fewew rows than rowsPerPage, but is if there are more.

  14. Jim said

    oops on repeated function in MyHandlerController … but I think you get the idea :-)

  15. saurabh said

    friends,
    Now I am able to retrieve the records,but they are just scattered and I am not able to see the GRID yet inspite of getting dojo loaded message!

    Jim,
    your settings stopped entire rendering(i get blank page)..so commented out those lines

  16. saurabh said

    thanks everyone for help,my problem is solved,I can see the grid now.

  17. Faheem,
    1st, thanks for the tutorial. It’s a real help when the documentation at dojo central is so sparse.

    I think I’m missing something as I can’t get data into the grid

    My layout looks like this:

    Id
    Title
    Send Status
    Send Date

    I can’t yet see any output in the table yet, but it does display the table structure.

    the URL /zwmail/adminjson/viewmitems/ does work. I tested it by a direct call using
    function viewList(idList) {
    var data = {’idList’:idList};

    dojo.xhrGet( {
    url: “/zwmail/adminjson/viewmitems/”,
    handleAs: “json”,
    content: data,
    load: function(responseObject, ioArgs) {
    //check return here in firebug
    return responseObject;
    }
    // More properties for xhrGet…
    });
    }

    The dojo integration is working as I am able to display a tabbed page and pull in other data items via dojo.xhrGet() calls already.

    Also, I need to be able to update the table dynamically, i.e. when a parent record id changes. What javascript do I need to update the table on the fly? A demonstration of that would round your article off nicely.

    Thanks.

  18. Oops – the layout should be (trying with pre tags

    Id
    Title
    Send Status
    Send Date

  19. Nope, that didn’t work – any suggestions for embedding html in one of these comments?

  20. Faheem Abbas said

    If table structure is there, my question would be.
    Is the theme applied to that table. I mean tundra theme.
    If yes then you have problem with setting your url.
    dojo.xhrGet( {
    url: “/zwmail/adminjson/viewmitems/”,
    handleAs: “json”,
    content: data,
    load: function(responseObject, ioArgs) {
    //check return here in firebug
    return responseObject;
    }
    url must point to place, where you want it to be.
    Typing url and using it from a page may behave differently.so it would be better if you give your absolute path like
    “http://…” and check whether grid display the data.

  21. typing in a fqdn doesn’t work either

    I cannot get the view template source code into this editor to show you. (bah humbug). tell me how you do it and I’ll post it 2morrow.

    Thanks
    A

  22. Faheem, thanks for your patience. OK first off, the action script does get called by the view template. Here’s another example.

    1/ view script (Just so I can get this displaying in these comments I’m replacing the xhtml brackets with [ and ])

    [div dojoType="dojox.data.QueryReadStore" jsId="subsStore", url="/zwmail/adminjson/viewsubs/"][/div]
    [div dojoType="dojox.grid.data.DojoData" jsId="subsModel" rowsPerPage="20" store="subsStore"][/div]
    [table id="zwmail_admin_subsGrid" dojoType="dojox.grid.Grid" model="subsModel" style="height:300px; width:300px;"]
    [thead]
    [tr]
    [th field="id"]Id[/th]
    [th field="lstName"]List Name[/th]
    [th field="dateJoined"]Start Date[/th]
    [th field="dateLeft"]End Date[/th]
    [/tr]
    [/thead]
    [/table]

    2/ action script

    $dojoData = new Zend_Dojo_Data(’subId’,$arrItem); //id must be set to an item in the array
    $dojoData->setMetadata(’numRows’,count($arrItem));//according to ZF docs dojo.data.grid reques numrows
    $dojoData->setLabel(’subsModel’); //maybe this does something?
    echo $dojoData->toJson();

    3/ response data returned by action script (viewable via firebug)

    {”identifier”:”subId”,”items”:[{"subId":"7","lstName":"ZWMail Newsletter","dateJoined":"23\/03\/2009"
    ,"dateLeft":"23\/03\/2009"}],”numRows”:1,”label”:”subsModel”}

    But the table doesn’t display on screen.

    TIA

  23. Faheem Abbas said

    Ashley Kitson,
    It seems that you are not following what i have done in the above article.
    Please tell me why don’t you want to follow my example and then play with the grid and make changes once you succeeded.
    From the above code I cannot guess where are you putting all the code. In single file or in different files.
    Please give some explanation about

    $dojoData = new Zend_Dojo_Data(’subId’,$arrItem); //id must be set to an item in the array
    $dojoData->setMetadata(’numRows’,count($arrItem));//according to ZF docs dojo.data.grid reques numrows
    $dojoData->setLabel(’subsModel’); //maybe this does something?
    echo $dojoData->toJson();

    where this code reside?

  24. Vishal said

    Thanks a lot abbbas for nice article please also tell how to obtain the data of a row on clicking but please in Zend 1.7

  25. Marta said

    Hi.

    I followed your example, but in the end I have only two checkboxes displayed instead of my grid.
    Is this a known problem?
    The first div does not fetch data from url (if i put some bug in the code no error is reported), but I’m quite sure the url is ok and if I check it in browser correct json data are displayed.

  26. Marta said

    Hmm, it seems that proper stylesheet is missing. I managed to make working example with DojoGrid (had the same problem):

    var storeM = new dojox.data.QueryReadStore({url:'baseUrl;?>/index/records'});

    ...

    with imported dojox/grid/resources/tundraGrid.css

    It doesn’t work for your example.
    Could you write what css files are you using?
    Thanks.

  27. Marta said

    Sorry, please forget about previous comment, I need to rest… :)

  28. Faheem Abbas said

    you might be missing

    "<body class=tundra">

    in your code.

  29. marc said

    Hello

    Thank you for the code.

    It is working but the load time is terribly slow do know what might be causing that when It seems to be the dojo.require(”dojox.grid.Grid”); that is causing the slow down.

    Thanks

  30. Faheem Abbas said

    Read my article on how to improve dojo performance.
    http://zendguru.wordpress.com/2009/01/07/improve-dojo-performance-in-zend-framework/

  31. Chitta Ranjan said

    Nice article. Keep it up.

    How can we implement searching and paging in this grid like extjs grid.

    Thanks.

  32. Ivan said

    Hi,
    I managed to rend a grid but I can’t see any data inside it. Seems like I don’t get any data at all from my recordsAction. How can I understand if the grid gets any data at all, and the most important for me is to know if it calls the recordsAction at all.

  33. ZfNoob said

    me too =(

  34. ZfNoob said

    IVAN you should edit the url=”records” to your records path…
    For example I have it here url=”/my_project/public/jobs/records”

    :)

  35. dhayal said

    Hi Mr Faheem Abbas,
    I read most of your articles. Really very useful for me.. I am new to Zend Framework. with your articles i am improving my skills thanks… This grid is very nice…

    Could u give me your Email?

  36. dhayal said

    http://download.dojotoolkit.org/release-1.2.0/dojo-release-1.2.0/dojox/grid/tests/test_tundra_edit.html

    have a look at this

  37. dhayal said

    http://download.dojotoolkit.org/release-1.2.0/dojo-release-1.2.0/dojox/grid/tests/test_yahoo_search.html

    in the above two grids, they provided in line edit and search inside grid…This would provide a strong user interface if we apply this in real world application,Hope if we try we can achieve it using ZendFramework …

  38. dhayal said

    this link will display all

    http://download.dojotoolkit.org/release-1.2.0/dojo-release-1.2.0/dojox/grid/tests/

  39. Gustavo said

    How can I do a CRUD application using the dojo grid?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>