How to get data from database and fill datagrid with its using Zend Framework

01 Apr 2009 at 13:43 Łukasz Lipiński (No Comments)
This article was written for Javeline Platform library. Examples contained therein are not fully compatible with the library Ajax.org Platform, which is the continuation of. Visit www.ajax.org for more details.

I assume that user have installed Zend Framework and downloaded Javeline Platform.

First we need to define Datagrid:

<j:datagrid
    id      = "DG"
    options = "sort|size"
    top     = "150"
    left    = "10"
    right   = "10"
    height  = "150"
    model   = "mdlDG"
> 
    <j:bindings>
        <j:column caption="Username" select="@username" width="50%"></j:column>
        <j:column caption="Email" select="@email" width="50%"></j:column>
        <j:traverse select="user" />
    </j:bindings>
    <j:model id="mdlDG" >
        <data>
        </data>
    </j:model>
</j:datagrid>

If we want set some default rows, we can do this between data tags.

<data>
    <user username="Somebody" email="someone@gmail.com"></user>
</data>

Next, we need to define button, which will be used to refreshing datagrid.

<j:button left="10" top="320" width="70" tooltip="Refresh datagrid" onclick="refresh()">Refresh</j:button>

When user clicked this button, refresh() function will be called.

function refresh() {
    socket.getUsers();
}

To communicating with server we’ll use Javeline Teleport:

<j:teleport>
    <j:rpc id="socket" protocol="cgi">
        <j:method
            name    = "getUsers"
            url        = "users/index/"
            receive  = "afterGetUsers">
         </j:method>
     </j:rpc>
</j:teleport>

Here we have created one method called getUsers refers to backend (PHP script).

Zend Framework understand “users/index” as: controller -> users, action -> index, of course we can put there link to “normal” script, for example: /modules/users.php.

After all, afterGetUsers function will be called automaticaly. getUsers and afterGetUsers its a javascript functions.

afterGetUsers function will be used for reloading datagrid with new content

function afterGetUsers(data, state, extra) {
    if (state == jpf.SUCCESS) {
        DG.getModel().load(data);
    }
}

Creating backend

Backend will be realy simple. We need to create one controller

application/controllers/UsersController.php

<?php
class UsersController extends Zend_Controller_Action {
    public $_model;
 
    public function indexAction() {
        $resp    = $this->getResponse();
 
        $resp->setHeader('Content-Type', 'text/xml');
 
        $model = $this->_getModel();
        $this->view->users = $model->getUsers();
 
        $resp->setHttpResponseCode(200);
    }
 
    protected function _getModel() {
        if (null === $this->_model) {
            require_once dirname(__FILE__).'/../models/Users.php';
            $this->_model = new Model_Users();
        }
        return $this->_model;
    }
}

where we receive data from database agency model which have implemented function to get it.

Model (application/models/Users.php):

class Model_Users {
    protected $_table;
 
    public function getTable() {
        if (null === $this->_table) {
            require_once dirname(__FILE__) . '/DbTable/Users.php';
            $this->_table = new Model_DbTable_Users;
        }
        return $this->_table;
    }
 
    public function getUsers() {
        $table = $this->getTable();
        $select = $table->getUsers();
 
        return $table->fetchAll($select)->toArray();
    }
}

Database table (application/models/DbTable/Users.php):

class Model_DbTable_Users extends Zend_Db_Table_Abstract {
 
    protected $_name = 'oda_user';
 
    public function getUsers() {
        return parent::select();
    }
}

If You want read more about it, please look at: Zend Framework Quick Start – Create a Model and Database Table

In next step we need to create view file, which parse our data to XML.

View (application/views/users/index.phtml):

$data = $this->users;
$len = count($data);
 
$result = '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
$result .= '<data>'."\n";
    if ($len > 0) {
        for($i = 0; $i < $len; $i++) {
            $result .= '<user username="'.$data[$i]["username"].'" email="'.$data[$i]["email"].'"></user>'."\n";
        }
    }
    else {
        //load empty row - You can leave this else
        $result .= '<user />'."\n";
    }
echo $result .= '</data>';

If You have problems with getting new data, press F9 button to open JPF Debugger (remember, You need to have included jpf_debug.js not jpf_release.js) and check request and received data.

Example – Requested and recived data

GL & HF with JPF.

P.S. If You don’t know what GL & HF means… check GL & HF meaning

Brak komentarzy

Dodaj pierwszy komentarz!

Dodaj komentarz